packages feed

polytropos-plugin 0.1.0.3 → 0.1.2.1

raw patch · API changes only · 8 files changed · hide whitespace changes · browse polytropos-plugin-0.1.2.1

+1200/−415 lines, 8 filesdep +bytestringdep +containersdep +deepseqdep ~basedep ~ghcdep ~polytropos-corePVP ok

Dependencies added: bytestring, containers, deepseq, ghc-internal, tasty-bench, text

Dependency ranges changed: base, ghc, polytropos-core, polytropos-plugin

API changes (from Hackage documentation)

0 removed, 13 added, 0 changed

version bump matches the API change (PVP)

+ Polytropos.Plugin.MergeMorph: MergeDisjointOverlap :: FastString -> MergeEvalResult
+ Polytropos.Plugin.MergeMorph: MergeReplaceMissing :: FastString -> MergeEvalResult
+ Polytropos.Plugin.MergeMorph: MergeSuccess :: [RowEntry] -> [Int] -> MergeEvalResult
+ Polytropos.Plugin.MergeMorph: RowEntry :: FastString -> Type -> Int -> RowEntry
+ Polytropos.Plugin.MergeMorph: [entryLabel] :: RowEntry -> FastString
+ Polytropos.Plugin.MergeMorph: [entrySlot] :: RowEntry -> Int
+ Polytropos.Plugin.MergeMorph: [entryType] :: RowEntry -> Type
+ Polytropos.Plugin.MergeMorph: data MergeEvalResult
+ Polytropos.Plugin.MergeMorph: data RowEntry
+ Polytropos.Plugin.MergeMorph: encodeGatherBytes :: [Int] -> ByteString
+ Polytropos.Plugin.MergeMorph: evalMergeOp :: MergeOp -> [RowEntry] -> [RowEntry] -> MergeEvalResult
+ Polytropos.Plugin.MergeMorph: instance GHC.Internal.Classes.Eq Polytropos.Plugin.MergeMorph.MergeEvalResult
+ Polytropos.Plugin.MergeMorph: instance GHC.Internal.Classes.Eq Polytropos.Plugin.MergeMorph.RowEntry

Files

CHANGELOG.md view
@@ -1,5 +1,20 @@ # Changelog for polytropos-plugin +## 0.1.2.0 — 2026-11-22++- Defer `RowEq`, `RowShow`, `RowEqSum`, `RowShowSum` whole-row solvers on open tails and unreduced type families.+- Fix `OpReplace` field ordering preserving declaration order of original row.+- Fix `OpRestrict` lookup reading source field slot indices.+- Unconditionally unwrap synonyms in `parseMergeOp`.+- Gate injected `Polytropos` imports to only modules containing transformed `REC` or `VAR` syntax.+- Properly parenthesize desugared expressions and patterns (`mkHsPar`).+- Persist interactive `OpenRecord` and `OpenVariant` declarations across GHCi prompt turns for GHC 10.1+.+- Enable `-dcore-lint` in smoke tests.++## 0.1.1.0 — 2026-11-18++- Add `KnownMergeMorph` constraint solver for skew Boolean row algebra operations.+ ## 0.1.0.3 — 2026-11-03  - Add `KnownRowMorph` constraint solver emitting literal `RowMorph` index arrays for static channel permutations.
+ bench/Main.hs view
@@ -0,0 +1,182 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# OPTIONS_GHC -Wno-orphans #-}++-- | Module: Main+-- Description: Runtime microbenchmarks for Polytropos vs native nominal ADTs and Data.Map+--+-- Run with allocation tracking enabled:+--   cabal v2-bench polytropos-bench --benchmark-options='--csv=dist-newstyle/polytropos-bench.csv +RTS -T -RTS'+module Main (main) where++import Control.DeepSeq (NFData(..))+import GHC.Generics (Generic)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import qualified Data.Text as T+import Polytropos+import Polytropos.Core (RowRep(..))+import Test.Tasty.Bench++-- | Stand-in NFData instance for Polytropos records in microbenchmarks.+instance NFData (RowRep f r row a) where+  rnf (RowRep _) = ()++-- ============================================================================+-- N = 4 Models+-- ============================================================================++data Nom4 = Nom4+  { n4_0 :: {-# UNPACK #-} !Int+  , n4_1 :: {-# UNPACK #-} !Int+  , n4_2 :: {-# UNPACK #-} !Int+  , n4_3 :: {-# UNPACK #-} !Int+  } deriving (Eq, Show, Generic, NFData)++type Poly4 = Record '["f0" ':= Int, "f1" ':= Int, "f2" ':= Int, "f3" ':= Int]++{-# NOINLINE sumNom4 #-}+sumNom4 :: Nom4 -> Int+sumNom4 r = n4_0 r + n4_1 r + n4_2 r + n4_3 r++{-# NOINLINE sumPoly4 #-}+sumPoly4 :: Poly4 -> Int+sumPoly4 r = r.f0 + r.f1 + r.f2 + r.f3++{-# NOINLINE sumMap4 #-}+sumMap4 :: Map Text Int -> Int+sumMap4 m =+  Map.findWithDefault 0 "f0" m+    + Map.findWithDefault 0 "f1" m+    + Map.findWithDefault 0 "f2" m+    + Map.findWithDefault 0 "f3" m++{-# NOINLINE updateNom4 #-}+updateNom4 :: Nom4 -> Nom4+updateNom4 r = r { n4_2 = 99 }++{-# NOINLINE updatePoly4 #-}+updatePoly4 :: Poly4 -> Poly4+updatePoly4 r = REC_UPD r { f2 = 99 :: Int }++-- ============================================================================+-- N = 16 Models+-- ============================================================================++data Nom16 = Nom16+  { n16_0  :: {-# UNPACK #-} !Int+  , n16_1  :: {-# UNPACK #-} !Int+  , n16_2  :: {-# UNPACK #-} !Int+  , n16_3  :: {-# UNPACK #-} !Int+  , n16_4  :: {-# UNPACK #-} !Int+  , n16_5  :: {-# UNPACK #-} !Int+  , n16_6  :: {-# UNPACK #-} !Int+  , n16_7  :: {-# UNPACK #-} !Int+  , n16_8  :: {-# UNPACK #-} !Int+  , n16_9  :: {-# UNPACK #-} !Int+  , n16_10 :: {-# UNPACK #-} !Int+  , n16_11 :: {-# UNPACK #-} !Int+  , n16_12 :: {-# UNPACK #-} !Int+  , n16_13 :: {-# UNPACK #-} !Int+  , n16_14 :: {-# UNPACK #-} !Int+  , n16_15 :: {-# UNPACK #-} !Int+  } deriving (Eq, Show, Generic, NFData)++type Poly16 = Record+  '[ "f0" ':= Int, "f1" ':= Int, "f2" ':= Int, "f3" ':= Int+   , "f4" ':= Int, "f5" ':= Int, "f6" ':= Int, "f7" ':= Int+   , "f8" ':= Int, "f9" ':= Int, "f10" ':= Int, "f11" ':= Int+   , "f12" ':= Int, "f13" ':= Int, "f14" ':= Int, "f15" ':= Int+   ]++{-# NOINLINE accessNom16 #-}+accessNom16 :: Nom16 -> Int+accessNom16 r = n16_0 r + n16_8 r + n16_15 r++{-# NOINLINE accessPoly16 #-}+accessPoly16 :: Poly16 -> Int+accessPoly16 r = r.f0 + r.f8 + r.f15++{-# NOINLINE accessMap16 #-}+accessMap16 :: Map Text Int -> Int+accessMap16 m =+  Map.findWithDefault 0 "f0" m+    + Map.findWithDefault 0 "f8" m+    + Map.findWithDefault 0 "f15" m++{-# NOINLINE updateNom16 #-}+updateNom16 :: Nom16 -> Nom16+updateNom16 r = r { n16_8 = 99 }++{-# NOINLINE updatePoly16 #-}+updatePoly16 :: Poly16 -> Poly16+updatePoly16 r = REC_UPD r { f8 = 99 :: Int }++-- ============================================================================+-- MergeMorph Models (N=4 + N=4 -> N=8)+-- ============================================================================++type PolyLeft = Record '["a0" ':= Int, "a1" ':= Int, "a2" ':= Int, "a3" ':= Int]+type PolyRight = Record '["b0" ':= Int, "b1" ':= Int, "b2" ':= Int, "b3" ':= Int]++{-# NOINLINE morphDisjoint #-}+morphDisjoint :: PolyLeft -> PolyRight -> Record '["a0" ':= Int, "a1" ':= Int, "a2" ':= Int, "a3" ':= Int, "b0" ':= Int, "b1" ':= Int, "b2" ':= Int, "b3" ':= Int]+morphDisjoint l r = l <+> r++-- ============================================================================+-- Main Benchmark Suite+-- ============================================================================++main :: IO ()+main = defaultMain+  [ bgroup "record-access/N4"+      [ env (pure (Nom4 1 2 3 4)) $ \r ->+          bench "nominal/Nom4" $ whnf sumNom4 r+      , env (pure (REC { f0 = 1 :: Int, f1 = 2 :: Int, f2 = 3 :: Int, f3 = 4 :: Int } :: Poly4)) $ \r ->+          bench "polytropos/Poly4" $ whnf sumPoly4 r+      , env (pure (Map.fromList [("f0", 1), ("f1", 2), ("f2", 3), ("f3", 4)])) $ \m ->+          bench "containers/Map4" $ whnf sumMap4 m+      ]+  , bgroup "record-update/N4"+      [ env (pure (Nom4 1 2 3 4)) $ \r ->+          bench "nominal/Nom4" $ whnf updateNom4 r+      , env (pure (REC { f0 = 1 :: Int, f1 = 2 :: Int, f2 = 3 :: Int, f3 = 4 :: Int } :: Poly4)) $ \r ->+          bench "polytropos/Poly4" $ whnf updatePoly4 r+      ]+  , bgroup "record-access/N16"+      [ env (pure (Nom16 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)) $ \r ->+          bench "nominal/Nom16" $ whnf accessNom16 r+      , env (pure (REC+          { f0 = 0 :: Int, f1 = 1 :: Int, f2 = 2 :: Int, f3 = 3 :: Int+          , f4 = 4 :: Int, f5 = 5 :: Int, f6 = 6 :: Int, f7 = 7 :: Int+          , f8 = 8 :: Int, f9 = 9 :: Int, f10 = 10 :: Int, f11 = 11 :: Int+          , f12 = 12 :: Int, f13 = 13 :: Int, f14 = 14 :: Int, f15 = 15 :: Int+          } :: Poly16)) $ \r ->+          bench "polytropos/Poly16" $ whnf accessPoly16 r+      , env (pure (Map.fromList [(T.pack ("f" ++ show i), i) | i <- [0..15 :: Int]])) $ \m ->+          bench "containers/Map16" $ whnf accessMap16 m+      ]+  , bgroup "record-update/N16"+      [ env (pure (Nom16 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)) $ \r ->+          bench "nominal/Nom16" $ whnf updateNom16 r+      , env (pure (REC+          { f0 = 0 :: Int, f1 = 1 :: Int, f2 = 2 :: Int, f3 = 3 :: Int+          , f4 = 4 :: Int, f5 = 5 :: Int, f6 = 6 :: Int, f7 = 7 :: Int+          , f8 = 8 :: Int, f9 = 9 :: Int, f10 = 10 :: Int, f11 = 11 :: Int+          , f12 = 12 :: Int, f13 = 13 :: Int, f14 = 14 :: Int, f15 = 15 :: Int+          } :: Poly16)) $ \r ->+          bench "polytropos/Poly16" $ whnf updatePoly16 r+      ]+  , bgroup "merge-morph/N8"+      [ env (pure ( REC { a0 = 1 :: Int, a1 = 2 :: Int, a2 = 3 :: Int, a3 = 4 :: Int } :: PolyLeft+                  , REC { b0 = 5 :: Int, b1 = 6 :: Int, b2 = 7 :: Int, b3 = 8 :: Int } :: PolyRight+                  )) $ \ ~(l, r) ->+          bench "polytropos/DisjointMerge" $ whnf (uncurry morphDisjoint) (l, r)+      ]+  ]
polytropos-plugin.cabal view
@@ -1,6 +1,6 @@ cabal-version:      3.0 name:               polytropos-plugin-version: 0.1.0.3+version:            0.1.2.1 synopsis:           TcPlugin that emits literal evidence for Polytropos row classes description:   A GHC typechecker plugin for <https://hackage.haskell.org/package/polytropos polytropos>@@ -46,13 +46,17 @@   import:           warnings   exposed-modules:  Polytropos.Plugin                   , Polytropos.Plugin.Source+                  , Polytropos.Plugin.MergeMorph   other-modules:    Polytropos.Plugin.Compat   hs-source-dirs:   src   default-language: GHC2021   build-depends:-      base       >= 4.18 && < 4.23-    , ghc         >= 9.6  && < 9.15+      base       >= 4.18 && < 4.24+    , ghc         >= 9.6  && < 10.2     , ghc-tcplugin-api >= 0.1 && < 0.21+    , bytestring >= 0.11 && < 0.13+    , containers >= 0.6 && < 0.9+    , polytropos-core >= 0.1.2.0 && < 0.2  test-suite polytropos-plugin-smoke   import:           warnings@@ -61,14 +65,39 @@   main-is:          Main.hs   default-language: GHC2021   build-depends:-      base       >= 4.18 && < 4.23-    , polytropos-core+      base       >= 4.18 && < 4.24+    , ghc-internal+    , polytropos-core >= 0.1.2.0 && < 0.2     , primitive     , tasty         >= 1.4  && < 1.6     , tasty-hunit   >= 0.10 && < 0.11-    , polytropos-plugin+    , polytropos-plugin >= 0.1.2.0 && < 0.2     , process     , directory+    , bytestring    ghc-options:       -fplugin=Polytropos.Plugin+      -- -dcore-lint++benchmark polytropos-bench+  import:           warnings+  type:             exitcode-stdio-1.0+  hs-source-dirs:   bench+  main-is:          Main.hs+  default-language: GHC2021+  ghc-options:+      -Wall+      -Wcompat+      -O2+      -rtsopts+      "-with-rtsopts=-T"+      -fplugin=Polytropos.Plugin+  build-depends:+      base              >= 4.18 && < 4.24+    , containers        >= 0.6  && < 0.9+    , deepseq           >= 1.4  && < 1.6+    , text              >= 2.0  && < 2.2+    , polytropos-core   >= 0.1.2.0 && < 0.2+    , polytropos-plugin >= 0.1.2.0 && < 0.2+    , tasty-bench       >= 0.3.5 && < 0.6
src/Polytropos/Plugin.hs view
@@ -131,7 +131,6 @@   , mkCoreConApps   , mkCoreLams   , mkCharExpr-  , mkStringExpr   , mkIfThenElse   , mkListExpr   )@@ -143,6 +142,9 @@   , CoreExpr   , Expr(..)   , Type+#if __GLASGOW_HASKELL__ >= 1001+  , mkDataOcc+#endif   , mkTcOcc   , nameOccName   , mkTyConTy@@ -159,6 +161,7 @@   , wordTyCon   , Var(..)   , varType+  , charTy   , intTy   , stringTy   , mkVarOcc@@ -202,7 +205,11 @@   ( eqType   ) +#if __GLASGOW_HASKELL__ >= 1001+import GHC.Builtin.WiredIn.Types+#else import GHC.Builtin.Types+#endif   ( trueDataCon   , falseDataCon   , maybeTyCon@@ -222,6 +229,12 @@   ( Boxity(..)   ) +#if __GLASGOW_HASKELL__ >= 1001+import GHC.Builtin.Modules+  ( gHC_CLASSES+  , gHC_INTERNAL_TYPEERROR+  )+#else import GHC.Builtin.Names   ( gHC_CLASSES   , eqClassName@@ -230,6 +243,7 @@   , typeErrorTextDataConName   , typeErrorVAppendDataConName   )+#endif  import Polytropos.Plugin.Compat   ( modBase@@ -285,8 +299,22 @@  import Polytropos.Plugin.Source   ( sourcePlugin+#if __GLASGOW_HASKELL__ >= 1001+  , sourceStmtPlugin+  , sourceDeclsPlugin+#endif   ) +import Polytropos.MergeMorph+  ( MergeOp (..)+  )++import Polytropos.Plugin.MergeMorph+  ( MergeEvalResult (..)+  , RowEntry (..)+  , evalMergeOp+  )+ {- ================================================================================                                 GHC NOTES ARCHITECTURE@@ -627,6 +655,10 @@ plugin = defaultPlugin   { tcPlugin           = const $ Just $ mkTcPlugin polytroposPlugin   , parsedResultAction = \opts _modSummary -> sourcePlugin opts+#if __GLASGOW_HASKELL__ >= 1001+  , parsedStmtAction   = sourceStmtPlugin+  , parsedDeclsAction  = sourceDeclsPlugin+#endif   }  polytroposPlugin :: TcPlugin@@ -674,6 +706,7 @@   , psPromotedVcat          :: !TyCon -- ^ promoted ':$$:   , psUnsafeMkRowMorph      :: !Var   -- ^ Polytropos.RowMorph.unsafeMkRowMorph   , psUnsafeMkFrame         :: !Var   -- ^ Polytropos.RowMorph.unsafeMkFramePlan+  , psUnsafeMkMergeMorph    :: !Var   -- ^ Polytropos.MergeMorph.unsafeMkMergeMorph   , psPairTyCon             :: !TyCon -- ^ Polytropos.Core.Pair   , psPromotedPair          :: !TyCon -- ^ promoted '(:=)   }@@ -702,10 +735,15 @@   psShowChar      <- lookupIdInModule modShow "showChar"   psFShowInt      <- lookupIdInModule modShow "$fShowInt"   psFShowBool     <- lookupIdInModule modShow "$fShowBool"-+#if __GLASGOW_HASKELL__ >= 1001+  eqName        <- lookupOrig gHC_CLASSES            (mkTcOcc   "Eq")+  showName      <- lookupOrig modShow                (mkTcOcc   "Show")+  psEqCls       <- tcLookupClass eqName+  psShowCls     <- tcLookupClass showName+#else   psEqCls   <- tcLookupClass eqClassName   psShowCls <- tcLookupClass showClassName-+#endif   psComp <- lookupIdInModule modBase "."    rowFlavourName <- lookupOrig coreMod (mkTcOcc "RowFlavour")@@ -728,11 +766,18 @@    fieldNamesOcc <- lookupOrig coreMod (mkTcOcc "FieldNames")   psFieldNamesTyCon <- tcLookupTyCon fieldNamesOcc-+#if __GLASGOW_HASKELL__ >= 1001+  teFamName        <- lookupOrig gHC_INTERNAL_TYPEERROR (mkTcOcc   "TypeError")+  textDcName       <- lookupOrig gHC_INTERNAL_TYPEERROR (mkDataOcc "Text")+  vcatDcName       <- lookupOrig gHC_INTERNAL_TYPEERROR (mkDataOcc ":$$:")+  psTypeErrorTyCon <- tcLookupTyCon   teFamName+  textDataCon      <- tcLookupDataCon textDcName+  vcatDataCon      <- tcLookupDataCon vcatDcName+#else   psTypeErrorTyCon <- tcLookupTyCon errorMessageTypeErrorFamName   textDataCon      <- tcLookupDataCon typeErrorTextDataConName   vcatDataCon      <- tcLookupDataCon typeErrorVAppendDataConName-+#endif   let psPromotedText = promoteDataCon textDataCon       psPromotedVcat = promoteDataCon vcatDataCon @@ -746,6 +791,9 @@   psUnsafeMkRowMorph <- lookupIdInModule rowMorphMod "unsafeMkRowMorph"   psUnsafeMkFrame    <- lookupIdInModule rowMorphMod "unsafeMkFramePlan" +  mergeMorphMod <- findModule "Polytropos.MergeMorph" (Just "polytropos-core")+  psUnsafeMkMergeMorph <- lookupIdInModule mergeMorphMod "unsafeMkMergeMorph"+   pure PluginState{..}  findModule :: String -> Maybe String -> TcPluginM 'Init Module@@ -770,7 +818,7 @@ -- Type family rewriting (FieldNames, SimpleFieldTypes, FieldTypes) ------------------------------------------------------------------------------- --- | Type family rewriter for FieldNames, SimpleFieldTypes, and FieldTypes.+-- Type family rewriter for FieldNames, SimpleFieldTypes, and FieldTypes. -- Evaluates closed row reflection queries in O(1) during GHC's type rewriting stage. -- See Note [Type-Level Metadata Rewriting and Defunctionalization] [ref:note-metadata-rewriting] -- See Note [Row Type Anatomy: Open vs Closed Rows and Fixed vs Unfixed Tails] [ref:note-row-anatomy]@@ -781,7 +829,7 @@   , (psFieldNamesTyCon state, rewriteFieldNames (psFieldNamesTyCon state))   ] --- | Extracts fields from a row type. Fails (returns Nothing) if the tail is unfixed or open.+-- Extracts fields from a row type. Fails (returns Nothing) if the tail is unfixed or open. -- See Note [Row Type Anatomy: Open vs Closed Rows and Fixed vs Unfixed Tails] [ref:note-row-anatomy] -- See Note [OCaml Subtype/Unify Correlation and Row Tail Algebra] [ref:note-ocaml-row-algebra] walkRowFields_maybe :: Type -> Maybe [(FastString, Type)]@@ -858,7 +906,7 @@ -- See Note [Diagnostic Recovery and Cascading Error Prevention] [ref:note-diagnostic-prevention] ------------------------------------------------------------------------------- --- | Computes the Levenshtein edit distance between two strings using dynamic+-- Computes the Levenshtein edit distance between two strings using dynamic -- programming. Used to rank fuzzy typo suggestions when a requested field or -- constructor label is not found in a closed row. --@@ -889,7 +937,7 @@        [] -> 0        res -> last res --- | Filters and ranks candidate field/constructor names against a target typo.+-- Filters and ranks candidate field/constructor names against a target typo. -- -- Policy: -- - Candidates with edit distance <= 2 are retained. Distance 2 is the empirical@@ -902,7 +950,7 @@   let scored = [ (c, d) | c <- candidates, let d = levenshtein target c, d <= 2 ]   in map fst (sortOn snd scored) --- | Formats a product row's schema for display in compiler diagnostics:+-- Formats a product row's schema for display in compiler diagnostics: -- "{ field1 :: Type1, field2 :: Type2, ... }" -- -- Unrolls GHC Core Types to human-readable strings via 'ppr' and 'showSDocUnsafe'.@@ -914,7 +962,7 @@       | nullFS n  = showSDocUnsafe (ppr ty)       | otherwise = unpackFS n ++ " :: " ++ showSDocUnsafe (ppr ty) --- | Formats a sum row's schema for display in compiler diagnostics:+-- Formats a sum row's schema for display in compiler diagnostics: -- "< Con1 RecordPayload | Con2 TypePayload | Con3 >" -- -- Handles empty constructors, single-field bare constructors, and multi-field@@ -931,7 +979,7 @@             [(_, fn, ty)] | nullFS fn -> unpackFS n ++ " :: " ++ showSDocUnsafe (ppr ty)             fs -> unpackFS n ++ " " ++ formatRecordRow fs --- | Formats a field suggestion clause:+-- Formats a field suggestion clause: -- - If close matches exist: "Did you mean: 'name' or 'age'?" -- - If no close matches: lists all available fields in the record. -- - If the record is empty: reports "(no fields in record)".@@ -943,7 +991,7 @@       _  -> "Available fields: " ++ intercalate ", " (map (\c -> "'" ++ c ++ "'") candidates)     suggs -> "Did you mean: " ++ intercalate " or " (map (\s -> "'" ++ s ++ "'") suggs) ++ "?" --- | Formats a constructor suggestion clause for variants.+-- Formats a constructor suggestion clause for variants. formatCtorSuggestion :: String -> [String] -> String formatCtorSuggestion target candidates =   case suggestSimilar target candidates of@@ -952,22 +1000,22 @@       _  -> "Available constructors: " ++ intercalate ", " (map (\c -> "'" ++ c ++ "'") candidates)     suggs -> "Did you mean: " ++ intercalate " or " (map (\s -> "'" ++ s ++ "'") suggs) ++ "?" --- | Checks whether a Type contains no free type or coercion variables.+-- Checks whether a Type contains no free type or coercion variables. -- A closed type is fully grounded and ready for terminal diagnostic reporting. isClosedType :: Type -> Bool isClosedType ty = isEmptyVarSet (tyCoVarsOfType (unwrapSynonyms ty)) --- | Wraps a Haskell string into GHC's promoted 'Text constructor for type-level ErrorMessage.+-- Wraps a Haskell string into GHC's promoted 'Text constructor for type-level ErrorMessage. mkTextMsg :: PluginState -> String -> Type mkTextMsg state s = mkTyConApp (psPromotedText state) [mkStrLitTy (fsLit s)] --- | Combines multiple promoted 'Text messages vertically using ':$$: (promoted Vcat).+-- Combines multiple promoted 'Text messages vertically using ':$$: (promoted Vcat). mkVcatMsgs :: PluginState -> [Type] -> Type mkVcatMsgs _ [] = error "mkVcatMsgs: empty list" mkVcatMsgs _ [m] = m mkVcatMsgs state (m : ms) = mkTyConApp (psPromotedVcat state) [m, mkVcatMsgs state ms] --- | Synthesizes a new wanted GHC 'TypeError' constraint from a list of diagnostic strings.+-- Synthesizes a new wanted GHC 'TypeError' constraint from a list of diagnostic strings. -- -- Mechanics: -- 1. Promotes each string into an 'ErrorMessage ('Text ...)'.@@ -986,7 +1034,7 @@   ev <- newWanted loc predTy   pure (mkNonCanonical ev) --- | Synthesizes a dummy dictionary for GHC.Records.HasField that produces a safe bottom+-- Synthesizes a dummy dictionary for GHC.Records.HasField that produces a safe bottom -- value at runtime via 'noInlineUnsafeCo ()'. -- -- Why dummy dictionaries are necessary:@@ -1025,7 +1073,7 @@ -- Constraint solving ------------------------------------------------------------------------------- --- | Top-level constraint solver entry point for @Polytropos.Plugin@.+-- Top-level constraint solver entry point for @Polytropos.Plugin@. -- -- Invoked by GHC during constraint simplification with 'givens' and 'wanteds'. -- See Note [Solving Pipeline: Wanteds, Givens, and Staged Evidence Synthesis] [ref:note-solving-pipeline]@@ -1088,6 +1136,8 @@             -> solveKnownRowMorph state ct cls tys             | nameOccName name == mkTcOcc "FrameWire"             -> solveFrameWire state ct cls tys+            | nameOccName name == mkTcOcc "KnownMergeMorph"+            -> solveKnownMergeMorph state ct cls tys             | nameOccName name == mkTcOcc "IsLabel"             -> pure $ Right ()             | otherwise@@ -1101,7 +1151,7 @@ -- FieldIndex solver ------------------------------------------------------------------------------- --- | Solves the 'FieldIndex' constraint by statically locating the field's 0-based+-- Solves the 'FieldIndex' constraint by statically locating the field's 0-based -- offset in the row and returning literal Int evidence. -- -- See Note [Literal Evidence Synthesis vs Type-Level Search] [ref:note-literal-evidence]@@ -1234,7 +1284,7 @@ -- ConstructorIndex solver ------------------------------------------------------------------------------- --- | Solves the 'ConstructorIndex' constraint by statically locating the constructor's+-- Solves the 'ConstructorIndex' constraint by statically locating the constructor's -- 0-based tag in the sum row and returning literal Word evidence. -- -- See Note [Literal Evidence Synthesis vs Type-Level Search] [ref:note-literal-evidence]@@ -1314,7 +1364,7 @@ -- RowEq solver ------------------------------------------------------------------------------- --- | Solves the 'RowEq' constraint by synthesizing an unrolled comparison expression over all fields.+-- Solves the 'RowEq' constraint by synthesizing an unrolled comparison expression over all fields. -- -- See Note [Literal Evidence Synthesis vs Type-Level Search] [ref:note-literal-evidence] -- See Note [Row Type Anatomy: Open vs Closed Rows and Fixed vs Unfixed Tails] [ref:note-row-anatomy]@@ -1344,85 +1394,85 @@   -> Class   -> [Type]   -> TcPluginM 'Solve (Either ((EvTerm, Ct), [Ct]) ())-solveRowEq state ct cls tys = do-  let rowTy  = last tys-      rTy    = tys !! (length tys - 2)-      fields = walkRowWithTypes rowTy-      loc    = ctLoc ct--      -- Superclass evidence for RowFlavour r-      scEvidence = evDataConApp (classDataCon (psRowFlavourCls state)) [rTy] []+solveRowEq state ct cls tys+  | rowTy : rTy : _ <- reverse tys+  , Just fields <- walkRowWithTypes_maybe rowTy+  , let loc = ctLoc ct+  = do+           -- Superclass evidence for RowFlavour r+       let scEvidence = evDataConApp (classDataCon (psRowFlavourCls state)) [rTy] [] -      -- Extract repEq method type and bind lambda arguments: \r1 r2 -> ...-      repEqId = case classMethods cls of-        (m : _) -> m-        []      -> error "Polytropos.Plugin: RowEq class has no methods"-      methodFullTy = piResultTys (varType repEqId) tys-      (_, _, methodInDictTy) = splitFunTy methodFullTy-      (tyVars, tauTy) = splitForAllTyCoVars methodInDictTy-      (argTys, _) = splitFunTys tauTy-      scaledR1Ty = argTys !! 0-      scaledR2Ty = argTys !! 1+           -- Extract repEq method type and bind lambda arguments: \r1 r2 -> ...+           repEqId = case classMethods cls of+             (m : _) -> m+             []      -> error "Polytropos.Plugin: RowEq class has no methods"+           methodFullTy = piResultTys (varType repEqId) tys+           (_, _, methodInDictTy) = splitFunTy methodFullTy+           (tyVars, tauTy) = splitForAllTyCoVars methodInDictTy+           (argTys, _) = splitFunTys tauTy+           scaledR1Ty = argTys !! 0+           scaledR2Ty = argTys !! 1 -  r1Name <- unsafeLiftTcM $ newName (mkVarOcc "r1")-  r2Name <- unsafeLiftTcM $ newName (mkVarOcc "r2")-  let r1Var = mkLocalId r1Name (scaledMult scaledR1Ty) (scaledThing scaledR1Ty)-      r2Var = mkLocalId r2Name (scaledMult scaledR2Ty) (scaledThing scaledR2Ty)+       r1Name <- unsafeLiftTcM $ newName (mkVarOcc "r1")+       r2Name <- unsafeLiftTcM $ newName (mkVarOcc "r2")+       let r1Var = mkLocalId r1Name (scaledMult scaledR1Ty) (scaledThing scaledR1Ty)+           r2Var = mkLocalId r2Name (scaledMult scaledR2Ty) (scaledThing scaledR2Ty) -      kATy   = mkTyVarTy (tyVars !! 0)-      fTy    = mkTyVarTy (tyVars !! 1)-      aTy    = mkTyVarTy (tyVars !! 2)-      kRowTy = typeKind rowTy+           kATy   = mkTyVarTy (tyVars !! 0)+           fTy    = mkTyVarTy (tyVars !! 1)+           aTy    = mkTyVarTy (tyVars !! 2)+           kRowTy = typeKind rowTy -      -- Unpack RowRep wrappers: unRowRep r1, unRowRep r2-      unRowRepTypeArgs = [Type kRowTy, Type kATy, Type fTy, Type rTy, Type rowTy, Type aTy]-      rep1 = mkCoreApps (Var (psUnRowRep state)) (unRowRepTypeArgs ++ [Var r1Var])-      rep2 = mkCoreApps (Var (psUnRowRep state)) (unRowRepTypeArgs ++ [Var r2Var])+           -- Unpack RowRep wrappers: unRowRep r1, unRowRep r2+           unRowRepTypeArgs = [Type kRowTy, Type kATy, Type fTy, Type rTy, Type rowTy, Type aTy]+           rep1 = mkCoreApps (Var (psUnRowRep state)) (unRowRepTypeArgs ++ [Var r1Var])+           rep2 = mkCoreApps (Var (psUnRowRep state)) (unRowRepTypeArgs ++ [Var r2Var]) -      -- Structural header checks: repTag and repArity-      repTypeArgs = [Type kATy, Type fTy, Type aTy]-      tag1 = mkCoreApps (Var (psRepTag state)) (repTypeArgs ++ [rep1])-      tag2 = mkCoreApps (Var (psRepTag state)) (repTypeArgs ++ [rep2])-      eqTag = mkCoreApps (Var (psEqClass state)) [Type (mkTyConTy wordTyCon), Var (psFEqWord state), tag1, tag2]+           -- Structural header checks: repTag and repArity+           repTypeArgs = [Type kATy, Type fTy, Type aTy]+           tag1 = mkCoreApps (Var (psRepTag state)) (repTypeArgs ++ [rep1])+           tag2 = mkCoreApps (Var (psRepTag state)) (repTypeArgs ++ [rep2])+           eqTag = mkCoreApps (Var (psEqClass state)) [Type (mkTyConTy wordTyCon), Var (psFEqWord state), tag1, tag2] -      arity1 = mkCoreApps (Var (psRepArity state)) (repTypeArgs ++ [rep1])-      arity2 = mkCoreApps (Var (psRepArity state)) (repTypeArgs ++ [rep2])-      eqArity = mkCoreApps (Var (psEqClass state)) [Type intTy, Var (psFEqInt state), arity1, arity2]+           arity1 = mkCoreApps (Var (psRepArity state)) (repTypeArgs ++ [rep1])+           arity2 = mkCoreApps (Var (psRepArity state)) (repTypeArgs ++ [rep2])+           eqArity = mkCoreApps (Var (psEqClass state)) [Type intTy, Var (psFEqInt state), arity1, arity2] -  -- Spawn wanted Eq constraints for every field type in the row-  wanteds <- forM fields $ \(i, _nameFS, fieldTy) -> do-    ev <- newWanted loc (mkAppTy (mkTyConTy (classTyCon (psEqCls state))) fieldTy)-    pure (i, fieldTy, ev)+       -- Spawn wanted Eq constraints for every field type in the row+       wanteds <- forM fields $ \(i, _nameFS, fieldTy) -> do+         ev <- newWanted loc (mkAppTy (mkTyConTy (classTyCon (psEqCls state))) fieldTy)+         pure (i, fieldTy, ev) -  -- Synthesize comparison expression for slot i:-  -- (==) @fieldTy eqDict (noInlineUnsafeCo (fieldAt @i rep1)) (noInlineUnsafeCo (fieldAt @i rep2))-  let compareField (i, fieldTy, ev) =-        let fieldAtTypeArgs = [Type kATy, Type fTy, Type aTy, Type fieldTy]-            idxExpr = mkIntExpr i-            raw1 = mkCoreApps (Var (psFieldAt state)) (fieldAtTypeArgs ++ [idxExpr, rep1])-            raw2 = mkCoreApps (Var (psFieldAt state)) (fieldAtTypeArgs ++ [idxExpr, rep2])-            fFieldTy = mkAppTy fTy fieldTy-            val1 = mkCoreApps (Var (psNoInlineCo state)) [Type fFieldTy, Type fieldTy, raw1]-            val2 = mkCoreApps (Var (psNoInlineCo state)) [Type fFieldTy, Type fieldTy, raw2]-            eqDict = ctEvExpr ev-        in mkCoreApps (Var (psEqClass state)) [Type fieldTy, eqDict, val1, val2]+       -- Synthesize comparison expression for slot i:+       -- (==) @fieldTy eqDict (noInlineUnsafeCo (fieldAt @i rep1)) (noInlineUnsafeCo (fieldAt @i rep2))+       let compareField (i, fieldTy, ev) =+             let fieldAtTypeArgs = [Type kATy, Type fTy, Type aTy, Type fieldTy]+                 idxExpr = mkIntExpr i+                 raw1 = mkCoreApps (Var (psFieldAt state)) (fieldAtTypeArgs ++ [idxExpr, rep1])+                 raw2 = mkCoreApps (Var (psFieldAt state)) (fieldAtTypeArgs ++ [idxExpr, rep2])+                 fFieldTy = mkAppTy fTy fieldTy+                 val1 = mkCoreApps (Var (psNoInlineCo state)) [Type fFieldTy, Type fieldTy, raw1]+                 val2 = mkCoreApps (Var (psNoInlineCo state)) [Type fFieldTy, Type fieldTy, raw2]+                 eqDict = ctEvExpr ev+             in mkCoreApps (Var (psEqClass state)) [Type fieldTy, eqDict, val1, val2] -      fieldComps = map compareField wanteds+           fieldComps = map compareField wanteds -      -- Fold all comparisons left-to-right with short-circuiting Boolean (&&)-      andFn e1 e2 = mkCoreApps (Var (psAnd state)) [e1, e2]-      bodyExpr = foldl andFn (andFn eqTag eqArity) fieldComps-      repEqExpr = mkCoreLams (tyVars ++ [r1Var, r2Var]) bodyExpr+           -- Fold all comparisons left-to-right with short-circuiting Boolean (&&)+           andFn e1 e2 = mkCoreApps (Var (psAnd state)) [e1, e2]+           bodyExpr = foldl andFn (andFn eqTag eqArity) fieldComps+           repEqExpr = mkCoreLams (tyVars ++ [r1Var, r2Var]) bodyExpr -      dictExpr = evDataConApp (classDataCon cls) tys [scEvidence, repEqExpr]-      newWanteds = [mkNonCanonical ev | (_, _, ev) <- wanteds]-  pure $ Left ((EvExpr dictExpr, ct), newWanteds)+           dictExpr = evDataConApp (classDataCon cls) tys [scEvidence, repEqExpr]+           newWanteds = [mkNonCanonical ev | (_, _, ev) <- wanteds]+       pure $ Left ((EvExpr dictExpr, ct), newWanteds)+  | otherwise = pure $ Right ()  ------------------------------------------------------------------------------- -- RowShow solver ------------------------------------------------------------------------------- --- | Solves the 'RowShow' constraint by synthesizing an unrolled showsPrec expression over all fields.+-- Solves the 'RowShow' constraint by synthesizing an unrolled showsPrec expression over all fields. -- -- See Note [Literal Evidence Synthesis vs Type-Level Search] [ref:note-literal-evidence] -- See Note [Row Type Anatomy: Open vs Closed Rows and Fixed vs Unfixed Tails] [ref:note-row-anatomy]@@ -1444,88 +1494,88 @@   -> Class   -> [Type]   -> TcPluginM 'Solve (Either ((EvTerm, Ct), [Ct]) ())-solveRowShow state ct cls tys = do-  let rowTy  = last tys-      rTy    = tys !! (length tys - 2)-      fields = walkRowWithTypes rowTy-      loc    = ctLoc ct--      -- Superclass evidence for RowFlavour r-      scEvidence = evDataConApp (classDataCon (psRowFlavourCls state)) [rTy] []+solveRowShow state ct cls tys+  | rowTy : rTy : _ <- reverse tys+  , Just fields <- walkRowWithTypes_maybe rowTy+  , let loc = ctLoc ct+  = do+           -- Superclass evidence for RowFlavour r+       let scEvidence = evDataConApp (classDataCon (psRowFlavourCls state)) [rTy] [] -      -- Extract repShowsPrec method type and bind lambda arguments: \p r -> ...-      repShowsPrecId = case classMethods cls of-        (m : _) -> m-        []      -> error "Polytropos.Plugin: RowShow class has no methods"-      methodFullTy = piResultTys (varType repShowsPrecId) tys-      (_, _, methodInDictTy) = splitFunTy methodFullTy-      (tyVars, tauTy) = splitForAllTyCoVars methodInDictTy-      (argTys, _) = splitFunTys tauTy-      scaledPrecTy = argTys !! 0-      scaledRTy    = argTys !! 1+           -- Extract repShowsPrec method type and bind lambda arguments: \p r -> ...+           repShowsPrecId = case classMethods cls of+             (m : _) -> m+             []      -> error "Polytropos.Plugin: RowShow class has no methods"+           methodFullTy = piResultTys (varType repShowsPrecId) tys+           (_, _, methodInDictTy) = splitFunTy methodFullTy+           (tyVars, tauTy) = splitForAllTyCoVars methodInDictTy+           (argTys, _) = splitFunTys tauTy+           scaledPrecTy = argTys !! 0+           scaledRTy    = argTys !! 1 -  precName <- unsafeLiftTcM $ newName (mkVarOcc "p")-  rName <- unsafeLiftTcM $ newName (mkVarOcc "r")-  let precVar = mkLocalId precName (scaledMult scaledPrecTy) (scaledThing scaledPrecTy)-      rVar    = mkLocalId rName (scaledMult scaledRTy) (scaledThing scaledRTy)+       precName <- unsafeLiftTcM $ newName (mkVarOcc "p")+       rName <- unsafeLiftTcM $ newName (mkVarOcc "r")+       let precVar = mkLocalId precName (scaledMult scaledPrecTy) (scaledThing scaledPrecTy)+           rVar    = mkLocalId rName (scaledMult scaledRTy) (scaledThing scaledRTy) -      kATy   = mkTyVarTy (tyVars !! 0)-      fTy    = mkTyVarTy (tyVars !! 1)-      aTy    = mkTyVarTy (tyVars !! 2)-      kRowTy = typeKind rowTy+           kATy   = mkTyVarTy (tyVars !! 0)+           fTy    = mkTyVarTy (tyVars !! 1)+           aTy    = mkTyVarTy (tyVars !! 2)+           kRowTy = typeKind rowTy -      -- Unpack RowRep wrapper: unRowRep r-      unRowRepTypeArgs = [Type kRowTy, Type kATy, Type fTy, Type rTy, Type rowTy, Type aTy]-      rep = mkCoreApps (Var (psUnRowRep state)) (unRowRepTypeArgs ++ [Var rVar])+           -- Unpack RowRep wrapper: unRowRep r+           unRowRepTypeArgs = [Type kRowTy, Type kATy, Type fTy, Type rTy, Type rowTy, Type aTy]+           rep = mkCoreApps (Var (psUnRowRep state)) (unRowRepTypeArgs ++ [Var rVar]) -      -- Determine record display prefix-      rowName = case splitTyConApp_maybe rowTy of-        Just (tc, _)-          | let name = occNameString (getOccName tc)-          , name /= ":" && name /= "[]" && name /= "''[]"-          -> name-        _ -> "R" ++ show (length fields)+           -- Determine record display prefix+           rowName = case splitTyConApp_maybe rowTy of+             Just (tc, _)+               | let name = occNameString (getOccName tc)+               , name /= ":" && name /= "[]" && name /= "''[]"+               -> name+             _ -> "R" ++ show (length fields) -  prefixExpr <- unsafeLiftTcM $ mkStringExpr (rowName ++ " ")-  let prefixShowS = mkCoreApps (Var (psShowString state)) [prefixExpr]-      spaceShowS  = mkCoreApps (Var (psShowChar state)) [mkCharExpr ' ']+       let prefixExpr  = mkCoreStringExpr (rowName ++ " ")+           prefixShowS = mkCoreApps (Var (psShowString state)) [prefixExpr]+           spaceShowS  = mkCoreApps (Var (psShowChar state)) [mkCharExpr ' '] -  -- Spawn wanted Show constraints for every field type in the row-  wanteds <- forM fields $ \(i, _nameFS, fieldTy) -> do-    ev <- newWanted loc (mkAppTy (mkTyConTy (classTyCon (psShowCls state))) fieldTy)-    pure (i, fieldTy, ev)+       -- Spawn wanted Show constraints for every field type in the row+       wanteds <- forM fields $ \(i, _nameFS, fieldTy) -> do+         ev <- newWanted loc (mkAppTy (mkTyConTy (classTyCon (psShowCls state))) fieldTy)+         pure (i, fieldTy, ev) -  -- Synthesize ShowS expression for slot i:-  -- showsPrec @fieldTy showDict 0 (noInlineUnsafeCo (fieldAt @i rep))-  let showField (i, fieldTy, ev) =-        let fieldAtTypeArgs = [Type kATy, Type fTy, Type aTy, Type fieldTy]-            idxExpr = mkIntExpr i-            raw = mkCoreApps (Var (psFieldAt state)) (fieldAtTypeArgs ++ [idxExpr, rep])-            fFieldTy = mkAppTy fTy fieldTy-            val = mkCoreApps (Var (psNoInlineCo state)) [Type fFieldTy, Type fieldTy, raw]-            showDict = ctEvExpr ev-            zeroPrec = mkIntExpr 0-        in mkCoreApps (Var (psShowsPrecMeth state)) [Type fieldTy, showDict, zeroPrec, val]+       -- Synthesize ShowS expression for slot i:+       -- showsPrec @fieldTy showDict 0 (noInlineUnsafeCo (fieldAt @i rep))+       let showField (i, fieldTy, ev) =+             let fieldAtTypeArgs = [Type kATy, Type fTy, Type aTy, Type fieldTy]+                 idxExpr = mkIntExpr i+                 raw = mkCoreApps (Var (psFieldAt state)) (fieldAtTypeArgs ++ [idxExpr, rep])+                 fFieldTy = mkAppTy fTy fieldTy+                 val = mkCoreApps (Var (psNoInlineCo state)) [Type fFieldTy, Type fieldTy, raw]+                 showDict = ctEvExpr ev+                 zeroPrec = mkIntExpr 0+             in mkCoreApps (Var (psShowsPrecMeth state)) [Type fieldTy, showDict, zeroPrec, val] -      fieldShows = map showField wanteds-      showParts = case fieldShows of-        [] -> [prefixShowS]-        (f0 : fs) -> prefixShowS : f0 : concatMap (\f -> [spaceShowS, f]) fs+           fieldShows = map showField wanteds+           showParts = case fieldShows of+             [] -> [prefixShowS]+             (f0 : fs) -> prefixShowS : f0 : concatMap (\f -> [spaceShowS, f]) fs -      -- Chain all ShowS functions via (.) function composition-      compFn f g = mkCoreApps (Var (psComp state)) [Type stringTy, Type stringTy, Type stringTy, f, g]-      bodyExpr = foldr1 compFn showParts-      repShowsPrecExpr = mkCoreLams (tyVars ++ [precVar, rVar]) bodyExpr+           -- Chain all ShowS functions via (.) function composition+           compFn f g = mkCoreApps (Var (psComp state)) [Type stringTy, Type stringTy, Type stringTy, f, g]+           bodyExpr = foldr1 compFn showParts+           repShowsPrecExpr = mkCoreLams (tyVars ++ [precVar, rVar]) bodyExpr -      dictExpr = evDataConApp (classDataCon cls) tys [scEvidence, repShowsPrecExpr]-      newWanteds = [mkNonCanonical ev | (_, _, ev) <- wanteds]-  pure $ Left ((EvExpr dictExpr, ct), newWanteds)+           dictExpr = evDataConApp (classDataCon cls) tys [scEvidence, repShowsPrecExpr]+           newWanteds = [mkNonCanonical ev | (_, _, ev) <- wanteds]+       pure $ Left ((EvExpr dictExpr, ct), newWanteds)+  | otherwise = pure $ Right ()  ------------------------------------------------------------------------------- -- RowEqSum / RowShowSum solvers ------------------------------------------------------------------------------- --- | Solves the 'RowEqSum' constraint by synthesizing constructor branch comparison Core trees.+-- Solves the 'RowEqSum' constraint by synthesizing constructor branch comparison Core trees. -- -- See Note [Literal Evidence Synthesis vs Type-Level Search] [ref:note-literal-evidence] -- See Note [Row Type Anatomy: Open vs Closed Rows and Fixed vs Unfixed Tails] [ref:note-row-anatomy]@@ -1549,92 +1599,94 @@   -> Class   -> [Type]   -> TcPluginM 'Solve (Either ((EvTerm, Ct), [Ct]) ())-solveRowEqSum state ct cls tys = do-  let rowTy  = last tys-      rTy    = tys !! (length tys - 2)-      constructors = walkSumRowWithTypes rowTy-      loc    = ctLoc ct--      -- Superclass evidence for RowFlavour r-      scEvidence = evDataConApp (classDataCon (psRowFlavourCls state)) [rTy] []+solveRowEqSum state ct cls tys+  | rowTy : rTy : _ <- reverse tys+  , Just constructors    <- walkSumRowWithTypes_maybe rowTy+  , Just ctorSchemas+      <- forM constructors \(i, nm, conRowTy) ->+                              (i, nm,) <$> walkRowWithTypes_maybe conRowTy+  , let loc          = ctLoc ct+  = do+           -- Superclass evidence for RowFlavour r+       let scEvidence = evDataConApp (classDataCon (psRowFlavourCls state)) [rTy] [] -      -- Extract repEqSum method type and bind lambda arguments: \r1 r2 -> ...-      repEqSumId = case classMethods cls of-        (m : _) -> m-        []      -> error "Polytropos.Plugin: RowEqSum class has no methods"-      methodFullTy = piResultTys (varType repEqSumId) tys-      (_, _, methodInDictTy) = splitFunTy methodFullTy-      (tyVars, tauTy) = splitForAllTyCoVars methodInDictTy-      (argTys, _) = splitFunTys tauTy-      scaledR1Ty = argTys !! 0-      scaledR2Ty = argTys !! 1+           -- Extract repEqSum method type and bind lambda arguments: \r1 r2 -> ...+           repEqSumId = case classMethods cls of+             (m : _) -> m+             []      -> error "Polytropos.Plugin: RowEqSum class has no methods"+           methodFullTy = piResultTys (varType repEqSumId) tys+           (_, _, methodInDictTy) = splitFunTy methodFullTy+           (tyVars, tauTy) = splitForAllTyCoVars methodInDictTy+           (argTys, _) = splitFunTys tauTy+           scaledR1Ty = argTys !! 0+           scaledR2Ty = argTys !! 1 -  r1Name <- unsafeLiftTcM $ newName (mkVarOcc "r1")-  r2Name <- unsafeLiftTcM $ newName (mkVarOcc "r2")-  let r1Var = mkLocalId r1Name (scaledMult scaledR1Ty) (scaledThing scaledR1Ty)-      r2Var = mkLocalId r2Name (scaledMult scaledR2Ty) (scaledThing scaledR2Ty)+       r1Name <- unsafeLiftTcM $ newName (mkVarOcc "r1")+       r2Name <- unsafeLiftTcM $ newName (mkVarOcc "r2")+       let r1Var = mkLocalId r1Name (scaledMult scaledR1Ty) (scaledThing scaledR1Ty)+           r2Var = mkLocalId r2Name (scaledMult scaledR2Ty) (scaledThing scaledR2Ty) -      kATy   = mkTyVarTy (tyVars !! 0)-      fTy    = mkTyVarTy (tyVars !! 1)-      aTy    = mkTyVarTy (tyVars !! 2)-      kRowTy = typeKind rowTy+           kATy   = mkTyVarTy (tyVars !! 0)+           fTy    = mkTyVarTy (tyVars !! 1)+           aTy    = mkTyVarTy (tyVars !! 2)+           kRowTy = typeKind rowTy -      -- Unpack RowRep wrappers: unRowRep r1, unRowRep r2-      unRowRepTypeArgs = [Type kRowTy, Type kATy, Type fTy, Type rTy, Type rowTy, Type aTy]-      rep1 = mkCoreApps (Var (psUnRowRep state)) (unRowRepTypeArgs ++ [Var r1Var])-      rep2 = mkCoreApps (Var (psUnRowRep state)) (unRowRepTypeArgs ++ [Var r2Var])+           -- Unpack RowRep wrappers: unRowRep r1, unRowRep r2+           unRowRepTypeArgs = [Type kRowTy, Type kATy, Type fTy, Type rTy, Type rowTy, Type aTy]+           rep1 = mkCoreApps (Var (psUnRowRep state)) (unRowRepTypeArgs ++ [Var r1Var])+           rep2 = mkCoreApps (Var (psUnRowRep state)) (unRowRepTypeArgs ++ [Var r2Var]) -      -- Extract and compare constructor tags: repTag rep1 == repTag rep2-      repTypeArgs = [Type kATy, Type fTy, Type aTy]-      tag1 = mkCoreApps (Var (psRepTag state)) (repTypeArgs ++ [rep1])-      tag2 = mkCoreApps (Var (psRepTag state)) (repTypeArgs ++ [rep2])-      eqTag = mkCoreApps (Var (psEqClass state)) [Type (mkTyConTy wordTyCon), Var (psFEqWord state), tag1, tag2]+           -- Extract and compare constructor tags: repTag rep1 == repTag rep2+           repTypeArgs = [Type kATy, Type fTy, Type aTy]+           tag1 = mkCoreApps (Var (psRepTag state)) (repTypeArgs ++ [rep1])+           tag2 = mkCoreApps (Var (psRepTag state)) (repTypeArgs ++ [rep2])+           eqTag = mkCoreApps (Var (psEqClass state)) [Type (mkTyConTy wordTyCon), Var (psFEqWord state), tag1, tag2] -      falseExpr = mkCoreConApps falseDataCon []-      trueExpr  = mkCoreConApps trueDataCon []-      andFn e1 e2 = mkCoreApps (Var (psAnd state)) [e1, e2]+           falseExpr = mkCoreConApps falseDataCon []+           trueExpr  = mkCoreConApps trueDataCon []+           andFn e1 e2 = mkCoreApps (Var (psAnd state)) [e1, e2] -  -- Spawn wanted Eq constraints for all fields of all constructors-  ctorWanteds <- forM constructors $ \(i, conName, conRowTy) -> do-    let fields = walkRowWithTypes conRowTy-    fWanteds <- forM fields $ \(fi, _nameFS, fieldTy) -> do-      ev <- newWanted loc (mkAppTy (mkTyConTy (classTyCon (psEqCls state))) fieldTy)-      pure (fi, fieldTy, ev)-    pure (i, conName, fWanteds)+       -- Spawn wanted Eq constraints for all fields of all constructors+       ctorWanteds <- forM ctorSchemas \(i, conName, fields) -> do+         fWanteds <- forM fields \(fi, _nameFS, fieldTy) -> do+           ev <- newWanted loc . flip mkAppTy fieldTy . mkTyConTy . classTyCon $ psEqCls state+           pure (fi, fieldTy, ev)+         pure (i, conName, fWanteds) -  -- Compare fields within an active constructor payload-  let compareConFields fWanteds =-        let fieldComps = [ compareField fi fieldTy ev | (fi, fieldTy, ev) <- fWanteds ]-        in foldl andFn trueExpr fieldComps+       -- Compare fields within an active constructor payload+       let compareConFields fWanteds =+             let fieldComps = [ compareField fi fieldTy ev | (fi, fieldTy, ev) <- fWanteds ]+             in foldl andFn trueExpr fieldComps -      compareField fi fieldTy ev =-        let fieldAtTypeArgs = [Type kATy, Type fTy, Type aTy, Type fieldTy]-            idxExpr = mkIntExpr fi-            raw1 = mkCoreApps (Var (psFieldAt state)) (fieldAtTypeArgs ++ [idxExpr, rep1])-            raw2 = mkCoreApps (Var (psFieldAt state)) (fieldAtTypeArgs ++ [idxExpr, rep2])-            fFieldTy = mkAppTy fTy fieldTy-            val1 = mkCoreApps (Var (psNoInlineCo state)) [Type fFieldTy, Type fieldTy, raw1]-            val2 = mkCoreApps (Var (psNoInlineCo state)) [Type fFieldTy, Type fieldTy, raw2]-            eqDict = ctEvExpr ev-        in mkCoreApps (Var (psEqClass state)) [Type fieldTy, eqDict, val1, val2]+           compareField fi fieldTy ev =+             let fieldAtTypeArgs = [Type kATy, Type fTy, Type aTy, Type fieldTy]+                 idxExpr = mkIntExpr fi+                 raw1 = mkCoreApps (Var (psFieldAt state)) (fieldAtTypeArgs ++ [idxExpr, rep1])+                 raw2 = mkCoreApps (Var (psFieldAt state)) (fieldAtTypeArgs ++ [idxExpr, rep2])+                 fFieldTy = mkAppTy fTy fieldTy+                 val1 = mkCoreApps (Var (psNoInlineCo state)) [Type fFieldTy, Type fieldTy, raw1]+                 val2 = mkCoreApps (Var (psNoInlineCo state)) [Type fFieldTy, Type fieldTy, raw2]+                 eqDict = ctEvExpr ev+             in mkCoreApps (Var (psEqClass state)) [Type fieldTy, eqDict, val1, val2] -      -- Synthesize recursive branch test: if tag == i then compareConFields else buildTree (rest)-      buildTree _ [] = falseExpr-      buildTree tagExpr ((i, _conName, fWanteds) : rest) =-        let iLit = mkWordExpr (fromIntegral i)-            cond = mkCoreApps (Var (psEqClass state)) [Type (mkTyConTy wordTyCon), Var (psFEqWord state), tagExpr, iLit]-        in mkIfThenElse cond (compareConFields fWanteds) (buildTree tagExpr rest)+           -- Synthesize recursive branch test: if tag == i then compareConFields else buildTree (rest)+           buildTree _ [] = falseExpr+           buildTree tagExpr ((i, _conName, fWanteds) : rest) =+             let iLit = mkWordExpr (fromIntegral i)+                 cond = mkCoreApps (Var (psEqClass state)) [Type (mkTyConTy wordTyCon), Var (psFEqWord state), tagExpr, iLit]+             in mkIfThenElse cond (compareConFields fWanteds) (buildTree tagExpr rest) -      -- Top-level check: only inspect payload if constructor tags are equal-      bodyExpr = mkIfThenElse eqTag (buildTree tag1 ctorWanteds) falseExpr-      repEqSumExpr = mkCoreLams (tyVars ++ [r1Var, r2Var]) bodyExpr+           -- Top-level check: only inspect payload if constructor tags are equal+           bodyExpr = mkIfThenElse eqTag (buildTree tag1 ctorWanteds) falseExpr+           repEqSumExpr = mkCoreLams (tyVars ++ [r1Var, r2Var]) bodyExpr -      dictExpr = evDataConApp (classDataCon cls) tys [scEvidence, repEqSumExpr]-      allNewWanteds = [ mkNonCanonical ev | (_, _, fWanteds) <- ctorWanteds, (_, _, ev) <- fWanteds ]+           dictExpr = evDataConApp (classDataCon cls) tys [scEvidence, repEqSumExpr]+           allNewWanteds = [ mkNonCanonical ev | (_, _, fWanteds) <- ctorWanteds, (_, _, ev) <- fWanteds ] -  pure $ Left ((EvExpr dictExpr, ct), allNewWanteds)+       pure $ Left ((EvExpr dictExpr, ct), allNewWanteds)+  | otherwise = pure $ Right () --- | Solves the 'RowShowSum' constraint by synthesizing constructor branch showsPrec Core trees.+-- Solves the 'RowShowSum' constraint by synthesizing constructor branch showsPrec Core trees. -- -- See Note [Literal Evidence Synthesis vs Type-Level Search] [ref:note-literal-evidence] -- See Note [Row Type Anatomy: Open vs Closed Rows and Fixed vs Unfixed Tails] [ref:note-row-anatomy]@@ -1656,98 +1708,100 @@   -> Class   -> [Type]   -> TcPluginM 'Solve (Either ((EvTerm, Ct), [Ct]) ())-solveRowShowSum state ct cls tys = do-  let rowTy  = last tys-      rTy    = tys !! (length tys - 2)-      constructors = walkSumRowWithTypes rowTy-      loc    = ctLoc ct--      -- Superclass evidence for RowFlavour r-      scEvidence = evDataConApp (classDataCon (psRowFlavourCls state)) [rTy] []+solveRowShowSum state ct cls tys+  | rowTy : rTy : _ <- reverse tys+  , Just constructors <- walkSumRowWithTypes_maybe rowTy+  , Just ctorSchemas+      <- forM constructors \(i, nm, conRowTy) ->+                              (i, nm,) <$> walkRowWithTypes_maybe conRowTy+  , let loc          = ctLoc ct+  = do+           -- Superclass evidence for RowFlavour r+       let scEvidence = evDataConApp (classDataCon (psRowFlavourCls state)) [rTy] [] -      -- Extract repShowsPrecSum method type and bind lambda arguments: \p r -> ...-      repShowsPrecSumId = case classMethods cls of-        (m : _) -> m-        []      -> error "Polytropos.Plugin: RowShowSum class has no methods"-      methodFullTy = piResultTys (varType repShowsPrecSumId) tys-      (_, _, methodInDictTy) = splitFunTy methodFullTy-      (tyVars, tauTy) = splitForAllTyCoVars methodInDictTy-      (argTys, _) = splitFunTys tauTy-      scaledPrecTy = argTys !! 0-      scaledRTy    = argTys !! 1+           -- Extract repShowsPrecSum method type and bind lambda arguments: \p r -> ...+           repShowsPrecSumId = case classMethods cls of+             (m : _) -> m+             []      -> error "Polytropos.Plugin: RowShowSum class has no methods"+           methodFullTy = piResultTys (varType repShowsPrecSumId) tys+           (_, _, methodInDictTy) = splitFunTy methodFullTy+           (tyVars, tauTy) = splitForAllTyCoVars methodInDictTy+           (argTys, _) = splitFunTys tauTy+           scaledPrecTy = argTys !! 0+           scaledRTy    = argTys !! 1 -  precName <- unsafeLiftTcM $ newName (mkVarOcc "p")-  rName <- unsafeLiftTcM $ newName (mkVarOcc "r")-  let precVar = mkLocalId precName (scaledMult scaledPrecTy) (scaledThing scaledPrecTy)-      rVar    = mkLocalId rName (scaledMult scaledRTy) (scaledThing scaledRTy)+       precName <- unsafeLiftTcM $ newName (mkVarOcc "p")+       rName <- unsafeLiftTcM $ newName (mkVarOcc "r")+       let precVar = mkLocalId precName (scaledMult scaledPrecTy) (scaledThing scaledPrecTy)+           rVar    = mkLocalId rName (scaledMult scaledRTy) (scaledThing scaledRTy) -      kATy   = mkTyVarTy (tyVars !! 0)-      fTy    = mkTyVarTy (tyVars !! 1)-      aTy    = mkTyVarTy (tyVars !! 2)-      kRowTy = typeKind rowTy+           kATy   = mkTyVarTy (tyVars !! 0)+           fTy    = mkTyVarTy (tyVars !! 1)+           aTy    = mkTyVarTy (tyVars !! 2)+           kRowTy = typeKind rowTy -      -- Unpack RowRep wrapper: unRowRep r-      unRowRepTypeArgs = [Type kRowTy, Type kATy, Type fTy, Type rTy, Type rowTy, Type aTy]-      rep = mkCoreApps (Var (psUnRowRep state)) (unRowRepTypeArgs ++ [Var rVar])+           -- Unpack RowRep wrapper: unRowRep r+           unRowRepTypeArgs = [Type kRowTy, Type kATy, Type fTy, Type rTy, Type rowTy, Type aTy]+           rep = mkCoreApps (Var (psUnRowRep state)) (unRowRepTypeArgs ++ [Var rVar]) -      repTypeArgs = [Type kATy, Type fTy, Type aTy]-      tag = mkCoreApps (Var (psRepTag state)) (repTypeArgs ++ [rep])+           repTypeArgs = [Type kATy, Type fTy, Type aTy]+           tag = mkCoreApps (Var (psRepTag state)) (repTypeArgs ++ [rep]) -      spaceShowS  = mkCoreApps (Var (psShowChar state)) [mkCharExpr ' ']-      compFn f g = mkCoreApps (Var (psComp state)) [Type stringTy, Type stringTy, Type stringTy, f, g]+           spaceShowS  = mkCoreApps (Var (psShowChar state)) [mkCharExpr ' ']+           compFn f g = mkCoreApps (Var (psComp state)) [Type stringTy, Type stringTy, Type stringTy, f, g] -  -- Spawn wanted Show constraints for every field of every constructor-  ctorWanteds <- forM constructors $ \(i, conNameFS, conRowTy) -> do-    let fields = walkRowWithTypes conRowTy-    fWanteds <- forM fields $ \(fi, _nameFS, fieldTy) -> do-      ev <- newWanted loc (mkAppTy (mkTyConTy (classTyCon (psShowCls state))) fieldTy)-      pure (fi, fieldTy, ev)-    pure (i, conNameFS, fWanteds)+       -- Spawn wanted Show constraints for every field of every constructor+       ctorWanteds <- forM ctorSchemas \(i, conName, fields) -> do+         fWanteds <- forM fields \(fi, _nameFS, fieldTy) -> do+           ev <- newWanted loc . flip mkAppTy fieldTy . mkTyConTy . classTyCon $ psShowCls state+           pure (fi, fieldTy, ev)+         pure (i, conName, fWanteds) -  let showField fi fieldTy ev =-        let fieldAtTypeArgs = [Type kATy, Type fTy, Type aTy, Type fieldTy]-            idxExpr = mkIntExpr fi-            raw = mkCoreApps (Var (psFieldAt state)) (fieldAtTypeArgs ++ [idxExpr, rep])-            fFieldTy = mkAppTy fTy fieldTy-            val = mkCoreApps (Var (psNoInlineCo state)) [Type fFieldTy, Type fieldTy, raw]-            showDict = ctEvExpr ev-            zeroPrec = mkIntExpr 0-        in mkCoreApps (Var (psShowsPrecMeth state)) [Type fieldTy, showDict, zeroPrec, val]+       let showField fi fieldTy ev =+             let fieldAtTypeArgs = [Type kATy, Type fTy, Type aTy, Type fieldTy]+                 idxExpr = mkIntExpr fi+                 raw = mkCoreApps (Var (psFieldAt state)) (fieldAtTypeArgs ++ [idxExpr, rep])+                 fFieldTy = mkAppTy fTy fieldTy+                 val = mkCoreApps (Var (psNoInlineCo state)) [Type fFieldTy, Type fieldTy, raw]+                 showDict = ctEvExpr ev+                 zeroPrec = mkIntExpr 0+             in mkCoreApps (Var (psShowsPrecMeth state)) [Type fieldTy, showDict, zeroPrec, val] -      showConFields conNameFS fWanteds = do-        let conName = unpackFS conNameFS-        prefixExpr <- unsafeLiftTcM $ mkStringExpr (conName ++ " ")-        let prefixShowS = mkCoreApps (Var (psShowString state)) [prefixExpr]-            fieldShows = [ showField fi fieldTy ev | (fi, fieldTy, ev) <- fWanteds ]-            showParts = case fieldShows of-              [] -> [prefixShowS]-              (f0 : fs) -> prefixShowS : f0 : concatMap (\f -> [spaceShowS, f]) fs-        pure $ foldr1 compFn showParts+           showConFields conNameFS fWanteds = do+             let conName = unpackFS conNameFS+                 prefixExpr = mkCoreStringExpr (conName ++ " ")+                 prefixShowS = mkCoreApps (Var (psShowString state)) [prefixExpr]+                 fieldShows = [ showField fi fieldTy ev | (fi, fieldTy, ev) <- fWanteds ]+                 showParts = case fieldShows of+                   [] -> [prefixShowS]+                   (f0 : fs) -> prefixShowS : f0 : concatMap (\f -> [spaceShowS, f]) fs+             pure $ foldr1 compFn showParts -  -- Synthesize recursive branch dispatcher: if tag == i then showConFields else buildTree (rest)-  let buildTree _tagExpr [] = do-        errorPrefix <- unsafeLiftTcM $ mkStringExpr "??? "-        pure $ mkCoreApps (Var (psShowString state)) [errorPrefix]-      buildTree tagExpr ((i, conNameFS, fWanteds) : rest) = do-        let iLit = mkWordExpr (fromIntegral i)-            cond = mkCoreApps (Var (psEqClass state)) [Type (mkTyConTy wordTyCon), Var (psFEqWord state), tagExpr, iLit]-        trueBranch <- showConFields conNameFS fWanteds-        falseBranch <- buildTree tagExpr rest-        pure $ mkIfThenElse cond trueBranch falseBranch+       -- Synthesize recursive branch dispatcher: if tag == i then showConFields else buildTree (rest)+       let buildTree _tagExpr [] = do+             let errorPrefix = mkCoreStringExpr "??? "+             pure $ mkCoreApps (Var (psShowString state)) [errorPrefix]+           buildTree tagExpr ((i, conNameFS, fWanteds) : rest) = do+             let iLit = mkWordExpr (fromIntegral i)+                 cond = mkCoreApps (Var (psEqClass state)) [Type (mkTyConTy wordTyCon), Var (psFEqWord state), tagExpr, iLit]+             trueBranch <- showConFields conNameFS fWanteds+             falseBranch <- buildTree tagExpr rest+             pure $ mkIfThenElse cond trueBranch falseBranch -  bodyExpr <- buildTree tag ctorWanteds-  let repShowsPrecSumExpr = mkCoreLams (tyVars ++ [precVar, rVar]) bodyExpr+       bodyExpr <- buildTree tag ctorWanteds+       let repShowsPrecSumExpr = mkCoreLams (tyVars ++ [precVar, rVar]) bodyExpr -      dictExpr = evDataConApp (classDataCon cls) tys [scEvidence, repShowsPrecSumExpr]-      allNewWanteds = [ mkNonCanonical ev | (_, _, fWanteds) <- ctorWanteds, (_, _, ev) <- fWanteds ]+           dictExpr = evDataConApp (classDataCon cls) tys [scEvidence, repShowsPrecSumExpr]+           allNewWanteds = [ mkNonCanonical ev | (_, _, fWanteds) <- ctorWanteds, (_, _, ev) <- fWanteds ] -  pure $ Left ((EvExpr dictExpr, ct), allNewWanteds)+       pure $ Left ((EvExpr dictExpr, ct), allNewWanteds)+  | otherwise = pure $ Right ()  ------------------------------------------------------------------------------- -- HasField solver ------------------------------------------------------------------------------- --- | Solves GHC's 'HasField' class for records, enabling standard dot-syntax selection+-- Solves GHC's 'HasField' class for records, enabling standard dot-syntax selection -- (@rec.fieldName@) via literal slot offsets without runtime hash lookups. -- -- See Note [Literal Evidence Synthesis vs Type-Level Search] [ref:note-literal-evidence]@@ -1874,7 +1928,7 @@ -- AllFields solver (generic field-class dictionary supply) ------------------------------------------------------------------------------- --- | Solves 'AllFields' by synthesizing a flat array of type-erased 'DictAny' dictionaries.+-- Solves 'AllFields' by synthesizing a flat array of type-erased 'DictAny' dictionaries. -- -- See Note [Literal Evidence Synthesis vs Type-Level Search] [ref:note-literal-evidence] -- See Note [Row Type Anatomy: Open vs Closed Rows and Fixed vs Unfixed Tails] [ref:note-row-anatomy]@@ -1943,7 +1997,7 @@ -- See Note [Diagnostic Recovery and Cascading Error Prevention] [ref:note-diagnostic-prevention] ------------------------------------------------------------------------------- --- | Solves the 'SubRow sub super' constraint by synthesizing literal index projection lists.+-- Solves the 'SubRow sub super' constraint by synthesizing literal index projection lists. -- -- Intuition: -- A sub-record 'sub' can be projected out of a super-record 'super' if every field@@ -2043,7 +2097,7 @@ -- See Note [Diagnostic Recovery and Cascading Error Prevention] [ref:note-diagnostic-prevention] ------------------------------------------------------------------------------- --- | Solves the 'KnownRowMorph r1 r2' constraint by synthesizing an unboxed 'RowMorph'+-- Solves the 'KnownRowMorph r1 r2' constraint by synthesizing an unboxed 'RowMorph' -- permutation array directly into Core AST. -- -- Algorithmic Mechanics:@@ -2140,7 +2194,7 @@ -- See Note [Diagnostic Recovery and Cascading Error Prevention] [ref:note-diagnostic-prevention] ------------------------------------------------------------------------------- --- | Solves the 'FrameWire frameIn opIn opOut frameOut' constraint:+-- Solves the 'FrameWire frameIn opIn opOut frameOut' constraint: -- 1. Checks open-tail deferral on 'frameIn', 'opIn', and 'opOut'. -- 2. Verifies 'opIn' is a sub-row of 'frameIn', mapping gather indices and --    emitting nominal equality constraints for polymorphic port types.@@ -2276,8 +2330,105 @@                          ]               pure $ Left diag --- | Solves the 'SubSum sub super' constraint by synthesizing literal injection and narrowing arrays.+-------------------------------------------------------------------------------+-- KnownMergeMorph solver+-------------------------------------------------------------------------------++-- | Solves 'KnownMergeMorph (op :: MergeOp) (r1 :: Row) (r2 :: Row) (rOut :: Row)'. --+-- Algorithmic Mechanics:+-- 1. Evaluates promoted 'MergeOp' to determine the Skew Boolean operation.+-- 2. Walks 'r1' and 'r2' field lists via 'walkRowWithTypes_maybe'.+-- 3. If tails are unfixed, defers constraint until closed.+-- 4. Runs 'evalMergeOp' to compute gather indices and the synthesized output row.+-- 5. Synthesizes 'rOut' type-level row and emits an equality wanted constraint 'rOut ~ rOutSynth'.+-- 6. Emits Core call to 'unsafeMkMergeMorph' wrapped in the 'KnownMergeMorph' dictionary.+solveKnownMergeMorph+  :: PluginState+  -> Ct+  -> Class+  -> [Type]+  -> TcPluginM 'Solve (Either ((EvTerm, Ct), [Ct]) ())+solveKnownMergeMorph state ct cls tys+  | length tys >= 4+  , let opTy    = tys !! (length tys - 4)+        r1Ty    = tys !! (length tys - 3)+        r2Ty    = tys !! (length tys - 2)+        rOutTy  = last tys+        loc     = ctLoc ct+  , Just op     <- parseMergeOp opTy+  , Just r1List <- walkRowWithTypes_maybe r1Ty+  , Just r2List <- walkRowWithTypes_maybe r2Ty+  = do+      let r1Entries = [ RowEntry name ty slot | (slot, name, ty) <- r1List ]+          r2Entries = [ RowEntry name ty slot | (slot, name, ty) <- r2List ]+      case evalMergeOp op r1Entries r2Entries of+        MergeSuccess reIndexed gatherIdxs -> do+          let kTy = case reIndexed of+                (e : _) -> typeKind (entryType e)+                _       -> liftedTypeKind+              entryKind = mkTyConApp (psPairTyCon state) [typeSymbolKind, kTy]+              entries =+                [ mkTyConApp (psPromotedPair state)+                             [ typeSymbolKind+                             , typeKind (entryType e)+                             , mkStrLitTy (entryLabel e)+                             , entryType e+                             ]+                | e <- reIndexed+                ]+              synthOutTy = mkPromotedListTy entryKind entries++          outEqCts <- if rOutTy `eqType` synthOutTy+            then pure []+            else do+              outEqEv <- newWanted loc (mkEqPredRole Nominal rOutTy synthOutTy)+              pure [mkNonCanonical outEqEv]++          let gatherExpr = mkListExpr intTy (map mkIntExpr gatherIdxs)+              evExpr     = mkCoreApps (Var (psUnsafeMkMergeMorph state))+                            (map Type tys ++ [gatherExpr])+              dictExpr   = evDataConApp (classDataCon cls) tys [evExpr]++          pure $ Left ((EvExpr dictExpr, ct), outEqCts)++        MergeDisjointOverlap badLabel -> do+          let diag = [ "Polytropos MergeMorph Error:"+                     , "  Disjoint merge (<+>) failed: field '" ++ unpackFS badLabel ++ "' occurs in both records."+                     ]+              dummyExpr = mkCoreApps (Var (psUnsafeMkMergeMorph state))+                            (map Type tys ++ [mkListExpr intTy []])+              dummyDict = evDataConApp (classDataCon cls) tys [dummyExpr]+          errCt <- mkTypeErrorCt state loc diag+          pure $ Left ((EvExpr dummyDict, ct), [errCt])++        MergeReplaceMissing badLabel -> do+          let diag = [ "Polytropos MergeMorph Error:"+                     , "  Subset update (//~) failed: field '" ++ unpackFS badLabel ++ "' is missing in base record."+                     ]+              dummyExpr = mkCoreApps (Var (psUnsafeMkMergeMorph state))+                            (map Type tys ++ [mkListExpr intTy []])+              dummyDict = evDataConApp (classDataCon cls) tys [dummyExpr]+          errCt <- mkTypeErrorCt state loc diag+          pure $ Left ((EvExpr dummyDict, ct), [errCt])++  | otherwise = pure $ Right ()+  where+    parseMergeOp :: Type -> Maybe MergeOp+    parseMergeOp ty = case splitTyConApp_maybe (unwrapSynonyms ty) of+      Just (tc, []) -> case occNameString (getOccName tc) of+        "OpOverrideR" -> Just OpOverrideR+        "OpOverrideL" -> Just OpOverrideL+        "OpDisjoint"  -> Just OpDisjoint+        "OpReplace"   -> Just OpReplace+        "OpRestrict"  -> Just OpRestrict+        "OpDiff"      -> Just OpDiff+        "OpSymDiff"   -> Just OpSymDiff+        _             -> Nothing+      _ -> Nothing++-- Solves the 'SubSum sub super' constraint by synthesizing literal injection and narrowing arrays.+-- -- Intuition: -- A sub-variant 'sub' can be widened into a super-variant 'super' if every constructor -- declared in 'sub' also exists in 'super' with an identical payload schema.@@ -2397,7 +2548,7 @@ -- KnownHash solver ------------------------------------------------------------------------------- --- | FNV-1a 64-bit hash for a type-level label symbol.+-- FNV-1a 64-bit hash for a type-level label symbol. -- -- Algorithmic Details: -- - Uses the standard Fowler-Noll-Vo 64-bit non-cryptographic hash algorithm (FNV-1a).@@ -2413,7 +2564,7 @@   where     step !h !c = (h `xor` fromIntegral (ord c)) * 1099511628211 --- | Solves the 'KnownHash' constraint by computing the compile-time 64-bit FNV-1a hash+-- Solves the 'KnownHash' constraint by computing the compile-time 64-bit FNV-1a hash -- of a type-level Symbol and emitting literal Word evidence. -- -- See Note [Literal Evidence Synthesis vs Type-Level Search] [ref:note-literal-evidence]@@ -2449,7 +2600,7 @@ -- Row walking & schema extraction helpers ------------------------------------------------------------------------------- --- | Walks a record row type to extract its field schema.+-- Walks a record row type to extract its field schema. -- Returns 'Nothing' if the row tail is unfixed or open (deferring solving until -- the row tail is unified by downstream inference). --@@ -2470,7 +2621,7 @@           -> Just (i, n, fieldTy)         _ -> Just (i, nilFS, elemTy) --- | Walks a variant sum row type to extract its constructor schema.+-- Walks a variant sum row type to extract its constructor schema. -- Returns 'Nothing' if the row tail is unfixed or open. -- -- See Note [Row Type Anatomy: Open vs Closed Rows and Fixed vs Unfixed Tails] [ref:note-row-anatomy]@@ -2490,14 +2641,14 @@           -> Just (i, n, conRowTy)         _ -> Just (i, nilFS, elemTy) --- | Fully unrolls GHC type synonyms to expose the underlying type constructor.+-- Fully unrolls GHC type synonyms to expose the underlying type constructor. -- Uses 'coreView' recursively until no further synonyms can be stripped. unwrapSynonyms :: Type -> Type unwrapSynonyms ty = case coreView ty of   Just ty' -> unwrapSynonyms ty'   Nothing  -> ty --- | Extracts elements from a promoted type-level list (@'[a, b, c]@).+-- Extracts elements from a promoted type-level list (@'[a, b, c]@). -- -- Invariants: -- - Returns 'Just [a, b, c]' for closed lists terminating in @'[]@.@@ -2515,7 +2666,7 @@   Just (tc, [_]) | occNameString (getOccName tc) == "[]" -> Just []   _ -> Nothing --- | Pure version of 'walkRowWithTypes_maybe' that defaults open tails to '[]'.+-- Pure version of 'walkRowWithTypes_maybe' that defaults open tails to '[]'. walkRowWithTypes :: Type -> [(Int, FastString, Type)] walkRowWithTypes rowTy =   case myExtractPromotedList (unwrapSynonyms rowTy) of { Just xs -> zipWith extractField [0..] xs; Nothing -> [] }@@ -2530,7 +2681,7 @@           -> (i, n, fieldTy)         _ -> (i, nilFS, elemTy) --- | Pure version of 'walkSumRowWithTypes_maybe' that defaults open tails to '[]'.+-- Pure version of 'walkSumRowWithTypes_maybe' that defaults open tails to '[]'. walkSumRowWithTypes :: Type -> [(Int, FastString, Type)] walkSumRowWithTypes rowTy =   case myExtractPromotedList (unwrapSynonyms rowTy) of { Just xs -> zipWith extractCon [0..] xs; Nothing -> [] }@@ -2545,28 +2696,28 @@           -> (i, n, conRowTy)         _ -> (i, nilFS, elemTy) --- | Find 0-based constructor tag by name in a sum row.+-- Find 0-based constructor tag by name in a sum row. findConstructorIndex :: FastString -> Type -> Maybe Word findConstructorIndex conName rowTy =   case [fromIntegral i | (i, n, _) <- walkSumRowWithTypes rowTy, n == conName] of     (w : _) -> Just w     []      -> Nothing --- | Find 0-based field index by matching field payload type.+-- Find 0-based field index by matching field payload type. findFieldIndexByType :: Type -> Type -> Maybe Int findFieldIndexByType targetTy rowTy =   case [i | (i, _, ty) <- walkRowWithTypes rowTy, targetTy `eqType` ty] of     (i : _) -> Just i     []      -> Nothing --- | Find 0-based constructor tag by matching constructor payload type.+-- Find 0-based constructor tag by matching constructor payload type. findConstructorIndexByType :: Type -> Type -> Maybe Word findConstructorIndexByType targetTy rowTy =   case [fromIntegral i | (i, _, ty) <- walkSumRowWithTypes rowTy, targetTy `eqType` ty] of     (w : _) -> Just w     []      -> Nothing --- | Find 0-based field index and field type by name in a product row.+-- Find 0-based field index and field type by name in a product row. findFieldType :: FastString -> Type -> Maybe (Int, Type) findFieldType fieldName rowTy =   case [(i, ty) | (i, n, ty) <- walkRowWithTypes rowTy, n == fieldName] of@@ -2577,7 +2728,7 @@ -- Utilities ------------------------------------------------------------------------------- --- | Construct a boxed Int Core expression from an Int value.+-- Construct a boxed Int Core expression from an Int value. -- -- Generates: 'GHC.Types.I# <literal>' -- Used by TcPlugin to emit literal 0-based slot offsets into dictionary evidence.@@ -2585,10 +2736,13 @@ mkIntExpr :: Int -> CoreExpr mkIntExpr i = mkCoreConApps intDataCon [Lit (LitNumber LitNumInt (toInteger i))] --- | Construct a boxed Word Core expression from a Word value.+-- Construct a boxed Word Core expression from a Word value. -- -- Generates: 'GHC.Types.W# <literal>' -- Used by TcPlugin to emit literal 0-based constructor tags into dictionary evidence. -- See Note [Literal Evidence Synthesis vs Type-Level Search] [ref:note-literal-evidence] mkWordExpr :: Word -> CoreExpr mkWordExpr w = mkCoreConApps wordDataCon [Lit (LitNumber LitNumWord (toInteger w))]++mkCoreStringExpr :: String -> CoreExpr+mkCoreStringExpr s = mkListExpr charTy (map mkCharExpr s)
src/Polytropos/Plugin/Compat.hs view
@@ -1,6 +1,7 @@ {-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-}  #if __GLASGOW_HASKELL__ >= 914@@ -19,9 +20,12 @@   , matchRecordUpd   , extractRecUpdField   , pattern PrefixConPat+  , pattern RecConPat   , stripHsPar+  , mkHsPar   , polyLabel   , mkPolytroposImportDecl+  , compatImportModName   , mkHsApp   , mkTupArg   , mkLambda@@ -35,6 +39,11 @@ import GHC.Plugins   ( Module   , FastString+#if __GLASGOW_HASKELL__ >= 1001+  , unpackFS+#else+  , moduleNameString+#endif   , unLoc   , mkModuleName   , rdrNameOcc@@ -53,6 +62,9 @@   , ImportDecl(..)   , ImportDeclQualifiedStyle(..)   , IsBootInterface(..)+#if __GLASGOW_HASKELL__ >= 1001+  , NoExtField+#endif   , noAnn   , noLocA #if __GLASGOW_HASKELL__ >= 910@@ -79,6 +91,12 @@ import Language.Haskell.Syntax.Expr   ( HsTupArg(..)   )+#if __GLASGOW_HASKELL__ >= 1001+import Language.Haskell.Syntax.Type (XPrefixCon)+import Language.Haskell.Syntax.Text (packHText)+import Language.Haskell.Syntax.Module.Name (HsModuleName(..), hsModuleNameString)+import GHC.Types.UnresolvedImport (ImportDeclOrigin(..))+#endif  import GHC.Hs.ImpExp   ( XImportDeclPass(..)@@ -88,7 +106,11 @@   ( SourceText(..)   ) -#if __GLASGOW_HASKELL__ >= 910+#if __GLASGOW_HASKELL__ >= 1001+import GHC.Builtin.Modules+  ( gHC_INTERNAL_BASE+  )+#elif __GLASGOW_HASKELL__ >= 910 import GHC.Builtin.Names   ( gHC_INTERNAL_BASE   , gHC_INTERNAL_SHOW@@ -114,7 +136,9 @@  -- | Location of GHC.Show (or GHC.Internal.Show in 9.10+) modShow :: Module-#if __GLASGOW_HASKELL__ >= 910+#if __GLASGOW_HASKELL__ >= 1001+modShow = mkModule (moduleUnit modBase) (mkModuleName "GHC.Internal.Show")+#elif __GLASGOW_HASKELL__ >= 910 modShow = gHC_INTERNAL_SHOW #else modShow = gHC_SHOW@@ -166,13 +190,26 @@ -------------------------------------------------------------------------------  -- | Pattern synonym matching PrefixCon constructor details across GHC versions.-#if __GLASGOW_HASKELL__ >= 914+#if __GLASGOW_HASKELL__ >= 1001+pattern PrefixConPat :: (XPrefixCon p ~ NoExtField) => [arg] -> HsConDetails p arg rec+pattern PrefixConPat args <- PrefixCon _ args where+  PrefixConPat args = PrefixCon noExtField args++pattern RecConPat :: rec -> HsConDetails p arg rec+pattern RecConPat r <- RecCon _ r+#elif __GLASGOW_HASKELL__ >= 914 pattern PrefixConPat :: [arg] -> HsConDetails arg rec pattern PrefixConPat args = PrefixCon args++pattern RecConPat :: rec -> HsConDetails arg rec+pattern RecConPat r <- RecCon r #else pattern PrefixConPat :: [arg] -> HsConDetails tyarg arg rec pattern PrefixConPat args <- PrefixCon _ args   where PrefixConPat args = PrefixCon [] args++pattern RecConPat :: rec -> HsConDetails tyarg arg rec+pattern RecConPat r <- RecCon r #endif  -- | Strip enclosing parenthesis expressions across GHC versions.@@ -184,9 +221,19 @@ #endif stripHsPar e = e +-- | Construct a parenthesized expression across GHC versions.+mkHsPar :: LHsExpr GhcPs -> LHsExpr GhcPs+#if __GLASGOW_HASKELL__ >= 910+mkHsPar e = noLocA (HsPar noAnn e)+#else+mkHsPar e = noLocA (HsPar noAnn noAnn e noAnn)+#endif+ -- | Construct an overloaded label expression across GHC 9.6-9.14. polyLabel :: FastString -> LHsExpr GhcPs-#if __GLASGOW_HASKELL__ >= 912+#if __GLASGOW_HASKELL__ >= 1001+polyLabel fs = noLocA (HsOverLabel NoSourceText (packHText (unpackFS fs)))+#elif __GLASGOW_HASKELL__ >= 912 polyLabel fs = noLocA (HsOverLabel NoSourceText fs) #elif __GLASGOW_HASKELL__ >= 910 polyLabel fs = noLocA (HsOverLabel noExtField NoSourceText fs)@@ -196,8 +243,20 @@  -- | Construct the 'import qualified Polytropos as Polytropos' declaration. mkPolytroposImportDecl :: LImportDecl GhcPs-#if __GLASGOW_HASKELL__ >= 914+#if __GLASGOW_HASKELL__ >= 1001 mkPolytroposImportDecl = noLocA $ ImportDecl+  { ideclExt        = XImportDeclPass noAnn NoSourceText UserWrittenImport+  , ideclName       = noLocA (HsModuleName (packHText "Polytropos"))+  , ideclPkgQual    = NoRawPkgQual+  , ideclSource     = NotBoot+  , ideclLevelSpec  = NotLevelled+  , ideclSafe       = False+  , ideclQualified  = QualifiedPre+  , ideclAs         = Just (noLocA (HsModuleName (packHText "Polytropos")))+  , ideclImportList = Nothing+  }+#elif __GLASGOW_HASKELL__ >= 914+mkPolytroposImportDecl = noLocA $ ImportDecl   { ideclExt       = XImportDeclPass noAnn NoSourceText False   , ideclName      = noLocA (mkModuleName "Polytropos")   , ideclPkgQual   = NoRawPkgQual@@ -219,6 +278,16 @@   , ideclAs        = Just (noLocA (mkModuleName "Polytropos"))   , ideclImportList = Nothing   }+#endif++-- | Extract the imported module name as a String across GHC versions.+compatImportModName :: LImportDecl GhcPs -> String+#if __GLASGOW_HASKELL__ >= 1001+compatImportModName (unLoc -> ImportDecl{ ideclName = unLoc -> modNm }) =+  hsModuleNameString modNm+#else+compatImportModName (unLoc -> ImportDecl{ ideclName = unLoc -> modNm }) =+  moduleNameString modNm #endif  -- | Construct a function application expression across GHC 9.6-9.14.
+ src/Polytropos/Plugin/MergeMorph.hs view
@@ -0,0 +1,166 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE StrictData #-}++-- |+-- Module      : Polytropos.Plugin.MergeMorph+-- Description : Compile-time Skew Boolean row solver and .rodata gather byte encoder.+--+-- Evaluates 'MergeOp' row equations inside 'Polytropos.Plugin' in O(|r1| + |r2|)+-- time and serializes the resulting two-complement gather codes into static+-- C-string bytes.+module Polytropos.Plugin.MergeMorph+  ( RowEntry(..)+  , MergeEvalResult(..)+  , evalMergeOp+  , encodeGatherBytes+  ) where++import Data.Bits (complement)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BSB+import qualified Data.ByteString.Lazy as BSL+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import GHC.Core.TyCo.Compare (eqType)+import GHC.Plugins (FastString, Type, unpackFS)+import Polytropos.MergeMorph (MergeOp(..))++-- | Single field entry in a ground type-level Row.+data RowEntry = RowEntry+  { entryLabel :: !FastString+  , entryType  :: !Type+  , entrySlot  :: !Int+  }++instance Eq RowEntry where+  e1 == e2 =+    entryLabel e1 == entryLabel e2+      && entrySlot e1 == entrySlot e2+      && entryType e1 `eqType` entryType e2++-- | Outcome of compile-time Skew Boolean row algebra evaluation.+data MergeEvalResult+  = MergeSuccess ![RowEntry] ![Int]+  | MergeDisjointOverlap !FastString+  | MergeReplaceMissing !FastString+  deriving (Eq)++-- | Pure compile-time evaluator for all 7 Skew Boolean row operations.+--+-- Left entries use slot >= 0.+-- Right entries use slot < 0, encoded as 'complement slot2'.+evalMergeOp :: MergeOp -> [RowEntry] -> [RowEntry] -> MergeEvalResult+evalMergeOp op r1 r2 =+  let m1 = Map.fromList [ (unpackFS (entryLabel e), e) | e <- r1 ]+      m2 = Map.fromList [ (unpackFS (entryLabel e), e) | e <- r2 ]+      s1 = Map.keysSet m1+      s2 = Map.keysSet m2+  in case op of+       OpOverrideR ->+         let keys = Set.toList (Set.union s1 s2)+             outEntries =+               [ case Map.lookup k m2 of+                   Just e2 -> (e2, complement (entrySlot e2))+                   Nothing -> case Map.lookup k m1 of+                     Just e1 -> (e1, entrySlot e1)+                     Nothing -> error "evalMergeOp: impossible key"+               | k <- keys+               ]+             reIndexed = zipWith (\idx (e, _) -> e { entrySlot = idx }) [0..] outEntries+             gather = map snd outEntries+         in MergeSuccess reIndexed gather++       OpOverrideL ->+         let keys = Set.toList (Set.union s1 s2)+             outEntries =+               [ case Map.lookup k m1 of+                   Just e1 -> (e1, entrySlot e1)+                   Nothing -> case Map.lookup k m2 of+                     Just e2 -> (e2, complement (entrySlot e2))+                     Nothing -> error "evalMergeOp: impossible key"+               | k <- keys+               ]+             reIndexed = zipWith (\idx (e, _) -> e { entrySlot = idx }) [0..] outEntries+             gather = map snd outEntries+         in MergeSuccess reIndexed gather++       OpDisjoint ->+         let overlap = Set.intersection s1 s2+         in case Set.lookupMin overlap of+              Just badKey ->+                let badFS = entryLabel (m1 Map.! badKey)+                in MergeDisjointOverlap badFS+              Nothing ->+                let keys = Set.toList (Set.union s1 s2)+                    outEntries =+                      [ case Map.lookup k m1 of+                          Just e1 -> (e1, entrySlot e1)+                          Nothing -> case Map.lookup k m2 of+                            Just e2 -> (e2, complement (entrySlot e2))+                            Nothing -> error "evalMergeOp: impossible key"+                      | k <- keys+                      ]+                    reIndexed = zipWith (\idx (e, _) -> e { entrySlot = idx }) [0..] outEntries+                    gather = map snd outEntries+                in MergeSuccess reIndexed gather++       OpReplace ->+         let missing = Set.difference s2 s1+         in case Set.lookupMin missing of+              Just badKey ->+                let badFS = entryLabel (m2 Map.! badKey)+                in MergeReplaceMissing badFS+              Nothing ->+                let outEntries =+                      [ case Map.lookup (unpackFS (entryLabel e1)) m2 of+                          Just e2 -> (e2, complement (entrySlot e2))+                          Nothing -> (e1, entrySlot e1)+                      | e1 <- r1+                      ]+                    reIndexed = zipWith (\idx (e, _) -> e { entrySlot = idx }) [0..] outEntries+                    gather = map snd outEntries+                in MergeSuccess reIndexed gather++       OpRestrict ->+         let keys = Set.toList (Set.intersection s1 s2)+             outEntries =+               [ case Map.lookup k m1 of+                   Just e1 -> (e1, entrySlot e1)+                   Nothing -> error "evalMergeOp: impossible key"+               | k <- keys+               ]+             reIndexed = zipWith (\idx (e, _) -> e { entrySlot = idx }) [0..] outEntries+             gather = map snd outEntries+         in MergeSuccess reIndexed gather++       OpDiff ->+         let keys = Set.toList (Set.difference s1 s2)+             outEntries =+               [ case Map.lookup k m1 of+                   Just e1 -> (e1, entrySlot e1)+                   Nothing -> error "evalMergeOp: impossible key"+               | k <- keys+               ]+             reIndexed = zipWith (\idx (e, _) -> e { entrySlot = idx }) [0..] outEntries+             gather = map snd outEntries+         in MergeSuccess reIndexed gather++       OpSymDiff ->+         let keys = Set.toList (Set.difference (Set.union s1 s2) (Set.intersection s1 s2))+             outEntries =+               [ case Map.lookup k m1 of+                   Just e1 -> (e1, entrySlot e1)+                   Nothing -> case Map.lookup k m2 of+                     Just e2 -> (e2, complement (entrySlot e2))+                     Nothing -> error "evalMergeOp: impossible key"+               | k <- keys+               ]+             reIndexed = zipWith (\idx (e, _) -> e { entrySlot = idx }) [0..] outEntries+             gather = map snd outEntries+         in MergeSuccess reIndexed gather++-- | Serialize each gather slot (64-bit integer) into 8 little-endian bytes.+encodeGatherBytes :: [Int] -> BS.ByteString+encodeGatherBytes slots =+  BSL.toStrict $ BSB.toLazyByteString $+    mconcat [ BSB.int64LE (fromIntegral s) | s <- slots ]
src/Polytropos/Plugin/Source.hs view
@@ -1,8 +1,12 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE BlockArguments #-} {-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-}  #if __GLASGOW_HASKELL__ >= 914@@ -19,7 +23,7 @@ --    @REC { x = 1, y = True }@ (bare) and @REC_F { x = Just 1 }@ (HKD) --    with field punning support. -- 2. __Variant Injection:__---    @VAR { Ok = 200 }@ or @VARIANT { Err = "fail" }@.+--    @VAR { Ok = REC { val = 200 } }@ or @VARIANT { Err = REC { msg = "fail" } }@. -- 3. __Record Updates:__ --    @REC_UPD r { x = 42 }@ into 'Polytropos.setField' chains. -- 4. __Pattern Matching:__@@ -30,13 +34,17 @@ --    and @data Status = Active | Inactive String deriving OpenVariant@. module Polytropos.Plugin.Source   ( sourcePlugin+#if __GLASGOW_HASKELL__ >= 1001+  , sourceDeclsPlugin+  , sourceStmtPlugin+#endif   ) where  import Prelude  import Data.Data   ( Data-  , gmapT+  , gmapM   , Typeable   , cast   )@@ -46,7 +54,15 @@ import Data.List.NonEmpty   ( NonEmpty(..)   )+import Data.Maybe (fromMaybe)+import Data.Monoid (Any(..)) +#if __GLASGOW_HASKELL__ >= 1001+import Control.Monad.IO.Class (liftIO)+import Data.IORef (IORef, newIORef, readIORef, atomicModifyIORef')+import System.IO.Unsafe (unsafePerformIO)+#endif+ import GHC.Plugins   ( CommandLineOption   , FastString@@ -62,7 +78,6 @@   , rdrNameOcc   , occNameString   , occNameFS-  , moduleNameString   )  import GHC.Hs.Extension@@ -82,9 +97,7 @@   , LPat   , LHsDecl   , noLocA-  , HsConDetails(..)   , LImportDecl-  , ImportDecl(..)   , noAnn   , noExtField   , HsDecl(..)@@ -101,6 +114,9 @@ import Language.Haskell.Syntax.Basic   ( Boxity(..)   )+#if __GLASGOW_HASKELL__ >= 1001+import Language.Haskell.Syntax.Expr (GhciLStmt)+#endif  import GHC.Driver.Plugins   ( ParsedResult(..)@@ -111,7 +127,10 @@   , matchRecordUpd   , extractRecUpdField   , pattern PrefixConPat+  , pattern RecConPat+  , compatImportModName   , stripHsPar+  , mkHsPar   , polyLabel   , mkPolytroposImportDecl   , mkHsApp@@ -134,13 +153,13 @@ 1. Native Syntax Feel:    Developers write natural record syntax:      @REC { name = "Alice", age = 30 }@-     @VAR { Ok = 200 }@+     @VAR { Ok = REC { val = 200 } }@      @REC_UPD user { age = 31 }@    without requiring language extensions that modify the lexical grammar or external    preprocessors (like CPP or Template Haskell quotes). 2. Elimination of Downstream Complexity:-   By lowering syntactic forms to standard Polytropos combinators ('emptyRecord',-   'insertField', 'setField', 'injectVariant', 'projectVariant', 'recordField') before+   By lowering syntactic forms to standard Polytropos combinators (@emptyRecord@,+   @insertField@, @setField@, @injectVariant@, @projectVariant@, @recordField@) before    renaming, the GHC Typechecker receives standard Haskell function applications    and view patterns. The typechecker plugin ('Polytropos.Plugin') can then solve    the resulting 'FieldIndex', 'ConstructorIndex', and 'SubRow' constraints with@@ -165,14 +184,14 @@   @data Person = Person { name :: String, age :: Int } deriving OpenRecord@   @data Status = Active | Inactive String deriving OpenVariant@ -GHC's built-in deriving engine would reject 'OpenRecord' and 'OpenVariant' because they+GHC's built-in deriving engine would reject @OpenRecord@ and @OpenVariant@ because they are not built-in deriving strategies. The source plugin solves this via a two-stage process:  Stage 1 (Declaration Harvesting & Scrubbing):-- Scans 'hsmodDecls' for 'DataDecl's containing deriving clauses referencing 'OpenRecord'-  or 'OpenVariant'.+- Scans 'hsmodDecls' for 'DataDecl's containing deriving clauses referencing @OpenRecord@+  or @OpenVariant@. - Extracts the type name and constructor names into 'knownRecs' and 'knownVars'.-- Scrubs (filters out) the 'OpenRecord' and 'OpenVariant' deriving clauses from the AST,+- Scrubs (filters out) the @OpenRecord@ and @OpenVariant@ deriving clauses from the AST,   so GHC's stock deriving engine never sees them.  Stage 2 (Expression and Pattern Interception):@@ -200,11 +219,11 @@    The plugin intercepts 'RecordUpd' (and its compat variants across GHC versions)    and folds the updates right-to-left:      @setField #x 42 (setField #y True r)@-   For HKD records, @REC_UPD_F@ desugars into 'setFieldF' chains.+   For HKD records, @REC_UPD_F@ desugars into @setFieldF@ chains.  2. Record Patterns & View Pattern Bundling:    A pattern like @REC { name = p1, age = p2 }@ cannot be matched with standard data constructors-   because 'Record' is backed by a flat 'SmallArray'.+   because @Record@ is backed by a flat @SmallArray@.    The plugin desugars this into GHC View Patterns ('ViewPat'):    - Single-field match:      @REC { name = p1 }@  ==>  @(recordField #name -> p1)@@@ -218,8 +237,8 @@ 3. Variant Patterns:    @VAR { Ok = p }@ is desugared into:      @(projectVariant #Ok -> Just p)@-   If the variant's active tag matches '#Ok', 'projectVariant' yields 'Just payload' and-   matching proceeds against 'p'. If the tag does not match, 'projectVariant' yields+   If the variant's active tag matches @#Ok@, @projectVariant@ yields @Just payload@ and+   matching proceeds against @p@. If the tag does not match, @projectVariant@ yields    'Nothing', causing GHC to fall through to the next pattern match branch. -} @@ -237,23 +256,27 @@   pure res { parsedResultModule = pm' }  -- | Transforms a parsed module AST through three sequential compiler passes:--- 1. Declaration Harvesting & Scrubbing: discovers 'OpenRecord' and 'OpenVariant' deriving+-- 1. Declaration Harvesting & Scrubbing: discovers @OpenRecord@ and @OpenVariant@ deriving --    clauses, registers their nominal constructors, and strips the clauses. --    See Note [Open Declarations: Lowering Nominal Declarations to Open Rows] [ref:note-open-declarations]--- 2. Expression Transformation: rewrites 'REC', 'VAR', 'REC_UPD', and nominal constructors+-- 2. Expression Transformation: rewrites @REC@, @VAR@, @REC_UPD@, and nominal constructors --    into Polytropos runtime function application chains.--- 3. Pattern Transformation: rewrites 'REC' and 'VAR' patterns into view patterns.+-- 3. Pattern Transformation: rewrites @REC@ and @VAR@ patterns into view patterns. --    See Note [Record Update and View Pattern Translation] [ref:note-view-patterns] -- 4. Import Management: ensures 'import qualified Polytropos as Polytropos' is present. transformParsedModule :: HsParsedModule -> HsParsedModule transformParsedModule pm@HsParsedModule{ hpm_module = L modLoc hsmod } =   let decls0 = hsmodDecls hsmod       (knownRecs, knownVars, decls1) = extractAndCleanDeclarations decls0-      decls2 = everywhere (mkT (transformExpr knownRecs knownVars)) decls1-      decls3 = everywhere (mkT (transformPat knownRecs knownVars)) decls2+      (Any exprChanged, decls2) = everywhereM (mkM (transformExpr knownRecs knownVars)) decls1+      (Any patChanged,  decls3) = everywhereM (mkM (transformPat knownRecs knownVars)) decls2+      imports' =+        if exprChanged || patChanged+          then ensurePolytroposImport (hsmodImports hsmod)+          else hsmodImports hsmod       hsmod' = hsmod         { hsmodDecls   = decls3-        , hsmodImports = ensurePolytroposImport (hsmodImports hsmod)+        , hsmodImports = imports'         }   in pm { hpm_module = L modLoc hsmod' } @@ -261,18 +284,18 @@   SYB Combinators (Self-contained Data.Data helpers) -------------------------------------------------------------------------------} --- | Casts a transformation function 'b -> b' over any type 'a' satisfying 'Typeable'.+-- | Casts a transformation function @b -> b@ over any type @a@ satisfying 'Typeable'. -- Provides lightweight Scrap Your Boilerplate traversal without external library dependencies.-mkT :: (Typeable a, Typeable b) => (b -> b) -> a -> a-mkT f x = case cast x of-  Just y -> case cast (f y) of-    Just x' -> x'-    Nothing -> x-  Nothing -> x+mkM :: (Monad m, Typeable a, Typeable b) => (b -> m b) -> a -> m a+mkM f x+  | Just y <- cast x+  = fromMaybe x . cast <$> f y+  | otherwise+  = pure x  -- | Bottom-up traversal over all subtrees of a data term.-everywhere :: (forall a. Data a => a -> a) -> (forall a. Data a => a -> a)-everywhere f x = f (gmapT (everywhere f) x)+everywhereM :: Monad m => (forall a. Data a => a -> m a) -> (forall a. Data a => a -> m a)+everywhereM f x = gmapM (everywhereM f) x >>= f  {-------------------------------------------------------------------------------   Declaration Analysis (OpenRecord & OpenVariant discovery)@@ -289,7 +312,9 @@   in (nub recs, nub vars, cleanedDecls)   where     step (L loc (TyClD x decl)) (rAcc, vAcc, dAcc)-      | DataDecl ext (L _ name) tyvars fixity (HsDataDefn defnExt ctxt mtype mkind cons derivs) <- decl+      | DataDecl{ tcdLName = L _ name+                , tcdDataDefn = defn@HsDataDefn{ dd_cons = cons, dd_derivs = derivs }+                } <- decl       , let hasOpenRec = any isDerivingOpenRecord derivs       , let hasOpenVar = any isDerivingOpenVariant derivs       = let typeNameStr = occNameString (rdrNameOcc name)@@ -297,8 +322,8 @@             vCons = if hasOpenVar then extractConNames cons else []             vAcc' = if hasOpenVar then vCons ++ vAcc else vAcc             cleanedDerivs = filter (\c -> not (isDerivingOpenRecord c || isDerivingOpenVariant c)) derivs-            defn' = HsDataDefn defnExt ctxt mtype mkind cons cleanedDerivs-            decl' = DataDecl ext (noLocA name) tyvars fixity defn'+            defn' = defn { dd_derivs = cleanedDerivs }+            decl' = decl { tcdDataDefn = defn' }         in (rAcc', vAcc', L loc (TyClD x decl') : dAcc)     step d (rAcc, vAcc, dAcc) =       (rAcc, vAcc, d : dAcc)@@ -340,19 +365,19 @@   Expression Rewriting -------------------------------------------------------------------------------} --- | Rewrites expressions matching syntactic sugar markers ('REC', 'VAR', 'REC_UPD',--- 'REC_UPD_F', and nominal constructors deriving 'OpenRecord' / 'OpenVariant') into+-- | Rewrites expressions matching syntactic sugar markers (@REC@, @VAR@, @REC_UPD@,+-- @REC_UPD_F@, and nominal constructors deriving @OpenRecord@ / @OpenVariant@) into -- standard Polytropos library combinator expressions. -- -- Supported Syntactic Forms: -- 1. Bare Record Construction: --    @REC { x = 1, y = True }@ or @Person { name = "Alice", age = 30 }@---    Lowered into a chain of 'insertField' calls ending in 'emptyRecord'.+--    Lowered into a chain of @insertField@ calls ending in @emptyRecord@. -- 2. HKD Record Construction: --    @REC_F { x = Just 1 }@---    Lowered into a chain of 'insertFieldF' calls ending in 'emptyRecordF'.+--    Lowered into a chain of @insertFieldF@ calls ending in @emptyRecordF@. -- 3. Variant Injection:---    @VAR { Ok = 200 }@ or @VARIANT { Err = "msg" }@+--    @VAR { Ok = REC { val = 200 } }@ or @VARIANT { Err = REC { msg = "msg" } }@ --    Lowered into @injectVariant #Tag val@. -- 4. Functional Record Update: --    @REC_UPD r { x = 42 }@ (or @REC_UPD (r { x = 42 })@ or @(REC_UPD r) { x = 42 }@)@@ -361,35 +386,35 @@ --    - Record payload: @Success { val = 200 }@ ==> @injectVariant #Success (REC { val = 200 })@ --    - Prefix payload: @Success val@           ==> @injectVariant #Success val@ --    - Nullary:        @Loading@               ==> @injectVariant #Loading emptyRecord@-transformExpr :: [String] -> [String] -> HsExpr GhcPs -> HsExpr GhcPs+transformExpr :: [String] -> [String] -> HsExpr GhcPs -> (Any, HsExpr GhcPs) transformExpr knownRecs knownVars expr = case expr of   -- 1. Record Construction: REC { x = 1, y = True } or Person { x = 1, y = True }   RecordCon _ext (L _ nm) HsRecFields{ rec_flds = flds }     | let conStr = occNameString (rdrNameOcc nm)     , conStr == "REC" || conStr `elem` knownRecs-    -> desugarRecordCon False flds+    -> (Any True, desugarRecordCon False flds)    -- 2. HKD Record Construction: REC_F { x = Just 1 }   RecordCon _ext (L _ nm) HsRecFields{ rec_flds = flds }     | occNameString (rdrNameOcc nm) == "REC_F"-    -> desugarRecordCon True flds+    -> (Any True, desugarRecordCon True flds) -  -- 3. Variant Injection: VAR { Ok = 200 } or VARIANT { Err = "msg" }+  -- 3. Variant Injection: VAR { Ok = REC { val = 200 } } or VARIANT { Err = REC { msg = "msg" } }   RecordCon _ext (L _ nm) HsRecFields{ rec_flds = flds }     | let conStr = occNameString (rdrNameOcc nm)     , conStr == "VAR" || conStr == "VARIANT"-    -> desugarVariantCon flds+    -> (Any True, desugarVariantCon flds)    -- 4. Record Update: REC_UPD r { x = 42 } or REC_UPD (r { x = 42 }) or (REC_UPD r) { x = 42 } or REC_UPD_F   (matchRecordUpd -> Just (stripHsPar -> L _ (HsApp _ (stripHsPar -> L _ (HsVar _ (L _ nm))) r), flds))     | let nmStr = occNameString (rdrNameOcc nm)     , nmStr == "REC_UPD" || nmStr == "REC_UPD_F"-    -> desugarRecordUpd (nmStr == "REC_UPD_F") r flds+    -> (Any True, desugarRecordUpd (nmStr == "REC_UPD_F") r flds)    HsApp _ (stripHsPar -> L _ (HsVar _ (L _ nm))) (stripHsPar -> L _ (matchRecordUpd -> Just (r, flds)))     | let nmStr = occNameString (rdrNameOcc nm)     , nmStr == "REC_UPD" || nmStr == "REC_UPD_F"-    -> desugarRecordUpd (nmStr == "REC_UPD_F") r flds+    -> (Any True, desugarRecordUpd (nmStr == "REC_UPD_F") r flds)    -- 5. Open Variant Constructor Application (Lowering nominal forms to Variant)   -- 5a. Record syntax payload: Success { val = 200 }@@ -399,7 +424,7 @@     -> let injFn = polyVar "injectVariant"            lblExpr = polyLabel (fsLit conStr)            recPayload = noLocA (desugarRecordCon False flds)-       in unLoc (mkHsApp (mkHsApp injFn lblExpr) recPayload)+       in (Any True, unLoc $ mkHsApp (mkHsApp injFn lblExpr) recPayload)    -- 5b. Prefix payload application: Success r   HsApp appExt (L _ (HsVar _ (L _ nm))) arg@@ -407,7 +432,7 @@     , conStr `elem` knownVars     -> let injFn = polyVar "injectVariant"            lblExpr = polyLabel (fsLit conStr)-       in HsApp appExt (mkHsApp injFn lblExpr) arg+       in (Any True, HsApp appExt (mkHsApp injFn lblExpr) arg)    -- 5c. Nullary constructor: Loading (payload is emptyRecord)   HsVar _ (L _ nm)@@ -416,15 +441,15 @@     -> let injFn = polyVar "injectVariant"            lblExpr = polyLabel (fsLit conStr)            emptyFn = polyVar "emptyRecord"-       in unLoc (mkHsApp (mkHsApp injFn lblExpr) emptyFn)+       in (Any True, unLoc $ mkHsApp (mkHsApp injFn lblExpr) emptyFn) -  other -> other+  other -> (Any False, other) --- | Desugars record construction into a nested fold of 'insertField' calls:+-- | Desugars record construction into a nested fold of @insertField@ calls: -- @REC { x = 1, y = True }@ ==> @insertField #x 1 (insertField #y True emptyRecord)@ ----- When 'isHKD' is true, emits 'insertFieldF' and 'emptyRecordF' instead.--- Supports field punning: @REC { x }@ extracts local variable 'x' as argument.+-- When @isHKD@ is true, emits @insertFieldF@ and @emptyRecordF@ instead.+-- Supports field punning: @REC { x }@ extracts local variable @x@ as argument. desugarRecordCon :: Bool -> [LHsRecField GhcPs (LHsExpr GhcPs)] -> HsExpr GhcPs desugarRecordCon isHKD flds =   let emptyFn = polyVar (if isHKD then "emptyRecordF" else "emptyRecord")@@ -434,24 +459,24 @@         let (lbl, arg) = extractRecField fld             insFn = polyVar insertFnName             lblExpr = polyLabel lbl-        in mkHsApp (mkHsApp (mkHsApp insFn lblExpr) arg) acc-  in unLoc $ foldr foldStep emptyFn flds+        in mkHsApp (mkHsApp (mkHsApp insFn lblExpr) (mkHsPar arg)) (mkHsPar acc)+  in unLoc $ mkHsPar (foldr foldStep emptyFn flds)  -- | Desugars variant injection into @injectVariant #Tag val@:--- @VAR { Ok = 200 }@ ==> @injectVariant #Ok 200@+-- @VAR { Ok = REC { val = 200 } }@ ==> @injectVariant #Ok (REC { val = 200 })@ desugarVariantCon :: [LHsRecField GhcPs (LHsExpr GhcPs)] -> HsExpr GhcPs desugarVariantCon [] =-  error "Polytropos.Plugin.Source: VAR {} requires a constructor tag (e.g. VAR { Ok = 200 })"+  error "Polytropos.Plugin.Source: VAR {} requires a constructor tag (e.g. VAR { Ok = REC { val = 200 } })" desugarVariantCon (fld : _) =   let (lbl, arg) = extractRecField fld       injFn = polyVar "injectVariant"       lblExpr = polyLabel lbl-  in unLoc (mkHsApp (mkHsApp injFn lblExpr) arg)+  in unLoc (mkHsPar (mkHsApp (mkHsApp injFn lblExpr) (mkHsPar arg))) --- | Desugars functional record update into a fold of 'setField' calls:+-- | Desugars functional record update into a fold of @setField@ calls: -- @REC_UPD r { x = 42, y = False }@ ==> @setField #x 42 (setField #y False r)@ ----- When 'isHKD' is true, emits 'setFieldF' instead.+-- When @isHKD@ is true, emits @setFieldF@ instead. desugarRecordUpd :: Bool -> LHsExpr GhcPs -> [CompatRecUpdField] -> HsExpr GhcPs desugarRecordUpd isHKD r flds =   let setFnName = if isHKD then "setFieldF" else "setField"@@ -460,8 +485,8 @@         let (fs, arg) = extractRecUpdField fld             setFn = polyVar setFnName             lblExpr = polyLabel fs-        in mkHsApp (mkHsApp (mkHsApp setFn lblExpr) arg) acc-  in unLoc $ foldr foldStep r flds+        in mkHsApp (mkHsApp (mkHsApp setFn lblExpr) (mkHsPar arg)) (mkHsPar acc)+  in unLoc $ mkHsPar (foldr foldStep r flds)  -- | Extracts the field label and value expression from a record field node. -- Handles GHC field punning: if @pun@ flag is set, synthesizes a variable@@ -492,51 +517,48 @@ --    - Record payload: @Success { val }@ ==> @(projectVariant #Success -> Just (val view pattern))@ --    - Prefix payload: @Success p@      ==> @(projectVariant #Success -> Just p)@ --    - Nullary:        @Loading@        ==> @(projectVariant #Loading -> Just _)@-transformPat :: [String] -> [String] -> Pat GhcPs -> Pat GhcPs+transformPat :: [String] -> [String] -> Pat GhcPs -> (Any, Pat GhcPs) transformPat knownRecs knownVars pat = case pat of   -- 1. Record Pattern: REC { x, y } or Person { x, y }-  ConPat _ext (L _ nm) (RecCon HsRecFields{ rec_flds = flds })+  ConPat _ext (L _ nm) (RecConPat HsRecFields{ rec_flds = flds })     | let conStr = occNameString (rdrNameOcc nm)     , conStr == "REC" || conStr `elem` knownRecs-    -> desugarRecordPat flds+    -> (Any True, desugarRecordPat flds)    -- 2. Variant Pattern: VAR { Ok = p } or VARIANT { Err = p }-  ConPat _ext (L _ nm) (RecCon HsRecFields{ rec_flds = flds })+  ConPat _ext (L _ nm) (RecConPat HsRecFields{ rec_flds = flds })     | let conStr = occNameString (rdrNameOcc nm)     , conStr == "VAR" || conStr == "VARIANT"-    -> desugarVariantPat flds+    -> (Any True, desugarVariantPat flds)    -- 3. Open Variant Constructor Pattern (Lowering nominal constructor patterns)   -- 3a. Record syntax payload: Success { val }-  ConPat _ext (L _ nm) (RecCon HsRecFields{ rec_flds = flds })+  ConPat _ext (L _ nm) (RecConPat HsRecFields{ rec_flds = flds })     | let conStr = occNameString (rdrNameOcc nm)     , conStr `elem` knownVars     -> let viewExpr = mkHsApp (polyVar "projectVariant") (polyLabel (fsLit conStr))-           justCon  = noLocA (mkRdrUnqual (mkDataOcc "Just"))            innerPat = noLocA (desugarRecordPat flds)-           justPat  = noLocA $ ConPat noAnn justCon (PrefixConPat [innerPat])-       in ViewPat noAnn viewExpr justPat+           justPat  = mkJustConPat innerPat+       in (Any True, ViewPat noAnn viewExpr justPat)    -- 3b. 1-arg prefix pattern: Success r   ConPat _ext (L _ nm) (PrefixConPat [argPat])     | let conStr = occNameString (rdrNameOcc nm)     , conStr `elem` knownVars     -> let viewExpr = mkHsApp (polyVar "projectVariant") (polyLabel (fsLit conStr))-           justCon  = noLocA (mkRdrUnqual (mkDataOcc "Just"))-           justPat  = noLocA $ ConPat noAnn justCon (PrefixConPat [argPat])-       in ViewPat noAnn viewExpr justPat+           justPat  = mkJustConPat argPat+       in (Any True, ViewPat noAnn viewExpr justPat)    -- 3c. Nullary prefix pattern: Loading   ConPat _ext (L _ nm) (PrefixConPat [])     | let conStr = occNameString (rdrNameOcc nm)     , conStr `elem` knownVars     -> let viewExpr = mkHsApp (polyVar "projectVariant") (polyLabel (fsLit conStr))-           justCon  = noLocA (mkRdrUnqual (mkDataOcc "Just"))            wildPat  = noLocA (WildPat noExtField)-           justPat  = noLocA $ ConPat noAnn justCon (PrefixConPat [wildPat])-       in ViewPat noAnn viewExpr justPat+           justPat  = mkJustConPat wildPat+       in (Any True, ViewPat noAnn viewExpr justPat) -  other -> other+  other -> (Any False, other)  -- | Desugars record pattern matching into GHC View Patterns ('ViewPat'). --@@ -562,12 +584,12 @@       rPat         = noLocA (VarPat noExtField (noLocA rVar))       lamExpr      = mkLambda [rPat] tupExpr       tupPat       = noLocA $ TuplePat noAnn pats Boxed-  in ViewPat noAnn lamExpr tupPat+  in ViewPat noAnn (mkHsPar lamExpr) tupPat  -- | Desugars variant pattern matching into @(projectVariant #Tag -> Just p)@: -- @VAR { Ok = p }@ ==> @(projectVariant #Ok -> Just p)@ ----- If the runtime tag matches '#Ok', 'projectVariant' returns 'Just payload' and+-- If the runtime tag matches @#Ok@, @projectVariant@ returns @Just payload@ and -- succeeds; otherwise it returns 'Nothing' and pattern matching falls through. desugarVariantPat :: [LHsRecField GhcPs (LPat GhcPs)] -> Pat GhcPs desugarVariantPat [] =@@ -575,12 +597,11 @@ desugarVariantPat (fld : _) =   let (lbl, p)   = extractRecPatField fld       viewExpr   = mkHsApp (polyVar "projectVariant") (polyLabel lbl)-      justCon    = noLocA (mkRdrUnqual (mkDataOcc "Just"))-      justPat    = noLocA $ ConPat noAnn justCon (PrefixConPat [p])+      justPat    = mkJustConPat p   in ViewPat noAnn viewExpr justPat  -- | Extracts the field label and sub-pattern from a record pattern field node.--- Supports field punning: @REC { x }@ binds to pattern variable 'x'.+-- Supports field punning: @REC { x }@ binds to pattern variable @x@. extractRecPatField :: LHsRecField GhcPs (LPat GhcPs) -> (FastString, LPat GhcPs) extractRecPatField (L _ (HsFieldBind _ (L _ (FieldOcc _ (L _ lbl))) p pun)) =   let fs = occNameFS (rdrNameOcc lbl)@@ -591,6 +612,15 @@   Helper Functions -------------------------------------------------------------------------------} +mkJustConPat :: LPat GhcPs -> LPat GhcPs+mkJustConPat p =+  let justCon = noLocA (mkRdrUnqual (mkDataOcc "Just"))+#if __GLASGOW_HASKELL__ >= 1001+  in noLocA $ ConPat noExtField justCon (PrefixConPat [p])+#else+  in noLocA $ ConPat noAnn justCon (PrefixConPat [p])+#endif+ -- | Synthesizes a qualified RdrName expression: @Polytropos.<identifier>@. -- Ensures that transformed expressions reference canonical Polytropos symbols -- regardless of userland import shadowing.@@ -601,10 +631,32 @@ -- Injected automatically during 'transformParsedModule' so generated combinators resolve cleanly. ensurePolytroposImport :: [LImportDecl GhcPs] -> [LImportDecl GhcPs] ensurePolytroposImport imps =-  if any isPolytroposImport imps+  if any (\imp -> compatImportModName imp == "Polytropos") imps     then imps     else mkPolytroposImportDecl : imps-  where-    isPolytroposImport (L _ ImportDecl{ ideclName = L _ modNm }) =-      moduleNameString modNm == "Polytropos"-    isPolytroposImport _ = False++#if __GLASGOW_HASKELL__ >= 1001+-- | Session-scoped, append-only registry storing nominal record and variant+-- constructor names across interactive GHCi prompt turns.+{-# NOINLINE interactiveOpenDeclsRef #-}+interactiveOpenDeclsRef :: IORef ([String], [String])+interactiveOpenDeclsRef = unsafePerformIO (newIORef ([], []))++sourceStmtPlugin :: [CommandLineOption] -> GhciLStmt GhcPs -> Hsc (GhciLStmt GhcPs)+sourceStmtPlugin _opts stmt0 = do+  (knownRecs, knownVars) <- liftIO (readIORef interactiveOpenDeclsRef)+  let (_, stmt1) = everywhereM (mkM $ transformExpr knownRecs knownVars) stmt0+      (_, stmt2) = everywhereM (mkM $ transformPat  knownRecs knownVars) stmt1+  pure stmt2++sourceDeclsPlugin :: [CommandLineOption] -> [LHsDecl GhcPs] -> Hsc [LHsDecl GhcPs]+sourceDeclsPlugin _opts decls0 = do+  let (newRecs, newVars, decls1) = extractAndCleanDeclarations decls0+  (knownRecs, knownVars) <- liftIO $ atomicModifyIORef' interactiveOpenDeclsRef $ \(rs, vs) ->+    let !rs' = nub (newRecs ++ rs)+        !vs' = nub (newVars ++ vs)+    in ((rs', vs'), (rs', vs'))+  let (_, decls2) = everywhereM (mkM $ transformExpr knownRecs knownVars) decls1+      (_, decls3) = everywhereM (mkM $ transformPat  knownRecs knownVars) decls2+  pure decls3+#endif
tests/smoke/Main.hs view
@@ -38,6 +38,8 @@  import Polytropos.Core import Polytropos+import Polytropos.Plugin.MergeMorph+import qualified Data.ByteString as BS  -- | R2: a two-field product: a :: Int, b :: Bool. type R2 = '[ "a" := Int, "b" := Bool ]@@ -593,6 +595,93 @@             , "< StateEff | LogEff >"             ]       ]+  , testGroup "Plugin MergeMorph Skew Boolean Row Solver"+      [ testCase "evalMergeOp OpOverrideR encodes right-biased union" $ do+          let bytes = encodeGatherBytes [0, -1]+          BS.length bytes @?= 16+      , testCase "solveKnownMergeMorph solves (//>) right-biased union" $ do+          let r1 = REC { name = "Nadia" :: String }+              r2 = REC { age = 50 :: Int }+              rMerged = r1 //> r2+          rMerged.name @?= "Nadia"+          rMerged.age @?= 50+      , testCase "solveKnownMergeMorph solves (<+>) disjoint merge" $ do+          let r1 = (#name ("Nadia" :: String))+              r2 = (#age (50 :: Int))+              rMerged = r1 <+> r2+          rMerged.name @?= "Nadia"+          rMerged.age @?= (50 :: Int)+      ]+  , testGroup "Soundness, Deferral, and Source Plugin Regressions"+      [ testCase "unannotated (<+>), (|<), and (//~) evaluation + Show + Eq on unsorted rows" $ do+          let r1 = REC { z = 10 :: Int, a = True }+              r2 = REC { b = "hi" :: String, y = (42 :: Int) }+              rMerged = r1 <+> r2+          show rMerged @?= "R4 True \"hi\" 42 10"+          (rMerged == rMerged) @?= True++          let rRestrictKey = REC { z = () :: (), unused = 100 :: Int }+              rRestricted = rMerged |< rRestrictKey+          show rRestricted @?= "R1 10"+          (rRestricted == rRestricted) @?= True+          rRestricted.z @?= Identity (10 :: Int)++          let rReplVal = REC { z = 99 :: Int }+              rReplaced = rMerged //~ rReplVal+          show rReplaced @?= "R4 True \"hi\" 42 99"+          (rReplaced == rReplaced) @?= True+          rReplaced.z @?= Identity (99 :: Int)+          rReplaced.a @?= Identity True+      , testCase "Show and Eq on Variant values under -dcore-lint" $ do+          let v1 :: Variant '[ "ok" := '[ "val" := Int ], "err" := '[ "msg" := String ] ]+              v1 = VAR { ok = REC { val = 200 :: Int } }+              v1_same = VAR { ok = REC { val = 200 :: Int } }+              v1_diff = VAR { ok = REC { val = 404 :: Int } }+              v2 :: Variant '[ "ok" := '[ "val" := Int ], "err" := '[ "msg" := String ] ]+              v2 = VAR { err = REC { msg = "oops" :: String } }+          (v1 == v1_same) @?= True+          (v1 == v1_diff) @?= False+          (v1 == v2) @?= False+          show v1 @?= "ok 200"+          show v2 @?= "err \"oops\""+      , testCase "ppr round-trip of multi-field REC and REC_UPD" $ do+          let r1 = REC { a = 1 :: Int, b = True, c = "hello" :: String }+              r2 = REC_UPD r1 { a = 42 :: Int, b = False }+              r3 = REC_UPD r2 { b = True, c = "world" :: String }+          r1.a @?= Identity (1 :: Int)+          r1.b @?= Identity True+          r1.c @?= Identity ("hello" :: String)+          r2.a @?= Identity (42 :: Int)+          r2.b @?= Identity False+          r2.c @?= Identity ("hello" :: String)+          r3.a @?= Identity (42 :: Int)+          r3.b @?= Identity True+          r3.c @?= Identity ("world" :: String)+          show r1 @?= "R3 1 True \"hello\""+          show r2 @?= "R3 42 False \"hello\""+          show r3 @?= "R3 42 True \"world\""+      , testCase "injectVariant payload mismatch rejects wrong field in payload record" $+          checkGhcDiag+            (unlines+              [ "{-# LANGUAGE DataKinds, OverloadedLabels, TypeOperators #-}"+              , "module Test where"+              , "import Polytropos"+              , "type S = '[ \"ok\" := '[ \"val\" := Int ] ]"+              , "v :: Variant S"+              , "v = injectVariant #ok (REC { wrong = \"hi\" })"+              ])+            [ "Couldn't match type"+            ]+      , testCase "module compiled with -fplugin=Polytropos.Plugin -Werror=unused-imports with no REC/VAR" $+          checkGhcSuccess+            (unlines+              [ "{-# LANGUAGE NoImplicitPrelude #-}"+              , "module CleanTest where"+              , "import Prelude (Int, (+))"+              , "addOne :: Int -> Int"+              , "addOne x = x + 1"+              ])+      ]   ]  checkGhcDiag :: String -> [String] -> IO ()@@ -606,6 +695,10 @@     "ghc"     ([ "-fno-code"      , tmpFile+     , "-package"+     , "polytropos-plugin"+     , "-package"+     , "polytropos-core"      , "-fplugin=Polytropos.Plugin"      ] ++ extraFlags)     ""@@ -615,6 +708,31 @@     assertBool       ("Expected diagnostic to contain: " ++ show expected ++ "\nActual stderr:\n" ++ stderr)       (expected `isInfixOf` stderr)++checkGhcSuccess :: String -> IO ()+checkGhcSuccess snippet = do+  tmpDir <- getTemporaryDirectory+  (tmpFile, h) <- openTempFile tmpDir "PolytroposSuccessTest.hs"+  hPutStr h snippet+  hClose h+  extraFlags <- maybe [] words <$> lookupEnv "POLYTROPOS_TEST_GHC_FLAGS"+  (exitCode, stdout, stderr) <- readProcessWithExitCode+    "ghc"+    ([ "-fno-code"+     , tmpFile+     , "-package"+     , "polytropos-plugin"+     , "-package"+     , "polytropos-core"+     , "-fplugin=Polytropos.Plugin"+     , "-Wall"+     , "-Werror=unused-imports"+     ] ++ extraFlags)+    ""+  removeFile tmpFile+  assertBool+    ("Expected clean compilation, but failed with:\nStdout:\n" ++ stdout ++ "\nStderr:\n" ++ stderr)+    (exitCode == ExitSuccess)  -- | Use a supplied array of type-erased Show dictionaries to show every slot. showAllFields :: DictAllFields Show