liquidhaskell-boot 0.9.14.1.1 → 0.9.14.1.2
raw patch · 67 files changed
+5051/−1465 lines, 67 filesdep −ghc-internaldep ~basedep ~liquid-fixpointdep ~megaparsec
Dependencies removed: ghc-internal
Dependency ranges changed: base, liquid-fixpoint, megaparsec, tasty, tasty-hunit, template-haskell, unordered-containers
Files
- ghc-api-tests/GhcApiTests.hs +89/−1
- liquidhaskell-boot.cabal +18/−23
- src-ghc/Liquid/GHC/API.hs +99/−22
- src/Language/Haskell/Liquid/Bare.hs +202/−7
- src/Language/Haskell/Liquid/Bare/Axiom.hs +24/−52
- src/Language/Haskell/Liquid/Bare/Check.hs +6/−10
- src/Language/Haskell/Liquid/Bare/DataType.hs +2/−2
- src/Language/Haskell/Liquid/Bare/Elaborate.hs +58/−13
- src/Language/Haskell/Liquid/Bare/Expand.hs +8/−6
- src/Language/Haskell/Liquid/Bare/Measure.hs +12/−8
- src/Language/Haskell/Liquid/Bare/Plugged.hs +49/−10
- src/Language/Haskell/Liquid/Bare/Resolve.hs +50/−9
- src/Language/Haskell/Liquid/Bare/ToBare.hs +3/−2
- src/Language/Haskell/Liquid/Bare/Typeclass.hs +19/−12
- src/Language/Haskell/Liquid/Constraint/Generate.hs +98/−21
- src/Language/Haskell/Liquid/Constraint/Init.hs +24/−7
- src/Language/Haskell/Liquid/Constraint/Qualifier.hs +4/−5
- src/Language/Haskell/Liquid/Constraint/Relational.hs +20/−7
- src/Language/Haskell/Liquid/Constraint/RewriteCase.hs +0/−1
- src/Language/Haskell/Liquid/Constraint/Split.hs +18/−4
- src/Language/Haskell/Liquid/Constraint/Termination.hs +23/−10
- src/Language/Haskell/Liquid/Constraint/ToFixpoint.hs +78/−10
- src/Language/Haskell/Liquid/GHC/Interface.hs +37/−31
- src/Language/Haskell/Liquid/GHC/Misc.hs +48/−16
- src/Language/Haskell/Liquid/GHC/Play.hs +1/−104
- src/Language/Haskell/Liquid/GHC/Plugin.hs +196/−105
- src/Language/Haskell/Liquid/GHC/Plugin/Cache.hs +46/−0
- src/Language/Haskell/Liquid/GHC/Plugin/Iface.hs +267/−0
- src/Language/Haskell/Liquid/GHC/Plugin/Serialisation.hs +130/−65
- src/Language/Haskell/Liquid/GHC/Plugin/SpecFinder.hs +101/−41
- src/Language/Haskell/Liquid/GHC/Plugin/Types.hs +15/−9
- src/Language/Haskell/Liquid/LHNameResolution.hs +128/−27
- src/Language/Haskell/Liquid/Liquid.hs +13/−12
- src/Language/Haskell/Liquid/Measure.hs +37/−66
- src/Language/Haskell/Liquid/Parse.hs +36/−31
- src/Language/Haskell/Liquid/RefCore/Calculus.hs +552/−0
- src/Language/Haskell/Liquid/RefCore/CoreToLH.hs +405/−0
- src/Language/Haskell/Liquid/RefCore/Extract.hs +215/−0
- src/Language/Haskell/Liquid/RefCore/Misc.hs +84/−0
- src/Language/Haskell/Liquid/RefCore/Names.hs +43/−0
- src/Language/Haskell/Liquid/RefCore/Parse.hs +144/−0
- src/Language/Haskell/Liquid/RefCore/Simplify.hs +111/−0
- src/Language/Haskell/Liquid/RefCore/SpecToLH.hs +305/−0
- src/Language/Haskell/Liquid/Transforms/ANF.hs +36/−4
- src/Language/Haskell/Liquid/Transforms/CoreToLogic.hs +84/−6
- src/Language/Haskell/Liquid/Transforms/InlineAux.hs +101/−19
- src/Language/Haskell/Liquid/Transforms/QuestionMark.hs +53/−17
- src/Language/Haskell/Liquid/Transforms/Rewrite.hs +11/−5
- src/Language/Haskell/Liquid/Types/Equality.hs +1/−1
- src/Language/Haskell/Liquid/Types/Errors.hs +23/−0
- src/Language/Haskell/Liquid/Types/Names.hs +8/−4
- src/Language/Haskell/Liquid/Types/PredType.hs +50/−21
- src/Language/Haskell/Liquid/Types/PrettyPrint.hs +12/−23
- src/Language/Haskell/Liquid/Types/RType.hs +268/−198
- src/Language/Haskell/Liquid/Types/RTypeOp.hs +256/−91
- src/Language/Haskell/Liquid/Types/RefType.hs +150/−151
- src/Language/Haskell/Liquid/Types/Specs.hs +55/−12
- src/Language/Haskell/Liquid/Types/Types.hs +13/−27
- src/Language/Haskell/Liquid/UX/Annotate.hs +5/−4
- src/Language/Haskell/Liquid/UX/CmdLine.hs +38/−10
- src/Language/Haskell/Liquid/UX/Config.hs +3/−1
- src/Language/Haskell/Liquid/UX/Errors.hs +5/−9
- src/Language/Haskell/Liquid/UX/QuasiQuoter.hs +0/−1
- src/Language/Haskell/Liquid/UX/Tidy.hs +5/−17
- src/Language/Haskell/Liquid/WiredIn.hs +9/−37
- tests/Parser.hs +47/−5
- tests/WiredInTests.hs +0/−53
ghc-api-tests/GhcApiTests.hs view
@@ -2,7 +2,7 @@ import Control.Monad import Control.Monad.IO.Class (liftIO)-import Data.List (find)+import Data.List (find, isPrefixOf) import Data.Time (getCurrentTime) import Liquid.GHC.API ( ApiComment(ApiBlockComment)@@ -12,13 +12,17 @@ , LitNumType(..) , Literal(..) , apiCommentsParsedSource+ , InstDecl(ClsInstD)+ , hsGroupInstDecls , occNameString , pAT_ERROR_ID , showPprQualified , splitDollarApp+ , tcg_rn_decls , untick ) import Liquid.GHC.API.Extra (addNoInlinePragmasToBinds)+import GHC.Hs (cid_binds) import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.Runners.AntXML@@ -56,6 +60,7 @@ , testCase "dollarDesugaring" testDollarDesugaring , testCase "deadBindingPreservation" testDeadBindingPreservation , testCase "exportedBindingNotInlined" testExportedBindingNotInlined+ , testCase "derivingCheck" testDerivingCheck ] -- Tests that Liquid.GHC.API.Extra.apiComments can retrieve the comments in@@ -308,3 +313,86 @@ go (GHC.Cast e _) = go e go (GHC.Tick _ e) = go e go _ = False++-- | Tests that the SrcSpans of methods in a class instance contain the+-- SrcSpans of the corresponding core bindings, and that the instance+-- declaration SrcSpan contains the method SrcSpans.+--+-- The instance has two methods: 'method1' (two equations) and 'method2'+-- (one equation), so the test exercises multi-equation method spans too.+testDerivingCheck :: IO ()+testDerivingCheck = do+ let inputSource = unlines+ [ "module InstMethods where"+ , "class MyClass a where"+ , " method1 :: a -> a -> a"+ , " method2 :: a -> Bool"+ , ""+ , "instance MyClass Int where"+ , " method1 0 y = y"+ , " method1 x y = x + y"+ , " method2 x = x > 0"+ ]++ (instSpan, methodBindings, coreProgram) <-+ GHC.runGhc (Just libdir) $ do+ (_, tcMod) <- typecheckSourceCode "InstMethods" inputSource+ let (tcg, _) = GHC.tm_internals_ tcMod+ (iSpan, mBinds) <- liftIO $ case tcg_rn_decls tcg of+ Nothing -> fail "No renamed declarations found"+ Just grp ->+ case [ ( GHC.getLocA d+ , cid_binds inst+ )+ | d <- hsGroupInstDecls grp+ , ClsInstD _ inst <- [GHC.unLoc d]+ ] of+ [(is, bs)] -> return (is, bs)+ other ->+ fail $ "Expected exactly one instance, got " ++ show (length other)+ dsMod <- GHC.desugarModule tcMod+ let core = GHC.mg_binds $ GHC.dm_core_module dsMod+ return (iSpan, mBinds, core)++ -- Check that the instance declaration span contains all method spans.+ forM_ methodBindings $ \mb -> do+ let ms = GHC.getLocA mb+ unless (ms `GHC.isSubspanOf` instSpan) $+ fail $ "Method span " ++ show ms +++ " is not a subspan of instance span " ++ show instSpan++ -- Build a mapping from method names to their spans.+ let methodNameToSpans :: [(String, GHC.SrcSpan)]+ methodNameToSpans =+ [ (occNameString (GHC.occName mn), GHC.getLocA mb)+ | mb <- methodBindings+ , let bindLoc = GHC.unLoc mb+ mn = case bindLoc of+ GHC.FunBind {GHC.fun_id = fid} -> GHC.unLoc fid+ _ -> error "Unexpected bind type in instance"+ ]++ -- Check that each instance method core binder's span is contained in+ -- the corresponding method span. Instance method core binders have+ -- names starting with "$c" (e.g. "$cmethod1").+ let coreBinders = concatMap collectBinders coreProgram+ instMethodBinders =+ filter (isPrefixOf "$c" . occNameString . GHC.occName) coreBinders+ when (null instMethodBinders) $+ fail "No instance method core binders found (expected names starting with $c)"+ forM_ instMethodBinders $ \v -> do+ let coreSpan = GHC.getSrcSpan v+ coreBinderName = occNameString (GHC.occName v)+ methodName = drop 2 coreBinderName -- Remove "$c" prefix+ case lookup methodName methodNameToSpans of+ Nothing ->+ fail $ "Core binder " ++ coreBinderName ++ " does not correspond to any method"+ Just methodSpan ->+ unless (coreSpan `GHC.isSubspanOf` methodSpan) $+ fail $ "Core binder " ++ coreBinderName +++ " with span " ++ show coreSpan +++ " is not a subspan of method span " ++ show methodSpan+ where+ collectBinders :: GHC.CoreBind -> [GHC.Id]+ collectBinders (GHC.NonRec b _) = [b]+ collectBinders (GHC.Rec pairs) = map fst pairs
liquidhaskell-boot.cabal view
@@ -1,6 +1,6 @@ cabal-version: 2.4 name: liquidhaskell-boot-version: 0.9.14.1.1+version: 0.9.14.1.2 synopsis: Liquid Types for Haskell description: This package provides a plugin to verify Haskell programs. But most likely you should be using the [liquidhaskell package](https://hackage.haskell.org/package/liquidhaskell)@@ -71,6 +71,9 @@ Language.Haskell.Liquid.GHC.TypeRep Language.Haskell.Liquid.GHC.Plugin Language.Haskell.Liquid.GHC.Plugin.Tutorial+ Language.Haskell.Liquid.RefCore.Calculus+ Language.Haskell.Liquid.RefCore.Extract+ Language.Haskell.Liquid.RefCore.Names Language.Haskell.Liquid.LHNameResolution Language.Haskell.Liquid.Liquid Language.Haskell.Liquid.Measure@@ -117,12 +120,19 @@ LiquidHaskellBoot Paths_liquidhaskell_boot other-modules: Language.Haskell.Liquid.GHC.Plugin.Serialisation+ Language.Haskell.Liquid.GHC.Plugin.Cache+ Language.Haskell.Liquid.GHC.Plugin.Iface Language.Haskell.Liquid.GHC.Plugin.SpecFinder Language.Haskell.Liquid.GHC.Plugin.Types+ Language.Haskell.Liquid.RefCore.CoreToLH+ Language.Haskell.Liquid.RefCore.Misc+ Language.Haskell.Liquid.RefCore.Parse+ Language.Haskell.Liquid.RefCore.Simplify+ Language.Haskell.Liquid.RefCore.SpecToLH hs-source-dirs: src src-ghc src-ghc-9.10 build-depends: base >= 4.11.1.0 && < 5- , Diff >= 0.3 && < 1.1+ , Diff >= 0.3 , array , aeson , binary@@ -141,7 +151,7 @@ , gitrev , hashable >= 1.3 && < 1.6 , hscolour >= 1.22- , liquid-fixpoint == 0.9.6.3.7+ , liquid-fixpoint == 0.9.6.3.8 , mtl >= 2.1 , githash , megaparsec >= 8@@ -160,26 +170,9 @@ , extra default-language: Haskell98 default-extensions: PatternGuards, RecordWildCards, DoAndIfThenElse- ghc-options: -W -fwarn-missing-signatures -Wno-x-partial- if flag(devel)- ghc-options: -Wall -Werror -Wno-x-partial--test-suite wiredin-tests- type: exitcode-stdio-1.0- main-is: WiredInTests.hs- hs-source-dirs: tests- build-depends: base- , ghc-internal- , ghc-prim- , liquidhaskell-boot- , tasty- , tasty-ant-xml- , tasty-hunit- , template-haskell- , unordered-containers- default-language: Haskell2010+ ghc-options: -W -fwarn-missing-signatures -Wno-x-partial -Wno-incomplete-record-selectors if flag(devel)- ghc-options: -W -Werror+ ghc-options: -Wall -Werror -Wno-x-partial -Wno-incomplete-record-selectors test-suite ghc-api-tests type: exitcode-stdio-1.0@@ -205,7 +198,9 @@ , filepath , liquid-fixpoint , liquidhaskell-boot- , megaparsec+ -- earlier versions of megaparsec produce different output+ -- on parse errors+ , megaparsec >= 9.8.2 , syb , tasty >= 0.10 , tasty-ant-xml
src-ghc/Liquid/GHC/API.hs view
@@ -40,6 +40,7 @@ , HsBndrVar(HsBndrVar) , HsDecl(SigD) , HsExpr(ExprWithTySig, HsOverLit, HsVar)+ , HsGroup , HsModule(hsmodDecls) , HsOuterTyVarBndrs(HsOuterImplicit) , HsSigType(HsSig)@@ -57,7 +58,7 @@ , LexicalFixity(Prefix) , Located , LocatedN- , ModIface_(mi_anns, mi_exports, mi_module)+ , LoadHowMuch(LoadAllTargets) , ModLocation(ml_hs_file) , ModSummary(ms_hspp_file, ms_hspp_opts, ms_location, ms_mod) , Module@@ -85,11 +86,14 @@ , dataConFieldLabels , dataConWrapperType , desugarModule+ , emptyRnGroup , getLocA , getLogger , getName , getOccName , getSession+ , getSessionDynFlags+ , guessTarget , gopt , hsTypeToHsSigType , hsTypeToHsSigWcType@@ -111,6 +115,7 @@ , isTypeSynonymTyCon , isVanillaDataCon , lookupName+ , load , mkHsApp , mkHsDictLet , mkHsForAllInvisTele@@ -123,6 +128,13 @@ , moduleName , moduleNameString , moduleUnit+ , noLoc+ , parseDynamicFlags+ , runGhc+ , setSession+ , setSessionDynFlags+ , setTargets+ , SuccessFlag(Succeeded, Failed) , ms_mod_name , nameModule , nameSrcSpan@@ -164,6 +176,7 @@ , Unique , and_RDR , bindMName+ , eq_RDR , eqClassKey , eqClassName , ge_RDR@@ -369,7 +382,12 @@ , mkTyVarTys ) import GHC.Core.TyCo.Compare as Ghc (eqType, nonDetCmpType)-import GHC.Core.TyCo.Subst as Ghc (extendSubstInScopeSet, substCo, zipTvSubst)+import GHC.Core.TyCo.Subst as Ghc+ ( extendSubstInScope+ , extendSubstInScopeSet+ , substCo+ , zipTvSubst+ ) import GHC.Core.TyCon as Ghc ( TyConBinder , TyConBndrVis(AnonTCB)@@ -423,6 +441,8 @@ import GHC.Core.Utils as Ghc (exprType) import GHC.Data.Bag as Ghc ( Bag, bagToList )+import GHC.Data.IOEnv as Ghc+ ( IOEnvFailure(..) ) import GHC.Data.FastString as Ghc ( FastString , bytesFS@@ -444,9 +464,16 @@ ) import GHC.Driver.Plugins as Ghc ( ParsedResult(..)+ , Plugins(staticPlugins)+ , PluginWithArgs(PluginWithArgs)+ , StaticPlugin(StaticPlugin) ) import GHC.Driver.Phases as Ghc (Phase(StopLn)) import GHC.Driver.Pipeline as Ghc (compileFile)+import GHC.Driver.Pipeline.Execute as Ghc (runPhase)+import GHC.Driver.Pipeline.Phases as Ghc (PhaseHook(PhaseHook), TPhase(T_HscPostTc))+import GHC.Driver.Hooks as Ghc (Hooks(runPhaseHook))+import GHC.Fingerprint as Ghc (Fingerprint(Fingerprint)) import GHC.Driver.Session as Ghc ( getDynFlags , gopt_set@@ -458,19 +485,30 @@ import GHC.HsToCore.Monad as Ghc ( DsM, initDsTc, initDsWithModGuts, newUnique ) import GHC.Iface.Syntax as Ghc- ( IfaceAnnotation(ifAnnotatedValue) )-import GHC.Plugins as Ghc ( Serialized(Serialized)- , deserializeWithData- , fromSerialized- , toSerialized- , defaultPlugin- , emptyPlugins- , Plugin(..)- , CommandLineOption- , purePlugin- , extendIdSubst- , substExpr- )+ ( IfaceAnnotation(IfaceAnnotation, ifAnnotatedValue) )+import GHC.Iface.Ext.Fields as Ghc+ ( FieldName, readField, writeField, getExtensibleFields )+import GHC.Iface.Make as Ghc (mkFullIface)+import GHC.Plugins as Ghc+ ( Serialized(Serialized)+ , deserializeWithData+ , fromSerialized+ , toSerialized+ , defaultPlugin+ , emptyPlugins+ , Plugin(..)+ , CommandLineOption+ , purePlugin+ , extendIdSubst+ , extendIdSubstList+ , extendSubst+ , extendSubstList+ , extendTvSubst+ , extendTvSubstList+ , mkEmptySubst+ , substExpr+ , Subst+ ) import GHC.Core.FVs as Ghc ( exprFreeVars , exprFreeVarsList@@ -487,12 +525,13 @@ , dopt_set ) import GHC.Driver.Env as Ghc- ( HscEnv(hsc_NC, hsc_unit_env, hsc_dflags, hsc_plugins)+ ( HscEnv(hsc_NC, hsc_unit_env, hsc_dflags, hsc_plugins, hsc_hooks, hsc_logger) , Hsc , hscSetFlags, hscUpdateFlags+ , hsc_HUG, lookupIfaceByModuleHsc ) import GHC.Driver.Main as Ghc- ( hscDesugar )+ ( hscDesugar, hscMaybeWriteIface ) import GHC.Driver.Errors as Ghc ( printMessages ) import GHC.Driver.Ppr as Ghc@@ -501,6 +540,9 @@ ) import GHC.Hs as Ghc ( HsParsedModule(..)+ , ClsInstDecl(cid_binds)+ , InstDecl(ClsInstD)+ , hsGroupInstDecls ) import GHC.HsToCore.Expr as Ghc ( dsLExpr )@@ -533,6 +575,7 @@ ) import GHC.Tc.Types as Ghc ( Env(env_top)+ , FrontendResult(FrontendTypecheck) , TcGblEnv ( tcg_anns , tcg_exports@@ -540,7 +583,9 @@ , tcg_insts , tcg_mod , tcg_rdr_env+ , tcg_rn_decls , tcg_type_env+ , tcg_th_state ) , TcM , TcRn@@ -573,6 +618,8 @@ import GHC.Tc.Utils.TcType as Ghc (tcSplitDFunTy, tcSplitMethodTy) import GHC.Tc.Zonk.Type as Ghc ( zonkTopLExpr )+import GHC.ThToHs as Ghc+ ( thRdrNameGuesses ) import GHC.Types.PkgQual as Ghc ( PkgQual(NoPkgQual) ) import GHC.Types.Annotations as Ghc@@ -601,6 +648,7 @@ , isStrongLoopBreaker , noOccInfo , topPrec+ , TyConFlavour (..) ) import GHC.Types.CostCentre as Ghc ( CostCentre(cc_loc)@@ -624,6 +672,7 @@ , idInfo , idOccInfo , isConLikeId+ , isDataConId_maybe , idInlinePragma , modifyIdInfo , mkExportedLocalId@@ -645,7 +694,7 @@ ) import GHC.Types.Literal as Ghc ( LitNumType(LitNumInt)- , Literal(LitChar, LitDouble, LitFloat, LitNumber, LitString)+ , Literal(LitChar, LitDouble, LitFloat, LitNullAddr, LitNumber, LitString) , literalType ) import GHC.Types.Name as Ghc@@ -685,6 +734,7 @@ import GHC.Types.Name.Cache as Ghc (NameCache) import GHC.Types.Name.Occurrence as Ghc ( NameSpace+ , isDerivedOccName , isFieldNameSpace , mkOccName , dataName@@ -693,9 +743,9 @@ import GHC.Types.Name.Reader as Ghc ( FieldsOrSelectors(WantNormal) , GlobalRdrEnv- , GREInfo+ , GREInfo (..) , ImpItemSpec(ImpAll)- , LookupGRE(LookupRdrName)+ , LookupGRE(LookupOccName, LookupRdrName) , WhichGREs ( SameNameSpace , RelevantGREs@@ -706,6 +756,8 @@ , getRdrName , globalRdrEnvElts , greName+ , greInfo+ , greParent_maybe , isLocalGRE , lookupGRE , lookupGRE_Name@@ -736,6 +788,7 @@ , UnhelpfulWiredIn ) , combineSrcSpans+ , isSubspanOf , mkGeneralSrcSpan , mkRealSrcLoc , mkRealSrcSpan@@ -767,13 +820,14 @@ , varUnique ) import GHC.Types.Var.Env as Ghc- ( emptyInScopeSet, mkRnEnv2 )+ ( emptyInScopeSet, mkInScopeSet, mkRnEnv2 ) import GHC.Types.Var.Set as Ghc ( VarSet , elemVarSet , emptyVarSet , extendVarSet , extendVarSetList+ , unionVarSet , unitVarSet ) import GHC.Unit.Env as Ghc@@ -790,6 +844,7 @@ ) import GHC.Unit.Home.ModInfo as Ghc ( HomeModInfo(hm_iface) )+import GHC.Unit.Home.Graph as Ghc (lookupHugByModule) import GHC.Unit.Home.PackageTable as Ghc ( HomePackageTable, lookupHpt ) import GHC.Unit.Module as Ghc@@ -808,7 +863,26 @@ , unitString ) import GHC.Unit.Module.Deps as Ghc- ( ImportAvails(imp_mods) )+ ( ImportAvails(imp_mods), Usage(UsagePackageModule) )+import GHC.Unit.Module.ModIface as Ghc+ ( ModIface, ModIface_, IfaceSelfRecomp(mi_sr_usages)+ , pattern ModIface+ , emptyFullModIface, emptyPartialModIface+ , mi_anns, mi_exports, mi_module, mi_mod_hash, mi_self_recomp_info+ , mi_decls, mi_simplified_core, mi_mod_info, mi_deps, mi_fixities+ , mi_warns, mi_defaults, mi_insts, mi_fam_insts, mi_rules, mi_trust+ , mi_trust_pkg, mi_complete_matches, mi_docs, mi_top_env, mi_ext_fields+ , mi_sig_of, mi_hsc_src, mi_iface_hash, mi_public, mi_abi_hashes+ , mi_ext_fields, mi_hi_bytes, mi_fix_fn, mi_hash_fn, mi_decl_warn_fn+ , mi_export_warn_fn+ , set_mi_decls, set_mi_simplified_core, set_mi_mod_info, set_mi_deps+ , set_mi_exports, set_mi_fixities, set_mi_warns, set_mi_anns+ , set_mi_defaults, set_mi_insts, set_mi_fam_insts, set_mi_rules+ , set_mi_trust, set_mi_trust_pkg, set_mi_complete_matches, set_mi_docs+ , set_mi_top_env, set_mi_ext_fields, set_mi_self_recomp+ )+import GHC.Unit.Module.Status as Ghc+ ( HscBackendAction(HscRecomp, hscs_partial_iface, HscUpdate) ) import GHC.Unit.Module.Imported as Ghc ( ImportedMods , ImportedModsVal(imv_name, imv_qualified)@@ -828,7 +902,9 @@ import GHC.Unit.Types as Ghc ( moduleUnitId , unitIdString+ , mainUnit, mkModule )+import GHC.Types.ForeignStubs as Ghc (ForeignStubs(NoStubs)) import GHC.Utils.Binary as Ghc ( Binary(get, put_) , getByte@@ -838,6 +914,7 @@ , withBinBuffer ) import GHC.Utils.Error as Ghc (pprLocMsgEnvelope, withTiming)+import GHC.Utils.Fingerprint as Ghc (fingerprintByteString) import GHC.Utils.Logger as Ghc ( LogFlags , Logger(logFlags)
src/Language/Haskell/Liquid/Bare.hs view
@@ -20,6 +20,8 @@ import Control.Monad (forM, mplus, when) import qualified Control.Exception as Ex+import Data.Either (fromRight)+import Data.Foldable (traverse_) import qualified Data.Maybe as Mb import qualified Data.List as L import qualified Data.HashMap.Strict as M@@ -65,6 +67,11 @@ import Data.Hashable (Hashable) import Data.Bifunctor (bimap, first) import Data.Function (on)+import qualified Data.IORef as IORef+import qualified GHC.Tc.Utils.TcType as TcType+import qualified GHC.Tc.Utils.Monad as TcMonad+import qualified GHC.Types.Var.Set as VarSet+import qualified GHC.Data.IOEnv as IOEnv {- $creatingTargetSpecs@@ -181,6 +188,8 @@ [ [(x, rSort t) | (x, Loc _ _ t) <- gsMeas (_gsData sp)] , [(symbol v, rSort t) | (v, Loc _ _ t) <- gsCtors (_gsData sp)] , [(symbol v, vSort v) | v <- gsReflects (_gsRefl sp)]+ , [(symbol v, vSort v) | (v, _) <- gsTySigs (_gsSig sp), Mb.isJust (Ghc.isClassOpId_maybe v)]+ , [(symbol v, vSort v) | (v, _) <- gsAsmSigs (_gsSig sp), Mb.isJust (Ghc.isClassOpId_maybe v)] , [(x, RR s mempty) | (x, s) <- wiredSortedSyms ] , [(x, RR s mempty) | (x, s) <- _gsImps sp ] ]@@ -231,14 +240,15 @@ if allowTC then Bare.makeClassAuxTypes (elaborateSpecType coreToLg simplifier) datacons instMethods >>= elaborateSig sig else pure sig- let (dg3, refl) = withDiagnostics $ makeSpecRefl src specs env name elaboratedSig tycEnv+ checkedSig <- if checkRefinements cfg then addRefinementChecks elaboratedSig else pure elaboratedSig+ let (dg3, refl) = withDiagnostics $ makeSpecRefl src specs env name checkedSig tycEnv let eqs = gsHAxioms refl let (dg4, measEnv) = withDiagnostics $ addOpaqueReflMeas cfg tycEnv env mySpec measEnv0 specs eqs let qual = makeSpecQual cfg env globalRdrEnv tycEnv measEnv rtEnv mySpec iSpecs2 let (dg5, spcVars) = withDiagnostics $ makeSpecVars cfg src mySpec env measEnv let (dg6, spcTerm) = withDiagnostics $ makeSpecTerm cfg mySpec lenv env- let sData = makeSpecData src env sigEnv measEnv elaboratedSig specs- let finalLiftedSpec = makeLiftedSpec name src env refl sData elaboratedSig qual myRTE (lSpec0 <> lSpec1)+ let sData = makeSpecData src env sigEnv measEnv checkedSig specs+ let finalLiftedSpec = makeLiftedSpec name src env refl sData checkedSig qual myRTE (lSpec0 <> lSpec1) let diags = mconcat [dg0, dg1, dg2, dg3, dg4, dg5, dg6] -- Dump reflections, if requested@@ -255,7 +265,7 @@ pure (diags, SP { _gsConfig = cfg , _gsImps = makeImports mspecs- , _gsSig = addReflSigs env name rtEnv measEnv refl elaboratedSig+ , _gsSig = addReflSigs env name rtEnv measEnv refl checkedSig , _gsRefl = refl , _gsData = sData , _gsQual = qual@@ -345,6 +355,50 @@ si { gsTySigs = F.notracepp ("asmSigs" ++ F.showpp (gsAsmSigs si)) tySigs ++ auxsig } + addRefinementChecks si = do+ ref <- Ghc.liftIO $ IORef.newIORef []+ logger <- Ghc.getLogger+ let collect signatureType e queryType =+ let coreType = Ghc.exprType e+ (typeBinders, constraints, _) = TcType.tcSplitSigmaTy coreType+ hasFreeTypeVariables = not . VarSet.isEmptyVarSet $ Ghc.tyCoVarsOfType coreType+ hasEvidenceVariables = VarSet.anyVarSet GM.isEvidenceVar (Ghc.exprFreeVars e)+ in when (null typeBinders && null constraints && not hasFreeTypeVariables && not hasEvidenceVariables) $+ Ghc.liftIO $ IORef.modifyIORef' ref+ (RefinementCheck e (F.atLoc signatureType queryType) :)+ checkSignature (x, signatureType) = do+ oldChecks <- Ghc.liftIO $ IORef.readIORef ref+ -- Conversion helpers currently report unsupported Liquid-only+ -- constructs with GhcException (via `todo`/`panic`), which+ -- `tryMostM` deliberately does not catch. Treat those as a+ -- failed best-effort conversion as well.+ -- Keep `tryTc` on the outside: if conversion panics after adding+ -- wanted constraints, it must still get a chance to restore the+ -- typechecker state before we continue with the module.+ result <- if null (allTyVars (F.val signatureType))+ then TcMonad.tryTc $ IOEnv.tryAllM $ TcMonad.discardWarnings $ TcMonad.discardConstraints $+ traverse_+ (elaborateSpecTypeWith (collect signatureType) coreToLg simplifier)+ signatureType+ else pure (Nothing, mempty)+ case result of+ (Just (Right ()), _) -> pure ()+ _ -> do+ -- Elaboration may have collected earlier refinements from the+ -- same signature before encountering an unsupported one.+ Ghc.liftIO $ IORef.writeIORef ref oldChecks+ let warning = mkWarning+ (GM.sourcePos2SrcSpan (F.loc signatureType) (F.locE signatureType))+ (text $ "Cannot check refinements for " ++ F.showpp x +++ ": not every predicate has a Haskell equivalent.")+ Ghc.liftIO $ printWarning logger warning+ -- Elaboration supplies the dependent lambda type for every refinement.+ -- This is a best-effort pass: Liquid-only predicates are left to the+ -- ordinary sort checker and reported with a warning.+ mapM_ checkSignature (gsTySigs si)+ checks <- reverse <$> Ghc.liftIO (IORef.readIORef ref)+ pure si { gsReftChecks = checks }+ simplifier :: Ghc.CoreExpr -> Ghc.TcRn Ghc.CoreExpr simplifier = pure -- no simplification allowTC = typeclass cfg@@ -595,7 +649,13 @@ ------------------------------------------------------------------------------------------ makeSpecVars cfg src mySpec env measEnv = do let tgtVars = Mb.mapMaybe (`M.lookup` hvars) (checks cfg)- igVars <- sMapM (Bare.lookupGhcIdLHName env) (Ms.ignores mySpec)+ -- Name resolution for ignore annotations is finished at this point since the variables+ -- that we need refer to Core bindings in the case of instance ignores rather+ -- than Haskell names.+ let (instIgnores, topIgnores) = partitionIgnores (_giInstSpans src) (Ms.ignores mySpec)+ igVarsTop <- resolveTopLevelIgnores env topIgnores+ igVarsInst <- resolveInstanceIgnores env src instIgnores+ let igVars = igVarsTop <> igVarsInst lVars <- sMapM (Bare.lookupGhcIdLHName env) (Ms.lvars mySpec) return (SpVar tgtVars igVars lVars cMethods) where@@ -605,6 +665,74 @@ | b <- Ghc.bindersOfBinds (_giCbs src) ] +-- | Partition ignore annotations into those inside instance declarations+-- and those at the top level, based on source position.+partitionIgnores+ :: [Ghc.SrcSpan]+ -> S.HashSet (F.Located LHName)+ -> ([F.Located LHName], [F.Located LHName]) -- ^ (instance ignores, top-level ignores)+partitionIgnores instSpans ignores =+ L.partition isInInstance (S.toList ignores)+ where+ isInInstance lname =+ let sp = GM.sourcePosSrcSpan (F.loc lname)+ in any (sp `Ghc.isSubspanOf`) instSpans++-- | Resolve top-level (non-instance) ignore annotations.+-- Produces an error if the name refers to a class method.+resolveTopLevelIgnores :: Bare.Env -> [F.Located LHName] -> Bare.Lookup (S.HashSet Ghc.Var)+resolveTopLevelIgnores env lnames = do+ vars <- mapM (resolveTopLevelIgnore env) lnames+ return (S.fromList vars)++resolveTopLevelIgnore :: Bare.Env -> F.Located LHName -> Bare.Lookup Ghc.Var+resolveTopLevelIgnore env lname = do+ v <- Bare.lookupGhcIdLHName env lname+ case Ghc.isClassOpId_maybe v of+ Just _cls -> Left [ErrBadIgnore sp+ (pprint (F.val lname))+ (text "class method can only be ignored inside an instance declaration")]+ Nothing -> Right v+ where+ sp = GM.fSrcSpan lname++-- | Resolve instance-level ignore annotations.+-- Finds the $c-prefixed Core binding for the method in the matching instance.+resolveInstanceIgnores :: Bare.Env -> GhcSrc -> [F.Located LHName] -> Bare.Lookup (S.HashSet Ghc.Var)+resolveInstanceIgnores env src lnames = do+ vars <- mapM (resolveInstanceIgnore env src) lnames+ return (S.fromList vars)++resolveInstanceIgnore :: Bare.Env -> GhcSrc -> F.Located LHName -> Bare.Lookup Ghc.Var+resolveInstanceIgnore env src lname = do+ -- First resolve the name to check it's a class method+ v <- Bare.lookupGhcIdLHName env lname+ case Ghc.isClassOpId_maybe v of+ Nothing -> Left [ErrBadIgnore sp+ (pprint (F.val lname))+ (text "only class methods can be ignored inside an instance declaration")]+ Just _cls -> do+ let methodName = Ghc.occNameString (Ghc.getOccName v)+ cName = "$c" ++ methodName+ annotSpan = GM.sourcePosSrcSpan (F.loc lname)+ -- Find the $c-prefixed binding whose span is within the same instance+ matchingInstSpan = L.find (annotSpan `Ghc.isSubspanOf`) (_giInstSpans src)+ matchingVars = do+ instSp <- matchingInstSpan+ -- This ignores the possibility of multiple instance declarations+ -- but that is not something we expect to happen to go through the+ -- trouble of checking it every time.+ flip L.find (Ghc.bindersOfBinds (_giCbs src)) $ \b ->+ Ghc.occNameString (Ghc.getOccName b) == cName+ && Ghc.getSrcSpan b `Ghc.isSubspanOf` instSp+ case matchingVars of+ Just c -> Right c+ Nothing -> Left [ErrBadIgnore sp+ (pprint (F.val lname))+ (text $ "could not find instance method binding for " ++ methodName)]+ where+ sp = GM.fSrcSpan lname+ sMapM :: (Monad m, Eq b, Hashable b) => (a -> m b) -> S.HashSet a -> m (S.HashSet b) sMapM f xSet = do ys <- mapM f (S.toList xSet)@@ -883,11 +1011,20 @@ reflected = S.fromList $ fst <$> notReflActualTySigs notReflected xt = fst xt `notElem` reflected +-- | Resolves the binders of the @ple@ and @automatic-instances@ annotations.+--+-- They are read only under @--ple-local@, and @--ple@ already covers the whole+-- module, so with neither flag set the annotation would be dropped without a+-- word. Report it. See #2737. makeAutoInst :: Bare.Env -> Ms.BareSpec -> Bare.Lookup (S.HashSet Ghc.Var)-makeAutoInst env spec = S.fromList <$> kvs+makeAutoInst env spec+ | not (S.null autois), not (allowPLE (getConfig env)) =+ Left [ ErrPleDisabled (GM.fSrcSpan lx) (pprint (val lx)) | lx <- S.toList autois ]+ | otherwise = S.fromList <$> kvs where- kvs = forM (S.toList (Ms.autois spec)) $+ autois = Ms.autois spec+ kvs = forM (S.toList autois) $ Bare.lookupGhcIdLHName env @@ -922,6 +1059,7 @@ , gsTexprs = [ (v, t, es) | (v, t, Just es) <- mySigs ] , gsRelation = relation , gsAsmRel = asmRel+ , gsReftChecks = [] }) where (instances, dicts) = Bare.makeSpecDictionaries env sigEnv (name, mySpec) (M.toList specs)@@ -1155,6 +1293,62 @@ getTy n l _ = Ex.throw (mkErr n l) mkErr n l = ErrOther (GM.sourcePosSrcSpan l) ("Bad new type declaration:" <+> F.pprint n) :: UserError +-- | For every user-declared @newtype@ we synthesize a datatype invariant.+--+-- The invariant states for every value @v@ the measure equations that the+-- defined measures provide. It also states the predicates in the refinement+-- type of the newtype. For example, for the newtype+--+-- > newtype Pos = Pos { unPos :: { v:Int | v > 0 } }+--+-- and the measure+--+-- > {-@ measure m @-}+-- > m :: Pos -> Int+-- > m (Pos v) = v + 1+--+-- the invariant is+--+-- > {-@ invariant {v:Pos | m v = unPos v + 1 && unPos v > 0 && v == Pos (unPos v)} @-}+--+-- See note [Newtype checking] in "Language.Haskell.Liquid.Constraint.Generate".+makeNewTypeInvariants :: Bare.Env -> Bare.MeasEnv -> Bare.ModSpecs -> [(Maybe Ghc.Var, LocSpecType)]+makeNewTypeInvariants env measEnv specs =+ [ (Nothing, inv)+ | (name, spec) <- M.toList specs+ , d <- Ms.newtyDecls spec+ , Just tc <- [fromRight Nothing (Bare.lookupGhcDnTyCon env name (tycName d))]+ , Just dc <- [Ghc.tyConSingleDataCon_maybe tc]+ , [_] <- [Ghc.dataConOrigArgTys dc] -- exactly one field+ , Just dcT <- [lookup (Ghc.dataConWorkId dc) dcSpecs]+ , Just inv <- [mkNewTypeInvariant tc dc (val dcT) (tycSrcPos d)]+ ]+ where+ dcSpecs = Bare.meDataCons measEnv++mkNewTypeInvariant :: Ghc.TyCon -> Ghc.DataCon -> SpecType -> F.SourcePos -> Maybe LocSpecType+mkNewTypeInvariant tc dc dcT l = do+ fl <- Mb.listToMaybe (Ghc.dataConFieldLabels dc)+ let r = -- {v:_ | v == dc y}+ dataConReft dc [y]+ `meet`+ -- Refinement type with measures+ dataConMsReft dcT [y]+ -- Refinement type of the argument (singleton list)+ pf = [ p `F.subst1` (w, F.EVar y) | t <- dcArgTys, let F.Reft (w, p) = rTypeReft t ]+ pr = F.PAnd $ F.reftPred r : pf+ b = F.reftBind r+ -- The argument of the newtype data constructor+ selE = F.mkEApp (dummyLoc (F.symbol (Ghc.flSelector fl))) [F.EVar b]+ -- Eliminate the temporary variable y+ invR = F.Reft (b, F.subst (F.mkSubst [(y, selE)]) pr)+ return (Loc l l (strengthen resT (MkUReft invR mempty)))+ where+ -- A temporary variable to represent the argument of the newtype datacon+ y = F.tempSymbol "lqNewtypeField" 0+ resT = ofType (Ghc.mkTyConApp tc (Ghc.mkTyVarTy <$> Ghc.tyConTyVars tc)) :: SpecType+ dcArgTys = let (_, _, ts, _, _) = bkArrowDeep dcT in ts+ ------------------------------------------------------------------------------------------ makeSpecData :: GhcSrc -> Bare.Env -> Bare.SigEnv -> Bare.MeasEnv -> GhcSpecSig -> Bare.ModSpecs -> GhcSpecData@@ -1182,6 +1376,7 @@ name = _giTargetMod src (minvs,usI) = makeMeasureInvariants sig mySpec invs = minvs ++ concatMap (makeInvariants env sigEnv) (M.toList specs)+ ++ makeNewTypeInvariants env measEnv specs makeIAliases :: Bare.Env -> Bare.SigEnv -> (ModName, Ms.BareSpec) -> [(LocSpecType, LocSpecType)] makeIAliases env sigEnv (name, spec)
src/Language/Haskell/Liquid/Bare/Axiom.hs view
@@ -328,7 +328,7 @@ mkError :: PPrint a => Located a -> String -> Error mkError x str = ErrHMeas (sourcePosSrcSpan $ loc x) (pprint $ val x) (PJ.text str) --- This function is uded to generate the fixpoint code for reflected functions+-- This function is used to generate the fixpoint code for reflected functions makeAssumeType :: Config -> F.TCEmb Ghc.TyCon -> LogicMap -> DataConMap -> LocSymbol -> Maybe SpecType@@ -380,10 +380,12 @@ -- Negative Debruijn indices (levels :^)) are safer freeSort = [-1, -2 ..] + normalizedExpr = normalizeCoreExpr allowTC def+ inScopeSubst =+ Ghc.emptySubst `Ghc.extendSubstInScopeSet` Ghc.exprFreeVars normalizedExpr (xs, def') = GM.notracePpr "grabBody" $- grabBody allowTC (Ghc.expandTypeSynonyms τ) $- normalizeCoreExpr allowTC def+ grabBody allowTC inScopeSubst (Ghc.expandTypeSynonyms τ) normalizedExpr su = F.mkSubst $ zip (F.symbol <$> xs) xArgs ++ zip (simplesymbol <$> xs) xArgs xts = [(F.symbol x, rTypeSortExp tce t) | (x, t) <- aargs at]@@ -392,25 +394,27 @@ rTypeSortExp tce = typeSort tce . Ghc.expandTypeSynonyms . toType False grabBody :: Bool -- ^ typeclass enabled+ -> Ghc.Subst -- ^ in-scope set for capture-avoiding substitution -> Ghc.Type -> Ghc.CoreExpr -> ([Ghc.Var], Ghc.CoreExpr)-grabBody allowTC (Ghc.ForAllTy _ ty) e- = grabBody allowTC ty e-grabBody allowTC@False Ghc.FunTy{ Ghc.ft_arg = tx, Ghc.ft_res = t} e | Ghc.isClassPred tx- = grabBody allowTC t e-grabBody allowTC@True Ghc.FunTy{ Ghc.ft_arg = tx, Ghc.ft_res = t} e | isEmbeddedDictType tx- = grabBody allowTC t e-grabBody allowTC torig@Ghc.FunTy {} (Ghc.Let (Ghc.NonRec x e) body)- = grabBody allowTC torig (subst (x,e) body)-grabBody allowTC Ghc.FunTy{ Ghc.ft_res = t} (Ghc.Lam x e)- = (x:xs, e') where (xs, e') = grabBody allowTC t e-grabBody allowTC t (Ghc.Tick _ e)- = grabBody allowTC t e-grabBody allowTC ty@Ghc.FunTy{} e+grabBody allowTC inScope (Ghc.ForAllTy _ ty) e+ = grabBody allowTC inScope ty e+grabBody allowTC@False inScope Ghc.FunTy{ Ghc.ft_arg = tx, Ghc.ft_res = t} e | Ghc.isClassPred tx+ = grabBody allowTC inScope t e+grabBody allowTC@True inScope Ghc.FunTy{ Ghc.ft_arg = tx, Ghc.ft_res = t} e | isEmbeddedDictType tx+ = grabBody allowTC inScope t e+grabBody allowTC inScope torig@Ghc.FunTy {} (Ghc.Let (Ghc.NonRec x e) body)+ = grabBody allowTC inScope torig (Ghc.substExpr (Ghc.extendIdSubst inScope x e) body)+grabBody allowTC inScope Ghc.FunTy{ Ghc.ft_res = t} (Ghc.Lam x e)+ = (x:xs, e')+ where (xs, e') = grabBody allowTC (Ghc.extendSubstInScope inScope x) t e+grabBody allowTC inScope t (Ghc.Tick _ e)+ = grabBody allowTC inScope t e+grabBody allowTC inScope ty@Ghc.FunTy{} e = (txs++xs, e') where (ts,tr) = splitFun ty- (xs, e') = grabBody allowTC tr (foldl Ghc.App e (Ghc.Var <$> txs))+ (xs, e') = grabBody allowTC inScope tr (foldl Ghc.App e (Ghc.Var <$> txs)) txs = [ stringVar ("ls" ++ show i) t | (t,i) <- zip ts [(1::Int)..]]-grabBody _ _ e+grabBody _ _ _ e = ([], e) splitFun :: Ghc.Type -> ([Ghc.Type], Ghc.Type)@@ -420,7 +424,7 @@ isBoolBind :: Ghc.Var -> Bool-isBoolBind v = isBool (ty_res $ toRTypeRep ((ofType $ Ghc.varType v) :: RRType ()))+isBoolBind v = isBool (ty_res $ toRTypeRep ((ofType $ Ghc.varType v) :: RRType NoReft)) strengthenRes :: SpecType -> F.Reft -> SpecType strengthenRes st rf = go st@@ -430,38 +434,6 @@ go (RFun x i tx t r) = RFun x i tx (go t) r go t = t `strengthen` ofReft rf -class Subable a where- subst :: (Ghc.Var, Ghc.CoreExpr) -> a -> a--instance Subable Ghc.Var where- subst (x, ex) z- | x == z, Ghc.Var y <- ex = y- | otherwise = z--instance Subable Ghc.CoreExpr where- subst (x, ex) (Ghc.Var y)- | x == y = ex- | otherwise = Ghc.Var y- subst su (Ghc.App f e)- = Ghc.App (subst su f) (subst su e)- subst su (Ghc.Lam x e)- = Ghc.Lam x (subst su e)- subst su (Ghc.Case e x t alts)- = Ghc.Case (subst su e) x t (subst su <$> alts)- subst su (Ghc.Let (Ghc.Rec xes) e)- = Ghc.Let (Ghc.Rec (fmap (subst su) <$> xes)) (subst su e)- subst su (Ghc.Let (Ghc.NonRec x ex) e)- = Ghc.Let (Ghc.NonRec x (subst su ex)) (subst su e)- subst su (Ghc.Cast e t)- = Ghc.Cast (subst su e) t- subst su (Ghc.Tick t e)- = Ghc.Tick t (subst su e)- subst _ e- = e--instance Subable Ghc.CoreAlt where- subst su (Ghc.Alt c xs e) = Ghc.Alt c xs (subst su e)- data AxiomType = AT { aty :: SpecType, aargs :: [(F.Symbol, SpecType)], ares :: SpecType } deriving Show @@ -495,7 +467,7 @@ | x /= F.dummySymbol = x | otherwise = F.symbol ("lq" ++ show i) -singletonApp :: F.Symbolic a => F.Symbol -> [a] -> UReft F.Reft+singletonApp :: F.Symbolic a => F.Symbol -> [a] -> UReft singletonApp s ys = MkUReft r mempty where r = F.exprReft (F.eApps (F.EVar s) (F.eVar <$> ys))
src/Language/Haskell/Liquid/Bare/Check.hs view
@@ -6,8 +6,6 @@ {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE TypeOperators #-} -{-# OPTIONS_GHC -Wno-incomplete-record-selectors #-}- module Language.Haskell.Liquid.Bare.Check ( checkTargetSpec , checkBareSpec@@ -270,7 +268,7 @@ -- allowTC = typeclass (getConfig sp) bsc = bscope (getConfig tsp) noPrune = not (pruneFlag tsp)- txCtors ts = [(v, fmap (fmap (fmap (F.filterUnMatched temps))) t) | (v, t) <- ts]+ txCtors ts = [(v, fmap (mapReft (mapReftField (F.filterUnMatched temps))) t) | (v, t) <- ts] temps = F.makeTemplates $ gsUnsorted $ gsData tsp ef = mkElabFlags (smtsolver $ getConfig tsp) @@ -581,7 +579,7 @@ insertPEnv p γ = insertsSEnv γ (fmap (rTypeSortedReft emb) <$> pbinds p) pbinds p = (pname p, pvarRType p :: RSort) : [(x, tx) | (tx, x, _) <- pargs p] -tyToBind :: F.TCEmb TyCon -> RTVar RTyVar RSort -> [(F.Symbol, F.SortedReft)]+tyToBind :: F.TCEmb TyCon -> SpecRTVar -> [(F.Symbol, F.SortedReft)] tyToBind emb = go . ty_var_info where go RTVInfo{..} = [(rtv_name, rTypeSortedReft emb rtv_kind)]@@ -616,9 +614,7 @@ expectedArity = tyConRealArity tc -checkAbstractRefs- :: (PPrint t, IsReft t, ReftBind t ~ F.Symbol, ReftVar t ~ F.Symbol, SubsTy RTyVar RSort t) =>- RType RTyCon RTyVar (UReft t) -> Maybe Doc+checkAbstractRefs :: SpecType -> Maybe Doc checkAbstractRefs rt = go rt where penv = mkPEnv rt@@ -675,7 +671,7 @@ -- TODO remove the unused UReft arg checkReft :: (PPrint r, IsReft r, ReftBind r ~ F.Symbol, ReftVar r ~ F.Symbol, SubsTy RTyVar (RType RTyCon RTyVar NoReft) r)- => F.SrcSpan -> F.SEnv F.SortedReft -> F.TCEmb TyCon -> Maybe (RRType (UReft r)) -> UReft r -> ElabM (Maybe Doc)+ => F.SrcSpan -> F.SEnv F.SortedReft -> F.TCEmb TyCon -> Maybe (RRType r) -> r -> ElabM (Maybe Doc) checkReft _ _ _ Nothing _ = pure Nothing -- TODO:RPropP/Ref case, not sure how to check these yet. checkReft sp env emb (Just t) _ = do me <- checkSortedReftFull sp env r pure $ (\z -> dr $+$ z) <$> me@@ -796,12 +792,12 @@ ++ " contains an inner refinement." -isRefined :: ToReft r => RType c tv r -> Bool+isRefined :: (IsReft r, Eq (ReftVar r)) => RType c tv r -> Bool isRefined ty | Just r <- stripRTypeBase ty = not $ isTauto r | otherwise = False -hasInnerRefinement :: ToReft r => RType c tv r -> Bool+hasInnerRefinement :: (IsReft r, Eq (ReftVar r)) => RType c tv r -> Bool hasInnerRefinement (RFun _ _ rIn rOut _) = isRefined rIn || isRefined rOut hasInnerRefinement (RAllT _ ty _) =
src/Language/Haskell/Liquid/Bare/DataType.hs view
@@ -738,7 +738,7 @@ getPsSigPs m pos (RProp _ (RHole r)) = addps m pos r getPsSigPs m pos (RProp _ t) = getPsSig m pos t -addps :: [(UsedPVar, a)] -> b -> UReft t -> [(a, b)]+addps :: [(UsedPVar, a)] -> b -> UReft -> [(a, b)] addps m pos (MkUReft _ ps) = (, pos) . f <$> pvars ps where f = Mb.fromMaybe (panic Nothing "Bare.addPs: notfound") . (`L.lookup` m) . RT.uPVar@@ -804,7 +804,7 @@ RFun x' i tx <$> local (extend x') (go t) <*> pure (meet r r') go t = RT.strengthen t . singletonApp s . L.reverse <$> reader snd -singletonApp :: F.Symbolic a => F.LocSymbol -> [a] -> UReft F.Reft+singletonApp :: F.Symbolic a => F.LocSymbol -> [a] -> UReft singletonApp s ys = MkUReft r mempty where r = F.exprReft (F.mkEApp s (F.eVar <$> ys))
src/Language/Haskell/Liquid/Bare/Elaborate.hs view
@@ -16,6 +16,7 @@ module Language.Haskell.Liquid.Bare.Elaborate ( fixExprToHsExpr , elaborateSpecType+ , elaborateSpecTypeWith -- , buildSimplifier ) where@@ -287,7 +288,25 @@ -> SpecType -> TcRn SpecType elaborateSpecType coreToLogic simplifier t = GM.withWiredIn $ do- (t', xs) <- elaborateSpecType' (pure ()) coreToLogic simplifier t+ elaborateSpecTypeWith (\_ _ -> pure ()) coreToLogic simplifier t++-- | Elaborate a specification to make type class dictionaries explicit,+-- and expose the Core expression generated for every non-trivial+-- refinement together with its refined checking type.+--+-- @elaborateSpecTypeWith collect coreToLogic simplify (x0:t0 -> ... -> v:tn)@ calls+-- @collect et (\<env> -> ti')@ for each @i@, where @ti'@ is @ti@ with the+-- refinement predicate replaced by @true@, @et@ is the elaborated Core+-- expression of @\<env> -> ti@, and @env@ are the local bindings @xi@, @v@ in+-- scope.+elaborateSpecTypeWith+ :: (CoreExpr -> SpecType -> TcRn ())+ -> (CoreExpr -> F.Expr)+ -> (CoreExpr -> TcRn CoreExpr)+ -> SpecType+ -> TcRn SpecType+elaborateSpecTypeWith collect coreToLogic simplifier t = GM.withWiredIn $ do+ (t', xs) <- elaborateSpecType' collect (pure ()) coreToLogic simplifier t case xs of _ : _ -> panic Nothing@@ -295,13 +314,14 @@ _ -> pure t' elaborateSpecType'- :: PartialSpecType+ :: (CoreExpr -> SpecType -> TcRn ())+ -> PartialSpecType -> (CoreExpr -> F.Expr) -- core to logic -> (CoreExpr -> TcRn CoreExpr) -> SpecType -> TcRn (SpecType, [F.Symbol]) -- binders for dictionaries -- should have returned Maybe [F.Symbol]-elaborateSpecType' partialTp coreToLogic simplify t =+elaborateSpecType' collect partialTp coreToLogic simplify t = case F.notracepp "elaborateSpecType'" t of RVar (RTV tv) (MkUReft reft@(F.Reft (vv, _oldE)) p) -> do elaborateReft@@ -315,8 +335,8 @@ let partialFunTp = Free (RFunF bind i (wrap $ specTypeToPartial tin) (pure ()) ureft) :: PartialSpecType partialTp' = partialTp >> partialFunTp :: PartialSpecType- (eTin , bs ) <- elaborateSpecType' partialTp coreToLogic simplify tin- (eTout, bs') <- elaborateSpecType' partialTp' coreToLogic simplify tout+ (eTin , bs ) <- elaborateSpecType' collect partialTp coreToLogic simplify tin+ (eTout, bs') <- elaborateSpecType' collect partialTp' coreToLogic simplify tout let buildRFunContTrivial | isClassType tin, dictBinder : bs0' <- bs' = do let (eToutRenamed, canonicalBinders) =@@ -368,6 +388,7 @@ -- support for RankNTypes/ref RAllT (RTVar tv ty) tout ureft@(MkUReft ref@(F.Reft (vv, _oldE)) p) -> do (eTout, bs) <- elaborateSpecType'+ collect (partialTp >> Free (RAllTF (RTVar tv ty) (pure ()) ureft)) coreToLogic simplify@@ -387,6 +408,7 @@ -- todo: might as well print an error message? RAllP pvbind tout -> do (eTout, bts') <- elaborateSpecType'+ collect (partialTp >> Free (RAllPF pvbind (pure ()))) coreToLogic simplify@@ -398,7 +420,7 @@ | isClass tycon -> pure (t, []) | otherwise -> do args' <- mapM- (fmap fst . elaborateSpecType' partialTp coreToLogic simplify)+ (fmap fst . elaborateSpecType' collect partialTp coreToLogic simplify) args elaborateReft (reft, t)@@ -407,8 +429,8 @@ pure (RApp tycon args' pargs (MkUReft (F.Reft (vv, ee)) p), bs') ) RAppTy arg res ureft@(MkUReft reft@(F.Reft (vv, _)) p) -> do- (eArg, bs ) <- elaborateSpecType' partialTp coreToLogic simplify arg- (eRes, bs') <- elaborateSpecType' partialTp coreToLogic simplify res+ (eArg, bs ) <- elaborateSpecType' collect partialTp coreToLogic simplify arg+ (eRes, bs') <- elaborateSpecType' collect partialTp coreToLogic simplify res let (eResRenamed, canonicalBinders) = canonicalizeDictBinder bs (eRes, bs') elaborateReft@@ -424,8 +446,8 @@ ) -- todo: Existential support REx bind allarg ty -> do- (eAllarg, bs ) <- elaborateSpecType' partialTp coreToLogic simplify allarg- (eTy , bs') <- elaborateSpecType' partialTp coreToLogic simplify ty+ (eAllarg, bs ) <- elaborateSpecType' collect partialTp coreToLogic simplify allarg+ (eTy , bs') <- elaborateSpecType' collect partialTp coreToLogic simplify ty let (eTyRenamed, canonicalBinders) = canonicalizeDictBinder bs (eTy, bs') pure (REx bind eAllarg eTyRenamed, canonicalBinders) -- YL: might need to filter RExprArg out and replace RHole with ghc wildcard@@ -463,6 +485,11 @@ (hsTypeToHsSigWcType (specTypeToLHsType querySpecType)) eeWithLamsCore <- GM.elabRnExpr exprWithTySigs eeWithLamsCore' <- simplify eeWithLamsCore+ -- Preserve refinements on the surrounding signature arguments: they+ -- are the local assumptions under which the predicate occurs. Erase+ -- the refinement on the final value argument (the value whose+ -- predicate we are checking) as well as the synthetic Bool result.+ collect eeWithLamsCore' (eraseCheckedRefinement querySpecType) let (_, tyBinders) = collectSpecTypeBinders@@ -496,6 +523,21 @@ ) -- (GM.dropModuleUnique <$> bs') pure (F.notracepp "result" ret) -- (F.substa )+ eraseCheckedRefinement (RAllT a ty r) = RAllT a (eraseCheckedRefinement ty) r+ eraseCheckedRefinement (RAllP p ty) = RAllP p (eraseCheckedRefinement ty)+ eraseCheckedRefinement (RFun x i arg res r)+ | hasValueArgument res = RFun x i arg (eraseCheckedRefinement res) r+ | otherwise = RFun x i+ (mapReft (const mempty) arg)+ (mapReft (const mempty) res)+ r+ eraseCheckedRefinement ty = mapReft (const mempty) ty++ hasValueArgument (RAllT _ ty _) = hasValueArgument ty+ hasValueArgument (RAllP _ ty) = hasValueArgument ty+ hasValueArgument RFun{} = True+ hasValueArgument _ = False+ isTrivial' :: F.Reft -> Bool isTrivial' (F.Reft (_, F.PTrue)) = True isTrivial' _ = False@@ -629,12 +671,15 @@ brelToHsExpr :: F.Brel -> LHsExpr GhcPs brelToHsExpr brel = noLocA (HsVar Ghc.noExtField (noLocA (f brel))) where- f F.Eq = mkVarUnqual (mkFastString "==")+ f F.Eq = eq_RDR f F.Gt = gt_RDR f F.Lt = lt_RDR f F.Ge = ge_RDR f F.Le = le_RDR- f F.Ne = mkVarUnqual (mkFastString "/=")+ f F.Ne = case Ghc.thRdrNameGuesses False '(/=) of+ [] -> impossible Nothing "brelToExpr: Could not find (/=) in GHC"+ [x] -> x+ _ -> impossible Nothing "brelToExpr: Found multiple (/=) in GHC" f _ = impossible Nothing "brelToExpr: Unsupported operation" symbolToRdrNameNs :: NameSpace -> F.Symbol -> RdrName@@ -692,7 +737,7 @@ REx _ tin tout -> nlHsFunTy (specTypeToLHsType tin) (specTypeToLHsType tout) RAppTy _ (RExprArg _) _ -> impossible Nothing "RExprArg should not appear here"- RAppTy t t' _ -> nlHsFunTy (specTypeToLHsType t) (specTypeToLHsType t')+ RAppTy t t' _ -> nlHsAppTy (specTypeToLHsType t) (specTypeToLHsType t') RRTy _ _ _ t -> specTypeToLHsType t RHole _ -> noLocA $ HsWildCardTy Ghc.noAnn RExprArg _ ->
src/Language/Haskell/Liquid/Bare/Expand.hs view
@@ -310,7 +310,7 @@ expand rtEnv l (F.Reft (v, ra)) = F.Reft (v, expand rtEnv l ra) instance Expand RReft where- expand rtEnv l = fmap (expand rtEnv l)+ expand rtEnv l (MkUReft r p) = MkUReft (expand rtEnv l r) p expandReft :: (Expand r) => BareRTEnv -> F.SourcePos -> RType c tv r -> RType c tv r expandReft rtEnv l = fmap (expand rtEnv l)@@ -366,13 +366,13 @@ , tycPropTy = expand rtEnv l (tycPropTy d) } -instance Expand BareMeasure where+instance Expand (Measure LocBareType ctor) where expand rtEnv l m = m { msSort = expand rtEnv l (msSort m) , msEqns = expand rtEnv l (msEqns m) } -instance Expand BareDef where+instance Expand (Def LocBareType ctor) where expand rtEnv l d = d { dsort = expand rtEnv l (dsort d) , binds = [ (x, expand rtEnv l t) | (x, t) <- binds d]@@ -401,6 +401,8 @@ expandBareSpec :: BareRTEnv -> F.SourcePos -> Ms.BareSpec -> Ms.BareSpec expandBareSpec rtEnv l sp = sp { measures = expand rtEnv l (measures sp)+ , cmeasures = expand rtEnv l (cmeasures sp)+ , imeasures = expand rtEnv l (imeasures sp) , asmSigs = map (second (expand rtEnv l)) (asmSigs sp) , sigs = map (second (expand rtEnv l)) (sigs sp) , ialiases = [ (f x, f y) | (x, y) <- ialiases sp ]@@ -703,7 +705,7 @@ expandEApp :: BareRTEnv -> F.SourcePos -> (Expr, [Expr]) -> Expr expandEApp rtEnv l (EVar f, es) = case mBody of- Just re -> expandApp l re es'+ Just re -> expandExpr rtEnv l (expandApp l re es') Nothing -> F.eApps (EVar f) es' where eAs = M.mapKeys lhNameToResolvedSymbol $ exprAliases rtEnv@@ -800,7 +802,7 @@ t' = ofRSort tx `RT.strengthen` RT.uTop r r = F.exprReft e -expToBindRef :: UReft r -> State ExSt (UReft r)+expToBindRef :: UReft -> State ExSt UReft expToBindRef (MkUReft r (Pr p)) = mapM expToBind p <&> (MkUReft r . Pr) @@ -815,7 +817,7 @@ pargs' <- mapM expToBindParg pargs0 return $ p { pargs = pargs' } -expToBindParg :: (((), F.Symbol, F.Expr), RSort) -> State ExSt ((), F.Symbol, F.Expr)+expToBindParg :: ((NoReft, F.Symbol, F.Expr), RSort) -> State ExSt (NoReft, F.Symbol, F.Expr) expToBindParg ((t, s, e), s') = fmap ((,,) t s) (expToBindExpr e s') expToBindExpr :: F.Expr -> RSort -> State ExSt F.Expr
src/Language/Haskell/Liquid/Bare/Measure.hs view
@@ -296,15 +296,17 @@ (as, ts, xt) = {- F.tracepp ("bkDatacon dc = " ++ F.showpp (dc, n)) $ -} bkDataCon permitTC dc n err = panic Nothing $ "DataCon " ++ show dc ++ "does not have " ++ show i ++ " fields" --- bkDataCon :: DataCon -> Int -> ([RTVar RTyVar RSort], [SpecType], (Symbol, SpecType, RReft))-bkDataCon :: (PPrint r, IsReft r) => Bool -> Ghc.DataCon -> Int -> ([RTVar RTyVar RSort], [RRType r], (F.Symbol, RFInfo, RRType r, r))+-- bkDataCon :: DataCon -> Int -> ([SpecRTVar], [SpecType], (Symbol, SpecType, RReft))+bkDataCon :: (PPrint r, IsReft r) => Bool -> Ghc.DataCon -> Int -> ([SpecRTVar], [RRType r], (F.Symbol, RFInfo, RRType r, r)) bkDataCon permitTC dcn nFlds = (as, ts, (F.dummySymbol, classRFInfo permitTC, t, trueReft)) where- ts = RT.ofType <$> Misc.takeLast nFlds (map Ghc.irrelevantMult _ts)+ ts = RT.ofType <$> Misc.takeLast nFlds _ts+ _ts = if permitTC && Ghc.isClassTyCon (Ghc.dataConTyCon dcn) then dicts ++ ts1 else ts1+ ts1 = map Ghc.irrelevantMult ts0 t = -- Misc.traceShow ("bkDataConResult" ++ GM.showPpr (dc, _t, _t0)) $ RT.ofType $ Ghc.mkTyConApp tc tArgs' as = makeRTVar . RT.rTyVar <$> (αs ++ αs')- ((αs,αs',_,_,_ts,_t), _t0) = hammer dcn+ ((αs,αs',_,dicts,ts0,_t), _t0) = hammer dcn tArgs' = take (nArgs - nVars) tArgs ++ (Ghc.mkTyVarTy <$> αs) nVars = length αs nArgs = length tArgs@@ -412,7 +414,7 @@ -- Undefined ones are those that are not already defined in the measure environement and are not wired dcsUndefinedInLogic = S.filter notWired $ allDCInUnfoldings `S.difference` definedDCs -- Get the defined DataCons from the measure environement- definedDCs = S.fromList $ (GM.idDataConM . fst) `Mb.mapMaybe` Bare.meDataCons measEnv+ definedDCs = S.fromList $ (Ghc.isDataConId_maybe . fst) `Mb.mapMaybe` Bare.meDataCons measEnv allDCInUnfoldings = getDCsOfUnfoldingOfVars vars ----------------------------------------------------@@ -434,7 +436,9 @@ getVar sym = case Bare.lookupGhcIdLHName env sym of Right x -> x Left _ -> panic (Just $ GM.fSrcSpan sym) "function to reflect not in scope"- definedSymbols = getDefinedSymbolsInLogic env measEnv specs+ definedSymbols =+ getDefinedSymbolsInLogic env measEnv specs+ `S.union` S.fromList [F.eqName eq | (_, _, eq) <- eqs] undefinedInLogic v = not (S.member (F.symbol v) definedSymbols) -- Variables to consider varsUndefinedInLogic = S.unions $@@ -590,8 +594,8 @@ isSimpleType :: Ghc.Type -> Bool isSimpleType = isFirstOrder . RT.typeSort mempty -makeClassMeasureSpec :: MSpec (RType c tv (UReft r2)) t- -> [(Located LHName, CMeasure (RType c tv r2))]+makeClassMeasureSpec :: MSpec (RType c tv UReft) t+ -> [(Located LHName, CMeasure (RType c tv F.Reft))] makeClassMeasureSpec Ms.MSpec{..} = tx <$> M.elems cmeasMap where tx (M n s _ _ _) = (n, CM n (mapReft ur_reft s))
src/Language/Haskell/Liquid/Bare/Plugged.hs view
@@ -98,12 +98,20 @@ | mismatchTyVars = Ex.throw (err "type variables") | otherwise = F.atLoc ldcp $ F.notracepp "makePluggedDataCon" $ dcp { dcpFreeTyVars = dcVars+ , dcpTyConstrs = constrs , dcpTyArgs = reverse tArgs , dcpTyRes = tRes } where (tArgs, tRes) = plugMany allowTC embs tyi ldcp (das, dts, dt) (dcVars, dcArgs, dcpTyRes dcp)- (das, _, dts, dt) = {- F.notracepp ("makePluggedDC: " ++ F.showpp dc) $ -} Ghc.dataConSig dc+ (das, theta, originDts, dt) = {- F.notracepp ("makePluggedDC: " ++ F.showpp dc) $ -} Ghc.dataConSig dc+ consClassArgs = if allowTC && isClassDc then filter (not . GM.isEmbeddedDictType) theta else []+ dts = consClassArgs ++ originDts+ isClassDc = Ghc.isClassTyCon (Ghc.dataConTyCon dc)+ -- For class dictionary constructors, the dictionary arguments correspond to+ -- constructor fields and are included in `dts`, and not in `constrs`.+ constrs = if allowTC && isClassDc then [] else dcpTyConstrs dcp+ dcArgs = reverse $ filter (not . (if allowTC then isEmbeddedClass else isClassType) . snd) (dcpTyArgs dcp) dcVars = if isGADT then padGADVars $ L.nub (dcpFreeTyVars dcp ++ concatMap (map ty_var_value . freeTyVars) (dcpTyRes dcp:(snd <$> dcArgs)))@@ -149,7 +157,15 @@ ((xs,_,ts,_), t) = bkArrow (val pT) pT = plugHoles allowTC (Bare.LqTV dcName) embs tyi (const killHoles) hsT (F.atLoc ldcp lqT) hsT = foldr (Ghc.mkFunTy Ghc.FTF_T_T Ghc.ManyTy) hsRes hsArgs'- lqT = foldr (uncurry (rFun' (classRFInfo allowTC))) lqRes lqArgs'+ lqT = foldr (uncurry (rFun' (classRFInfo allowTC))) lqRes' lqArgs'+ -- Substitute the GHC type variables (hsAs) in lqRes with the corresponding+ -- LQ type variables (lqAs). This is needed because lqRes (= dcpTyRes) may+ -- have been derived from ofType/dataConOrigResTy and therefore carries the+ -- actual GHC TyVar objects, while lqAs (= dcpFreeTyVars) was built from+ -- symbolRTyVar and therefore carries distinct synthetic RTyVars.+ -- Without this substitution, runMapTyVars sees the same GHC type variable+ -- mapped to two different Liquid RTyVars and throws an ErrMismatch.+ lqRes' = subts (zip (rTyVar <$> hsAs) lqAs) lqRes hsArgs' = [ Ghc.mkTyVarTy a | a <- hsAs] ++ hsArgs lqArgs' = [(F.dummySymbol, RVar a mempty) | a <- lqAs] ++ map (Bifunctor.first lhNameToUnqualifiedSymbol) lqArgs nTyVars = length hsAs -- == length lqAs@@ -172,7 +188,10 @@ = Loc l l' . mkArrow (zip (updateRTVar <$> αs') rs) ps' [] . makeCls cs'- . goPlug tce tyi err f (subts su rt)+ -- Here `su` maps LH tyvars to GHC tyvars, so goPlug merges two types that+ -- both use GHC tyvars: binders inserted from the GHC side need no renaming,+ -- hence [].+ . goPlug tce tyi [] err f (subts su rt) . mapExprReft (\_ -> F.applyCoSub coSub) . subts su $ st@@ -203,7 +222,7 @@ = Loc l l' . mkArrow (zip (updateRTVar <$> as'') rs) ps [] . makeCls cs'- . goPlug tce tyi err f rt'+ . goPlug tce tyi su err f rt' $ st where rt' = tx rt@@ -230,7 +249,7 @@ = Loc l l' . mkArrow (zip (updateRTVar <$> as'') rs) ps (if length cs > length cs' then cs else cs') -- . makeCls cs'- . goPlug tce tyi err f rt'+ . goPlug tce tyi su err f rt' $ st where rt' = tx rt@@ -256,11 +275,11 @@ subRTVar :: [(RTyVar, RTyVar)] -> SpecRTVar -> SpecRTVar subRTVar su a@(RTVar v i) = Mb.maybe a (`RTVar` i) (lookup v su) -goPlug :: F.TCEmb Ghc.TyCon -> Bare.TyConMap -> (Doc -> Doc -> Error) -> (SpecType -> RReft -> RReft) -> SpecType -> SpecType+goPlug :: F.TCEmb Ghc.TyCon -> Bare.TyConMap -> [(RTyVar, RTyVar)] -> (Doc -> Doc -> Error) -> (SpecType -> RReft -> RReft) -> SpecType -> SpecType -> SpecType-goPlug tce tyi err f = go+goPlug tce tyi su err f = go where- go st (RHole r) = (addHoles t') { rt_reft = f st r }+ go st (RHole r) = mapRBase (const (f st r)) (addHoles t') where t' = everywhere (mkT $ addRefs tce tyi) st addHoles = everywhere (mkT addHole)@@ -273,7 +292,9 @@ go (RVar _ _) v@(RVar _ _) = v go (RFun _ _ i o _) (RFun x ii i' o' r) = RFun x ii (go i i') (go o o') r go (RAllT _ t _) (RAllT a t' r) = RAllT a (go t t') r- go (RAllT a t r) t' = RAllT a (go t t') r+ -- Binder comes from the GHC type but the body uses LH tyvars. Rename it via+ -- `su` or it binds nothing (Issue #2727).+ go (RAllT a t r) t' = RAllT (subRTVar su a) (go t t') r go t (RAllP p t') = RAllP p (go t t') go t (REx b x t') = REx b x (go t t') go t (RRTy e r o t') = RRTy e r o (go t t')@@ -283,8 +304,26 @@ go (RApp _ ts _ _) (RApp c ts' p r) -- Removing length check because Haskell types can contain kinds which is safe based on the comment above -- | length ts == length ts'- = RApp c (Misc.zipWithDef go ts $ Bare.matchKindArgs ts ts') p r+ = RApp c (Misc.zipWithDef go ts $ Bare.matchKindArgs ts ts') (goRProps c ts ts' p) r+ go hsT lqT = Ex.throw (err (F.pprint hsT) (F.pprint lqT))++ -- For dependent tuples, RProp at index j corresponds to the+ -- Haskell type arg at index j+1. Plug RProp bodies so that any+ -- RHole nodes inside them are elaborated against the GHC type+ -- (fixes issue #2590 crash with shorthand refinements).+ goRProps c hsTyArgs lqTyArgs ps+ | isTuple c =+ let hsTs = drop 1 hsTyArgs+ lqTs = drop 1 lqTyArgs+ in zipWith3 goRProp hsTs lqTs ps ++ drop (length hsTs) ps+ -- At the moment nested RHoles in RProp are only introduced by bTup (the+ -- desugaring of dependent tuples). Top-level RHoles in RProp are+ -- introduced by rPropP and eliminated by mkRTProp.+ | otherwise = ps+ goRProp hsT lqT (RProp ss body)+ | RHole{} <- lqT = RProp ss (go hsT body)+ | otherwise = RProp ss body -- otherwise = Ex.throw err -- If we reach the default case, there's probably an error, but we defer
src/Language/Haskell/Liquid/Bare/Resolve.hs view
@@ -309,7 +309,15 @@ -- fail = Misc.errorP "error-ofBareType" . F.showpp ofBareTypeE :: HasCallStack => Env -> F.SourcePos -> Maybe [PVar BSort] -> BareType -> Lookup SpecType-ofBareTypeE env l ps t = ofBRType env (const (resolveReft l ps t)) l t+ofBareTypeE env l ps t =+ ofBRType env rebindUReftBV (const (resolveReft l ps t)) l t+ where+ rebindUReftBV (x, y) (MkUReft (F.Reft (v, e)) p) =+ let su = (x, F.EVar y)+ e' = F.subst1 e su+ p' = F.subst1 p su+ in+ MkUReft (F.Reft (v, e')) p' resolveReft :: F.SourcePos -> Maybe [PVar BSort] -> BareType -> RReft -> RReft resolveReft l ps t@@ -337,7 +345,7 @@ ofBSort env l t = either (Misc.errorP "error-ofBSort" . F.showpp) id (ofBSortE env l t) ofBSortE :: HasCallStack => Env -> F.SourcePos -> BSort -> Lookup RSort-ofBSortE env l t = ofBRType env (const id) l t+ofBSortE env l t = ofBRType env (const id) (const id) l t ofBPVar :: Env -> F.SourcePos -> BPVar -> RPVar ofBPVar env l = fmap (ofBSort env l)@@ -366,6 +374,7 @@ -------------------------------------------------------------------------------- type Expandable r = ( PPrint r , IsReft r+ , Meet r , ReftBind r ~ F.Symbol , ReftVar r ~ F.Symbol , F.Subable r@@ -373,20 +382,37 @@ , SubsTy RTyVar (RType RTyCon RTyVar NoReft) r , HasCallStack) -ofBRType :: (Expandable r) => Env -> ([F.Symbol] -> r -> r) -> F.SourcePos -> BRType r- -> Lookup (RRType r)-ofBRType env f l = go []+ofBRType+ :: (Expandable r)+ => Env+ -> ((F.Symbol, F.Symbol) -> r -> r)+ -> ([F.Symbol] -> r -> r)+ -> F.SourcePos+ -> BRType r+ -> Lookup (RRType r)+ofBRType env rebindR f l = go [] where goReft bs r = return (f bs r)- goRFun bs x i t1 t2 r = RFun x i{permitTC = Just (typeclass (getConfig env))} <$> (rebind x <$> go bs t1) <*> go (x:bs) t2 <*> goReft bs r+ goRFun bs x i t1 t2 r =+ RFun x i{permitTC = Just (typeclass (getConfig env))}+ <$> (rebind x <$> go bs t1)+ <*> go (x:bs) t2+ <*> goReft bs r -- See the documentation of 'RFun' for what rebind accomplishes.- rebind x t = F.subst1 t (x, F.EVar $ rTypeValueVar t)+ rebind x t =+ let su = (x, rTypeValueVar t)+ in mapReftRecs (`F.subst1` (F.EVar <$> su)) (`F.subst1` (F.EVar <$> su)) (mapRBase (rebindR su) t) go bs (RAppTy t1 t2 r) = RAppTy <$> go bs t1 <*> go bs t2 <*> goReft bs r go bs (RApp tc ts rs r) = goRApp bs tc ts rs r go bs (RFun x i t1 t2 r) = goRFun bs x i t1 t2 r go bs (RVar a r) = RVar (RT.bareRTyVar a) <$> goReft bs r- go bs (RAllT a t r) = RAllT a' <$> go bs t <*> goReft bs r- where a' = dropTyVarInfo (mapTyVarValue RT.bareRTyVar a)+ go bs (RAllT (RTVar v i) t r) = RAllT <$> a' <*> go bs t <*> goReft bs r+ where a' = case i of+ RTVInfo{} -> do+ k' <- ofBSortE env l (rtv_kind i)+ pure $ RTVar (RT.bareRTyVar v) i {rtv_kind = k'}+ RTVNoInfo is_pol ->+ pure $ RTVar (RT.bareRTyVar v) (RTVNoInfo is_pol) go bs (RAllP a t) = RAllP a' <$> go bs t where a' = ofBPVar env l a go bs (REx x t1 t2) = REx x <$> go bs t1 <*> go (x:bs) t2@@ -401,6 +427,21 @@ where lc' = F.atLoc lc <$> lookupGhcTyConLHName (reTyLookupEnv env) lc lc = btc_tc tc++ -- | Applies the given functions to the recursive occurrences of the RTypeV,+ -- but only where rTypeReft retrieves a value.+ --+ -- This is needed when rebinding to ensure that name changes are applied+ -- over the scope of the names.+ mapReftRecs+ :: (RTypeBV b v c tv r -> RTypeBV b v c tv r)+ -> (RTPropBV b v c tv r -> RTPropBV b v c tv r)+ -> RTypeBV b v c tv r -> RTypeBV b v c tv r+ mapReftRecs ft gt (RApp c ts rs r) = RApp c (ft <$> ts) (gt <$> rs) r+ mapReftRecs ft _ (RFun x i t t' r) = RFun x i (ft t) (ft t') r+ mapReftRecs ft _ (RAppTy t t' r) = RAppTy (ft t) (ft t') r+ mapReftRecs ft _ (RAllT α t r) = RAllT α (ft t) r+ mapReftRecs _ _ t = t lookupGhcTyConLHName :: HasCallStack => GHCTyLookupEnv -> Located LHName -> Lookup Ghc.TyCon lookupGhcTyConLHName env lc = do
src/Language/Haskell/Liquid/Bare/ToBare.hs view
@@ -74,10 +74,11 @@ goPV = txPV cF vF txRTV :: (c1 -> c2) -> (tv1 -> tv2) -> RTVU c1 tv1 -> RTVU c2 tv2-txRTV cF vF (RTVar α z) = RTVar (vF α) (txRType cF vF <$> z)+txRTV _cF vF (RTVar α (RTVNoInfo p)) = RTVar (vF α) (RTVNoInfo p)+txRTV cF vF (RTVar α ri@RTVInfo{rtv_kind=k}) = RTVar (vF α) ri{rtv_kind = txRType cF vF k} txPV :: (c1 -> c2) -> (tv1 -> tv2) -> PVU c1 tv1 -> PVU c2 tv2-txPV cF vF (PV sym k y txes) = PV sym k' y txes'+txPV cF vF (PV sym k txes) = PV sym k' txes' where txes' = [ (tx t, x, e) | (t, x, e) <- txes] k' = tx k
src/Language/Haskell/Liquid/Bare/Typeclass.hs view
@@ -15,6 +15,7 @@ import Control.Monad ( forM, guard ) import Data.Bifunctor (second)+import Data.Char (isDigit) import qualified Data.List as L import qualified Data.HashSet as S import Data.Hashable ()@@ -90,10 +91,6 @@ methods = [ makeGHCLHNameLocatedFromId x | (_, xs) <- instmethods, x <- xs ] -- instance methods - mkSymbol x- | Ghc.isDictonaryId x = F.mappendSym "$" (F.dropSym 2 $ GM.simplesymbol x)- | otherwise = F.dropSym 2 $ GM.simplesymbol x- instmethods :: [(Ghc.ClsInst, [Ghc.Var])] instmethods = [ (inst, ms)@@ -111,7 +108,7 @@ instClss = [ (inst, cls) | inst <- mconcat . Mb.maybeToList . _gsCls $ src- , Ghc.moduleName (Ghc.nameModule (Ghc.getName inst)) == getModName name+ , (Ghc.moduleName <$> Ghc.nameModule_maybe (Ghc.getName inst)) == Just (getModName name) , let cls = Ghc.is_cls inst , cls `elem` refinedClasses ]@@ -124,7 +121,6 @@ either (const Nothing) Just (Bare.lookupGhcTyConLHName (Bare.reTyLookupEnv env) $ dataNameSymbol $ tycName d) >>= Ghc.tyConClass_maybe - -- a list of class with user defined refinements makeClassDataDecl :: [(Ghc.Class, [(Ghc.Id, LocBareType)])] -> [DataDecl] makeClassDataDecl = fmap (uncurry classDeclToDataDecl)@@ -391,12 +387,7 @@ -- Monoid.mappend, ... clsMethods = filter (\x -> GM.dropModuleNames (F.symbol x) `elem` fmap mkSymbol methods) $ Ghc.classAllSelIds (Ghc.is_cls inst)- yts = [(lhNameToResolvedSymbol y, t) | (y, t) <- dcpTyArgs dcp]- mkSymbol x- | -- F.notracepp ("isDictonaryId:" ++ GM.showPpr x) $- Ghc.isDictonaryId x = F.mappendSym "$" (F.dropSym 2 $ GM.simplesymbol x)- | otherwise = F.dropSym 2 $ GM.simplesymbol x- -- res = dcpTyRes dcp+ yts = [(lhNameToUnqualifiedSymbol y, t) | (y, t) <- dcpTyArgs dcp] clsTvs = dcpFreeTyVars dcp -- copy/pasted from Bare/Class.hs subst [] t = t@@ -427,3 +418,19 @@ go (F.PIff e0 e1) = F.PIff (go e0) (go e1) go (F.PAtom brel e0 e1) = F.PAtom brel (go e0) (go e1) go e = F.notracepp "LEAF" e++-- Normalise typeclass names for looking up class selector symbols.+-- Instance methods are named `$c(method)`. GHC 9 can also expose superclass+-- dictionary bindings named `$cp(n)(Class)`, where (n) is the index of the+-- superclass. These correspond to `$p(n)(Class)` selector symbols.+-- Since class methods are always identified by variables with the `$c`+-- prefix, we can ignore other cases.+-- The digit is what distinguishes a superclass binding from a method whose+-- name starts with 'p'.+mkSymbol :: Ghc.Var -> F.Symbol+mkSymbol x =+ case Ghc.getOccString x of+ '$' : 'c' : 'p' : rest@(d : _)+ | isDigit d -> F.symbol ('$' : 'p' : rest)+ '$' : 'c' : rest -> F.symbol rest+ occ -> impossible Nothing $ "mkSymbol : should only be called with class methods, received " ++ F.showpp occ
src/Language/Haskell/Liquid/Constraint/Generate.hs view
@@ -12,7 +12,6 @@ {-# OPTIONS_GHC -Wno-orphans #-} {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}-{-# OPTIONS_GHC -Wno-incomplete-record-selectors #-} -- | This module defines the representation of Subtyping and WF Constraints, -- and the code for syntax-directed constraint generation.@@ -38,7 +37,6 @@ import qualified Data.HashMap.Strict as M import qualified Data.HashSet as S import qualified Data.List as L-import qualified Data.Foldable as F import qualified Data.Functor.Identity import Language.Fixpoint.Misc (errorP, safeZip ) import Language.Fixpoint.Types.Visitor@@ -68,9 +66,10 @@ import Language.Haskell.Liquid.Constraint.RewriteCase import Language.Haskell.Liquid.Transforms.CoreToLogic (weakenResult, runToLogic, coreToLogic) import Language.Haskell.Liquid.Bare.DataType (dataConMap, makeDataConChecker)+import Language.Haskell.Liquid.Bare.Misc (simpleSymbolVar) import Language.Haskell.Liquid.UX.Config ( HasConfig(getConfig),- Config(typeclass, checkDerived, extensionality,+ Config(typeclass, extensionality, nopolyinfer, dependantCase, rankNTypes, warnOnTermHoles), patternFlag, higherOrderFlag, warnOnTermHoles )@@ -138,6 +137,24 @@ -- -- https://odr.chalmers.se/server/api/core/bitstreams/640ee29b-b13a-44d5-9e20-200a91a11021/content ++-- Note [Newtype checking]+--+-- Unlike regular data types, newtypes do not show up in core with data+-- constructors and selectors. Instead, they are represented with coercions+-- between the newtype and its representation type.+--+-- We make sure to interpret these coercions as either data constructor+-- applications or as selectors when generating constraints+-- ('castTyNewtypeWrap') and when reflecting code to the logic+-- ('Language.Haskell.Liquid.Transforms.CoreToLogic.newtypeCoercionDataCon').+--+-- Because pattern matching on newtypes is erased in core, we also need to make+-- sure that LH inserts the appropriate predicates from measures and from the+-- refinement types of the newtype's representation where there is a binding to+-- a value of a newtype. This is done with invariants+-- ('Language.Haskell.Liquid.Bare.makeNewtypeInvariants').+ -------------------------------------------------------------------------------- -- | Constraint Generation: Toplevel ------------------------------------------- --------------------------------------------------------------------------------@@ -324,7 +341,7 @@ xs = bindersOf cb tt = trueTy (typeclass cfg) . varType addB γ x = tt x >>= (\t -> γ += ("derived", F.symbol x, t))- trustVar x = not (checkDerived cfg) && derivedVar (giSrc info) x+ trustVar x = derivedVar (giSrc info) x consCBTop _ _ γ cb = do oldtcheck <- gets tcheck@@ -471,7 +488,7 @@ return $ Asserted t killSubst :: RReft -> RReft-killSubst = fmap killSubstReft+killSubst = mapReftField killSubstReft killSubstReft :: F.Reft -> F.Reft killSubstReft = trans ks@@ -483,7 +500,7 @@ -- Used during type application to record how type variables are instantiated, -- so the solver can apply the correct sort substitution to qualifier solutions. addTyVarSubToKVars :: F.Symbol -> F.Sort -> SpecType -> SpecType-addTyVarSubToKVars sym sort = fmap (fmap (trans addSub))+addTyVarSubToKVars sym sort = mapReft (mapReftField (trans addSub)) where addSub (F.PKVar k tsu su) = let tsu' = M.map (F.applyCoercion sym sort) tsu@@ -616,7 +633,7 @@ = cconsE γ (f e) t cconsE' γ e@(Cast e' c) t- = do t' <- (`strengthen` uTop (rTypeReft t)) <$> castTy γ (exprType e) e' c+ = do t' <- castTy γ (exprType e) e' c addC (SubC γ (F.notracepp ("Casted Type for " ++ GM.showPpr e ++ "\n init type " ++ showpp t) t') t) ("cconsE Cast: " ++ GM.showPpr e) cconsE' γ e t@@ -635,7 +652,7 @@ addHole (RealSrcSpan srcSpan Strict.Nothing) x t γ _ -> return () -lambdaSingleton :: CGEnv -> F.TCEmb TyCon -> Var -> CoreExpr -> CG (UReft F.Reft)+lambdaSingleton :: CGEnv -> F.TCEmb TyCon -> Var -> CoreExpr -> CG UReft lambdaSingleton γ tce x e | higherOrderFlag γ = do expr <- lamExpr γ e@@ -741,9 +758,9 @@ = do t0 <- varRefType γ x -- NV: The check is expected to fail most times, so -- it is cheaper than direclty fmap ignoreSelf.- let hasSelf = selfSymbol `elem` F.syms t0+ let hasSelf = selfSymbol `S.member` F.syms t0 let t = if hasSelf- then fmap ignoreSelf <$> t0+ then mapReft (mapReftField ignoreSelf) t0 else t0 addLocA (Just x) (getLocation γ) (varAnn γ x t) return t@@ -756,6 +773,10 @@ consE _ (Lit c) = refreshVV $ uRType $ literalFRefType c +consE γ e@App{}+ | Just l <- boxedLiteralExpr γ e+ = refreshVV $ strengthenMeet (ofType $ exprType e) (uTop $ F.exprReft l)+ consE γ e'@(App _ _) = do t <- if warnOnTermHoles (getConfig γ) then synthesizeWithHole else consEApp γ e'@@ -1019,16 +1040,37 @@ return (fromMaybe sp msp) castTy γ t e (SymCo (AxiomCo ca _))- = do mtc <- case isNewtypeAxiomRule_maybe ca of- Just (tc, _) -> lookupNewType tc- _ -> return Nothing- F.forM_ mtc (cconsE γ e)- castTy' γ t e+ | Just (tc, _) <- isNewtypeAxiomRule_maybe ca+ = do+ -- When the user gave an explicit @{-@ newtype … @-}@ spec, we must also+ -- check the representation @e@ against the declared field invariant.+ mtc <- lookupNewType tc+ forM_ mtc $ cconsE γ e+ -- A newtype wrap is, logically, the constructor applied to @e@. Whenever+ -- possible we type it as that constructor application ('castTyNewtypeWrap')+ -- the same as in the @data@ case.+ case Ghc.tyConSingleDataCon_maybe tc of+ Just dc -> castTyNewtypeWrap γ t e dc+ Nothing -> castTy' γ t e castTy γ t e _ = castTy' γ t e +-- | A @newtype@ /wrap/ cast @e |> Sym (Rep ~ NT)@ is, logically, the newtype+-- constructor applied to @e@. We type the equivalent constructor application+-- @MkNT \@ts e@, which reuses the datacon's refined type carrying the+-- measure/selector refinements. This makes measures over a @newtype@ reduce+-- just like their @data@ counterparts.+--+-- See note [Newtype checking]+castTyNewtypeWrap :: CGEnv -> Type -> CoreExpr -> Ghc.DataCon -> CG SpecType+castTyNewtypeWrap γ τ e dc+ | Just (_, tyArgs) <- Ghc.splitTyConApp_maybe τ+ = consE γ (foldl App (Var (Ghc.dataConWorkId dc)) (map Type tyArgs ++ [e]))+ | otherwise+ = castTy' γ τ e + castTy' γ τ (Var x) = do t0 <- trueTy (typeclass (getConfig γ)) τ tx <- varRefType γ x@@ -1134,7 +1176,7 @@ checkUnbound :: (PPrint a, Show a2, F.Subable a, F.Variable a ~ F.Symbol) => CGEnv -> CoreExpr -> F.Symbol -> a -> a2 -> a checkUnbound γ e x t a- | x `notElem` F.syms t = t+ | not (x `S.member` F.syms t) = t | otherwise = panic (Just $ getLocation γ) msg where msg = unlines [ "checkUnbound: " ++ show x ++ " is elem of syms of " ++ showpp t@@ -1214,14 +1256,14 @@ -- SELF special substitutions ------------------------------------------------------ -substSelf :: UReft F.Reft -> UReft F.Reft+substSelf :: UReft -> UReft substSelf (MkUReft r p) = MkUReft (substSelfReft r) p substSelfReft :: F.Reft -> F.Reft substSelfReft (F.Reft (v, e)) = F.Reft (v, F.subst1 e (selfSymbol, F.EVar v)) ignoreSelf :: F.Reft -> F.Reft-ignoreSelf = F.mapExpr (\r -> if selfSymbol `elem` F.syms r then F.PTrue else r)+ignoreSelf = F.mapExpr (\r -> if selfSymbol `S.member` F.syms r then F.PTrue else r) -------------------------------------------------------------------------------- -- | `projectTypes` masks (i.e. true's out) all types EXCEPT those@@ -1248,7 +1290,7 @@ unfoldR td (RApp _ ts rs _) ys = (t3, tvys ++ yts, ignoreOblig rt) where tbody = instantiatePvs (instantiateTys td ts) (reverse rs)- ((ys0,_,yts',_), rt) = safeBkArrow (F.notracepp msg $ instantiateTys tbody tvs')+ ((ys0,_,yts',_), rt) = safeBkArrow (F.notracepp msg $ defaultPvs $ instantiateTys tbody tvs') msg = "INST-TY: " ++ F.showpp (td, ts, tbody, ys, tvs') yts'' = zipWith F.subst sus (yts'++[rt]) (t3,yts) = (last yts'', init yts'')@@ -1272,6 +1314,24 @@ go (RAllP p tbody) r = replacePreds "instantiatePv" tbody [(p, r)] go t _ = errorP "" ("Constraint.instantiatePvs: t = " ++ showpp t) +-- | @defaultPvs@ instantiates any leftover abstract-refinement binders (i.e.+-- 'RAllP') with a trivial (i.e. @True@) predicate. This is needed when the+-- scrutinee's type carries fewer abstract-refinement arguments than the data+-- constructor expects. That happens, for example, when the scrutinee's type+-- is derived directly from a GHC 'Type' (as for @ignore@d bindings), since+-- @ofType@ produces an 'RApp' with an empty list of predicate arguments,+-- while the constructor's type (e.g. the dependent-pair encoding of tuples)+-- still quantifies over the abstract refinement.+--+-- See IgnoreTupleAbsRef for an example that used to crash without this+-- function.+defaultPvs :: SpecType -> SpecType+defaultPvs (RAllP p tbody) = defaultPvs (replacePreds "defaultPvs" tbody [(p, trueSpecProp p)])+defaultPvs t = t++trueSpecProp :: RPVar -> SpecProp+trueSpecProp p = RProp [(s, t) | (t, s, _) <- pargs p] (ofRSort (pvType p))+ checkTyCon :: (Outputable a) => (String, a) -> CGEnv -> SpecType -> SpecType checkTyCon _ _ t@RApp{} = t checkTyCon x g t = checkErr x g t@@ -1298,7 +1358,7 @@ -- | Helpers: Creating Fresh Refinement ------------------------------- ----------------------------------------------------------------------- freshPredRef :: CGEnv -> CoreExpr -> PVar RSort -> CG SpecProp-freshPredRef γ e (PV _ rsort _ as)+freshPredRef γ e (PV _ rsort as) = do t <- freshTyType (typeclass (getConfig γ)) PredInstE e (toType False rsort) args <- mapM (const fresh) as let targs = [(x, s) | (x, (s, y, z)) <- zip args as, F.EVar y == z ]@@ -1322,6 +1382,7 @@ argExpr :: CGEnv -> CoreExpr -> Maybe F.Expr argExpr _ (Var v) = Just $ F.eVar v argExpr γ (Lit c) = snd $ literalConst (emb γ) c+argExpr γ e@App{} | Just l <- boxedLiteralExpr γ e = Just l argExpr γ (Tick _ e) = argExpr γ e argExpr γ (App e (Type _)) = argExpr γ e argExpr _ _ = Nothing@@ -1368,6 +1429,8 @@ -- | create singleton types for function application makeSingleton :: CGEnv -> CoreExpr -> SpecType -> SpecType makeSingleton γ cexpr t+ | Just e <- boxedLiteralExpr γ (simplify cexpr)+ = strengthenMeet t (uTop $ F.exprReft e) | higherOrderFlag γ, App f x <- simplify cexpr = case (funExpr γ f, argForAllExpr x) of (Just f', Just x')@@ -1390,8 +1453,22 @@ argForAllExpr e = argExpr γ e +boxedLiteralExpr :: CGEnv -> CoreExpr -> Maybe F.Expr+boxedLiteralExpr γ e+ | (Var box, args) <- collectArgs e+ , [Lit c] <- filter isTermArg args+ , box == dataConWorkId intDataCon+ || simpleSymbolVar box `elem` ["I#", "W#", "F#", "D#"]+ = snd $ literalConst (emb γ) c+boxedLiteralExpr _ _ = Nothing +isTermArg :: CoreExpr -> Bool+isTermArg Type{} = False+isTermArg Coercion{} = False+isTermArg _ = True ++ funExpr :: CGEnv -> CoreExpr -> Maybe F.Expr funExpr _ (Var v)@@ -1416,7 +1493,7 @@ simplify e = e -singletonReft :: (F.Symbolic a) => a -> UReft F.Reft+singletonReft :: (F.Symbolic a) => a -> UReft singletonReft = uTop . F.symbolReft . F.symbol -- | RJ: `nomeet` replaces `strengthenS` for `strengthen` in the definition
src/Language/Haskell/Liquid/Constraint/Init.hs view
@@ -29,7 +29,7 @@ import Language.Haskell.Liquid.Constraint.Env import Language.Haskell.Liquid.WiredIn (dictionaryVar) import qualified Language.Haskell.Liquid.GHC.SpanStack as Sp-import Language.Haskell.Liquid.GHC.Misc ( idDataConM, hasBaseTypeVar, isDataConId) -- dropModuleNames, simplesymbol)+import Language.Haskell.Liquid.GHC.Misc ( hasBaseTypeVar, isDataConId) -- dropModuleNames, simplesymbol) import Liquid.GHC.API as Ghc import Language.Fixpoint.Misc import Language.Haskell.Liquid.Constraint.Types@@ -72,7 +72,7 @@ fi <- refreshArgs' $ catMaybes $ [(x,) . val <$> getMethodType mt | (x, mt) <- gsMethods $ gsSig $ giSpec info ] (invs1, f41) <- traverse refreshArgs' $ makeAutoDecrDataCons dcsty (gsAutosize (gsTerm sp)) dcs (invs2, f42) <- traverse refreshArgs' $ makeAutoDecrDataCons dcsty' (gsAutosize (gsTerm sp)) dcs'- let f4 = mergeDataConTypes tce (mergeDataConTypes tce f40 (f41 ++ f42)) (filter (isDataConId . fst) f2)+ let f4 = mergeDataConTypes tce (mergeDataConTypes tce f40 (f41 ++ f42)) (filter (isDataConId . fst) (f2 ++ f3)) let tx = first F.symbol . addRInv ialias . predsUnify sp f6 <- map tx . addPolyInfo' <$> refreshArgs' (vals gsRefSigs (gsSig sp)) let bs = (tx <$> ) <$> [f0 ++ f0' ++ fi, f1 ++ f1', f2, f3 ++ f3', f4, f5]@@ -110,6 +110,13 @@ makeDataConTypes :: Bool -> Var -> CG (Var, SpecType) makeDataConTypes allowTC x = (x,) <$> trueTy allowTC (varType x) +-- | Refines the data constructors of every autosized type with an equation for+-- the @autolen@ measure, and returns one invariant per refined type stating+-- that the size is non-negative.+--+-- @dcts@ gives the unrefined type of every constructor, @specenv@ the types+-- declared @autosize@ and @dcs@ the constructors in scope. Constructors of a+-- type that was not declared @autosize@ are left alone. makeAutoDecrDataCons :: [(Id, SpecType)] -> S.HashSet TyCon -> [Id] -> ([LocSpecType], [(Id, SpecType)]) makeAutoDecrDataCons dcts specenv dcs = (simplify rsorts, tys)@@ -118,7 +125,7 @@ tycons = L.nub $ mapMaybe idTyCon dcs go tycon- | S.member tycon specenv = zipWith (makeSizedDataCons dcts) (tyConDataCons tycon) [0..]+ | S.member tycon specenv = zipWith (makeSizedDataCons specenv dcts) (tyConDataCons tycon) [0..] go _ = [] @@ -126,20 +133,30 @@ invariant = MkUReft (F.Reft (F.vv_, F.PAtom F.Ge (lenOf F.vv_) (F.ECon $ F.I 0)) ) mempty idTyCon :: Id -> Maybe TyCon-idTyCon = fmap dataConTyCon . idDataConM+idTyCon = fmap dataConTyCon . Ghc.isDataConId_maybe lenOf :: F.Symbol -> F.Expr lenOf x = F.mkEApp lenLocSymbol [F.EVar x] -makeSizedDataCons :: [(Id, SpecType)] -> DataCon -> Integer -> (RSort, (Id, SpecType))-makeSizedDataCons dcts x' n = (toRSort $ ty_res trep, (x, fromRTypeRep trep{ty_res = tres}))+-- | Refines the result type of @x'@, the @n@-th constructor of its type, with+-- an equation that puts its size at @n@ plus the size of every field whose+-- own type is autosized. Also returns the result sort, which+-- 'makeAutoDecrDataCons' turns into the non-negativity invariant.+--+-- Every autosized field counts, so the size grows along an edge between two+-- mutually recursive types. A field of a type that is not autosized has no+-- @autolen@ of its own and contributes nothing.+makeSizedDataCons :: S.HashSet TyCon -> [(Id, SpecType)] -> DataCon -> Integer -> (RSort, (Id, SpecType))+makeSizedDataCons specenv dcts x' n = (toRSort $ ty_res trep, (x, fromRTypeRep trep{ty_res = tres})) where x = dataConWorkId x' st = fromMaybe (impossible Nothing "makeSizedDataCons: this should never happen") $ L.lookup x dcts trep = toRTypeRep st tres = ty_res trep `strengthen` MkUReft (F.Reft (F.vv_, F.PAtom F.Eq (lenOf F.vv_) computelen)) mempty - recarguments = filter (\(t,_) -> toRSort t == toRSort tres) (zip (ty_args trep) (ty_binds trep))+ recarguments = filter (autosized . fst) (zip (ty_args trep) (ty_binds trep))+ autosized (RApp c _ _ _) = S.member (rtc_tc c) specenv+ autosized _ = False computelen = foldr (F.EBin F.Plus) (F.ECon $ F.I n) (lenOf . snd <$> recarguments) mergeDataConTypes :: F.TCEmb TyCon -> [(Var, SpecType)] -> [(Var, SpecType)] -> [(Var, SpecType)]
src/Language/Haskell/Liquid/Constraint/Qualifier.hs view
@@ -10,7 +10,7 @@ where import Prelude hiding (error)-import Data.List (delete, nub, partition)+import Data.List (partition) import Data.Maybe (isJust, catMaybes, fromMaybe, isNothing) import qualified Data.HashSet as S import qualified Data.HashMap.Strict as M@@ -186,14 +186,13 @@ insertsSEnv' = foldr (\(x, t) γ -> insertSEnv x (rTypeSort tce t) γ) -refTopQuals :: (PPrint t, IsReft t, ReftBind t ~ Symbol, ReftVar t ~ Symbol, SubsTy RTyVar RSort t)- => SEnv Sort+refTopQuals :: SEnv Sort -> ElabFlags -> SourcePos -> TCEmb TyCon -> RType RTyCon RTyVar r -> SEnv Sort- -> RRType (UReft t)+ -> SpecType -> [Qualifier] refTopQuals lEnv ef l tce t0 γ rrt = [ mkQ' v so pa | let (RR so (Reft (v, ra))) = rTypeSortedReft tce rrt@@ -239,7 +238,7 @@ -> Qualifier mkQual lEnv l _ γ v so p = mkQ "Auto" ((v, so) : xts) p l where- xs = delete v $ nub $ syms p+ xs = S.toList (S.delete v $ syms p) xts = catMaybes $ zipWith (envSort l lEnv γ) xs [0..] envSort :: SourcePos -> SEnv Sort -> SEnv Sort -> Symbol -> Integer -> Maybe (Symbol, Sort)
src/Language/Haskell/Liquid/Constraint/Relational.hs view
@@ -15,7 +15,6 @@ import Control.Monad (foldM, forM_) import Data.Bifunctor ( Bifunctor(bimap) )-import qualified Data.HashMap.Strict as M import qualified Data.List as L import Data.String ( IsString(..) ) import qualified Language.Fixpoint.Types as F@@ -31,12 +30,11 @@ , CoreBndr , CoreExpr , Expr(..)- , Type(..)+ , Type , TyVar , Var(..)) import qualified Liquid.GHC.API as Ghc import qualified Language.Haskell.Liquid.GHC.Misc as GM-import Language.Haskell.Liquid.GHC.Play (Subable(sub, subTy)) import qualified Language.Haskell.Liquid.GHC.SpanStack as Sp import Language.Haskell.Liquid.GHC.TypeRep () import Language.Haskell.Liquid.Misc@@ -163,7 +161,9 @@ forM_ (refts t1 ++ refts t2) (\r -> entlFunReft γ r "consRelCheckBind Rec") let xs' = zipWith mkRelCopies xs1 xs2 let (xs1', xs2') = unzip xs'- let (e1'', e2'') = L.foldl' subRel (e1', e2') (zip xs1 xs2)+ -- Strip lambdas first, then substitute in the bodies where xs are free+ let body1 = subVars xs1 xs1' (xbody e1')+ body2 = subVars xs2 xs2' (xbody e2') γ' <- γ += ("Bind Rec f1", F.symbol f1', t1) >>= (+= ("Bind Rec f2", F.symbol f2', t2)) γ'' <- foldM (\γγ (x, t) -> γγ += ("Bind Rec x1", F.symbol x, t)) γ' (zip (xs1' ++ xs2') (ts1 ++ ts2)) let vs2xs = F.subst $ F.mkSubst $ zip (vs1 ++ vs2) $ map (F.EVar . F.symbol) (xs1' ++ xs2')@@ -173,7 +173,7 @@ map vs2xs [F.PAnd fo, a] let p' = unapp rp (zip vs1 vs2) let ψ' = ho ++ ψ- consRelCheck γ''' ψ' (xbody e1'') (xbody e2'') (vs2xs $ ret t1) (vs2xs $ ret t2) (vs2xs $ concl (fromRelExpr p'))+ consRelCheck γ''' ψ' body1 body2 (vs2xs $ ret t1) (vs2xs $ ret t2) (vs2xs $ concl (fromRelExpr p')) where a = fromRelExpr ra p = fromRelExpr rp@@ -181,7 +181,6 @@ (e1', e2') = subRelCopies e1 f1 e2 f2 unapp :: RelExpr -> [(F.Symbol, F.Symbol)] -> RelExpr unapp = L.foldl' (\p' (v1, v2) -> unapplyRelArgsR v1 v2 p')- subRel (e1'', e2'') (x1, x2) = subRelCopies e1'' x1 e2'' x2 consRelCheckBind _ _ (Rec [(_, e1)]) (Rec [(_, e2)]) t1 t2 _ rp = F.panic $ "consRelCheckBind Rec: exprs, types, and pred should have same number of args " ++@@ -694,8 +693,22 @@ subRelCopies e1 x1 e2 x2 = (subVarAndTy x1 evar1 e1, subVarAndTy x2 evar2 e2) where (evar1, evar2) = mkRelCopies x1 x2 +-- | Rename a variable in a CoreExpr. subVarAndTy :: Var -> Var -> CoreExpr -> CoreExpr-subVarAndTy x v = subTy (M.singleton x $ TyVarTy v) . sub (M.singleton x $ Var v)+subVarAndTy x v e = Ghc.substExpr subst e+ where+ inScope = Ghc.mkInScopeSet (Ghc.exprFreeVars e `Ghc.extendVarSet` v)+ vE = if Ghc.isTyVar x then Type (Ghc.TyVarTy v) else Var v+ subst = Ghc.extendSubst (Ghc.mkEmptySubst inScope) x vE++-- | Rename multiple variables in a CoreExpr at once.+subVars :: [Var] -> [Var] -> CoreExpr -> CoreExpr+subVars xs vs e = Ghc.substExpr subst e -- (M.fromList (zip xs (Var <$> vs)))+ where+ fvs = Ghc.exprFreeVars e `Ghc.extendVarSetList` vs+ inScope = Ghc.mkInScopeSet fvs+ subst = Ghc.extendIdSubstList (Ghc.mkEmptySubst inScope)+ [ (x, Var v) | (x, v) <- zip xs vs ] mkRelCopies :: Var -> Var -> (Var, Var) mkRelCopies x1 x2 = (mkCopyWithSuffix relSuffixL x1, mkCopyWithSuffix relSuffixR x2)
src/Language/Haskell/Liquid/Constraint/RewriteCase.hs view
@@ -1,4 +1,3 @@-{-# OPTIONS_GHC -Wno-incomplete-record-selectors #-} module Language.Haskell.Liquid.Constraint.RewriteCase (getCaseRewrites) where
src/Language/Haskell/Liquid/Constraint/Split.hs view
@@ -5,9 +5,23 @@ {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-} --------------------------------------------------------------------------------- -- | Constraint Splitting ---------------------------------------------------------------------------------------------------------------------------------------+--+-- Constraint splitting is the process of decomposing high-level subtyping+-- constraints between LiquidHaskell refinement types into low-level Horn+-- clauses that the Liquid Fixpoint solver can check.+--+-- A subtyping constraint @t1 <: t2@ between two 'SpecType' values is created+-- during constraint generation (Generate.hs) whenever LH needs to verify that+-- one type is a subtype of another (e.g., function argument vs. parameter type,+-- branch types, etc.). These constraints are represented as @SubC γ t1 t2@+-- where @γ@ is the typing environment.+--+-- 'splitC' recursively walks the structure of @t1@ and @t2@ simultaneously,+-- peeling off type constructors until it reaches base refinements, at which+-- point it calls 'bsplitC' to emit a fixpoint `SubC`+-- (a Horn clause of the form @∀ binds. lhs-reft ⟹ rhs-reft@).+-- module Language.Haskell.Liquid.Constraint.Split ( @@ -140,7 +154,7 @@ splitfWithVariance f t1 t2 Covariant = f t1 t2 splitfWithVariance f t1 t2 Contravariant = f t2 t1 -updateEnv :: CGEnv -> RTVar RTyVar (RType RTyCon RTyVar b0) -> CG CGEnv+updateEnv :: CGEnv -> RTVar F.Symbol F.Symbol RTyCon RTyVar -> CG CGEnv updateEnv γ a | Just (x, s) <- rTVarToBind a = γ += ("splitS RAllT", x, fmap (const mempty) s)@@ -314,7 +328,7 @@ addLhsInv :: CGEnv -> SpecType -> SpecType addLhsInv γ t = addRTyConInv (invs γ) t `strengthen` r where- r = (mempty :: UReft F.Reft) { ur_reft = F.Reft (F.dummySymbol, p) }+ r = (mempty :: UReft) { ur_reft = F.Reft (F.dummySymbol, p) } p = constraintToLogic rE' (lcs γ) rE' = insertREnv v t (renv γ) v = rTypeValueVar t
src/Language/Haskell/Liquid/Constraint/Termination.hs view
@@ -184,9 +184,15 @@ autoenv <- gets autoSize ts <- forM ts' $ T.mapM refreshArgs let vs = zipWith collectArgs' ts es- is <- mapM makeDecrIndex (zip vars ts) >>= checkSameLens+ is0 <- mapM makeDecrIndex (zip vars ts) >>= checkSameLens+ sameTys <- checkEqTypes =<< mapM checkIndex (zip4 vars vs ts is0)+ -- The size function of a group is taken from the type of one decreasing+ -- parameter and applied to all of them, so a group whose parameters have+ -- different types has no metric to build. Drop it: building one anyway+ -- produces a refinement the solver cannot sort check, and the error from+ -- checkEqTypes never gets seen.+ let is = if sameTys then is0 else Nothing <$ is0 let xeets = zipWith (\v i -> [((v,i), x) | x <- zip3 vars is $ map unTemplate ts]) vs is- _ <- mapM checkIndex (zip4 vars vs ts is) >>= checkEqTypes let rts = (recType autoenv <$>) <$> xeets γ' <- foldM extender γ (zip vars ts) let γs = zipWith makeRecInvariants [γ' `setTRec` zip vars rts' | rts' <- rts] (filter (not . noMakeRec) <$> vs)@@ -198,19 +204,26 @@ (vars, es) = unzip xes dxs = F.pprint <$> vars collectArgs' = collectArguments . length . ty_binds . toRTypeRep . unOCons . unTemplate- checkEqTypes :: [Maybe SpecType] -> CG [SpecType]- checkEqTypes x = checkAllVsHead err1 toRSort (catMaybes x)+ checkEqTypes :: [Maybe SpecType] -> CG Bool+ checkEqTypes x =+ if allEqual (map toRSort $ catMaybes x) then+ return True+ else+ addWarning err1 >> return False err1 = ErrTermin loc dxs $ text "The decreasing parameters should be of same type" checkSameLens :: [Maybe Int] -> CG [Maybe Int]- checkSameLens = checkAllVsHead err2 length+ checkSameLens xs =+ if allEqual (map length xs) then+ return xs+ else+ addWarning err2 >> return [] err2 = ErrTermin loc dxs $ text "All Recursive functions should have the same number of decreasing parameters" loc = GHC.getSrcSpan (head vars) - checkAllVsHead :: Eq b => Error -> (a -> b) -> [a] -> CG [a]- checkAllVsHead _ _ [] = return []- checkAllVsHead err f (x:xs)- | all (== f x) (f <$> xs) = return (x:xs)- | otherwise = addWarning err >> return []+-- All elements of the input are equal to each other+allEqual :: Eq a => [a] -> Bool+allEqual [] = True+allEqual (x:xs) = all (== x) xs -- See Note [Shape of normalized terms] in -- Language.Haskell.Liquid.Transforms.ANF
src/Language/Haskell/Liquid/Constraint/ToFixpoint.hs view
@@ -14,7 +14,7 @@ import Liquid.GHC.API (Var, Id, TyCon) import qualified Language.Fixpoint.Types.Config as FC import qualified Language.Fixpoint.Types as F-import Language.Fixpoint.Solver.Rewrite (unify)+import Language.Fixpoint.Solver.Rewrite (matchExpr) import Language.Haskell.Liquid.Constraint.Types import qualified Language.Haskell.Liquid.Types.RefType as RT import Language.Haskell.Liquid.Constraint.Qualifier@@ -148,11 +148,11 @@ canRewrite :: S.HashSet F.Symbol -> F.Expr -> F.Expr -> Bool canRewrite freeVars' from to = noFreeSyms && doesNotDiverge where- fromSyms = S.intersection freeVars' (S.fromList $ F.syms from)- toSyms = S.intersection freeVars' (S.fromList $ F.syms to)+ fromSyms = S.intersection freeVars' (F.syms from)+ toSyms = S.intersection freeVars' (F.syms to) noFreeSyms = S.null $ S.difference toSyms fromSyms- doesNotDiverge = Mb.isNothing (unify (S.toList freeVars') from to)- || Mb.isJust (unify (S.toList freeVars') to from)+ doesNotDiverge = Mb.isNothing (matchExpr (S.toList freeVars') from to)+ || Mb.isJust (matchExpr (S.toList freeVars') to from) refinementEQs :: LocSpecType -> [(F.Expr, F.Expr)] refinementEQs t =@@ -205,37 +205,105 @@ -- 3. Don't create `define` for the ctor. -- Unfortunately 3 breaks a bunch of tests... +-- Note [GADT workers and coercion binders]+-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+--+-- For GADT constructors, GHC generates a *worker* and a *wrapper* DataCon.+-- The worker's type includes coercion arguments for each equality constraint+-- (e.g. @Succ n ~ n+1@ for a length-indexed vector). However, the fixpoint+-- SMT encoding drops those coercion arguments: a pattern match+-- @case xs of { (:>) x xr -> ... }@ produces a constraint+-- @xs = $:>(x, xr)@ with only the value arguments.+--+-- The spec type for the worker therefore has @nCoerce@ extra binders at the+-- front (one per equality constraint) that do NOT appear in the SMT+-- application. We build the application expression using only the remaining+-- *value* binders (@valBs@), so that the resulting rewrite has the right+-- arity to fire on the worker applications that appear in constraints.+--+-- Note [All rewrites keyed on the worker symbol]+-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+--+-- In LiquidHaskell, @F.Symbolic DataCon@ is defined as+-- @symbol = F.symbol . dataConWorkId@, so DataCon applications in fixpoint+-- constraints *always* carry the *worker* symbol (e.g. @$:>@, never @$W:>@).+--+-- User-written measures (e.g. @vlen@) are routed to the *wrapper* spec type+-- by 'isWorkerDef' in "Measure", so @makeSimplify@ receives a+-- @(DataConWrapId $W:>, wrRType)@ pair carrying the measure refinements.+-- To produce rewrites that PLE can actually fire, we must key them on the+-- *worker* symbol rather than the wrapper symbol. We do this by using+-- @dcSym = worker symbol@ in both the application expression @eVal@ and the+-- guard inside @go@, so the emitted 'F.SMeasure' entries are already+-- worker-keyed.++-- | Given @(dc, t)@ where @dc@ is a data constructor and @t@ is its spec type,+-- generate PLE rewrite rules for measures keyed on the worker DataCon symbol.+--+-- The measures are generated from the refinement in the result type of @t@,+-- which is expected to be of the form+--+-- > x0:t0 -> ... -> xn:tn -> { v: T | e }+--+-- where @e@ is a conjunction whose conjuncts have one of the following forms:+--+-- > f (dc x1 ... xn) = body+-- > f (dc x1 ... xn) <=> body+-- > f (dc x1 ... xn)+-- > not (f (dc x1 ... xn))+-- makeSimplify :: (Var, SpecType) -> [F.Rewrite] makeSimplify (var, t) | not (GM.isDataConId var) = [] | otherwise- = go $ specTypeToResultRef (F.eApps (F.EVar $ F.symbol var) (F.EVar <$> ty_binds (toRTypeRep t))) t+ = go $ specTypeToResultRef eVal t where+ trep = toRTypeRep t+ -- All rewrites are keyed on the *worker* symbol.+ -- See note [All rewrites keyed on the worker symbol].+ dcSym = case Ghc.idDetails var of+ Ghc.DataConWrapId dc -> F.symbol (Ghc.dataConWorkId dc)+ _ -> F.symbol var+ -- Value-only binders: for GADT workers, drop the leading coercion binders+ -- that are present in the spec type but absent in the SMT encoding.+ -- See note [GADT workers and coercion binders].+ valBs = case Ghc.idDetails var of+ Ghc.DataConWorkId dc ->+ let nCoerce = length $ filter (Ghc.isSimplePredTy . Ghc.irrelevantMult)+ $ Ghc.dataConRepArgTys dc+ -- Class dictionary constructors can take superclass dictionaries as+ -- arguments. Keep their binders so the dictionary arguments are retained.+ in if Ghc.isClassTyCon (Ghc.dataConTyCon dc)+ then ty_binds trep+ else drop nCoerce (ty_binds trep)+ _ -> ty_binds trep+ eVal = F.eApps (F.EVar dcSym) (F.EVar <$> valBs)+ go (F.PAnd es) = concatMap go es go (F.PAtom eq (F.EApp (F.EVar f) expr) bd) | eq `elem` [F.Eq, F.Ueq] , (F.EVar dc, xs) <- F.splitEApp expr- , dc == F.symbol var+ , dc == dcSym , all isEVar xs = [F.SMeasure f dc (fromEVar <$> xs) bd] go (F.PIff (F.EApp (F.EVar f) expr) bd) | (F.EVar dc, xs) <- F.splitEApp expr- , dc == F.symbol var+ , dc == dcSym , all isEVar xs = [F.SMeasure f dc (fromEVar <$> xs) bd] go (F.EApp (F.EVar f) expr) | (F.EVar dc, xs) <- F.splitEApp expr- , dc == F.symbol var+ , dc == dcSym , all isEVar xs = [F.SMeasure f dc (fromEVar <$> xs) F.PTrue] go (F.PNot (F.EApp (F.EVar f) expr)) | (F.EVar dc, xs) <- F.splitEApp expr- , dc == F.symbol var+ , dc == dcSym , all isEVar xs = [F.SMeasure f dc (fromEVar <$> xs) F.PFalse]
src/Language/Haskell/Liquid/GHC/Interface.hs view
@@ -28,6 +28,8 @@ , listLMap , classCons , derivedVars+ , manualMethodSpans+ , instanceSpans , importVars , modSummaryHsFile , makeFamInstEnv@@ -61,14 +63,12 @@ import Language.Haskell.Liquid.GHC.Misc import Language.Haskell.Liquid.GHC.Types (MGIModGuts(..)) import Language.Haskell.Liquid.GHC.Play-import Language.Haskell.Liquid.WiredIn (isDerivedInstance) import qualified Language.Haskell.Liquid.Measure as Ms import Language.Haskell.Liquid.Types.Errors import Language.Haskell.Liquid.Types.PrettyPrint import Language.Haskell.Liquid.Types.Specs import Language.Haskell.Liquid.Types.Types import Language.Haskell.Liquid.Types.Visitors-import Language.Haskell.Liquid.UX.Config import Language.Haskell.Liquid.UX.Tidy @@ -80,38 +80,44 @@ classCons Nothing = [] classCons (Just cs) = concatMap (dataConImplicitIds . head . tyConDataCons . classTyCon . is_cls) cs -derivedVars :: Config -> MGIModGuts -> [Var]-derivedVars cfg mg = concatMap (dFunIdVars cbs . is_dfun) derInsts- where- derInsts- | checkDer = insts- | otherwise = filter isDerivedInstance insts- insts = mgClsInstances mg- checkDer = checkDerived cfg- cbs = mgi_binds mg---mgClsInstances :: MGIModGuts -> [ClsInst]-mgClsInstances = fromMaybe [] . mgi_cls_inst--dFunIdVars :: CoreProgram -> DFunId -> [Id]-dFunIdVars cbs fd = notracepp msg $ concatMap bindersOf cbs' ++ deps+derivedVars :: [Ghc.SrcSpan] -> MGIModGuts -> [Var]+derivedVars instSpans mg =+ filter isGeneratedBinding (concatMap bindersOf (mgi_binds mg)) where- msg = "DERIVED-VARS-OF: " ++ showpp fd- cbs' = filter f cbs- f (NonRec x _) = eqFd x- f (Rec xes) = any eqFd (fst <$> xes)- eqFd x = varName x == varName fd- deps = concatMap unfoldDep unfolds- unfolds = realUnfoldingInfo . idInfo <$> concatMap bindersOf cbs'+ isGeneratedBinding v =+ let occ = Ghc.getOccName v+ in+ Ghc.isDerivedOccName occ &&+ -- default methods are always written by the user+ not ("$dm" `isPrefixOf` Ghc.occNameString occ) &&+ -- methods might be written by the user if they are in the manual spans+ (not ("$c" `isPrefixOf` Ghc.occNameString occ) ||+ not (any (Ghc.getSrcSpan v `Ghc.isSubspanOf`) instSpans)+ ) -unfoldDep :: Unfolding -> [Id]-unfoldDep (DFunUnfolding _ _ e) = concatMap exprDep e-unfoldDep CoreUnfolding {uf_tmpl = e} = exprDep e-unfoldDep _ = []+-- | Collect the source spans of all 'ClsInstDecl' nodes in the renamed AST.+-- These cover the full body of every manually-written instance declaration.+manualMethodSpans :: Ghc.TcGblEnv -> [Ghc.SrcSpan]+manualMethodSpans tcg = case Ghc.tcg_rn_decls tcg of+ Nothing -> []+ Just grp ->+ [ Ghc.getLocA b+ | d <- Ghc.hsGroupInstDecls grp+ , Ghc.ClsInstD _ inst <- [Ghc.unLoc d]+ , b <- Ghc.cid_binds inst+ ] -exprDep :: CoreExpr -> [Id]-exprDep = freeVars S.empty+-- | Collect the full source spans of instance declarations.+-- Unlike 'manualMethodSpans' which collects spans of individual bindings,+-- this collects the span of the entire instance declaration.+instanceSpans :: Ghc.TcGblEnv -> [Ghc.SrcSpan]+instanceSpans tcg = case Ghc.tcg_rn_decls tcg of+ Nothing -> []+ Just grp ->+ [ Ghc.getLocA d+ | d <- Ghc.hsGroupInstDecls grp+ , Ghc.ClsInstD _ _inst <- [Ghc.unLoc d]+ ] importVars :: CoreProgram -> [Id] importVars = freeVars S.empty
src/Language/Haskell/Liquid/GHC/Misc.hs view
@@ -334,16 +334,10 @@ isExternalId = isExternalName . getName isTupleId :: Id -> Bool-isTupleId = maybe False Ghc.isTupleDataCon . idDataConM--idDataConM :: Id -> Maybe DataCon-idDataConM x = case idDetails x of- DataConWorkId d -> Just d- DataConWrapId d -> Just d- _ -> Nothing+isTupleId = maybe False Ghc.isTupleDataCon . Ghc.isDataConId_maybe isDataConId :: Id -> Bool-isDataConId = isJust . idDataConM+isDataConId = isJust . Ghc.isDataConId_maybe getDataConVarUnique :: Var -> Unique getDataConVarUnique v@@ -775,18 +769,18 @@ tcInferRho rn_expr -- Generalise+ -- Simplify the constraints and keep the resulting evidence bindings. uniq <- newUnique let { fresh_it = itName uniq (getLocA rdr_expr) }- ((_qtvs, _dicts, evbs, _), residual)- <- captureConstraints $- simplifyInfer NotTopLevel tclvl NoRestrictions+ (_qtvs, _dicts, evbs, _)+ <- simplifyInfer NotTopLevel tclvl NoRestrictions [] {- No sig vars -} [(fresh_it, res_ty)] lie - -- Ignore the dictionary bindings- evbs' <- simplifyInteractive residual- full_expr <- zonkTopLExpr (mkHsDictLet (EvBinds evbs') (mkHsDictLet evbs tc_expr))+ -- Reintroduce the solved evidence before desugaring. In particular, this+ -- makes dictionary and superclass-selector bindings available.+ full_expr <- zonkTopLExpr (mkHsDictLet evbs tc_expr) (ds_msgs, me) <- initDsTc $ dsLExpr full_expr logger <- getLogger@@ -799,8 +793,46 @@ Just e -> do when (errorsOrFatalWarningsFound ds_msgs) failM- return e+ -- `collectArgs` only takes direct applications. Another option would+ -- be using `collectFunSimple` here, which also looks through casts and+ -- ticks. We use the more conservative `collectArgs` for now.+ return $ fst $ Ghc.collectArgs $ inlineEvidenceLets e +-- | inlineEvidenceLets will check traverse a Core expression and inline+-- the definition of let bindings which serve as evidence variables.+--+-- GHC introduces typeclass dictionaries, superclass selectors, and related+-- proof evidence as local Core bindings. LiquidHaskell needs that evidence to+-- occur directly in the elaborated expression, so that subsequent+-- translation can see the dictionary applications and their binders.+--+-- Ordinary program bindings are preserved, only dictionary and evidence+-- variables are substituted.+inlineEvidenceLets :: CoreExpr -> CoreExpr+inlineEvidenceLets = go+ where+ go (Let (NonRec x rhs) body)+ -- Keep ordinary bindings, but inline typeclass and evidence bindings.+ | isEvidenceVar x = substCoreVar x (go rhs) (go body)+ | otherwise = Let (NonRec x (go rhs)) (go body)+ go (Let (Rec xes) body) = Let (Rec [(x, go rhs) | (x, rhs) <- xes]) (go body)+ go (Lam x e) = Lam x (go e)+ go (App e1 e2) = App (go e1) (go e2)+ go (Case e x t alts) = Case (go e) x t [Alt c xs (go rhs) | Alt c xs rhs <- alts]+ go (Cast e co) = Cast (go e) co+ go (Tick tick e) = Tick tick (go e)+ go e = e++isEvidenceVar :: Var -> Bool+isEvidenceVar x = isDictonaryId x || isEvVar x++substCoreVar :: Id -> CoreExpr -> CoreExpr -> CoreExpr+substCoreVar x rhs body =+ substExpr subs body+ where+ fvs = exprFreeVars rhs `unionVarSet` exprFreeVars body+ subs = extendIdSubst (mkEmptySubst (mkInScopeSet fvs)) x rhs+ newtype HashableType = HashableType {getHType :: Type} instance Eq HashableType where@@ -953,4 +985,4 @@ prependGHCRealQual = varQual_RDR realModule isFromGHCReal :: NamedThing a => a -> Bool-isFromGHCReal x = Ghc.nameModule (Ghc.getName x) == realModule+isFromGHCReal x = Ghc.nameModule_maybe (Ghc.getName x) == Just realModule
src/Language/Haskell/Liquid/GHC/Play.hs view
@@ -7,14 +7,12 @@ import Prelude hiding (error) -import Control.Arrow ((***)) import qualified Data.HashMap.Strict as M import qualified Data.List as L import qualified Data.Maybe as Mb -import Liquid.GHC.API as Ghc hiding (panic, showPpr)+import Liquid.GHC.API as Ghc import Language.Haskell.Liquid.GHC.Misc ()-import Language.Haskell.Liquid.Types.Errors import Language.Haskell.Liquid.Types.Variance -------------------------------------------------------------------------------@@ -125,109 +123,8 @@ findOccurrence :: OccurrenceMap -> TyCon -> TyConOccurrence findOccurrence m tc = mconcat (snd <$> M.lookupDefault mempty tc m) ----isRecursivenewTyCon :: TyCon -> Bool-isRecursivenewTyCon c- | not (isNewTyCon c)- = False-isRecursivenewTyCon c- = go t- where- t = snd $ newTyConRhs c- go (AppTy t1 t2) = go t1 || go t2- go (TyConApp c' ts) = c == c' || any go ts- go (ForAllTy _ t1) = go t1- go (FunTy _ _ t1 t2) = go t1 || go t2- go (CastTy t1 _) = go t1- go _ = False-- dataConImplicitIds :: DataCon -> [Id] dataConImplicitIds dc = [ x | AnId x <- dataConImplicitTyThings dc]--class Subable a where- sub :: M.HashMap CoreBndr CoreExpr -> a -> a- subTy :: M.HashMap TyVar Type -> a -> a--instance Subable CoreExpr where- sub s (Var v) = M.lookupDefault (Var v) v s- sub _ (Lit l) = Lit l- sub s (App e1 e2) = App (sub s e1) (sub s e2)- sub s (Lam b e) = Lam b (sub s e)- sub s (Let b e) = Let (sub s b) (sub s e)- sub s (Case e b t a) = Case (sub s e) (sub s b) t (map (sub s) a)- sub s (Cast e c) = Cast (sub s e) c- sub s (Tick t e) = Tick t (sub s e)- sub _ (Type t) = Type t- sub _ (Coercion c) = Coercion c-- subTy s (Var v) = Var (subTy s v)- subTy _ (Lit l) = Lit l- subTy s (App e1 e2) = App (subTy s e1) (subTy s e2)- subTy s (Lam b e) | isTyVar b = Lam v' (subTy s e)- where v' = case M.lookup b s of- Just (TyVarTy v) -> v- _ -> b-- subTy s (Lam b e) = Lam (subTy s b) (subTy s e)- subTy s (Let b e) = Let (subTy s b) (subTy s e)- subTy s (Case e b t a) = Case (subTy s e) (subTy s b) (subTy s t) (map (subTy s) a)- subTy s (Cast e _c) = Cast (subTy s e) $ panic Nothing "subTy Coercion"- subTy s (Tick t e) = Tick t (subTy s e)- subTy s (Type t) = Type (subTy s t)- subTy _s (Coercion _c) = Coercion $ panic Nothing "subTy Coercion"--instance Subable (Alt Var) where- sub s (Alt a b e) = Alt a (map (sub s) b) (sub s e)- subTy s (Alt a b e) = Alt a (map (subTy s) b) (subTy s e)--instance Subable Var where- sub s v | M.member v s = subVar $ s M.! v- | otherwise = v- subTy s v = setVarType v (subTy s (varType v))--subVar :: Expr t -> Id-subVar (Var x) = x-subVar _ = panic Nothing "sub Var"--instance Subable (Bind Var) where- sub s (NonRec x e) = NonRec (sub s x) (sub s e)- sub s (Rec xes) = Rec ((sub s *** sub s) <$> xes)-- subTy s (NonRec x e) = NonRec (subTy s x) (subTy s e)- subTy s (Rec xes) = Rec ((subTy s *** subTy s) <$> xes)--instance Subable Type where- sub _ e = e- subTy = substTysWith--substTysWith :: M.HashMap Var Type -> Type -> Type-substTysWith s tv@(TyVarTy v) = M.lookupDefault tv v s-substTysWith s (FunTy aaf m t1 t2) = FunTy aaf m (substTysWith s t1) (substTysWith s t2)-substTysWith s (ForAllTy v t) = ForAllTy v (substTysWith (M.delete (binderVar v) s) t)-substTysWith s (TyConApp c ts) = TyConApp c (map (substTysWith s) ts)-substTysWith s (AppTy t1 t2) = AppTy (substTysWith s t1) (substTysWith s t2)-substTysWith _ (LitTy t) = LitTy t-substTysWith s (CastTy t c) = CastTy (substTysWith s t) c-substTysWith _ (CoercionTy c) = CoercionTy c--substExpr :: M.HashMap Var Var -> CoreExpr -> CoreExpr-substExpr s = go- where- subsVar v = M.lookupDefault v v s- go (Var v) = Var $ subsVar v- go (Lit l) = Lit l- go (App e1 e2) = App (go e1) (go e2)- go (Lam x e) = Lam (subsVar x) (go e)- go (Let (NonRec x ex) e) = Let (NonRec (subsVar x) (go ex)) (go e)- go (Let (Rec xes) e) = Let (Rec [(subsVar x', go e') | (x',e') <- xes]) (go e)- go (Case e b t alts) = Case (go e) (subsVar b) t [Alt c (subsVar <$> xs) (go e') | Alt c xs e' <- alts]- go (Cast e c) = Cast (go e) c- go (Tick t e) = Tick t (go e)- go (Type t) = Type t- go (Coercion c) = Coercion c mapType :: (Type -> Type) -> Type -> Type mapType f = go
src/Language/Haskell/Liquid/GHC/Plugin.hs view
@@ -17,6 +17,8 @@ import qualified Liquid.GHC.API as O import Liquid.GHC.API as GHC hiding (Type)+import GHC.Data.FastString (LexicalFastString (..))+import GHC.Types.Name (setNameLoc) import qualified Text.PrettyPrint.HughesPJ as PJ import qualified Language.Fixpoint.Types as F import qualified Language.Haskell.Liquid.GHC.Misc as LH@@ -32,6 +34,7 @@ import Language.Haskell.Liquid.GHC.Plugin.Types import qualified Language.Haskell.Liquid.GHC.Plugin.Serialisation as Serialisation+import qualified Language.Haskell.Liquid.GHC.Plugin.Iface as Iface import Language.Haskell.Liquid.GHC.Plugin.SpecFinder as SpecFinder @@ -41,6 +44,8 @@ import Control.Monad import qualified Control.Monad.Catch as Ex+import Control.Exception (SomeException, someExceptionContext)+import Control.Exception.Context import Control.Monad.IO.Class (MonadIO) import Data.Coerce@@ -49,11 +54,13 @@ import Data.IORef import qualified Data.Map as M import Data.Map ( Map )+import Data.Maybe ( fromMaybe ) import qualified Data.HashSet as HS import qualified Data.HashMap.Strict as HM +import System.IO ( hPutStrLn, stderr ) import System.IO.Unsafe ( unsafePerformIO ) import Language.Fixpoint.Types hiding ( errs , panic@@ -70,19 +77,16 @@ import Language.Haskell.Liquid.Types.PrettyPrint import Language.Haskell.Liquid.Types.Specs import Language.Haskell.Liquid.Types.Types+import Language.Haskell.Liquid.Types.RType (SpecType) import Language.Haskell.Liquid.Types.Visitors import Language.Haskell.Liquid.Bare import qualified Language.Haskell.Liquid.Bare.Resolve as Resolve import Language.Haskell.Liquid.UX.CmdLine import Language.Haskell.Liquid.UX.Config+import Language.Haskell.Liquid.RefCore.Extract (SrcInfo (..), extractCalculus, writeIlh, writeIlhBin) --- | Represents an abnormal but non-fatal state of the plugin. Because it is not--- meant to escape the plugin, it is not thrown in IO but instead carried around--- in an `Either`'s `Left` case and handled at the top level of the plugin--- function.-newtype LiquidCheckException = ErrorsOccurred [Filter] -- Unmatched expected errors- deriving (Eq, Ord, Show) + --------------------------------------------------------------------------------- -- | State and configuration management ----------------------------------------- ---------------------------------------------------------------------------------@@ -107,6 +111,7 @@ plugin = GHC.defaultPlugin { driverPlugin = lhDynFlags , parsedResultAction = parsePlugin+ , renamedResultAction = renamedPlugin , typeCheckResultAction = typecheckPlugin , pluginRecompile = purePlugin }@@ -120,9 +125,25 @@ parsePlugin opts ms parsedResult = liquidPlugin opts parsedResult $ \cfg -> parsedHook cfg ms parsedResult + -- | Ensure that 'tcg_rn_decls' is populated for use in 'typeCheckResultAction'.+ -- GHC only keeps renamed syntax when generating HIE files or haddock docs;+ -- we need it to distinguish manually-written from auto-derived instances.+ -- We prime 'tcg_rn_decls' with an empty group, since GHC seems to require+ -- it to collect rn_decls.+ renamedPlugin :: [CommandLineOption] -> TcGblEnv -> GHC.HsGroup GHC.GhcRn+ -> TcM (TcGblEnv, GHC.HsGroup GHC.GhcRn)+ renamedPlugin _opts tcg decls = do+ let tcg' = case tcg_rn_decls tcg of+ Nothing -> tcg { tcg_rn_decls = Just GHC.emptyRnGroup }+ Just _ -> tcg+ return (tcg', decls)+ typecheckPlugin :: [CommandLineOption] -> ModSummary -> TcGblEnv -> TcM TcGblEnv typecheckPlugin opts summary gblEnv = liquidPlugin opts gblEnv $ \cfg ->- typecheckPluginGo cfg summary gblEnv+ Ex.catch (typecheckPluginGo cfg summary gblEnv) $ \(e :: SomeException) -> do+ liftIO $ hPutStrLn stderr $ "LiquidHaskell plugin panics:\n" +++ displayExceptionContext (someExceptionContext e)+ Ex.throwM e typecheckPluginGo cfg summary gblEnv = do logger0 <- getLogger@@ -130,38 +151,8 @@ GHC.withTiming logger (text "LiquidHaskellCPU" <+> brackets (ppr $ ms_mod_name summary)) (const ()) $ GHC.withTimingWallClock- logger (text "LiquidHaskell" <+> brackets (ppr $ ms_mod_name summary)) (const ()) $ do- dynFlags <- getDynFlags- -- Haddock runs the LH plugin, but it does not expose the annotations of dependencies.- -- This makes verification fail, so for now, we disable the plugin when haddock runs it.- --- -- Detecting if Haddock is running the plugin is not obvious enough. We- -- try to see for now if Haddock comments are being collected and if the- -- noBackend is set.- --- -- See https://gitlab.haskell.org/ghc/ghc/-/issues/26761- -- and https://github.com/ucsd-progsys/liquidhaskell/issues/2188- if gopt Opt_Haddock dynFlags && GHC.backendName (backend dynFlags) == GHC.NoBackend- then do- -- Warn the user- let msg = PJ.vcat [ PJ.text "LH can't be run with Haddock."- , PJ.nest 4 $ PJ.text "Documentation will still be created."- ]- let srcLoc = mkSrcLoc (mkFastString $ ms_hspp_file summary) 1 1- let warning = mkWarning (mkSrcSpan srcLoc srcLoc) msg- liftIO $ printWarning logger warning- pure gblEnv- else do- newGblEnv <- typecheckHook cfg summary gblEnv- case newGblEnv of- -- Exit with success if all expected errors were found- Left (ErrorsOccurred []) -> pure gblEnv- -- Exit with error if there were unmatched expected errors- Left (ErrorsOccurred errorFilters) -> do- defaultFilterReporter (LH.modSummaryHsFile summary) errorFilters- failM- Right newGblEnv' ->- pure newGblEnv'+ logger (text "LiquidHaskell" <+> brackets (ppr $ ms_mod_name summary)) (const ()) $+ fromMaybe gblEnv <$> typecheckHook cfg summary gblEnv -- We instruct LH to collect timings instead of doing it directly to GHC -- This helps work around https://github.com/haskell/cabal/issues/11116@@ -213,7 +204,7 @@ lhDynFlags :: [CommandLineOption] -> HscEnv -> IO HscEnv lhDynFlags _ hscEnv =- return hscEnv+ return $ Iface.installInterfaceHook $ hscEnv { hsc_dflags = hsc_dflags hscEnv -- Ignore-interface-pragmas need to be unset to have access to@@ -286,7 +277,10 @@ -- grab from desugaring a postprocessed version of the typechecked module, so we are -- really independent from the \"normal\" compilation pipeline. ---typecheckHook :: Config -> ModSummary -> TcGblEnv -> TcM (Either LiquidCheckException TcGblEnv)+-- The return value is Nothing when the module has failed verification. The actual+-- errors are reported in the TcM monad.+--+typecheckHook :: Config -> ModSummary -> TcGblEnv -> TcM (Maybe TcGblEnv) typecheckHook cfg0 ms tcGblEnv = swapBreadcrumb thisModule Nothing >>= \case Just (Parsed specComments) -> typecheckHook' cfg0 ms tcGblEnv specComments@@ -294,26 +288,25 @@ -- The module has been verified by an earlier call to the plugin. -- This could happen if multiple @-fplugin=LiquidHaskell@ flags are passed to GHC. -- See 'Breadcrumb' for more information.- pure $ Right tcGblEnv+ pure $ Just tcGblEnv where thisModule = ms_mod ms -typecheckHook' :: Config -> ModSummary -> TcGblEnv -> [SpecComment] -> TcM (Either LiquidCheckException TcGblEnv)+typecheckHook' :: Config -> ModSummary -> TcGblEnv -> [SpecComment] -> TcM (Maybe TcGblEnv) typecheckHook' cfg ms tcGblEnv specComments = do debugLog $ "We are in module: " <> show (toStableModule thisModule) case parseSpecComments (coerce specComments) of- Left errors ->- LH.filterReportErrors thisFile GHC.failM continue (getFilters cfg) Full errors+ Left errors -> do+ LH.filterReportErrors thisFile (getFilters cfg) Full errors+ pure Nothing Right specs -> liquidCheckModule cfg ms tcGblEnv specs where thisModule = ms_mod ms thisFile = LH.modSummaryHsFile ms - continue = pure $ Left (ErrorsOccurred [])--liquidCheckModule :: Config -> ModSummary -> TcGblEnv -> [BPspec] -> TcM (Either LiquidCheckException TcGblEnv)+liquidCheckModule :: Config -> ModSummary -> TcGblEnv -> [BPspec] -> TcM (Maybe TcGblEnv) liquidCheckModule cfg0 ms tcg specs = do withPragmas cfg0 pragmas $ \cfg -> do pipelineData <- do@@ -359,21 +352,15 @@ -- liftIO $ putStrLn "liquidHaskellCheck 9" -- --- - serialisedSpec <- liftIO $ Serialisation.serialiseLiquidLib liquidLib thisModule- debugLog $ "Serialised annotation ==> " ++ (O.showSDocUnsafe . O.ppr $ serialisedSpec)-- -- liftIO $ putStrLn "liquidHaskellCheck 10"-- pure $ tcGblEnv { tcg_anns = serialisedSpec : tcg_anns tcGblEnv }- where- thisModule = tcg_mod tcGblEnv+ env <- getTopEnv+ liftIO $ Serialisation.serialiseLiquidLib env liquidLib tcGblEnv processInputSpec :: Config -> PipelineData -> ModSummary -> BareSpecParsed- -> TcM (Either LiquidCheckException LiquidLib)+ -> TcM (Maybe LiquidLib) processInputSpec cfg pipelineData modSummary inputSpec = do tcg <- getGblEnv debugLog $ " Input spec: \n" ++ show (fromBareSpecParsed inputSpec)@@ -391,11 +378,11 @@ -- liftIO $ putStrLn ("liquidHaskellCheck 6: " ++ show isIg) if isIgnore inputSpec- then pure $ Left (ErrorsOccurred [])+ then pure Nothing else checkLiquidHaskellContext lhContext liquidHaskellCheckWithConfig- :: Config -> PipelineData -> ModSummary -> TcM (Either LiquidCheckException LiquidLib)+ :: Config -> PipelineData -> ModSummary -> TcM (Maybe LiquidLib) liquidHaskellCheckWithConfig cfg pipelineData modSummary = do -- Parse the spec comments stored in the pipeline data. let inputSpec = snd $@@ -410,23 +397,45 @@ thisFile = LH.modSummaryHsFile modSummary thisModule = ms_mod modSummary - continue :: TcM (Either LiquidCheckException a)- continue = pure $ Left (ErrorsOccurred [])+ reportErrs :: F.PPrint e => [TError e] -> TcM (Maybe LiquidLib)+ reportErrs xs = do+ LH.filterReportErrors thisFile (getFilters cfg) Full xs+ pure Nothing - reportErrs :: F.PPrint e => [TError e] -> TcM (Either LiquidCheckException a)- reportErrs = LH.filterReportErrors thisFile GHC.failM continue (getFilters cfg) Full+mkSrcInfo :: LiquidHaskellContext -> TargetInfo -> [CoreBind] -> AnnInfo SpecType -> SrcInfo+mkSrcInfo lhContext targetInfo cbs infTypes = SrcInfo+ { s_moduleName = moduleName $ ms_mod $ lhModuleSummary lhContext+ , s_summary = lhModuleSummary lhContext+ , s_targetInfo = targetInfo+ , s_cbs = cbs+ , s_infTypes = infTypes+ , s_imports = lhRelevantModules lhContext+ } -checkLiquidHaskellContext :: LiquidHaskellContext -> TcM (Either LiquidCheckException LiquidLib)+-- | When the @--refcore@ flag is set, extract Calculus declarations and write+-- the .ilhb binary. With @--refcore-text@ also write the human-readable .ilh+-- text dump (debug only).+checkLiquidHaskellContext :: LiquidHaskellContext -> TcM (Maybe LiquidLib) checkLiquidHaskellContext lhContext = do pmr <- processModule lhContext case pmr of- Left e -> pure $ Left e- Right ProcessModuleResult{..} -> do+ Nothing -> pure Nothing+ Just ProcessModuleResult{..} -> do -- Call into the existing Liquid interface- out <- liftIO $ LH.checkTargetInfo pmrTargetInfo+ (programOut, infTypes) <- liftIO $ LH.checkTargetInfo pmrTargetInfo+ refinementOut <- case (o_result programOut, pmrRefinementTargetInfo) of+ (F.Safe _, Just refinementTargetInfo) -> fst <$> liftIO (LH.checkTargetInfo refinementTargetInfo)+ _ -> pure mempty+ let out = programOut <> refinementOut let bareSpec = lhInputSpec lhContext+ cfg = lhGlobalCfg lhContext + when (refcore cfg) $ liftIO $ do+ (calcSource, meta) <- extractCalculus (mkSrcInfo lhContext pmrTargetInfo pmrRefCoreCbs infTypes)+ writeIlhBin meta calcSource+ when (refcoreText cfg) $ writeIlh meta calcSource+ withPragmas (lhGlobalCfg lhContext) (Ms.pragmas bareSpec) $ \moduleCfg -> do let filters = getFilters moduleCfg file = LH.modSummaryHsFile $ lhModuleSummary lhContext@@ -438,9 +447,9 @@ -- -- F.Crash is also handled by reportResult and errorLogger case o_result out of- F.Safe _ -> return $ Right pmrClientLib+ F.Safe _ -> return $ Just pmrClientLib _ | json moduleCfg -> failM- | otherwise -> return $ Left $ ErrorsOccurred []+ | otherwise -> pure Nothing errorLogger :: FilePath -> [Filter] -> OutputResult -> TcM () errorLogger file filters outputResult = do@@ -448,8 +457,6 @@ FilterReportErrorsArgs { errorReporter = \errs -> LH.addTcRnUnknownMessages [(sp, e) | (sp, e) <- errs] , filterReporter = LH.defaultFilterReporter file- , failure = GHC.failM- , continue = pure () , matchingFilters = LH.reduceFilters (\(src, doc) -> PJ.render doc ++ " at " ++ LH.showPpr src) filters , filters = filters }@@ -462,30 +469,17 @@ -- | Working with bare & lifted specs ------------------------------------------ -------------------------------------------------------------------------------- --- | Loads the specs of direct dependencies and /their/ dependencies as well.-loadDependencies :: Config -> [Module] -> TcM TargetDependencies+-- | Load direct and transitive specifications, keeping each reference with its+-- specification while removing configuration-dependent exclusions.+loadDependencies :: Config -> [Module] -> TcM (HM.HashMap StableModule LoadedSpec) loadDependencies currentModuleConfig mods = do hscEnv <- env_top <$> getEnv- results <- SpecFinder.findRelevantSpecs- (excludeAutomaticAssumptionsFor currentModuleConfig) hscEnv mods- -- REVIEW: What does reversing the list accomplishes here?- let deps = TargetDependencies $ foldl' processResult mempty (reverse results)+ deps <- SpecFinder.findRelevantSpecs currentModuleConfig hscEnv mods redundant <- liftIO $ configToRedundantDependencies hscEnv currentModuleConfig debugLog $ "Redundant dependencies ==> " ++ show redundant - pure $ foldl' (flip dropDependency) deps redundant- where- processResult- :: HM.HashMap StableModule LiftedSpec- -> SpecFinderResult- -> HM.HashMap StableModule LiftedSpec- processResult acc (SpecNotFound _mdl) = acc- processResult acc (LibFound originalModule lib) =- HM.insert- (toStableModule originalModule)- (libTarget lib)- (acc <> getDependencies (libDeps lib))+ pure $ foldl' (flip HM.delete) deps redundant data LiquidHaskellContext = LiquidHaskellContext { lhGlobalCfg :: Config@@ -504,9 +498,14 @@ -- ^ The \"client library\" we will serialise on disk into an interface's 'Annotation'. , pmrTargetInfo :: TargetInfo -- ^ The 'GhcInfo' for the current 'Module' that LiquidHaskell will process.+ , pmrRefinementTargetInfo :: Maybe TargetInfo+ -- ^ An isolated target containing only synthetic Boolean refinement checks.+ , pmrRefCoreCbs :: [CoreBind]+ -- ^ Pre-'?'-elimination ANF binds, used by RefCore extraction (--refcore).+ -- Empty unless the @--refcore@ flag is set. } -processModule :: LiquidHaskellContext -> TcM (Either LiquidCheckException ProcessModuleResult)+processModule :: LiquidHaskellContext -> TcM (Maybe ProcessModuleResult) processModule LiquidHaskellContext{..} = do let modGuts0 = lhModuleGuts thisModule = mg_module modGuts0@@ -516,7 +515,8 @@ let bareSpec0 = lhInputSpec withPragmas lhGlobalCfg (Ms.pragmas bareSpec0) $ \moduleCfg -> do- dependencies <- loadDependencies moduleCfg lhRelevantModules+ selectedDeps <- loadDependencies moduleCfg lhRelevantModules+ let dependencies = TargetDependencies $ HM.map (\(LoadedSpec _ _ spec) -> spec) selectedDeps debugLog $ "Found " <> show (HM.size $ getDependencies dependencies) <> " dependencies:" when debugLogs $@@ -530,7 +530,15 @@ let preNormalizedCore = preNormalizeCore moduleCfg modGuts0 modGuts = modGuts0 { mg_binds = preNormalizedCore } file = LH.modSummaryHsFile lhModuleSummary- targetSrc <- liftIO $ makeTargetSrc moduleCfg file modGuts hscEnv (tcg_rdr_env tcg)+ (targetSrc, refCoreCbs) <- liftIO $+ makeTargetSrc+ moduleCfg+ file+ modGuts+ hscEnv+ (tcg_rdr_env tcg)+ (LH.manualMethodSpans tcg)+ (LH.instanceSpans tcg) logger <- getLogger -- See https://github.com/ucsd-progsys/liquidhaskell/issues/1711@@ -560,41 +568,120 @@ bareSpec dependencies - let continue = pure $ Left (ErrorsOccurred [])- reportErrs :: F.PPrint e => [TError e] -> TcRn (Either LiquidCheckException ProcessModuleResult)- reportErrs = LH.filterReportErrors file GHC.failM continue (getFilters moduleCfg) Full+ let reportErrs :: F.PPrint e => [TError e] -> TcRn (Maybe ProcessModuleResult)+ reportErrs xs = do+ LH.filterReportErrors file (getFilters moduleCfg) Full xs+ pure Nothing (case result of -- Print warnings and errors, aborting the compilation. Left diagnostics -> do liftIO $ mapM_ (printWarning logger) (allWarnings diagnostics) reportErrs $ allErrors diagnostics+ Right ((warnings, targetSpec, liftedSpec), bareSpec) -> do liftIO $ mapM_ (printWarning logger) warnings- let targetInfo = TargetInfo targetSrc targetSpec+ (normalizedTargetSrc, normalizedTargetSpec, refinementTargetInfo) <- liftIO $+ normalizeRefinementChecks moduleCfg hscEnv modGuts targetSrc targetSpec+ let targetInfo = TargetInfo normalizedTargetSrc normalizedTargetSpec debugLog $ "bareSpec ==> " ++ show bareSpec debugLog $ "liftedSpec ==> " ++ show liftedSpec - let clientLib = mkLiquidLib liftedSpec & addLibDependencies dependencies+ let dependencyRefs = L.sortOn specModule [ref | LoadedSpec _ ref _ <- HM.elems selectedDeps]+ clientLib = mkLiquidLib liftedSpec & addLibDependencies dependencyRefs let result' = ProcessModuleResult {- pmrClientLib = clientLib+ pmrClientLib = clientLib , pmrTargetInfo = targetInfo+ , pmrRefinementTargetInfo = refinementTargetInfo+ , pmrRefCoreCbs = refCoreCbs } - pure $ Right result')+ pure $ Just result') `Ex.catch` (\(e :: UserError) -> reportErrs [e]) `Ex.catch` (\(e :: Error) -> reportErrs [e]) `Ex.catch` (\(es :: [Error]) -> reportErrs es) +-- | Prepare the pending 'RefinementCheck' obligations for constraint+-- generation. See 'RefinementCheck' for how these checks are constructed and+-- what their Core expression and Liquid type represent.+--+-- "Normalizing" a refinement check means turning its synthetic Core function+-- into the same top-level, A-normal form expected by the ordinary LiquidHaskell+-- pipeline. This function attaches the refinement's source location, creates a+-- non-recursive binding for each normalized expression, and pairs that binding+-- with its synthetic Liquid signature.+--+-- The normalized bindings are returned in a separate 'TargetInfo'. In that+-- isolated target, the module's ordinary asserted signatures become+-- assumptions (providing the environment in which the predicates occur), and+-- only the generated Boolean bindings are asserted. The returned 'TargetSrc'+-- and 'TargetSpec' describe the ordinary program with the pending checks+-- removed, so the program and its refinement predicates can be checked in two+-- independent passes. 'Nothing' is returned when there are no checks.+normalizeRefinementChecks :: Config -> HscEnv -> ModGuts -> TargetSrc -> TargetSpec -> IO (TargetSrc, TargetSpec, Maybe TargetInfo)+normalizeRefinementChecks cfg hscEnv modGuts src spec+ | null checks = pure (src, spec, Nothing)+ | otherwise = do+ normalizedCbs <- anormalizeExprBinds cfg hscEnv modGuts (map locatedRefinementExpr checks)+ let cbs = zipWith locatedRefinementBind checks normalizedCbs+ let xs = map bindVar cbs+ refinementSigs = zip xs (map refinementCheckType checks)+ checkSrc = src+ { giCbs = cbs+ , giDefVars = xs+ , giUseVars = L.nub (readVars cbs ++ giUseVars src)+ , giImpVars = L.nub (LH.importVars cbs ++ giImpVars src)+ }+ -- Keep the checks out of the program's dependency graph. In this+ -- isolated pass, program signatures are assumptions and only the+ -- generated Boolean bindings are asserted and checked.+ checkSpec = spec+ { gsConfig = quietConfig+ -- Expected-failure annotations refer to bindings in the ordinary+ -- program, none of which are checked in this isolated target.+ , gsTerm = (gsTerm spec) { gsFail = mempty }+ , gsSig = sig+ { gsTySigs = refinementSigs+ , gsAsmSigs = gsTySigs sig ++ gsAsmSigs sig+ , gsRelation = []+ , gsAsmRel = []+ , gsReftChecks = []+ } }+ -- Both solver invocations are implementation details. Their results+ -- are combined and reported once by 'checkLiquidHaskellContext'.+ programSpec = spec+ { gsConfig = quietConfig+ , gsSig = sig { gsReftChecks = [] }+ }+ pure (src, programSpec, Just (TargetInfo checkSrc checkSpec))+ where+ sig = gsSig spec+ quietConfig = (gsConfig spec) { loggingVerbosity = Quiet }+ checks = gsReftChecks sig+ locatedRefinementExpr check =+ case LH.fSrcSpan (F.loc (refinementCheckType check)) of+ RealSrcSpan realSpan _ ->+ Tick (SourceNote realSpan (LexicalFastString (fsLit "Liquid refinement")))+ (refinementCheckExpr check)+ _ -> refinementCheckExpr check+ locatedRefinementBind check (NonRec x e) =+ NonRec (setVarName x (setNameLoc (varName x) (LH.fSrcSpan (F.loc (refinementCheckType check))))) e+ locatedRefinementBind _ _ =+ GHC.panic "A refinement predicate normalized to a recursive binding"+ bindVar (NonRec x _) = x+ bindVar _ = GHC.panic "A refinement predicate normalized to a recursive binding"+ makeTargetSrc :: Config -> FilePath -> ModGuts -> HscEnv -> GlobalRdrEnv- -> IO TargetSrc-makeTargetSrc cfg file modGuts hscEnv rdrEnv = do+ -> [GHC.SrcSpan]+ -> [GHC.SrcSpan]+ -> IO (TargetSrc, [CoreBind])+makeTargetSrc cfg file modGuts hscEnv rdrEnv methodSpans instanceSpans = do when (dumpPreNormalizedCore cfg) $ do putStrLn "\n*************** Pre-normalized CoreBinds *****************\n" putStrLn $ unlines $ L.intersperse "" $ map (GHC.showPpr (GHC.hsc_dflags hscEnv)) (mg_binds modGuts)@@ -617,28 +704,32 @@ debugLog $ "coreBinds => " ++ (O.showSDocUnsafe . O.ppr $ coreBinds) debugLog $ "impVars => " ++ (O.showSDocUnsafe . O.ppr $ impVars) debugLog $ "useVars => " ++ (O.showSDocUnsafe . O.ppr $ readVars coreBinds)- debugLog $ "derVars => " ++ (O.showSDocUnsafe . O.ppr $ HS.fromList (LH.derivedVars cfg mgiModGuts))+ debugLog $ "derVars => " ++ (O.showSDocUnsafe . O.ppr $ HS.fromList (LH.derivedVars methodSpans mgiModGuts)) debugLog $ "gsExports => " ++ show (mgi_exports mgiModGuts) debugLog $ "gsTcs => " ++ (O.showSDocUnsafe . O.ppr $ allTcs) debugLog $ "gsCls => " ++ (O.showSDocUnsafe . O.ppr $ mgi_cls_inst mgiModGuts) debugLog $ "gsFiTcs => " ++ (O.showSDocUnsafe . O.ppr $ fiTcs) debugLog $ "gsFiDcs => " ++ show fiDcs debugLog $ "gsPrimTcs => " ++ (O.showSDocUnsafe . O.ppr $ GHC.primTyCons)- return $ TargetSrc+ -- Keep the pre-'?'-elimination ANF binds for RefCore extraction (--refcore),+ -- which needs the '?' applications to emit proof hints.+ let refCoreCbs = if refcore cfg then coreBindsANF else []+ return (TargetSrc { giTarget = file , giTargetMod = ModName Target (moduleName (mg_module modGuts)) , giCbs = coreBinds , giImpVars = impVars , giDefVars = L.nub $ dataCons ++ letVars coreBinds , giUseVars = readVars coreBinds- , giDerVars = HS.fromList (LH.derivedVars cfg mgiModGuts)+ , giDerVars = HS.fromList (LH.derivedVars methodSpans mgiModGuts) , gsExports = mgi_exports mgiModGuts , gsTcs = allTcs , gsCls = mgi_cls_inst mgiModGuts , gsFiTcs = fiTcs , gsFiDcs = fiDcs , gsPrimTcs = GHC.primTyCons- }+ , giInstSpans = instanceSpans+ }, refCoreCbs) where mgiModGuts :: MGIModGuts mgiModGuts = miModGuts deriv modGuts
+ src/Language/Haskell/Liquid/GHC/Plugin/Cache.hs view
@@ -0,0 +1,46 @@+{-# LANGUAGE BangPatterns #-}++-- | A cache retaining every loaded value for reuse. The lock covers a miss and+-- insertion, so concurrent readers reuse the same entry.+module Language.Haskell.Liquid.GHC.Plugin.Cache+ ( Cache, newCache, cached ) where++import Control.Concurrent.MVar+import qualified Data.Map.Strict as M++-- | A mutable map from keys @k@ to retained values @v@, protected by an 'MVar'.+newtype Cache k v = Cache (MVar (M.Map k v))++newCache :: IO (Cache k v)+newCache = Cache <$> newMVar M.empty++-- | The cached function returns a retained value for a key,+-- or runs the supplied loader on a miss.+--+-- Side Effects:+-- * The cache lock covers lookup, loading, and updating the state.+-- * A loaded value and the updated map are evaluated to weak head normal form+-- before publishing the state. Values are not deeply evaluated.+-- This keeps evaluation failures inside 'modifyMVar', which restores the+-- previous state on exception instead of publishing a failing thunk.+-- * The loader must not call 'cached' on this same cache, or wait for another+-- operation that needs its lock. The lock is held while the loader runs,+-- so such a dependency would deadlock.+cached+ :: Ord k+ => Cache k v+ -- ^ Shared mutable cache to query and update.+ -> k+ -- ^ Identity of the requested value.+ -> IO v+ -- ^ Action that loads the value on a miss, while holding the cache lock.+ -> IO v+ -- ^ The retained or newly loaded value. Loader and cache-update exceptions propagate.+cached (Cache state) key load =+ modifyMVar state $ \entries ->+ case M.lookup key entries of+ Just value -> pure (entries, value)+ Nothing -> do+ !value <- load+ let !entries' = M.insert key value entries+ pure (entries', value)
+ src/Language/Haskell/Liquid/GHC/Plugin/Iface.hs view
@@ -0,0 +1,267 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | This module provides functions to manage the serialized form of+-- LifterSpecs.+--+-- LiftedSpec payloads are kept in an extensible interface field. ('fieldName')+-- They are too large to keep in module annotations with an @[Word8]@+-- representation.+--+-- Their version and fingerprint live in module annotations, which makes it+-- participate in GHC's ordinary interface fingerprinting and recompilation+-- checks.+module Language.Haskell.Liquid.GHC.Plugin.Iface+ ( PayloadId+ , PayloadMarker(..)+ , payloadId+ , payloadMarker+ , decodeMarker+ , stageSpec+ , installInterfaceHook+ , getPayload+ , hasPayload+ ) where++import qualified Data.Binary as B+import qualified Data.ByteString as BS+import qualified Data.ByteString.Lazy as BL+import Data.Dynamic+import Data.Typeable (typeOf, typeRep, Proxy(..))+import Data.IORef+import qualified Data.Map.Strict as M+import Data.Word+import qualified Liquid.GHC.API as GHC+++-- | Fingerprint of the encoded specification payload. The pair holds the two+-- 64-bit words of the 128-bit 'GHC.Fingerprint' produced by 'GHC.fingerprintByteString',+-- in the same order as that constructor's fields.+-- Stored in the interface marker and dependency references to detect payload+-- changes or mismatches. Together with the full module identity, it forms the+-- key used to reuse decoded specifications in the session cache.+type PayloadId = (Word64, Word64)++-- | 'B.encode' representation:+--+-- @+-- (version, (fingerprintWord1, fingerprintWord2))+-- :: (Word32, (Word64, Word64))+-- @+--+-- * @version@ is the marker format version, currently 1.+-- * The two fingerprint words form the 'PayloadId'+--+-- 'B.encode' writes these unsigned words consecutively in big-endian order:+--+-- @+-- Byte offsets Contents+-- 0..3 Format version (Word32)+-- 4..11 First fingerprint word (Word64)+-- 12..19 Second fingerprint word (Word64)+-- @+--+newtype PayloadMarker = PayloadMarker { markerBytes :: [Word8] }++-- | Information needed to produce an interface file.+--+-- It contains the serialized LiftedSpec to store, the fingerprint of the+-- LiftedSpec, and its dependencies in the form of 'GHC.Usages'.+--+data PendingSpec = PendingSpec !BS.ByteString !PayloadId ![GHC.Usage]++-- | Name used to store the serialized LiftedSpec in an extensible interface+-- field.+fieldName :: GHC.FieldName+fieldName = "liquidhaskell.spec.v1"++-- | Computes the fingerprint of a bytestring+payloadId :: BS.ByteString -> PayloadId+payloadId bytes =+ let GHC.Fingerprint a b = GHC.fingerprintByteString bytes+ in (a, b)++payloadMarker :: PayloadId -> PayloadMarker+payloadMarker fingerprint =+ PayloadMarker $ BL.unpack $ B.encode (1 :: Word32, fingerprint)++-- | Checks that the marker has the expected version and extracts the+-- fingerprint.+decodeMarker :: PayloadMarker -> Either String PayloadId+decodeMarker (PayloadMarker bytes) = case B.decodeOrFail (BL.pack bytes) of+ Left (_, _, err) -> Left $ "Malformed LiquidHaskell interface marker: " ++ err+ Right (rest, _, (version :: Word32, fingerprint))+ | version /= 1 -> Left "Unsupported LiquidHaskell interface version; rebuild dependencies."+ | not (BL.null rest) -> Left "Malformed LiquidHaskell interface marker."+ | otherwise -> Right fingerprint++-- | Stores a bytestring in the 'GHC.TcGblEnv' in the TH-state map.+--+-- Returns the marker corresponding to the bytestring.+--+-- The given 'GHC.ModIface's are recorded as usages so they cause recompilation+-- when they change.+--+stageSpec :: GHC.TcGblEnv -> BS.ByteString -> [GHC.ModIface] -> IO PayloadMarker+stageSpec tcg bytes ifaces = do+ pending@(PendingSpec _ fingerprint _) <- mkPendingSpec+ atomicModifyIORef' (GHC.tcg_th_state tcg) $ \state ->+ (M.insert (typeOf pending) (toDyn pending) state, ())+ pure $ payloadMarker fingerprint+ where+ mkPendingSpec = do+ usages <- mapM asUsage ifaces+ return $ PendingSpec bytes (payloadId bytes) usages++ asUsage iface =+ let !mdl = GHC.mi_module iface+ !fingerprint = GHC.mi_mod_hash iface+ in pure (GHC.UsagePackageModule mdl fingerprint False)++-- | Add a payload marker to the ModIface, and recompute the hashes.+rebuildSimpleIface :: GHC.HscEnv -> PayloadMarker -> GHC.ModIface -> IO GHC.ModIface+rebuildSimpleIface env pmarker iface = do+ -- Recomputing the hashes of the interface requires rebuilding it, so we+ -- take measures in _arityGuard and _unused_fields to ensure that we don't+ -- forget to copy relevant fields.+ let marker = GHC.IfaceAnnotation (GHC.ModuleTarget $ GHC.mi_module iface) $+ GHC.toSerialized markerBytes pmarker+ GHC.mkFullIface env (GHC.set_mi_anns (marker : GHC.mi_anns iface) partial) Nothing Nothing GHC.NoStubs []+ where+ partial =+ GHC.set_mi_decls (map snd $ GHC.mi_decls iface) $+ GHC.set_mi_simplified_core (GHC.mi_simplified_core iface) $+ GHC.set_mi_mod_info (GHC.mi_mod_info iface) $+ GHC.set_mi_deps (GHC.mi_deps iface) $+ GHC.set_mi_exports (GHC.mi_exports iface) $+ GHC.set_mi_fixities (GHC.mi_fixities iface) $+ GHC.set_mi_warns (GHC.mi_warns iface) $+ GHC.set_mi_defaults (GHC.mi_defaults iface) $+ GHC.set_mi_insts (GHC.mi_insts iface) $+ GHC.set_mi_fam_insts (GHC.mi_fam_insts iface) $+ GHC.set_mi_rules (GHC.mi_rules iface) $+ GHC.set_mi_trust (GHC.mi_trust iface) $+ GHC.set_mi_trust_pkg (GHC.mi_trust_pkg iface) $+ GHC.set_mi_complete_matches (GHC.mi_complete_matches iface) $+ GHC.set_mi_docs (GHC.mi_docs iface) $+ GHC.set_mi_top_env (GHC.mi_top_env iface) $+ GHC.set_mi_ext_fields (GHC.mi_ext_fields iface) $+ GHC.set_mi_self_recomp (GHC.mi_self_recomp_info iface) $+ GHC.emptyPartialModIface (GHC.mi_module iface)++ {- HLINT ignore "Use record patterns" -}+ -- Compile-time guard to catch arity changes in ModIface when upgrading GHC.+ _arityGuard :: GHC.ModIface -> ()+ _arityGuard+ (GHC.ModIface+ _ _ _ _ _ _ _ _ _ _+ _ _ _ _ _ _ _ _ _ _+ _ _ _ _ _ _ _ _ _ _) = ()++ {- HLINT ignore "Evaluate" -}+ -- Compile-time guard to catch changes in the fields that are unused when+ -- upgrading GHC.+ _unused_fields :: ()+ _unused_fields =+ const+ ()+ ( GHC.mi_sig_of+ , GHC.mi_hsc_src+ , GHC.mi_iface_hash+ , GHC.mi_public+ , GHC.mi_abi_hashes+ , GHC.mi_hi_bytes+ , GHC.mi_fix_fn+ , GHC.mi_hash_fn+ , GHC.mi_decl_warn_fn+ , GHC.mi_export_warn_fn+ )++addPayloadToExtFields :: BS.ByteString -> GHC.ModIface_ phase -> IO (GHC.ModIface_ phase)+addPayloadToExtFields bytes iface = do+ fields <- GHC.writeField fieldName bytes (GHC.mi_ext_fields iface)+ pure $ GHC.set_mi_ext_fields fields iface++getPayload :: GHC.ModIface -> IO (Maybe BS.ByteString)+getPayload = GHC.readField fieldName . GHC.mi_ext_fields++hasPayload :: GHC.ModIface -> Bool+hasPayload = M.member fieldName . GHC.getExtensibleFields . GHC.mi_ext_fields++-- | Install a hook that inserts LiftedSpecs in interfaces.+--+-- There are two kinds of interface files that GHC can write: simple and full.+-- Simple interfaces are produced when using @-fno-code@.+-- See Note [Writing interface files] in "GHC.Driver.Main" for more details.+--+-- We need to insert LiftedSpecs in both kinds of interfaces, and we achieve+-- this with 'GHC.runPhaseHook'.+--+-- When a LiftedSpec is ready, @serialiseLiquidLib@ is called. This stages the+-- serialized spec with 'stageSpec' for inclusion in the interface.+--+-- When GHC produces the interface, the hook installed here adds the staged spec+-- to the interface.+--+-- TODO: When upgrading to ghc 10.2 remove this hook, taking advantage of+-- * https://gitlab.haskell.org/ghc/ghc/-/merge_requests/16841+-- With this we can store specs in annotations again.+-- * https://gitlab.haskell.org/ghc/ghc/-/merge_requests/16754+-- With this, annotations end up in interface files even when using haddock+-- or -fno-code+installInterfaceHook :: GHC.HscEnv -> GHC.HscEnv+installInterfaceHook env =+ env { GHC.hsc_hooks = hooks { GHC.runPhaseHook = Just $ GHC.PhaseHook run } }+ where+ hooks = GHC.hsc_hooks env+ runPreviousHook :: GHC.TPhase a -> IO a+ runPreviousHook = case GHC.runPhaseHook hooks of+ Nothing -> GHC.runPhase+ Just (GHC.PhaseHook hook) -> hook++ run :: GHC.TPhase a -> IO a+ -- Typechecking has completed+ run phase@(GHC.T_HscPostTc hscEnv summary (GHC.FrontendTypecheck tcg) _ _) = do+ -- Retrieve the staged serialized LiftedSpec+ pendingSpec <- do+ state <- readIORef (GHC.tcg_th_state tcg)+ let md = M.lookup (typeRep (Proxy :: Proxy PendingSpec)) state+ return (md >>= fromDynamic)+ result <- runPreviousHook phase+ case pendingSpec of+ -- If there is no pending spec, there is no need to change the interface.+ Nothing -> pure result+ Just (PendingSpec bytes fingerprint usages) -> case result of+ -- The module needs recompilation so we add the serialized LiftedSpec.+ recomp@GHC.HscRecomp { GHC.hscs_partial_iface = iface } -> do+ iface' <- addPayloadToExtFields bytes $ addUsages usages iface+ pure recomp { GHC.hscs_partial_iface = iface' }+ -- The module does not need recompilation, but the interface needs+ -- updating. This case is entered when GHC is called with -fno-code.+ -- The interface file has been already written, so after updating the+ -- interface we write it to disk again.+ GHC.HscUpdate iface -> do+ -- Extra wart: in this path, GHC ignores tcg_anns and our payload+ -- marker in it. We use rebuildSimpleIface to still add the marker+ -- to the interface file.+ rebuilt <- rebuildSimpleIface+ hscEnv+ (payloadMarker fingerprint)+ (addUsages usages iface)+ iface' <- addPayloadToExtFields bytes rebuilt+ -- GHC writes simple (-fno-code/boot) interfaces inside PostTc.+ -- Rewrite with the field attached, respecting GHC's write flags+ -- and dynamic-too handling.+ GHC.hscMaybeWriteIface (GHC.hsc_logger hscEnv) (GHC.hsc_dflags hscEnv)+ True iface' Nothing (GHC.ms_location summary)+ pure $ GHC.HscUpdate iface'+ run phase = runPreviousHook phase++ addUsages :: [GHC.Usage] -> GHC.ModIface_ phase -> GHC.ModIface_ phase+ addUsages usages iface =+ let updateSRUsages info =+ info { GHC.mi_sr_usages = usages ++ GHC.mi_sr_usages info }+ in GHC.set_mi_self_recomp+ (updateSRUsages <$> GHC.mi_self_recomp_info iface)+ iface
src/Language/Haskell/Liquid/GHC/Plugin/Serialisation.hs view
@@ -3,27 +3,35 @@ -- * Serialising and deserialising things from/to specs. serialiseLiquidLib , deserialiseLiquidLib- , deserialiseLiquidLibFromEPS ) where import qualified Data.Array as Array-import Data.Foldable ( asum ) import Control.Monad+import Control.Concurrent.MVar import qualified Data.Binary as B import qualified Data.Binary.Builder as Builder import qualified Data.Binary.Put as B import qualified Data.ByteString.Lazy as B import Data.Data (Data)+import Control.Exception+import Control.Exception.Backtrace+import Control.Exception.Context import Data.Generics (ext0, gmapAccumT)-import Data.HashMap.Strict as M-import Data.Maybe ( listToMaybe )-import Data.Word (Word8)+import qualified Data.HashMap.Strict as M+import Data.Maybe ( listToMaybe, mapMaybe )+import Data.IORef+import Data.Unique+import GHC.Stack (HasCallStack)+import System.IO.Unsafe (unsafePerformIO)+import System.Mem.Weak (Weak, deRefWeak) import qualified Liquid.GHC.API as GHC-import Language.Haskell.Liquid.GHC.Plugin.Types (LiquidLib)+import Language.Haskell.Liquid.GHC.Plugin.Types (LiquidLib, SpecReference(..), libDeps)+import qualified Language.Haskell.Liquid.GHC.Plugin.Iface as Iface+import qualified Language.Haskell.Liquid.GHC.Plugin.Cache as Cache import Language.Haskell.Liquid.Types.Names @@ -31,71 +39,121 @@ -- Serialising and deserialising Specs -- -getLiquidLibBytesFromEPS- :: GHC.Module- -> GHC.ExternalPackageState- -> Maybe LiquidLibBytes-getLiquidLibBytesFromEPS thisModule eps = extractFromEps- where- extractFromEps :: Maybe LiquidLibBytes- extractFromEps = listToMaybe $ GHC.findAnns LiquidLibBytes (GHC.eps_ann_env eps) (GHC.ModuleTarget thisModule)+-- | Adds the 'LiquidLib' to the 'GHC.TcGblEnv' in serialiased form.+--+-- The spec is staged in the TH map, and the fingerprint is added to+-- the annotations.+serialiseLiquidLib :: GHC.HscEnv -> LiquidLib -> GHC.TcGblEnv -> IO GHC.TcGblEnv+serialiseLiquidLib env lib tcg = do+ bytes <- B.toStrict <$> encodeLiquidLib lib+ ifaces <- forM (libDeps lib) $ \ref ->+ GHC.lookupIfaceByModuleHsc env (GHC.unStableModule $ specModule ref) >>=+ maybe (ioError $ userError "LiquidHaskell: dependency interface disappeared during verification") pure+ marker <- Iface.stageSpec tcg bytes ifaces+ let ann = GHC.Annotation (GHC.ModuleTarget $ GHC.tcg_mod tcg) $+ GHC.toSerialized Iface.markerBytes marker+ pure $ tcg { GHC.tcg_anns = ann : GHC.tcg_anns tcg } -getLiquidLibBytes :: GHC.Module- -> GHC.ExternalPackageState- -> GHC.HomePackageTable- -> IO (Maybe LiquidLibBytes)-getLiquidLibBytes thisModule eps hpt = do- fromHpt <- extractFromHpt- pure $ asum [fromHpt, getLiquidLibBytesFromEPS thisModule eps]- where- extractFromHpt :: IO (Maybe LiquidLibBytes)- extractFromHpt = do- mb_modInfo <- GHC.lookupHpt hpt (GHC.moduleName thisModule)- pure $ do- modInfo <- mb_modInfo- guard (thisModule == (GHC.mi_module . GHC.hm_iface $ modInfo))- xs <- mapM (GHC.fromSerialized LiquidLibBytes . GHC.ifAnnotatedValue) (GHC.mi_anns . GHC.hm_iface $ modInfo)- listToMaybe xs+-- GHC's interface cache holds encoded data; this cache holds canonical decoded+-- module specs, never merged transitive closures. Retain decoded libraries for+-- the most recently used session. Switching sessions replaces this cache;+-- returning to an earlier session starts a fresh cache. The EPS weak key also+-- releases the cache when its session is garbage collected.+type LibraryCache = Cache.Cache SpecReference LiquidLib+-- The unique identifier prevents a replaced session's finalizer from clearing+-- a newer cache. The weak EPS reference identifies the owning GHC session.+data SessionCache = SessionCache !Unique !(Weak (IORef GHC.ExternalPackageState)) !LibraryCache -newtype LiquidLibBytes = LiquidLibBytes { unLiquidLibBytes :: [Word8] }+{-# NOINLINE sessionCache #-}+sessionCache :: MVar (Maybe SessionCache)+sessionCache = unsafePerformIO $ newMVar Nothing --- | Serialise a 'LiquidLib', removing the termination checks from the target.-serialiseLiquidLib :: LiquidLib -> GHC.Module -> IO GHC.Annotation-serialiseLiquidLib lib thisModule = do- bs <- encodeLiquidLib lib- return $ GHC.Annotation- (GHC.ModuleTarget thisModule)- (GHC.toSerialized unLiquidLibBytes (LiquidLibBytes $ B.unpack bs))+getLibraryCache :: GHC.HscEnv -> IO LibraryCache+getLibraryCache env = modifyMVar sessionCache $ \session -> do+ found <- case session of+ Nothing -> pure Nothing+ Just (SessionCache _ weak cache) -> do+ alive <- deRefWeak weak+ pure $ if alive == Just epsRef then Just cache else Nothing+ case found of+ Just cache -> pure (session, cache)+ Nothing -> do+ cache <- Cache.newCache+ key <- newUnique+ weak <- mkWeakIORef epsRef $ modifyMVar_ sessionCache $ \current ->+ case current of+ Just (SessionCache k _ _) | k == key -> pure Nothing+ _ -> pure current+ pure (Just (SessionCache key weak cache), cache)+ where+ epsRef = GHC.euc_eps $ GHC.ue_eps $ GHC.hsc_unit_env env +-- | Retrieve a module's specification from the interfaces already available+-- in the GHC session. The caller is responsible for loading the interface;+-- this function does not discover imports or search for assumption modules.+--+-- Returns 'Nothing' when no specification marker is found and no compact+-- payload field is present in the available interface. This also includes+-- an unavailable interface with no marker. Otherwise returns 'Just' the+-- module-and-fingerprint reference and its decoded library. A matching+-- session-cache entry is reused; on a miss the payload is read, checked+-- against the marker's fingerprint, decoded, and retained.+--+-- Raises an 'IOError' for a malformed or unsupported marker, or a compact+-- payload without a marker. On a cache miss it also raises an 'IOError' if+-- the interface or payload is missing, or the payload fingerprint disagrees+-- with the marker. GHC and binary-decoding exceptions propagate rather than+-- being converted to 'Nothing'. The returned library is not fully evaluated,+-- so errors in lazy name resolution may arise when its contents are used.+--+-- May populate the session's decoded-library cache and GHC name cache. deserialiseLiquidLib- :: GHC.Module- -> GHC.ExternalPackageState- -> GHC.HomePackageTable- -> GHC.NameCache- -> IO (Maybe LiquidLib)-deserialiseLiquidLib thisModule eps hpt nameCache = do- mlibbs <- getLiquidLibBytes thisModule eps hpt- case mlibbs of- Just (LiquidLibBytes ws) -> do- let bs = B.pack ws- Just <$> decodeLiquidLib nameCache bs- _ -> return Nothing--deserialiseLiquidLibFromEPS- :: GHC.Module- -> GHC.ExternalPackageState- -> GHC.NameCache- -> IO (Maybe LiquidLib)-deserialiseLiquidLibFromEPS thisModule eps nameCache = do- let mlibbs = getLiquidLibBytesFromEPS thisModule eps- case mlibbs of- Just (LiquidLibBytes ws) -> do- let bs = B.pack ws- Just <$> decodeLiquidLib nameCache bs- _ -> return Nothing+ :: GHC.HscEnv+ -- ^ Supplies home-module interfaces and external-package annotations and+ -- interfaces, the EPS 'IORef' identifying the session's decoded-library+ -- cache, and the 'GHC.NameCache' used to resolve serialized GHC names.+ -> GHC.Module+ -- ^ Full module identity, including the package/unit, whose spec is requested.+ -> IO (Maybe (SpecReference, LiquidLib))+deserialiseLiquidLib env thisModule = do+ eps <- readIORef $ GHC.euc_eps $ GHC.ue_eps $ GHC.hsc_unit_env env+ home <- GHC.lookupHugByModule thisModule (GHC.hsc_HUG env)+ let homeAnnotations = case home of+ Just info | GHC.mi_module (GHC.hm_iface info) == thisModule ->+ GHC.ifAnnotatedValue <$> GHC.mi_anns (GHC.hm_iface info)+ _ -> []+ annotations decoder =+ mapMaybe (GHC.fromSerialized decoder) homeAnnotations +++ GHC.findAnns decoder (GHC.eps_ann_env eps) (GHC.ModuleTarget thisModule)+ case listToMaybe $ annotations Iface.PayloadMarker of+ Nothing -> do+ iface <- GHC.lookupIfaceByModuleHsc env thisModule+ -- A compact payload requires its marker for identification and validation.+ if maybe False Iface.hasPayload iface+ then ioError $ userError $ "LiquidHaskell: missing specification marker for " +++ GHC.renderModule thisModule ++ ". Rebuild this dependency with the current LiquidHaskell plugin."+ else pure Nothing+ Just marker -> do+ fingerprint <- either (ioError . userError) pure $ Iface.decodeMarker marker+ let reference = SpecReference (GHC.toStableModule thisModule) fingerprint+ cache <- getLibraryCache env+ lib <- Cache.cached cache reference $ do+ iface <- GHC.lookupIfaceByModuleHsc env thisModule+ bytes <- maybe (pure Nothing) Iface.getPayload iface >>= maybe missingPayload pure+ let actual = Iface.payloadId bytes+ unless (actual == fingerprint) $+ ioError $ userError $ "LiquidHaskell: corrupt specification for " ++ GHC.renderModule thisModule+ -- Lazy name decoding must retain only the NameCache, not a selector+ -- thunk keeping the entire HscEnv (and our weak session key) alive.+ let nameCache = GHC.hsc_NC env+ nameCache `seq` decodeLiquidLib nameCache (B.fromStrict bytes)+ pure $ Just (reference, lib)+ where+ missingPayload = ioError $ userError $ "LiquidHaskell: missing compact specification for " +++ GHC.renderModule thisModule ++ ". Rebuild this dependency with the current LiquidHaskell plugin." encodeLiquidLib :: LiquidLib -> IO B.ByteString-encodeLiquidLib lib0 = do+encodeLiquidLib lib0 = rethrowWithCallStackIO $ do let (lib1, ns) = collectLHNames lib0 bh <- GHC.openBinMem (1024*1024) GHC.putWithUserData GHC.QuietBinIFace GHC.SafeExtraCompression bh ns@@ -103,7 +161,7 @@ return $ Builder.toLazyByteString $ B.execPut (B.put lib1) <> Builder.fromByteString bs decodeLiquidLib :: GHC.NameCache -> B.ByteString -> IO LiquidLib-decodeLiquidLib nameCache bs0 = do+decodeLiquidLib nameCache bs0 = rethrowWithCallStackIO $ do case B.decodeOrFail bs0 of Left (_, _, err) -> error $ "decodeLiquidLib: decodeOrFail: " ++ err Right (bs1, _, lib) -> do@@ -141,3 +199,10 @@ collectName acc@(sz, m, xs) n = case M.lookup n m of Just i -> (acc, LHRIndex i) Nothing -> ((sz + 1, M.insert n sz m, n : xs), LHRIndex sz)++-- | Rethrow an exception so we have an indication of where it was thrown in+-- the stack trace.+rethrowWithCallStackIO :: HasCallStack => IO a -> IO a+rethrowWithCallStackIO action = catchNoPropagate action $ \(ExceptionWithContext ctx (e :: SomeException)) -> do+ btAnn <- collectBacktraces+ rethrowIO $ ExceptionWithContext (addExceptionAnnotation btAnn ctx) e
src/Language/Haskell/Liquid/GHC/Plugin/SpecFinder.hs view
@@ -21,30 +21,36 @@ module Language.Haskell.Liquid.GHC.Plugin.SpecFinder ( findRelevantSpecs- , SpecFinderResult(..)+ , LoadedSpec(..) , configToRedundantDependencies ) where import qualified Language.Haskell.Liquid.GHC.Plugin.Serialisation as Serialisation import Language.Haskell.Liquid.GHC.Plugin.Types+import Language.Haskell.Liquid.Types.Specs import Language.Haskell.Liquid.UX.Config import Liquid.GHC.API as GHC import Data.Bifunctor import qualified Data.Char-import Data.IORef import Data.Maybe--import Control.Monad.Trans.Maybe---type SpecFinder m = Module -> MaybeT IO SpecFinderResult+import Control.Monad (foldM, unless)+import qualified Data.HashMap.Strict as HM --- | The result of searching for a spec.-data SpecFinderResult =- SpecNotFound Module- | LibFound Module LiquidLib+-- | One selected specification in the dependency accumulator, indexed by the+-- module identity in its reference. Forcing the specification field prevents+-- a 'libTarget' selector thunk from retaining the whole decoded library and+-- its reference list.+data LoadedSpec = LoadedSpec+ !Bool+ -- ^ 'True' when selected as the target of an input module lookup, including+ -- an _LHAssumptions fallback. Such a selection takes precedence over one+ -- reached only through a saved dependency reference ('False').+ !SpecReference+ -- ^ Full module identity and payload fingerprint of the selected library.+ !LiftedSpec+ -- ^ That library's own exported specification, used for verification. -- | Load any relevant spec for the input list of 'Module's, by querying both the 'ExternalPackageState' -- and the 'HomePackageTable'.@@ -55,26 +61,94 @@ -- -- Assumptions are taken from _LHAssumptions modules only if the interface -- file of the matching module contains no spec.-findRelevantSpecs :: [String] -- ^ Package to exclude for loading LHAssumptions+--+-- The result maps full module identities to their selected 'LoadedSpec',+-- including specifications reached through saved dependency references. Each+-- entry keeps the specification and its reference together, so the caller can+-- filter configuration-dependent exclusions once before extracting the+-- verification specifications and the references to export.+findRelevantSpecs :: Config -- ^ Assumption exclusions for this module -> HscEnv -> [Module] -- ^ Any relevant module fetched during dependency-discovery.- -> TcM [SpecFinderResult]-findRelevantSpecs lhAssmPkgExcludes hscEnv mods = do- eps <- liftIO $ readIORef (euc_eps $ ue_eps $ hsc_unit_env hscEnv)- mapM (loadRelevantSpec eps) mods+ -> TcM (HM.HashMap StableModule LoadedSpec)+findRelevantSpecs cfg hscEnv mods = foldM loadAndMerge HM.empty mods where+ -- Load an input module's library (or its matching assumptions), resolve its+ -- saved dependency references with mergeDependency, then select its own+ -- libTarget in the accumulator. If no library is found, leave it unchanged.+ -- "Merge" means selecting one whole LiftedSpec per module key; it does not+ -- combine fields from different specifications.+ --+ -- The first directly selected target for a key wins. A direct selection+ -- replaces a dependency-only selection, reusing its spec when references+ -- match. Process inputs in order because loading assumptions updates GHC's+ -- external package state. Force each updated map before the next input.+ loadAndMerge+ :: HM.HashMap StableModule LoadedSpec+ -> Module+ -> TcM (HM.HashMap StableModule LoadedSpec)+ loadAndMerge entries currentModule = do+ found <- loadRelevantSpec currentModule+ case found of+ Nothing -> pure entries+ Just (ref, lib) -> do+ entries' <- foldM mergeDependency entries (libDeps lib)+ let key = specModule ref+ merged = case HM.lookup key entries' of+ Just (LoadedSpec True _ _) -> entries'+ Just (LoadedSpec False oldRef spec) | oldRef == ref ->+ HM.insert key (LoadedSpec True ref spec) entries'+ _ -> HM.insert key (LoadedSpec True ref $ libTarget lib) entries'+ -- foldM does not force its accumulator. Complete this merge before+ -- loading the next interface, including imports with no dependencies.+ merged `seq` pure merged - loadRelevantSpec :: ExternalPackageState -> Module -> TcM SpecFinderResult- loadRelevantSpec eps currentModule = do- res <- liftIO $ runMaybeT $- lookupInterfaceAnnotations eps (ue_hpt $ hsc_unit_env hscEnv) (hsc_NC hscEnv) currentModule+ -- Resolve one saved dependency reference into the accumulator. An existing+ -- direct selection is retained only if its reference matches; a mismatch+ -- is an error. A matching dependency-only selection is also reused.+ -- Otherwise load the referenced interface, check the library's fingerprint,+ -- and insert its libTarget, replacing any dependency-only selection for+ -- that module. Missing or stale specifications fail verification; loader+ -- exceptions propagate.+ --+ -- This selects a whole specification, not a field-by-field combination.+ -- The referenced library's dependencies are not traversed here: the+ -- importing library already stores its selected references as a flat list.+ mergeDependency+ :: HM.HashMap StableModule LoadedSpec+ -> SpecReference+ -> TcM (HM.HashMap StableModule LoadedSpec)+ mergeDependency entries ref = case HM.lookup (specModule ref) entries of+ Just (LoadedSpec True actual _) -> do+ checkReference ref actual+ pure entries+ Just (LoadedSpec _ oldRef _) | oldRef == ref -> pure entries+ _ -> do+ let mdl = unStableModule $ specModule ref+ -- References include package/unit identity and the exact saved spec+ -- fingerprint. Never resolve them by an unqualified module name.+ _ <- initIfaceTcRn $ loadInterface "liquidhaskell dependency" mdl ImportBySystem+ found <- liftIO $ Serialisation.deserialiseLiquidLib hscEnv mdl+ case found of+ Just (actual, lib) -> do+ checkReference ref actual+ let merged = HM.insert (specModule ref) (LoadedSpec False ref $ libTarget lib) entries+ merged `seq` pure merged+ Nothing -> failWithTc $ mkTcRnUnknownMessage $ mkPlainError [] $+ text "LiquidHaskell: missing dependency specification; rebuild dependencies:" <+> ppr mdl++ checkReference ref actual = unless (actual == ref) $+ failWithTc $ mkTcRnUnknownMessage $ mkPlainError [] $+ text "LiquidHaskell: stale dependency specification; rebuild the importing module:" <+>+ ppr (unStableModule $ specModule ref)++ loadRelevantSpec :: Module -> TcM (Maybe (SpecReference, LiquidLib))+ loadRelevantSpec currentModule = do+ res <- liftIO $ Serialisation.deserialiseLiquidLib hscEnv currentModule case res of- Nothing -> do- mAssm <- loadModuleLHAssumptionsIfAny currentModule- return $ fromMaybe (SpecNotFound currentModule) mAssm- Just specResult ->- return specResult+ Nothing -> loadModuleLHAssumptionsIfAny currentModule+ Just _ -> pure res loadModuleLHAssumptionsIfAny m | isImportExcluded m = return Nothing | otherwise = do@@ -93,10 +167,7 @@ case res of Found _ assumptionsMod -> do _ <- initIfaceTcRn $ loadInterface "liquidhaskell assumptions" assumptionsMod ImportBySystem- -- read the EPS again- eps2 <- liftIO $ readIORef (euc_eps $ ue_eps $ hsc_unit_env hscEnv)- -- now look up the assumptions- liftIO $ runMaybeT $ lookupInterfaceAnnotationsEPS eps2 (hsc_NC hscEnv) assumptionsMod+ liftIO $ Serialisation.deserialiseLiquidLib hscEnv assumptionsMod FoundMultiple{} -> failWithTc $ mkTcRnUnknownMessage $ mkPlainError [] $ missingInterfaceErrorDiagnostic (initIfaceMessageOpts $ hsc_dflags hscEnv) $ cannotFindModule hscEnv assumptionsModName res@@ -104,21 +175,10 @@ isImportExcluded m = let s = takeWhile Data.Char.isAlphaNum $ unitString (moduleUnit m)- in elem s lhAssmPkgExcludes+ in elem s (excludeAutomaticAssumptionsFor cfg) assumptionsModuleName m = mkModuleNameFS $ moduleNameFS (moduleName m) <> "_LHAssumptions"---- | Load specs from an interface file.-lookupInterfaceAnnotations :: ExternalPackageState -> HomePackageTable -> NameCache -> SpecFinder m-lookupInterfaceAnnotations eps hpt nameCache thisModule = do- lib <- MaybeT $ Serialisation.deserialiseLiquidLib thisModule eps hpt nameCache- pure $ LibFound thisModule lib--lookupInterfaceAnnotationsEPS :: ExternalPackageState -> NameCache -> SpecFinder m-lookupInterfaceAnnotationsEPS eps nameCache thisModule = do- lib <- MaybeT $ Serialisation.deserialiseLiquidLibFromEPS thisModule eps nameCache- pure $ LibFound thisModule lib -- | Returns a list of 'StableModule's which can be filtered out of the dependency list, because they are -- selectively \"toggled\" on and off by the LiquidHaskell's configuration, which granularity can be
src/Language/Haskell/Liquid/GHC/Plugin/Types.hs view
@@ -12,7 +12,7 @@ , mkSpecComment , libTarget , libDeps- , allDeps+ , SpecReference(..) , addLibDependencies -- * Carrying data across stages of the compilation pipeline@@ -27,6 +27,7 @@ import Language.Haskell.Liquid.Parse (BPspec) import Language.Haskell.Liquid.Types.Specs+import Language.Haskell.Liquid.GHC.Plugin.Iface (PayloadId) import Liquid.GHC.API as GHC import Language.Haskell.Liquid.GHC.Misc (realSrcLocSourcePos) import Language.Fixpoint.Types.Spans ( SourcePos, dummyPos )@@ -35,18 +36,27 @@ data LiquidLib = LiquidLib { llTarget :: LiftedSpec -- ^ The target /LiftedSpec/.- , llDeps :: TargetDependencies- -- ^ The specs which were necessary to produce the target 'BareSpec'.+ , llDeps :: [SpecReference]+ -- ^ The exact dependency selection used to check the target. This is a flat+ -- list of references, so configuration-sensitive exclusions are preserved+ -- without embedding the dependencies' specification bodies again. } deriving (Show, Data, Generic) instance B.Binary LiquidLib +data SpecReference = SpecReference+ { specModule :: StableModule+ , specFingerprint :: PayloadId+ } deriving (Eq, Ord, Show, Data, Generic)++instance B.Binary SpecReference+ -- | Creates a new 'LiquidLib' with no dependencies. mkLiquidLib :: LiftedSpec -> LiquidLib mkLiquidLib s = LiquidLib s mempty -- | Adds a set of dependencies to the input 'LiquidLib'.-addLibDependencies :: TargetDependencies -> LiquidLib -> LiquidLib+addLibDependencies :: [SpecReference] -> LiquidLib -> LiquidLib addLibDependencies deps lib = lib { llDeps = deps <> llDeps lib } -- | Returns the target 'LiftedSpec' of this 'LiquidLib'.@@ -54,12 +64,8 @@ libTarget = llTarget -- | Returns all the dependencies of this 'LiquidLib'.-libDeps :: LiquidLib -> TargetDependencies+libDeps :: LiquidLib -> [SpecReference] libDeps = llDeps---- | Extracts all the dependencies from a collection of 'LiquidLib's.-allDeps :: Foldable f => f LiquidLib -> TargetDependencies-allDeps = foldl' (\acc lib -> acc <> llDeps lib) mempty -- | Just a small wrapper around the 'SourcePos' and the text fragment of a LH spec comment. newtype SpecComment =
src/Language/Haskell/Liquid/LHNameResolution.hs view
@@ -25,6 +25,10 @@ -- * Next the names of logic entities are resolved. This pass produces -- a 'BareSpecLHName', where 'Symbol's are replaced with 'LHName'. --+-- * A bit of name resolution is done in 'makeSpecVars' in "Language.Haskell.Liquid.Bare"+-- to check if the names in @ignore@ annotations refer to functions or type+-- class methods.+-- -- 'BareSpecLHName' has an approximate bijection to 'BareSpec' via a 'LogicNameEnv' -- which allows to convert 'LHName' to an unambiguous form of 'Symbol' -- and back. The bijection is implemented with the functions 'toBareSpecLHName'@@ -85,7 +89,7 @@ import Language.Fixpoint.Types as F hiding (Error, panic) import qualified Language.Haskell.Liquid.Bare.Resolve as Resolve-import Language.Haskell.Liquid.Bare.Types (LocalVars(lvNames), LocalVarDetails(lvdLclEnv))+import Language.Haskell.Liquid.Bare.Types (LocalVars(lvNames), LocalVarDetails(lvdIsTopLevel, lvdLclEnv)) import Language.Fixpoint.Misc as Misc import Language.Haskell.Liquid.Name.LogicNameEnv import qualified Language.Haskell.Liquid.Types.DataDecl as DataDecl@@ -172,9 +176,21 @@ checkErrors + -- Pre-resolve the head names of data and newtype declarations to+ -- GHC TyCons, bypassing type alias lookup. This ensures that a+ -- user-defined data type is not confused with an imported type alias+ -- of the same name (e.g. 'TT' in GHC.Types_LHAssumptions). When+ -- the same name is used in a type position (as opposed to the head+ -- of a data declaration) the type alias continues to take priority+ -- via the normal 'resolveLHName' path below.+ let sp0' = sp0+ { dataDecls = map resolveDataDeclHeadName (dataDecls sp0)+ , newtyDecls = map resolveDataDeclHeadName (newtyDecls sp0)+ }+ -- First resolution pass: A generic traversal that resolves names -- of Haskell entities and type alias binders.- sp1 <- lift $ mapMLocLHNames (\l -> (<$ l) <$> resolveLHName l) sp0+ sp1 <- lift $ mapMLocLHNames (\l -> (<$ l) <$> resolveLHName l) sp0' -- Data decls contain fieldnames that introduce measures with the -- same names. We resolve them before constructing the logic@@ -245,6 +261,26 @@ LHNUnresolved LHLogicNameBinder s -> pure $ makeLogicLHName s thisModule Nothing _ -> panic Nothing $ "unexpected name: " ++ show n + -- | Pre-resolve the head name of a data/newtype declaration to a GHC+ -- TyCon, bypassing type alias resolution. This prevents an imported+ -- type alias (e.g. @type TT = {v:Bool|v}@ in GHC.Types_LHAssumptions)+ -- from shadowing a user-defined data type with the same name.+ -- 'mapMLocLHNames' leaves already-resolved names untouched, so any name+ -- resolved here will not be visited again in the first resolution pass.+ resolveDataDeclHeadName decl =+ decl { DataDecl.tycName = resolveDataName (DataDecl.tycName decl) }+ where+ resolveDataName (DataDecl.DnName lname) =+ DataDecl.DnName (resolveHeadLHName lname)+ resolveDataName dn = dn++ resolveHeadLHName lname = case val lname of+ LHNUnresolved (LHTcName lcl) s ->+ case GHC.lookupGRE globalRdrEnv (mkLookupGRE (LHTcName lcl) s) of+ [e] -> LHNResolved (LHRGHC (GHC.greName e)) s <$ lname+ _ -> lname -- leave unresolved; normal pass will handle it+ _ -> lname -- already resolved or not a TyCon name+ resolveLHName lname = case val lname of LHNUnresolved (LHTcName lcl) s@@ -327,9 +363,10 @@ LHLogicNameBinder -> "logic name binder" LHLogicName -> "logic name" - isDataCon s = case Text.uncons (Text.takeWhileEnd (/= '.') (symbolText s)) of- Just (c, _) -> Char.isUpper c || c == ':'- Nothing -> False+isDataCon :: Symbol -> Bool+isDataCon s = case Text.uncons (Text.takeWhileEnd (/= '.') (symbolText s)) of+ Just (c, _) -> Char.isUpper c || c == ':'+ Nothing -> False tupleArity :: Symbol -> Int tupleArity s =@@ -340,18 +377,31 @@ a errResolve :: [Symbol] -> PJ.Doc -> String -> LocSymbol -> Error-errResolve alts k msg ls =+errResolve = errResolveWithHint PJ.empty++-- | Like 'errResolve' but takes a hint to show at the end of the message.+errResolveWithHint :: PJ.Doc -> [Symbol] -> PJ.Doc -> String -> LocSymbol -> Error+errResolveWithHint hint alts k msg ls = ErrResolve (LH.fSrcSpan ls) k (pprint $ val ls)- (if null alts then- PJ.text msg- else- PJ.text msg PJ.$$- PJ.sep (PJ.text "Maybe you meant one of:" : map pprint alts)- )+ (PJ.text msg PJ.$$ similarNames PJ.$$ hint)+ where+ similarNames+ | null alts = PJ.empty+ | otherwise = PJ.sep (PJ.text "Maybe you meant one of:" : map pprint alts) +errTypeclassDisabled :: PPrint a => Located a -> TError t+errTypeclassDisabled locSym =+ ErrResolve+ (LH.fSrcSpan locSym)+ "logic name"+ (pprint $ val locSym)+ (PJ.vcat+ [ PJ.text "This is a class method, but typeclass support is disabled."+ , PJ.text "Enable it with {-@ LIQUID \"--typeclass\" @-}."+ ]) -- | Produces an LHName from a symbol by looking it in the rdr environment. resolveSymbolToTcName :: GHC.GlobalRdrEnv -> LocSymbol -> Either Error (Located LHName)@@ -799,35 +849,49 @@ imeasures <- mapM (mapMeasureNamesM resolveIMeasLogicName) (imeasures sp) emapSpecM (bscope cfg)- (map localVarToSymbol . maybe [] lvdLclEnv . (GHC.lookupNameEnv (lvNames localVars) <=< getLHGHCName))+ (map localVarToSymbol . maybe [] lvdLclEnv . lookupLocalVar) resolveLogicName- (emapBareTypeVM (bscope cfg) resolveLogicName)+ (emapBareTypeVM (bscope cfg) . resolveLogicName) sp {imeasures} where resolveIMeasLogicName lx = case val lx of- LHNUnresolved LHLogicName s -> (<$ lx) <$> resolveLogicName [] (s <$ lx)+ LHNUnresolved LHLogicName s -> (<$ lx) <$> resolveLogicName Nothing [] (s <$ lx) _ -> panic (Just $ LH.fSrcSpan lx) $ "unexpected name: " ++ show lx + lookupLocalVar = GHC.lookupNameEnv (lvNames localVars) <=< getLHGHCName+ localVarToSymbol = F.symbol . GHC.occNameString . GHC.nameOccName . GHC.varName - resolveLogicName :: [Symbol] -> LocSymbol -> State RenameOutput LHName- resolveLogicName ss ls+ -- The first parameter is the name of the definition whose specification+ -- contains the name to resolve, if there is one.+ resolveLogicName :: Maybe LHName -> [Symbol] -> LocSymbol -> State RenameOutput LHName+ resolveLogicName mdef ss ls -- The name is local | elem s ss = return $ makeLocalLHName s | otherwise = case lookupInScopeEnv env s of Left alts ->- -- If names are not in the environment, they must be data constructors,- -- or they must be reflected functions, or they must be in the logicmap.+ -- If names are not in the environment, they must be one of the+ -- following: class methods, data constructors, reflected functions,+ -- or they must be in the logicmap. case resolveDataConName ls `mplus` resolveVarName lmap0 ls of Just m -> m- Nothing- | elem s wiredInNames ->- return $ makeLocalLHName s- | otherwise -> do- addError $ errResolve alts "logic name" "Cannot resolve name" ls- return $ makeLocalLHName s+ Nothing ->+ case resolveClassMethodName ls of+ Just m+ | typeclass cfg -> m+ | otherwise -> do+ addError $ errTypeclassDisabled ls+ return $ makeLocalLHName s++ Nothing+ | elem s wiredInNames ->+ return $ makeLocalLHName s+ | otherwise -> do+ addError $+ errResolveWithHint desugaringHint alts "logic name" "Cannot resolve name" ls+ return $ makeLocalLHName s Right [(_, lhname, _)] -> pure lhname -- In case of multiple matches, we give precedence to locally defined -- logic entities for the user to be able to overwrite them.@@ -840,6 +904,15 @@ return $ makeLocalLHName s where s = val ls+ desugaringHint+ | Just lvd <- lookupLocalVar =<< mdef+ , not (lvdIsTopLevel lvd)+ , not (LH.isQualifiedSym s)+ , not (isDataCon s)+ = PJ.text $+ "Desugaring can rename function parameters. For workarounds, see " +++ "https://github.com/ucsd-progsys/liquidhaskell/issues/2704"+ | otherwise = PJ.empty wiredInNames = map fst wiredSortedSyms ++ map (lhNameToResolvedSymbol . fst) (concatMap (DataDecl.dcpTyArgs . val) wiredDataCons)@@ -895,7 +968,35 @@ (map (PJ.text . GHC.showPprUnsafe) es) ) return $ makeLocalLHName $ val s+ resolveClassMethodName s =+ case GHC.lookupGRE globalRdrEnv (mkLookupGRE (LHVarName LHAnyModuleNameF) $ val s) of+ [e]+ | GHC.Vanilla <- GHC.greInfo e+ , Just pName <- GHC.greParent_maybe e+ , isClassTyCon pName ->+ Just $ do+ let n = GHC.greName e+ -- Do not register the class selector as reflected: typeclass+ -- compilation reflects generated `$c...` implementation methods,+ -- not selector IDs. Don't add the selector to `lneReflected`,+ -- i.e. don't use `Just n` instead of `Nothing` in the argument of+ -- type `Maybe Name` in `makeLogicLHName`.+ let lhName = makeLogicLHName+ (symbol $ GHC.getOccString n)+ (GHC.nameModule n)+ Nothing+ addName lhName+ return lhName+ _ -> Nothing + isClassTyCon parentName =+ case GHC.lookupGRE globalRdrEnv (mkLookupGRE (LHTcName LHAnyModuleNameF) (symbol $ GHC.occNameString $ GHC.nameOccName parentName)) of+ [parentGre] ->+ case GHC.greInfo parentGre of+ GHC.IAmTyCon GHC.ClassFlavour -> True+ _ -> False+ _ -> False+ -- Resolves names of reflected functions or names in the logic map -- -- Names of reflected functions are resolved here because, to be in scope,@@ -969,8 +1070,8 @@ emapSpecM (bscope cfg) (const [])- symToLHName- (emapBareTypeVM (bscope cfg) symToLHName)+ (const symToLHName)+ (const $ emapBareTypeVM (bscope cfg) symToLHName) sp symToLHName = symbolToLHName "toBareSpecLHName" lenv unhandledNames
src/Language/Haskell/Liquid/Liquid.hs view
@@ -37,20 +37,22 @@ import qualified Language.Haskell.Liquid.Termination.Structural as ST import qualified Language.Haskell.Liquid.GHC.Misc as GM import Liquid.GHC.API as GHC hiding (text, vcat, ($+$), (<+>))+import Language.Haskell.Liquid.Types.RType (SpecType) +-- Second output is intended for Refcore ---------------------------------------------------------------------------------checkTargetInfo :: TargetInfo -> IO (Output Doc)+checkTargetInfo :: TargetInfo -> IO (Output Doc, AnnInfo SpecType) -------------------------------------------------------------------------------- checkTargetInfo info = do- out <- check+ (out, infTypes) <- check when (diffcheck cfg && not (compileSpec cfg)) $ DC.saveResult tgt out- pure out+ pure (out, infTypes) where- check :: IO (Output Doc)+ check :: IO (Output Doc, AnnInfo SpecType) check | compileSpec cfg = do -- donePhase Loud "Only compiling specifications [skipping verification]"- pure mempty { o_result = F.Safe mempty }+ pure (mempty { o_result = F.Safe mempty }, mempty) | otherwise = do when (loggingVerbosity cfg == Normal) $ do F.donePhase F.Loud "Extracted Core using GHC"@@ -90,13 +92,13 @@ maybeEither d Nothing = Left d maybeEither _ (Just x) = Right [x] -liquidQueries :: Config -> FilePath -> TargetInfo -> Either [CoreBind] [DC.DiffCheck] -> IO (Output Doc)+liquidQueries :: Config -> FilePath -> TargetInfo -> Either [CoreBind] [DC.DiffCheck] -> IO (Output Doc, AnnInfo SpecType) liquidQueries cfg tgt info (Left cbs') = liquidQuery cfg tgt info (Left cbs') liquidQueries cfg tgt info (Right dcs) = mconcat <$> mapM (liquidQuery cfg tgt info . Right) dcs -liquidQuery :: Config -> FilePath -> TargetInfo -> Either [CoreBind] DC.DiffCheck -> IO (Output Doc)+liquidQuery :: Config -> FilePath -> TargetInfo -> Either [CoreBind] DC.DiffCheck -> IO (Output Doc, AnnInfo SpecType) liquidQuery cfg tgt info edc = do let names = either (const Nothing) (Just . map show . DC.checkedVars) edc let oldOut = either (const mempty) DC.oldOutput edc@@ -109,7 +111,7 @@ -- whenLoud $ mapM_ putStrLn [ "****************** CGInfo ********************" -- , render (pprint cgi) ] out <- timedAction names $ solveCs cfg tgt cgi info3 names- return $ mconcat [oldOut, out]+ return $ mconcat [(oldOut, mempty), out] updTargetInfoTermVars :: TargetInfo -> TargetInfo updTargetInfoTermVars i = updInfo i (ST.terminationVars i)@@ -130,7 +132,7 @@ pprintMany :: (PPrint a) => [a] -> Doc pprintMany xs = vcat [ F.pprint x $+$ text " " | x <- xs ] -solveCs :: Config -> FilePath -> CGInfo -> TargetInfo -> Maybe [String] -> IO (Output Doc)+solveCs :: Config -> FilePath -> CGInfo -> TargetInfo -> Maybe [String] -> IO (Output Doc, AnnInfo SpecType) solveCs cfg tgt cgi info names = do finfo <- cgInfoFInfo info cgi let fcfg = fixConfig tgt cfg@@ -146,9 +148,8 @@ `addErrors` makeFailUseErrors (S.toList failBs) (giCbs $ giSrc info) let lErrors = applySolution finfo sol <$> logErrors cgi let resModel = resModel' `addErrors` (e2u cfg <$> lErrors)- let out0 = mkOutput cfg resModel finfo sol (annotMap cgi)- return $ out0 { o_vars = names }- { o_result = resModel }+ let (out0, infTypes) = mkOutput cfg resModel finfo sol (annotMap cgi)+ return (out0 { o_vars = names } { o_result = resModel }, infTypes) e2u :: Config -> Error -> UserError
src/Language/Haskell/Liquid/Measure.hs view
@@ -88,6 +88,9 @@ mkError m ms = ErrDupMeas (fSrcSpan m) (pprint (val m)) (fSrcSpan <$> ms) +-- | Returns the specification types of all data constructors augmented with+-- the refinements from the measures. Also returns the specification types of+-- the measures in the second component of the result. dataConTypes :: Bool -> MSpec (RRType Reft) DataCon -> ([(Var, RRType Reft)], [(F.Located LHName, RRType Reft)]) dataConTypes allowTC s = (ctorTys, measTys) where@@ -107,11 +110,16 @@ _msg = "makeDataConType0" ++ showpp (woId, t, ts) makeDataConType allowTC ds- = [(woId, extend allowTC loci woRType wrRType), (wrId, extend allowTC loci wrRType woRType)]+ = [(woId, noDummySyms woRType), (wrId, noDummySyms wrRType)] where- (wo, wr) = L.partition isWorkerDef ds+ -- A measure with missing argument types comes from a selector or checker+ -- measure that describes the worker data constructor. A measure+ -- with all the argument types available comes from a user definition+ -- and describes both the worker and the wrapper.+ (workerOnlyDs, bothDs) = L.partition hasMissingFieldTypes ds+ wo = workerOnlyDs ++ bothDs+ wr = bothDs dc = ctor $ head ds- loci = loc $ measure $ head ds woId = dataConWorkId dc wot = varType woId wrId = dataConWrapId dc@@ -122,76 +130,32 @@ wrRType = combineDCTypes "cdc1" wrt wrts woRType = combineDCTypes "cdc2" wot wots -- isWorkerDef def- -- types are missing for arguments, so definition came from a logical measure- -- and it is for the worker datacon- | any (Mb.isNothing . snd) (binds def)- = True- | otherwise- = length (binds def) == length (fst $ splitFunTys $ snd $ splitForAllTyCoVars wot)---extend :: Bool- -> SourcePos- -> RType RTyCon RTyVar Reft- -> RRType Reft- -> RType RTyCon RTyVar Reft-extend allowTC lc t1' t2- | Just su <- mapArgumens allowTC lc t1 t2- = t1 `strengthenResult` subst su (Mb.fromMaybe mempty (stripRTypeBase $ resultTy t2))- | otherwise- = t1- where- t1 = noDummySyms t1'---resultTy :: RType c tv r -> RType c tv r-resultTy = ty_res . toRTypeRep--strengthenResult :: Meet r => RType c tv r -> r -> RType c tv r-strengthenResult t r = fromRTypeRep $ rep {ty_res = ty_res rep `strengthen` r}- where- rep = toRTypeRep t-+ -- types are missing for arguments, so the definition came from a logical+ -- measure and it is for the worker datacon only+ hasMissingFieldTypes def = any (Mb.isNothing . snd) (binds def) -noDummySyms :: (OkRT c tv r, Subable r, Variable r ~ Symbol, IsReft r) => RType c tv r -> RType c tv r+-- | If there are any dummy symbols in the type, replace them with fresh+-- variables.+--+-- WARNING: the current implementation might rename variables named as+-- dummySymbols event if they are not in the scope of the binder of a+-- dummy symbol. Might not be a problem at the places where noDummySyms is used,+-- but be careful if you want to use it in other places.+noDummySyms+ :: (OkRT c tv r, Subable r, Variable r ~ Symbol, IsReft r, ReftVar r ~ Symbol)+ => RType c tv r -> RType c tv r noDummySyms t | any isDummy (ty_binds rep)- = subst su $ fromRTypeRep $ rep{ty_binds = xs'}+ = F.subst su t -- substitution forces renaming of ty_binds to fresh variables | otherwise = t where rep = toRTypeRep t- xs' = zipWith (\_ i -> symbol ("x" ++ show i)) (ty_binds rep) [(1::Int)..]- su = mkSubst $ zip (ty_binds rep) (EVar <$> xs')+ su = mkSubst [ (v, EVar v) | v <- ty_binds rep ] combineDCTypes :: String -> Type -> [RRType Reft] -> RRType Reft combineDCTypes _msg t ts = L.foldl' strengthenRefTypeGen (ofType t) ts -mapArgumens :: Bool -> SourcePos -> RRType Reft -> RRType Reft -> Maybe Subst-mapArgumens allowTC lc t1 t2 = go xts1' xts2'- where- xts1 = zip (ty_binds rep1) (ty_args rep1)- xts2 = zip (ty_binds rep2) (ty_args rep2)- rep1 = toRTypeRep t1- rep2 = toRTypeRep t2-- xts1' = dropWhile canDrop xts1- xts2' = dropWhile canDrop xts2-- canDrop (_, t) = if allowTC then isEmbeddedClass t else isClassType t || isEqType t-- go xs ys- | length xs == length ys && and (zipWith (==) (toRSort . snd <$> xts1') (toRSort . snd <$> xts2'))- = Just $ mkSubst $ zipWith (\y x -> (fst x, EVar $ fst y)) xts1' xts2'- | otherwise- = panic (Just $ sourcePosSrcSpan lc) ("The types for the wrapper and worker data constructors cannot be merged\n"- ++ showpp t1 ++ "\n" ++ showpp t2 ++ "\n"- ++ "If there are UNPACK pragmas in effect, consider compiling with\n"- ++ "-fomit-interface-pragmas to ignore them.\n"- ++ "See https://github.com/ucsd-progsys/liquidhaskell/issues/2629")- -- should constructors have implicits? probably not defRefType :: Bool -> Type -> Def (RRType Reft) DataCon -> RRType Reft defRefType allowTC tdc (Def f dc mt xs body)@@ -210,10 +174,10 @@ (αs, tb) = splitForAllTyCoVars t (ts, tr) = splitFunTys tb -stitchArgs :: (Monoid t1, PPrint a)+stitchArgs :: Monoid t1 => Bool -> SrcSpan- -> a+ -> DataCon -> [(Symbol, Maybe (RRType Reft))] -> [Type] -> [(Symbol, RFInfo, RRType Reft, t1)]@@ -222,14 +186,21 @@ ++ zipWith g xs (ofType <$> ts) | otherwise = panicFieldNumMismatch sp dc nXs nTs where- (pts, ts) = L.partition (\t -> notracepp ("isPredTy: " ++ showpp t) $ (if allowTC then isEmbeddedDictType else Ghc.isSimplePredTy ) t) allTs+ (pts, ts) = L.partition (\t -> notracepp ("isPredTy: " ++ showpp t) $ isErasable t) allTs (_ , xs) = L.partition (coArg . snd) allXs nXs = length xs nTs = length ts g (x, Just t) _ = (x, classRFInfo allowTC, t, mempty) g (x, _) t = (x, classRFInfo allowTC, t, mempty) coArg Nothing = False- coArg (Just t) = (if allowTC then isEmbeddedDictType else Ghc.isSimplePredTy ). toType False $ t+ coArg (Just t) = isErasable (toType False t)+ isClassDc = Ghc.isClassTyCon (Ghc.dataConTyCon dc)+ -- For ordinary constructors, class dictionaries are constraint evidence,+ -- not fields. For class dictionary constructors, superclass dictionaries+ -- are fields and must be retained+ isErasable t+ | allowTC = isEmbeddedDictType t || (not isClassDc && Ghc.isClassPred t)+ | otherwise = Ghc.isSimplePredTy t panicFieldNumMismatch :: (PPrint a, PPrint a1, PPrint a3) => SrcSpan -> a3 -> a1 -> a -> a2
src/Language/Haskell/Liquid/Parse.hs view
@@ -1,13 +1,9 @@-{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskellQuotes #-}-{-# LANGUAGE TypeApplications #-} {-# OPTIONS_GHC -Wno-orphans #-} module Language.Haskell.Liquid.Parse@@ -100,11 +96,10 @@ initPStateWithList :: LHPState initPStateWithList- = (initPState composeFun)- { empList = Just $ \lx -> EVar (symbol (show '[]) <$ lx)- , singList = Just (\lx e -> EApp (EApp (EVar (symbol (show '(:)) <$ lx)) e) (EVar (symbol (show '[]) <$ lx)))- }- where composeFun = Nothing+ = initPState+ { empList = Just $ \lx -> EVar (symbol (show '[]) <$ lx)+ , singList = Just (\lx e -> EApp (EApp (EVar (symbol (show '(:)) <$ lx)) e) (EVar (symbol (show '[]) <$ lx)))+ } ------------------------------------------------------------------------------- singleSpecP :: SourcePos -> String -> Either (ParseErrorBundle String Void) BPspec@@ -515,7 +510,7 @@ (replicate (length xts + 1) trueURef) ((snd <$> xts) ++ [t1]) <$> bareTypeP -trueURef :: UReftV v (ReftV v)+trueURef :: UReftV v trueURef = MkUReft F.trueReft (Pr []) constraintEnvP :: Parser [(LocSymbol, BareTypeParsed)]@@ -587,7 +582,7 @@ = symbol <$> tyVarIdP bPVar :: Symbol -> t -> [(Symbol, t1)] -> PVarV LocSymbol t1-bPVar p _ xts = PV p τ dummySymbol τxs+bPVar p _ xts = PV p τ τxs where (_, τ) = safeLast "bPVar last" xts τxs = [ (τ', x, EVar (dummyLoc x)) | (x, τ') <- init xts ]@@ -692,7 +687,7 @@ predVarUseP :: Parser (PVarV LocSymbol String) predVarUseP = do (p, xs) <- funArgsP- return $ PV p dummyTyId dummySymbol [ (dummyTyId, dummySymbol, x) | x <- xs ]+ return $ PV p dummyTyId [ (dummyTyId, dummySymbol, x) | x <- xs ] funArgsP :: Parser (Symbol, [ExprV LocSymbol]) funArgsP = try realP <|> empP <?> "funArgsP"@@ -752,7 +747,7 @@ ------------------------------------------------------------------------ bRProp :: [((Symbol, τ), Symbol)]- -> ExprV LocSymbol -> Ref τ (RTypeV LocSymbol c BTyVar (UReftV LocSymbol (ReftV LocSymbol)))+ -> ExprV LocSymbol -> Ref τ (RTypeV LocSymbol c BTyVar (UReftV LocSymbol)) bRProp [] _ = panic Nothing "Parse.bRProp empty list" bRProp syms' epr = RProp ss $ bRVar (BTV $ dummyLoc dummyName) (Pr []) r where@@ -767,20 +762,25 @@ notTrivial (x, EVar y) = x /= toB y notTrivial _ = True -bRVar :: tv -> PredicateV v -> r -> RTypeV v c tv (UReftV v r)+bRVar :: tv -> PredicateV v -> ReftV v -> RTypeV v c tv (UReftV v) bRVar α p r = RVar α (MkUReft r p) -bLst :: Maybe (RTypeV v BTyCon tv (UReftV v r))- -> [RTPropV v BTyCon tv (UReftV v r)]- -> r- -> RTypeV v BTyCon tv (UReftV v r)+bLst :: Maybe (RTypeV v BTyCon tv (UReftV v))+ -> [RTPropV v BTyCon tv (UReftV v)]+ -> ReftV v+ -> RTypeV v BTyCon tv (UReftV v) bLst (Just t) rs r = RApp (mkBTyCon $ dummyLoc $ makeUnresolvedLHName (LHTcName LHAnyModuleNameF) listConName) [t] rs (reftUReft r) bLst Nothing rs r = RApp (mkBTyCon $ dummyLoc $ makeUnresolvedLHName (LHTcName LHAnyModuleNameF) listConName) [] rs (reftUReft r) -bTup :: [(Maybe Symbol, BareTypeParsed)]- -> [RTPropV LocSymbol BTyCon BTyVar (UReftV LocSymbol (ReftV LocSymbol))]- -> ReftV LocSymbol- -> BareTypeParsed+-- | Makes the representation of a tuple type.+bTup+ -- | Types of the tuple components, with an optional binding.+ :: [(Maybe Symbol, BareTypeParsed)]+ -- | Abstract predicates of the tuple if any, like @r@ in @(a :: ta, tb) <r>@+ -> [RTPropV LocSymbol BTyCon BTyVar (UReftV LocSymbol)]+ -- | Refinement type for the tuple, like @{v:_|q}@ in @{v:(a :: ta, tb) | q}@+ -> ReftV LocSymbol+ -> BareTypeParsed bTup [(_,t)] rs r | not (null rs) = case appendRProps t rs of@@ -799,9 +799,14 @@ (mkBTyCon $ dummyLoc $ makeUnresolvedLHName (LHTcName LHAnyModuleNameF) $ tyTupleSizedSymbol (length ts)) (snd <$> ts) rs (reftUReft r) | otherwise+ -- there is more than one tuple component, and at least one of them has a+ -- binding, so this is a dependent tuple.+ --+ -- @(a :: ta, tb)@ is desugared to @(ta, _) <{\a -> tb}>)@. Keep the+ -- refinement on @ta@: there is no generated RProp from which to recover it. = RApp (mkBTyCon $ dummyLoc $ makeUnresolvedLHName (LHTcName LHAnyModuleNameF) $ tyTupleSizedSymbol (length ts))- (mapReft (const trueURef) . snd <$> ts)+ (snd (head ts) : [ RHole trueURef | _ <- tail ts ]) rs' (reftUReft r) where@@ -823,11 +828,11 @@ -- TODO RApp Int [] [p] true should be syntactically different than RApp Int [] [] p -- bCon b s [RProp _ (RHole r1)] [] _ r = RApp b [] [] $ r1 `meet` (MkUReft r mempty s) bCon :: c- -> [RTPropV v c tv (UReftV v r)]- -> [RTypeV v c tv (UReftV v r)]+ -> [RTPropV v c tv (UReftV v)]+ -> [RTypeV v c tv (UReftV v)] -> PredicateV v- -> r- -> RTypeV v c tv (UReftV v r)+ -> ReftV v+ -> RTypeV v c tv (UReftV v) bCon b rs ts p r = RApp b ts rs $ MkUReft r p bAppTy :: Foldable t => BTyVar -> t BareTypeParsed -> ReftV LocSymbol -> BareTypeParsed@@ -836,7 +841,7 @@ ts' = foldl' (\a b -> RAppTy a b (uTop F.trueReft)) (RVar v (uTop F.trueReft)) ts strengthenUReft- :: BareTypeParsed -> UReftV LocSymbol (ReftV LocSymbol) -> BareTypeParsed+ :: BareTypeParsed -> UReftV LocSymbol -> BareTypeParsed strengthenUReft = strengthenWith meetUReft where meetUReft (MkUReft r0 (Pr p0)) (MkUReft r1 (Pr p1)) =@@ -880,10 +885,10 @@ s2' = fromKVarSubst s2 -reftUReft :: r -> UReftV v r+reftUReft :: ReftV v -> UReftV v reftUReft r = MkUReft r (Pr []) -predUReft :: PredicateV v -> UReftV v (ReftV v)+predUReft :: PredicateV v -> UReftV v predUReft = MkUReft F.trueReft dummyTyId :: String@@ -1165,7 +1170,7 @@ <|> (reserved "infixr" >> fmap BFix infixrP ) <|> (reserved "infix" >> fmap BFix infixP ) <|> fallbackSpecP "inline" (fmap Inline locBinderThisModuleLHNameP)- <|> fallbackSpecP "ignore" (fmap Ignore locBinderThisModuleLHNameP)+ <|> fallbackSpecP "ignore" (fmap Ignore locBinderLHNameP) <|> fallbackSpecP "bound" (fmap PBound boundP) <|> (reserved "class"
+ src/Language/Haskell/Liquid/RefCore/Calculus.hs view
@@ -0,0 +1,552 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OrPatterns #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Grammars, printer and suable functions for ILH+module Language.Haskell.Liquid.RefCore.Calculus+ ( -- * Grammar+ Builtin (..),+ BaseType (..),+ RefType (..),+ Decl (..),+ Expr (..),+ Reft (..),+ ProjKind (..),+ Localization (..),+ DesState (..),+ Bop (..),+ ProofOp (..),++ -- * Builtin type and data constructors+ boolTp,+ ttTm,+ ffTm,+ unitTp,+ unitTm,++ -- * Construction and destruction+ mkVar,+ arrs,+ apps,+ renameParams,++ -- * Free variables and substitution+ HasVars (..),+ freeVars,+ fresh,+ rename,+ substs,+ )+where++import Data.Bifunctor (first)+import Data.Binary (Binary)+import Data.Data+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Set (Set)+import qualified Data.Set as Set+import GHC.Generics (Generic)+import Language.Haskell.Liquid.RefCore.Names (Id, boolTpName, ffTmName, freshVar, ttTmName, unitTmName, unitTpName)+import Text.PrettyPrint+import Text.PrettyPrint.HughesPJClass hiding (first)+import Prelude hiding (lookup, (<>))++-- * The grammar++-- ** Types++-- | Builtin types+-- In Fixpoint, we have the Constant types Integer, Double and Text. There, from GHC.Core,+-- Floats are stored as Double, and Chars and Strings are converted to Text (we switch back to+-- Strings for simplicity). Other GHC.Core literals are not relevant for us+--+-- > B ::= Integer | Double | String+data Builtin = Integer | Double | String deriving (Data, Eq, Show, Generic, Binary)++-- | Base Types+--+-- > A ::= B | TC+data BaseType = Builtin Builtin | TC Id deriving (Data, Eq, Show, Generic, Binary)++-- | Refinement types+--+-- > R ::= {x: A | r} | x:Rx -> R+data RefType+ = RefType Id BaseType Reft+ | ArrType Id RefType RefType+ deriving (Data, Show, Generic, Binary)++-- ** Declaration-level grammar++-- | Declarations+--+-- > D ::= data tc := (C :: R)*+-- > | (reflect)? def f :: R := e+data Decl+ = -- | type constructor: name and branches with (constructor name, type)+ Data Id [(Id, RefType)]+ | -- | (function) definition: name, type, body, is it reflected+ Definition Id RefType Expr Bool+ | -- | imported module: module name and its declarations+ Import Id [Decl]+ deriving (Data, Eq, Show, Generic, Binary)++-- | Structural expressions+--+-- > e ::= r+-- > | let x (:: R)? := e in e+-- > | case r of (C [(x,bool)]* |-> (e | unreachable))*+-- > | e ? (e proves r)+data Expr+ = -- | Refinement used as expression+ Reft Reft+ | -- | Let with type annotation. binds the dependent variables in R+ -- for lets in the code, we can always get an annotation, but we also create some for ANF+ Let Id (Maybe RefType) Expr Expr+ | -- | Pattern matching (includes conditionals), with Maybe for optional branches.+ -- The boolean in the list of parameters is true if the parameter is inductive+ -- and we are destructing one of the parameters of the function+ -- The last element indicates if the case must be translated to+ -- destruct (Nothing) or induction, in which case we have the list of variables to generalize+ Case Reft [((Id, [(Id, Bool)]), Maybe Expr)] (Maybe [Id])+ | QMark Expr Expr Reft+ deriving (Data, Show, Generic, Binary)++-- | Simple LH terms including formulas.+-- Terms of this type can occur as (sub)terms in refinements+-- Variables are annotated with their localization and,+-- if they are a function type, with their unrefined return type+--+-- > r ::= x/(A,loc)+-- > | lit ∈ B+-- > | C+-- > | r r+-- > | ¬r+-- > | r `op` r+-- > | r `pop` r+data Reft+ = Var Id (Maybe BaseType) Localization+ | StringLit String+ | IntLit Integer+ | FloatLit Double+ | DC Id+ | App Reft Reft+ | Neg Reft+ | Bop Bop Reft Reft+ | Pop ProofOp Reft Reft+ | Sub Reft RefType RefType+ | Inj Reft RefType+ | Proj ProjKind Reft+ deriving (Data, Eq, Show, Generic, Binary)++-- | The different kinds of projections:+-- `proj` from the generalized projections typeclass,+-- Rocq's `proj1_sig1` and `proj2_sig`+-- FIX: we shouldn't need this here, only in Rocq,+-- but Rocq cannot always find the correct instance+data ProjKind = GenProj | Sig1 | Sig2 deriving (Data, Eq, Show, Generic, Binary)++-- | Localization of the variables.+-- The recursive variables take the name of the induction variable+-- (this is used to clean up unused IHs) and the current branch pattern+--+-- loc ::= L | G | Y (x, σ)+data Localization = Local | Global | Recursive Id [DesState] deriving (Data, Eq, Show, Generic, Binary)++-- | State of the parameters: either intact (with name and arity) or destructed+-- This state is used to elaborate pattern matching and recursive variables, and to translate recursive calls+data DesState = Param Id Integer | Destructed deriving (Data, Eq, Show, Generic, Binary)++-- | Builtin binary operators (@op@)+data Bop+ = Plus+ | Minus+ | Times+ | Div+ | Mod+ | Eq+ | Neq+ | Leq+ | Geq+ | Lt+ | Gt+ | And+ | Or+ | Impl+ | Iff+ deriving (Data, Eq, Generic, Binary)++-- | Binary proof operators+--+-- > pop ::= === | =<= | =>=+data ProofOp = PEq | PLeq | PGeq deriving (Data, Eq, Generic, Binary)++-- Builtin type and data constructors++boolTp, unitTp :: BaseType+unitTm, ttTm, ffTm :: Reft+boolTp = TC boolTpName+unitTp = TC unitTpName++ttTm = DC ttTmName++ffTm = DC ffTmName++unitTm = DC unitTmName++-- * Functions on the terms++-- ** Constructions++-- | Make a local variable reference with a dummy type+mkVar :: Id -> Reft+mkVar x = Var x Nothing Local++-- ** Other functions++-- | arrs(R) := (x_i:R_i)_{i ≤ n} -> R' where n is maximal+arrs :: RefType -> ([(Id, RefType)], (Id, BaseType, Reft))+arrs (RefType x a r) = ([], (x, a, r))+arrs (ArrType x tpx tp) = ((x, tpx) :) `first` arrs tp++-- | Flattens an application+apps :: Reft -> (Reft, [Reft])+apps (App tm1 tm2) = let (hd, args) = apps tm1 in (hd, args ++ [tm2])+apps tm = (tm, [])++-- | Rename all the arguments of an arrow:+--+-- > renameParams([y1,y2], x1:{x1:B | True} -> x2:{x2:B | x1 == x2} -> {v:B | v = x1 + x2})+-- > = y1:{x1:B | True} -> y2:{x2:B | y1 == x2} -> {v:B | v = y1 + y2}+renameParams :: [Id] -> RefType -> RefType+renameParams = aux []+ where+ aux :: [(Id, Id)] -> [Id] -> RefType -> RefType+ aux σ _ tp@(RefType {}) = renames σ tp+ aux σ [] tp = renames σ tp+ aux σ (y : ys) (ArrType x tpx tp)+ | x `notElem` freeVars tp || x == y =+ ArrType y (renames σ tpx) (aux σ ys tp)+ -- NOTE: we could handle some of the error cases by applying the+ -- substitutions globally for each binder, or by traversing the type in the+ -- opposite direction. But with reasonable namings that should not be necessary+ aux _ (y : _) tp0@(ArrType x _ tp)+ | y `elem` freeVars tp =+ error . render $ "Name clash while renaming variable" <+> text x <+> "to" <+> text y <+> "in" <+> pPrint tp0+ aux σ (y : ys) (ArrType x tpx tp) =+ ArrType y (renames σ tpx) (aux ((y, x) : σ) ys tp)++-- * Typeclass related to free variables++class HasVars a where+ -- | Return the free variables with their return type and localization+ freeVarsAnnot :: a -> Map Id (Maybe BaseType, Localization)++ -- | Return the bound variables with their type (they are all local)+ boundVars :: a -> Set Id++ -- | subst r x tm is {r/x}tm+ subst :: Reft -> Id -> a -> a++freeVars :: (HasVars a) => a -> Set Id+freeVars tm = Map.keysSet $ freeVarsAnnot tm++-- | return a variable fresh wrt to the free and bound variables in the second argument+fresh :: (HasVars a) => Id -> a -> Id+fresh x tm = freshVar x (freeVars tm `Set.union` boundVars tm)++-- | Rename the second argument to the first in the third+--+-- > rename y x tm = {y/x}tm+rename :: (HasVars a) => Id -> Id -> a -> a+rename new old tm =+ maybe+ tm+ (\(tp, loc) -> subst (Var new tp loc) old tm)+ (Map.lookup old $ freeVarsAnnot tm)++-- | Apply a list of renamings, starting from the right+renames :: (HasVars a) => [(Id, Id)] -> a -> a+renames = flip (foldr (uncurry rename))++-- | Apply a list of substitutions, starting from the right+substs :: (HasVars a) => [(Reft, Id)] -> a -> a+substs = flip (foldr (uncurry subst))++instance HasVars Reft where+ freeVarsAnnot (Var x tp loc) = Map.singleton x (tp, loc)+ freeVarsAnnot (App hd arg) = freeVarsAnnot [hd, arg]+ freeVarsAnnot (Bop _ r1 r2) = freeVarsAnnot [r1, r2]+ freeVarsAnnot (Neg r) = freeVarsAnnot r+ freeVarsAnnot (StringLit _; IntLit _; FloatLit _; DC _) = Map.empty+ freeVarsAnnot (Pop _ r1 r2) = freeVarsAnnot [r1, r2]+ freeVarsAnnot (Sub r from to) = freeVarsAnnot r `Map.union` freeVarsAnnot [from, to]+ freeVarsAnnot (Inj r tp) = freeVarsAnnot r `Map.union` freeVarsAnnot tp+ freeVarsAnnot (Proj _ r) = freeVarsAnnot r++ -- Empty on unelaborated refinements, but has the bound variables of the types in casts+ boundVars (Var {}; StringLit _; IntLit _; FloatLit _; DC _) = Set.empty+ boundVars (App hd arg) = boundVars [hd, arg]+ boundVars (Bop _ r1 r2) = boundVars [r1, r2]+ boundVars (Neg r) = boundVars r+ boundVars (Pop _ r1 r2) = boundVars [r1, r2]+ boundVars (Sub r from to) = boundVars r `Set.union` boundVars [from, to]+ boundVars (Inj r tp) = boundVars r `Set.union` boundVars tp+ boundVars (Proj _ r) = boundVars r++ subst r' x (Var y _ _) | y == x = r'+ subst _ _ r0@(Var {}; StringLit _; IntLit _; FloatLit _; DC _) = r0+ subst r' x (App h arg) = App (subst r' x h) (subst r' x arg)+ subst r' x (Bop bop r1 r2) = Bop bop (subst r' x r1) (subst r' x r2)+ subst r' x (Neg r) = Neg $ subst r' x r+ subst r' x (Pop pop r1 r2) = Pop pop (subst r' x r1) (subst r' x r2)+ subst r' x (Sub r tps tpt) = Sub (subst r' x r) (subst r' x tps) (subst r' x tpt)+ subst r' x (Inj r tp) = Inj (subst r' x r) (subst r' x tp)+ subst r' x (Proj kind r) = Proj kind (subst r' x r)++instance HasVars Expr where+ freeVarsAnnot (Reft r) = freeVarsAnnot r+ freeVarsAnnot (Let x tp ex e) =+ freeVarsAnnot tp `Map.union` Map.delete x (freeVarsAnnot [ex, e])+ freeVarsAnnot (Case r branches _) =+ freeVarsAnnot r `Map.union` Map.unions (map fvBranch branches)+ where+ fvBranch ((_, ys), ebr) = freeVarsAnnot ebr `Map.withoutKeys` Set.fromList (map fst ys)+ freeVarsAnnot (QMark r rh rp) = freeVarsAnnot [r, rh, Reft rp]++ boundVars (Reft r) = boundVars r+ boundVars (Let x tp ex e) =+ Set.singleton x `Set.union` boundVars tp `Set.union` boundVars [ex, e]+ boundVars (Case r branches _) =+ boundVars r `Set.union` Set.unions (map bvBranch branches)+ where+ bvBranch ((_, ys), e) = Set.fromList (map fst ys) `Set.union` boundVars e+ boundVars (QMark r rh rp) = boundVars [r, rh, Reft rp]++ subst r x (Reft re) = Reft $ subst r x re+ subst r x (Let y tp ey e')+ | y == x = Let y (subst r x tp) (subst r x ey) e'+ | y `Set.member` freeVars r && x `Set.member` freeVars e' =+ Let z (subst r x tp) (subst r x ey) (subst r x $ rename z y e')+ | otherwise = Let y (subst r x tp) (subst r x ey) (subst r x e')+ where+ z = freshVar y (freeVars r `Set.union` freeVars (Let y tp ey e'))+ subst r x (Case r' branches genVars) =+ Case (subst r x r') (map substBranch branches) genVars+ where+ substBranch br@((_, ys), ebr)+ | x `elem` map fst ys || maybe True (notElem x . freeVars) ebr = br+ substBranch ((c, ys), ebr) = ((c, ys'), subst r x $ renames α ebr)+ where+ freshYs = foldr freshVars [] ys+ α = filter (uncurry (/=)) $ zipWith (\(y, _) z -> (z, y)) ys freshYs+ ys' = zipWith (\(_, b) z -> (z, b)) ys freshYs+ freshVars (y, _) vars =+ if y `elem` freeVars r+ then freshVar y (fvre `Set.union` Set.fromList vars) : vars+ else y : vars+ fvre = freeVars r `Set.union` freeVars (Case r' branches genVars)+ subst r x (QMark r' rh rp) = QMark (subst r x r') (subst r x rh) (subst r x rp)++instance HasVars RefType where+ freeVarsAnnot (RefType x _ r) = Map.delete x (freeVarsAnnot r)+ freeVarsAnnot (ArrType x tpx tp) =+ freeVarsAnnot tpx `Map.union` Map.delete x (freeVarsAnnot tp)++ boundVars (RefType x _ r) = Set.singleton x `Set.union` boundVars r+ boundVars (ArrType x tpx tp) = Set.singleton x `Set.union` boundVars [tpx, tp]++ subst _ x tp@(RefType y _ _) | y == x = tp+ subst r x (RefType y b reft) = RefType y b $ subst r x reft+ subst r x (ArrType y tpy tp')+ | y == x = ArrType y (subst r x tpy) tp'+ | y `Set.member` freeVars r && x `Set.member` freeVars tp' =+ ArrType z (subst r x tpy) (subst r x $ rename z y tp')+ | otherwise = ArrType y (subst r x tpy) (subst r x tp')+ where+ z = freshVar y (freeVars r `Set.union` freeVars (ArrType y tpy tp'))++instance (HasVars a) => HasVars [a] where+ freeVarsAnnot tms = Map.unions $ map freeVarsAnnot tms+ boundVars tms = Set.unions $ map boundVars tms+ subst r x = fmap (subst r x)++instance (HasVars a) => HasVars (Maybe a) where+ freeVarsAnnot = maybe Map.empty freeVarsAnnot+ boundVars = maybe Set.empty boundVars+ subst r x = fmap (subst r x)++-- * Equality instance using α-renaming++instance Eq RefType where+ tp1@(RefType x tpx rx) == tp2@(RefType y tpy ry) =+ let z = fresh x [tp1, tp2]+ (α1, α2) = if x /= y then ([(z, x)], [(z, y)]) else ([], [])+ in tpx == tpy && renames α1 rx == renames α2 ry+ tp1@(ArrType x tpx tp1') == tp2@(ArrType y tpy tp2') =+ let z = fresh x [tp1, tp2]+ (α1, α2) = if x /= y then ([(z, x)], [(z, y)]) else ([], [])+ in tpx == tpy && renames α1 tp1' == renames α2 tp2'+ _ == _ = False++instance Eq Expr where+ Reft r1 == Reft r2 = r1 == r2+ e1@(Let x tpx ex e1') == e2@(Let y tpy ey e2') =+ let z = fresh x [e1, e2]+ (α1, α2) = if x /= y then ([(z, x)], [(z, y)]) else ([], [])+ in tpx == tpy && ex == ey && renames α1 e1' == renames α2 e2'+ e1@(Case r1 alts1 genVars1) == e2@(Case r2 alts2 genVars2) =+ -- Equality is sensitive to the order of the alternatives+ r1 == r2 && all eqBranch (zip alts1 alts2) && genVars1 == genVars2+ where+ eqBranch (((c1, ys1), ebr1), ((c2, ys2), ebr2)) =+ let freshYs = foldr freshVars [] (zip ys1 ys2)+ α ys = filter (uncurry (/=)) $ zipWith (\(y, _) z -> (z, y)) ys freshYs+ in c1 == c2 && renames (α ys1) ebr1 == renames (α ys2) ebr2+ freshVars ((y1, _), (y2, _)) vars =+ if y1 /= y2+ then freshVar y1 (freeVars [e1, e2] `Set.union` Set.fromList vars) : vars+ else y1 : vars+ _ == _ = False++-- * Printer for the grammar++-- | Number of spaces in the indentation+identNb :: Int+identNb = 2++-- ** Precedence levels++-- TODO: harmonize with Rocq for simplicity++arrPrec :: Rational+arrPrec = 0++appPrec :: Rational+appPrec = 10++bopPrec :: Bop -> Rational+bopPrec Mod = 7+bopPrec Plus = 6+bopPrec Minus = 6+bopPrec Times = 7+bopPrec Div = 7+bopPrec Eq = 4+bopPrec Neq = 4+bopPrec Leq = 4+bopPrec Geq = 4+bopPrec Lt = 4+bopPrec Gt = 4+bopPrec And = 3+bopPrec Or = 2+bopPrec Impl = 1+bopPrec Iff = 1++popPrec :: ProofOp -> Rational+popPrec _ = 4++-- ** Instances++instance Pretty Builtin where+ pPrint = text . show++instance Pretty BaseType where+ pPrint (Builtin b) = pPrint b+ pPrint (TC tc) = text tc++instance Pretty RefType where+ pPrintPrec _ _ (RefType _ a r) | r == ttTm = braces $ pPrint a+ pPrintPrec _ _ (RefType _ a r) | a == unitTp = braces . braces $ pPrint r+ pPrintPrec _ _ (RefType x a r) =+ braces (text x <> colon <+> pPrint a <+> char '|' <+> pPrint r)+ pPrintPrec l p (ArrType x tpx tp) =+ maybeParens (p > arrPrec) $ sep [text x <> colon <+> pPrintPrec l (arrPrec + 1) tpx, "->" <+> pPrintPrec l arrPrec tp]++instance Pretty Decl where+ pPrint (Data tc constrs) =+ sep [ppTC, nest identNb . sep $ map (\dc -> char '|' <+> ppConstr dc) constrs]+ where+ ppTC = "data" <+> text tc <+> ":="+ ppConstr (c, tpc) = text c <+> "::" <+> pPrint tpc+ pPrint (Definition f tp e isRefl) =+ sep [ppRefl <+> ppF, nest identNb (pPrint e)]+ where+ ppRefl = if isRefl then "refl" else empty+ ppF = "def" <+> text f <+> "::" <+> pPrint tp <+> ":="+ pPrint (Import modName decls) =+ vcat $ ("import" <+> text modName) : map (nest identNb . pPrint) decls++instance Pretty Expr where+ pPrint (Reft r) = pPrint r+ pPrint (Let x tpx ex e) = sep [sep [ppLet, pPrint ex], nest 1 ("in" <+> pPrint e)]+ where+ ppLet = "let" <+> ppTp <+> ":="+ ppTp = case tpx of+ Nothing -> text x+ Just tp -> parens (text x <> colon <+> pPrint tp)+ pPrint (Case r alts genVars) =+ vcat $ (des <+> pPrint r <+> "of") : map ppAlt alts+ where+ des = case genVars of Nothing -> "destruct"; Just _ -> "induct"+ ppAlt (pat, e) = sep [char '|' <+> ppPat pat <+> "->", nest identNb $ maybe "undefined" pPrint e]+ ppPat (c, ys) = text c <+> hsep (map (text . fst) ys)+ pPrint (QMark r rh rp) =+ pPrint r <+> char '?' <+> parens (pPrint rh <+> "proves" <+> pPrint rp)++instance Pretty Reft where+ pPrintPrec _ _ (Var x _ _) = text x+ pPrintPrec _ _ (StringLit s) = quotes $ text s+ pPrintPrec _ _ (IntLit i) = integer i+ pPrintPrec _ _ (FloatLit f) = double f+ pPrintPrec _ _ (DC c) = text c+ pPrintPrec l p (App r1 r2) =+ maybeParens (p > appPrec) $ pPrintPrec l p r1 <+> pPrintPrec l (appPrec + 1) r2+ pPrintPrec l p (Neg r) =+ maybeParens (p > appPrec) $ "not" <+> pPrintPrec l (appPrec + 1) r+ pPrintPrec l p (Bop bop r1 r2) =+ maybeParens (p > bopPrec bop) $ pPrintPrec l (bopPrec bop) r1 <+> pPrint bop <+> pPrintPrec l (bopPrec bop) r2+ pPrintPrec l p (Pop pop r1 r2) =+ maybeParens (p > popPrec pop) $ pPrintPrec l (popPrec pop) r1 <+> pPrint pop <+> pPrintPrec l (popPrec pop) r2+ pPrintPrec _ p (Sub r from to) =+ maybeParens (p > appPrec) $ "sub" <+> parens (hsep $ punctuate comma (pPrint r : map pPrint [from, to]))+ pPrintPrec _ p (Inj r tp) =+ maybeParens (p > appPrec) $ "inj" <+> parens (pPrint r <> comma <+> pPrint tp)+ pPrintPrec l p (Proj _ r) =+ maybeParens (p > appPrec) $ "proj" <+> pPrintPrec l (appPrec + 1) r++instance Pretty Localization where+ pPrint Local = char 'L'+ pPrint Global = char 'G'+ pPrint (Recursive indVar _) = char 'Y' <+> text indVar++instance Show Bop where+ show Mod = "`mod`"+ show Plus = "+"+ show Minus = "-"+ show Times = "*"+ show Div = "/"+ show Eq = "=="+ show Neq = "/="+ show Leq = "<="+ show Geq = ">="+ show Lt = "<"+ show Gt = ">"+ show And = "&&"+ show Or = "||"+ show Impl = "=>"+ show Iff = "<=>"++instance Pretty Bop where+ pPrint = text . show++instance Show ProofOp where+ show PEq = "==="+ show PLeq = "=<="+ show PGeq = "=>="++instance Pretty ProofOp where+ pPrint = text . show
+ src/Language/Haskell/Liquid/RefCore/CoreToLH.hs view
@@ -0,0 +1,405 @@+{-# LANGUAGE ConstraintKinds #-}+{-# OPTIONS_GHC -Wall #-}++-- |+-- - Main module for the translation between GHC Core Haskell and RefCore Calculus+module Language.Haskell.Liquid.RefCore.CoreToLH (transBind, Def (..)) where++import Control.Exception (assert)+import Data.Bifunctor (first, second)+import Data.Char (isDigit)+import Data.Data (Data, showConstr, toConstr)+import qualified Data.HashMap.Strict as HM+import Data.List (find, intercalate, isPrefixOf)+import qualified Data.Map.Strict as M+import Data.Maybe (mapMaybe)+import qualified Data.Set as S+import qualified Data.Text as Text+import Text.PrettyPrint.HughesPJClass hiding (first)++import Debug.Trace (trace)+import GHC.Core+import GHC.Core.TyCo.Rep+import GHC.Types.Literal+import GHC.Types.Name (NamedThing, getSrcSpan)+import GHC.Utils.Outputable (ppr, showSDocUnsafe)+import Language.Haskell.Liquid.GHC.Misc (isDataConId)+import Language.Haskell.Liquid.Types.RType (SpecType)+import Language.Haskell.Liquid.Types.Types (AnnInfo (..))+import qualified Language.Haskell.Liquid.Types.Types ()++import qualified Language.Haskell.Liquid.RefCore.SpecToLH as SLH+import Language.Haskell.Liquid.RefCore.Misc+import Language.Haskell.Liquid.RefCore.Names (Id, hashName)+import qualified Language.Haskell.Liquid.RefCore.Calculus as Calc++-- | Constraint synonym for GHC Core binder variables+type CoreBinder b = (Data b, Show b, NamedThing b)++-- | A top-level definition extracted from GHC Core+data Def = Def+ { -- | the name of the definition+ defName :: Id,+ -- | the argument names+ defArgs :: [Id],+ -- | the translated body+ defBody :: Calc.Expr,+ -- | whether the definition is recursive+ defIsRec :: Bool+ }+ deriving (Eq, Show)++-- | A case branch in Calculus format+type Branch = ((Id, [(Id, Bool)]), Maybe Calc.Expr)++brCon :: Branch -> Id+brCon = fst . fst++brVarsWithInd :: Branch -> [(Id, Bool)]+brVarsWithInd = snd . fst++brVars :: Branch -> [Id]+brVars = map fst . brVarsWithInd++brBody :: Branch -> Maybe Calc.Expr+brBody = snd++modifyBrBody :: (Calc.Expr -> Calc.Expr) -> Branch -> Branch+modifyBrBody f ((c, xs), Just body) = ((c, xs), Just (f body))+modifyBrBody _ br = br++-- | Check if a variable occurs free in an expression+occursFreeIn :: Id -> Calc.Expr -> Bool+occursFreeIn x e = x `S.member` Calc.freeVars e++-- | Represent undefined/unreachable as a marker expression+undefinedReft :: Calc.Reft+undefinedReft = Calc.mkVar "undefined"++-- | Translate Haskell binders, with mutually recursive binders unsupported for now.+-- Entry point for the translations in this module+--+-- > transBind(NonRec f = e) = trans(f,e)+-- > transBind(Rec [f_1 = e_1, …, f_n = e_n]) = trans(f_1,e_1)+transBind :: (CoreBinder b) => String -> AnnInfo SpecType -> Bind b -> Def+transBind modId infTypes binds = case binds of+ NonRec b e -> mkDef b e+ Rec [(b, e)] -> mkDef b e+ Rec defs -> error $ "Mutually recursive definitions " ++ show (map fst defs) ++ " not yet supported."+ where+ mkDef b e =+ let (args, body) = flattenFun modId infTypes (f b) e+ in Def (f b) args body False+ f b = stripLegalName modId $ show b++-- | Classification of application head symbols.+data HeadSymbol+ = HNot+ | HLambda+ | HEqChain Calc.ProofOp+ | HCast+ | HQmark+ | HPatError+ | HConst Calc.Reft+ | HUnbox+ | HBinOp Calc.Bop+ | HGeneric Id+ | HDC Id+ deriving (Show)++-- | Classify an application head name into a 'HeadSymbol'.+classifyHead :: Id -> HeadSymbol+classifyHead "not" = HNot+classifyHead "lambda" = HLambda+classifyHead "===" = HEqChain Calc.PEq+classifyHead "=<=" = HEqChain Calc.PLeq+classifyHead "=>=" = HEqChain Calc.PGeq+classifyHead "***" = HCast+classifyHead "?" = HQmark+classifyHead "patError" = HPatError+classifyHead n+ | M.member n SLH.builtinDCs = HConst (transName n)+ | n `elem` ["I#", "I"] = HUnbox+ | Just op <- M.lookup n SLH.bops = HBinOp op+ | otherwise = HGeneric n++-- | The head of a flattened Core application.+data AppHead+ = -- | a classified variable+ VarHead HeadSymbol+ | -- | a non-variable expression+ ReftHead Calc.Reft++instance Pretty AppHead where+ pPrint (VarHead sym) = text "VarHead" <+> text (show sym)+ pPrint (ReftHead r) = text "ReftHead" <+> pPrint r++-- | Flatten and translate an application, returning a structured head and+-- surrounding let-bindings used to extract expressions from refinements+flattenCoreApp :: (CoreBinder b) => Id -> AnnInfo SpecType -> Id -> Expr b -> (Calc.Expr -> Calc.Expr, (AppHead, [Calc.Reft]))+flattenCoreApp modId infTypes f e =+ let (hd, args) = apps e+ argsT = map (trans modId infTypes f) args+ (letBindersArgs, sArgs) = first (foldr (.) id) . unzip $ map toReft argsT+ (letBinderHd, appHd) =+ case hd of+ Var name -> (id, VarHead headSym)+ where+ headSym = case classifyHead . stripLegalName modId $ show name of+ HGeneric n | isDataConId name -> HDC n+ h -> h+ _ -> second ReftHead . toReft $ trans modId infTypes f hd+ in (letBinderHd . letBindersArgs, (appHd, sArgs))+ where+ apps :: Expr b -> (Expr b, [Expr b])+ apps (App tm1 tm2) = second (++ [tm2]) $ apps tm1+ apps tm = (tm, [])+ toReft :: Calc.Expr -> (Calc.Expr -> Calc.Expr, Calc.Reft)+ toReft (Calc.Reft t) = (id, t)+ toReft tm = (Calc.Let x Nothing tm, Calc.mkVar x)+ where+ x = "x_" ++ hashName tm++-- | Translate a flattened application to Calculus.+transFlattenedApp :: AppHead -> [Calc.Reft] -> Calc.Expr+transFlattenedApp (ReftHead h) args = Calc.Reft $ foldl Calc.App h args+transFlattenedApp (VarHead (HDC n)) args = Calc.Reft $ foldl Calc.App (Calc.DC n) args+transFlattenedApp (VarHead (HGeneric n)) args = Calc.Reft $ foldl Calc.App (Calc.mkVar n) args+transFlattenedApp (VarHead HNot) [tm] = Calc.Reft $ Calc.Neg tm+transFlattenedApp (VarHead (HBinOp op)) (_ : _ : a : b : _) = Calc.Reft $ Calc.Bop op a b+transFlattenedApp (VarHead (HConst tm)) _ = Calc.Reft tm+transFlattenedApp (VarHead HUnbox) [singleArg] = Calc.Reft singleArg+transFlattenedApp (VarHead HPatError) _ = Calc.Reft undefinedReft+transFlattenedApp (VarHead (HEqChain pop)) [_, fstTerm, lstTerm] = Calc.Reft $ Calc.Pop pop fstTerm lstTerm+transFlattenedApp (VarHead HCast) [tm0, tm, Calc.DC "QED"] =+ Calc.QMark (Calc.Reft Calc.unitTm) (Calc.Reft tm) tm0+transFlattenedApp (VarHead HQmark) (_ : _ : firstArg : secondArg : _) =+ Calc.QMark (Calc.Reft firstArg) (Calc.Reft secondArg) Calc.ttTm+transFlattenedApp (VarHead HNot) args = Calc.Reft $ unexpected "not" args+transFlattenedApp (VarHead HLambda) args = Calc.Reft $ unexpected "lambda" args+transFlattenedApp (VarHead (HEqChain pop)) args = Calc.Reft $ unexpected (prettyShow pop) args+transFlattenedApp (VarHead HCast) args = Calc.Reft $ unexpected "***" args+transFlattenedApp (VarHead HQmark) args = Calc.Reft $ unexpected "?" args+transFlattenedApp (VarHead HUnbox) args = Calc.Reft $ unexpected "unbox" args+transFlattenedApp (VarHead (HBinOp _)) args = Calc.Reft $ unexpected "binop" args++unexpected :: Id -> [Calc.Reft] -> a+unexpected n as = error $ "transFlattenedApp: unexpected args for " ++ n ++ ": " ++ prettyShow as++transName :: Id -> Calc.Reft+transName "?" = error "Impossible: '?'"+transName n = M.findWithDefault (Calc.mkVar n) n SLH.builtinDCs++toStr :: (Data a) => a -> String+toStr = showConstr . toConstr++-- | Translate Haskell expressions.+-- The first argument is the name of the top-level binder we are translating.+-- Unsupported: casts, coercions, mutually recursive lets+-- Ignored: ticks+trans :: (CoreBinder b) => Id -> AnnInfo SpecType -> Id -> Expr b -> Calc.Expr+trans modId _ _ (Var n)+ | M.member strippedName SLH.builtinDCs = Calc.Reft $ transName strippedName+ | isDataConId n = Calc.Reft $ Calc.DC strippedName+ | otherwise =+ -- trace ("VAR: " ++ show n ++ " -> " ++ strippedName ++ " isDC=" ++ show (isDataConId n)) $+ Calc.Reft $ transName strippedName+ where+ strippedName = stripLegalName modId $ show n+trans modId infTypes f app@App {} = transApp modId infTypes f app+trans modId infTypes f (Case e _ _ alts) = transCase modId infTypes f e alts+trans modId infTypes f (Let bind e) = transLet modId infTypes f bind e+trans modId infTypes f (Tick _ e) = trans modId infTypes f e+trans _ _ _ (Type t) = transGHCType t+trans _ _ _ (Lit lit) = Calc.Reft $ transLit lit+trans _ _ _ c@Coercion {} = error $ "coercion expression not supported: " ++ toStr c+trans _ _ _ c@Cast {} = error $ "cast expression not supported: " ++ toStr c+trans _ _ _ l@(Lam {}) = error $ "lambda-abstraction outside of let-binding not supported: " ++ toStr l++-- | Translate type arguments.+transGHCType :: Type -> Calc.Expr+transGHCType (GHC.Core.TyCo.Rep.TyConApp tyCon []) = Calc.Reft (Calc.mkVar $ show tyCon)+transGHCType t = error $ "Polymorphism not supported: " ++ toStr t++-- | Translate applications by flattening them and translating the parsed application.+transApp :: (CoreBinder b) => Id -> AnnInfo SpecType -> Id -> Expr b -> Calc.Expr+transApp modId infTypes f app = letBinders $ transFlattenedApp appHead sArgs+ where+ (letBinders, (appHead, sArgs)) = flattenCoreApp modId infTypes f app++-- | Translate case expressions.+transCase :: (CoreBinder b) => Id -> AnnInfo SpecType -> Id -> Expr b -> [Alt b] -> Calc.Expr+transCase modId infTypes f e [] = trans modId infTypes f e+-- TODO: we now support match on simple terms, so change mkCase to support it+transCase modId infTypes f e alts = mkCaseExpr eT+ where+ mkCaseExpr (Calc.Reft (Calc.Var x' _ _)) = mkCase f x' branches+ mkCaseExpr (Calc.Reft {}) = Calc.Let y Nothing eT (mkCase f y branches)+ mkCaseExpr _ = error $ "unexpected case: case " ++ prettyShow eT ++ " of \n" ++ intercalate "\n" (map show branches)+ eT = trans modId infTypes f e+ y = "x_" ++ hashName eT+ branches = map (altToClause modId infTypes f) alts++-- | Translate let bindings.+transLet :: (CoreBinder b) => Id -> AnnInfo SpecType -> Id -> Bind b -> Expr b -> Calc.Expr+transLet modId infTypes f bind body =+ let (x, ex) = deconstructBind bind+ in case ex of+ Lit {} -> trans modId infTypes f body -- ignore let lit (part of patError)+ _ ->+ -- Since λ-abstractions are encoded in lets, we simply rename the+ -- variables bound in the translated type using the names introduced+ -- by the λs in Core+ let (ys, ex') = collectLambdas ex+ tp = SLH.transType "" (SLH.ConstrArgsCtx Nothing []) $ binderType infTypes x+ in Calc.Let+ (stripLegalName modId $ show x)+ (Just $ Calc.renameParams ys tp)+ (trans modId infTypes f ex')+ (trans modId infTypes f body)+ where+ collectLambdas (Lam y e) = first ((stripLegalName modId $ show y) :) $ collectLambdas e+ collectLambdas e = ([], e)++-- | Trivial translation of literals+transLit :: Literal -> Calc.Reft+transLit (LitNumber _ n) = Calc.IntLit n+transLit (LitString s) = Calc.StringLit $ show s+transLit (LitFloat x) = Calc.FloatLit $ fromRational x+transLit (LitDouble x) = Calc.FloatLit $ fromRational x+transLit other = error $ "Unsupported literal " ++ toStr other++-- | Fall back to non-mutually recursive binds.+deconstructBind :: (NamedThing b) => Bind b -> (b, Expr b)+deconstructBind (NonRec b e) = (b, e)+deconstructBind (Rec [(b, e)]) = (b, e)+deconstructBind (Rec (_ : _)) = error "Found list of mutually recursive binders while translating."+deconstructBind (Rec []) = error "Found empty list of mutually recursive binders while translating."++-- | Retrieves the type inferred by Liquid Haskell for a variable+binderType :: (Show b, NamedThing b) => AnnInfo SpecType -> b -> SpecType+binderType (AI infTypes) x =+ case HM.lookup (getSrcSpan x) infTypes of+ Just [(Just qualifName, tp)] ->+ assert (Text.unpack (snd $ Text.breakOnEnd (Text.singleton '.') qualifName) == show x) tp+ _ -> error $ "Type annotation for " ++ show x ++ " not found."++-- | Straightforward translation of Haskell cases+altToClause :: (CoreBinder b) => Id -> AnnInfo SpecType -> Id -> Alt b -> Branch+altToClause modId infTypes f (Alt con bs e) =+ ((go con, map (\b -> (stripLegalName modId $ show b, False)) bs), Just (trans modId infTypes f e))+ where+ go :: AltCon -> String+ -- NOTE: was `show dc`, but no show instance for DataCon+ go (DataAlt dc) = stripLegalName modId $ showSDocUnsafe (ppr dc)+ go (LitAlt lit) = show (transLit lit)+ go DEFAULT = "_"++-- | Flattens and translate abstractions+--+-- > flattenFun(λx1. λx2.…λxn.e) = λx1…xn.trans(e)+flattenFun :: (CoreBinder b) => Id -> AnnInfo SpecType -> Id -> Expr b -> ([Id], Calc.Expr)+flattenFun modId infTypes f (Lam b e) = first ((stripLegalName modId . show) b :) $ flattenFun modId infTypes f e+flattenFun modId infTypes f e = ([], trans modId infTypes f e)++{- The following is based on code liquidhaskell-boot Transforms/CoreToLogic -}++-- | Cut redundant branches and matches and construct the given match+mkCase :: Id -> Id -> [Branch] -> Calc.Expr+mkCase f x = transCaseExpr (Just f) x False++collapseUnproductiveMatches :: Branch -> Branch+collapseUnproductiveMatches = modifyBrBody go+ where+ go (Calc.Case x branches b) = Calc.Case x (map collapseUnproductiveMatches branches) b+ go e = e++-- | remove redundant branches/matches from a pattern match+transCaseExpr :: Maybe Id -> Id -> Bool -> [Branch] -> Calc.Expr+transCaseExpr = recurse []+ where+ recurse :: [(Id, (Id, [Id]))] -> Maybe Id -> Id -> Bool -> [Branch] -> Calc.Expr+ recurse prevPats fO indVar _ cases' =+ {- traceFuncRet ["recurse", show prevPats, show fO, indVar, show isRec, show cases] $ -}+ Calc.substs (map (\(x, r) -> (r, x)) substs) res+ where+ -- Replace occurrences of the induction variable with the constructor application in each branch+ cases =+ map+ ( \br ->+ let conApp = foldl Calc.App (Calc.DC (brCon br)) (map Calc.mkVar (brVars br))+ in modifyBrBody (Calc.subst conApp indVar) br+ )+ cases'+ res = caseOrInduct indVar branches+ (cutCases, substs) = cutRedundantBranches indVar prevPats cases+ cleanedCases = map collapseUnproductiveMatches cutCases+ isRecursive :: Calc.Expr -> Bool+ isRecursive e = maybe False (`occursFreeIn` e) fO+ branches = map (modifyBrBody transBranchE) cleanedCases+ transBranchE :: Calc.Expr -> Calc.Expr+ transBranchE e@(Calc.Case (Calc.Var x _ _) css _) = recurse prevPats fO x (isRecursive e) css+ transBranchE (Calc.Let x tpx def' tm) = Calc.Let x tpx (transBranchE def') (transBranchE tm)+ transBranchE e = e+ caseOrInduct :: Id -> [Branch] -> Calc.Expr+ caseOrInduct x brs = Calc.Case (Calc.mkVar x) brs Nothing++ -- \| Remove cases from nested matches whose patterns contradict the current branch's pattern in an ambient match+ cutRedundantBranches :: Id -> [(Id, (Id, [Id]))] -> [Branch] -> ([Branch], [(Id, Calc.Reft)])+ cutRedundantBranches n prevPats = second concat . unzip . cutBranches . filterBranches+ where+ filterBr br =+ ((n, (brCon br, brVars br)) `notElem` prevPats)+ || trace+ ( unwords+ [ "cutting case: ",+ show (brCon br, brVars br),+ show (brBody br),+ "from match on",+ show n,+ "due to redundancy with previous match patterns",+ show prevPats+ ]+ )+ False+ filterBranches = filter filterBr+ cutBranches :: [Branch] -> [(Branch, [(Id, Calc.Reft)])]+ cutBranches =+ mapMaybe+ ( \br -> case brBody br of+ Nothing -> Just (br, [])+ Just body ->+ first (\body' -> ((brCon br, brVarsWithInd br), Just body'))+ <$> cutRedundantMatches (prevPats ++ [(n, (brCon br, brVars br))]) body+ )++ -- \| Translate nested matches, replacing redundant matches with the translation of the only matching branch+ cutRedundantMatches :: [(Id, (Id, [Id]))] -> Calc.Expr -> Maybe (Calc.Expr, [(Id, Calc.Reft)])+ cutRedundantMatches prevPats (Calc.Case (Calc.Var m _ _) branches _) | m `elem` map fst prevPats = res+ where+ -- \| The previous pattern in which we already matched on the same variable as we do now, if any+ prevPat = find ((== m) . fst) prevPats+ -- \| Pattern and expression in the branch, in which the pattern matches the previous pattern, if any+ caseExpr = find ((== (fst . snd <$> prevPat)) . Just . brCon) branches+ caseVarSub = case (snd . snd <$> prevPat, brVars <$> caseExpr) of+ (Just args, Just args') -> newSubst+ where+ newSubst = mapMaybe mkSubstO (zip args args')+ mkSubstO (x, y) = case (unspecName x, unspecName y) of+ (True, False) -> Just (x, Calc.mkVar y) -- if variable is specified now, but not earlier use current name throughout+ (False, True) -> Just (y, Calc.mkVar x) -- if variable was specified before, but not now use previous name here as well+ (_, _) -> Nothing+ unspecName x = ("lq_anf" `isPrefixOf` x && all isDigit (removePrefix "lq_anf" x)) || "ds_d" `isPrefixOf` x+ _ -> []+ -- \| The translation of the only branch in which the pattern is consistent with the previously matched pattern matched against the same expression+ recO =+ ( \br -> case brBody br of+ Nothing -> Just (Calc.Reft undefinedReft, [])+ Just body -> cutRedundantMatches prevPats body+ )+ =<< caseExpr+ res = second (++ caseVarSub) <$> recO+ cutRedundantMatches prevPats (Calc.Case r@(Calc.Var m _ _) branches b) = Just (Calc.Case r branches' b, subs)+ where+ (branches', subs) = cutRedundantBranches m prevPats branches+ cutRedundantMatches _ tm = Just (tm, [])
+ src/Language/Haskell/Liquid/RefCore/Extract.hs view
@@ -0,0 +1,215 @@+{-# LANGUAGE OrPatterns #-}+{-# OPTIONS_GHC -Wall #-}++-- | Extracts Calculus declarations out of LiquidHaskell's TargetInfo + GHC core+-- binds.+module Language.Haskell.Liquid.RefCore.Extract+ ( SrcInfo (..)+ , CalcMeta (..)+ , OUT (..)+ , extractCalculus+ , writeIlh+ , writeOut+ , writeIlhBin+ , outPath+ ) where++import Control.Monad (unless)+import qualified Data.Binary as Bin+import Data.Bifunctor (bimap)+import Data.Char (isSpace)+import Data.List (intercalate, isPrefixOf)+import qualified Data.Map.Strict as M+import qualified Data.Set as S+import System.Directory (createDirectoryIfMissing, getCurrentDirectory)+import System.FilePath (joinPath, splitDirectories, takeDirectory, (</>))+import qualified Text.PrettyPrint.HughesPJClass as PP++import GHC.Core+import GHC.Plugins hiding (Id, split)+import qualified Language.Fixpoint.Types as F (Located, val)+import Language.Fixpoint.Utils.Files (tempDirectory)+import Language.Haskell.Liquid.Types.RType (SpecType, TyConP (..))+import qualified Language.Haskell.Liquid.Types.Specs as Specs+import Language.Haskell.Liquid.Types.Types (AnnInfo (..))+import Language.Haskell.Liquid.RefCore.Misc (isIgnoredBind, removeSuffix, split, stripLegalName)+import Language.Haskell.Liquid.RefCore.Names (Id)+import qualified Language.Haskell.Liquid.RefCore.Calculus as Calc+import qualified Language.Haskell.Liquid.RefCore.CoreToLH as CLH+import Language.Haskell.Liquid.RefCore.Parse+import Language.Haskell.Liquid.RefCore.Simplify (simplify)+import qualified Language.Haskell.Liquid.RefCore.SpecToLH as SLH++-- | Contains all information about the source Liquid Haskell file to translate+data SrcInfo = SrcInfo+ { s_moduleName :: ModuleName+ , s_summary :: ModSummary+ , s_targetInfo :: Specs.TargetInfo+ , s_cbs :: [CoreBind]+ -- ^ Pre-'?'-elimination ANF binds, saved before 'Specs.giCbs' strips '?' for constraint generation.+ , s_infTypes :: AnnInfo SpecType+ , s_imports :: [Module]+ }++-- | Metadata about the extracted Calculus independent of LH/GHC types.+data CalcMeta = CalcMeta+ { cmTarget :: FilePath+ , cmModuleName :: String+ }++-- | Extract the Calculus declarations for a module.+extractCalculus :: SrcInfo -> IO ([Calc.Decl], CalcMeta)+extractCalculus sinfo = do+ workingPath <- getCurrentDirectory+ let moduleId = takeWhile (not . isSpace) $ moduleNameString (s_moduleName sinfo)+ modulename = last $ split '.' moduleId+ examplesFolder = getSrcFolder moduleId filename workingPath+ target = workingPath </> filename+ pb = getBindsAndSpecs moduleId sinfo+ importNames = getModIdsAndImports sinfo+ localDecls = filterLocalPData (s_moduleName sinfo) (pb_decls pb)+ dataDecls = parsePData moduleId localDecls+ specMap = SLH.transSig moduleId Nothing <$> M.fromList (pb_specs pb)+ lhDefs = CLH.transBind moduleId (s_infTypes sinfo) . simplify <$> filter (not . isIgnoredBind) (pb_binds pb)+ defDecls = combineDefsAndLemmas $ pairLHDefsWithSigs moduleId lhDefs specMap (pb_vars pb)+ specSig = Specs.gsSig . Specs.giSpec $ s_targetInfo sinfo+ rawSpecs = Specs.gsTySigs specSig+ asmSpecs = Specs.gsAsmSigs specSig+ refSpecs = Specs.gsRefSigs specSig+ allSpecs = rawSpecs ++ asmSpecs ++ refSpecs+ importDecls = map (mkImportDecl moduleId (pb_decls pb) allSpecs) importNames+ -- Note: declarations are emitted in source order.+ calcSource = importDecls ++ dataDecls ++ defDecls+ meta = CalcMeta target modulename+ importedSourceFiles <- getImportFiles examplesFolder importNames+ putStrLn $ "Input file: " ++ filename+ unless (null importNames) $+ putStrLn ("Imported external files: " ++ intercalate ", " importedSourceFiles)+ pure (calcSource, meta)+ where+ filename = Specs.giTarget $ Specs.giSrc $ s_targetInfo sinfo++-- | Output formats for the un-elaborated Calculus produced by extraction.+data OUT = Text | Bin+ deriving (Show)++outPostfix :: OUT -> String+outPostfix Text = ".ilh"+outPostfix Bin = ".ilhb"++-- | The .liquid folder for the .ilh/.ilhb files.+binFolder :: CalcMeta -> FilePath+binFolder = tempDirectory . cmTarget++-- | Write the un-elaborated Calculus declarations to the .ilh text file.+writeIlh :: CalcMeta -> [Calc.Decl] -> IO ()+writeIlh meta calcSource = do+ createDirectoryIfMissing True (binFolder meta)+ writeOut (binFolder meta) (cmModuleName meta) (outPostfix Text) PP.empty calcSource++-- | Path of .ilh/.ilhb in the .liquid folder.+outPath :: OUT -> CalcMeta -> FilePath+outPath out meta = binFolder meta </> (cmModuleName meta ++ outPostfix out)++writeIlhBin :: CalcMeta -> [Calc.Decl] -> IO ()+writeIlhBin meta calcSource = do+ createDirectoryIfMissing True (binFolder meta)+ let path = outPath Bin meta+ putStrLn ("Writing serialized Calculus to " ++ path)+ Bin.encodeFile path calcSource++-- | Pretty-print a list of declarations to a file with the given filename+-- suffix.+writeOut :: (PP.Pretty a) => FilePath -> String -> String -> PP.Doc -> [a] -> IO ()+writeOut outputFolder modulename suffix pre decls = do+ let outputPath = outputFolder </> (modulename ++ suffix)+ putStrLn ("Writing output to file at " ++ outputPath)+ let body = PP.vcat (pre PP.<> PP.char '\n' : map ((PP.<> PP.char '\n') . PP.pPrint) decls)+ style = PP.Style {PP.mode = PP.PageMode, PP.lineLength = 120, PP.ribbonsPerLine = 1.2}+ writeFile outputPath (PP.renderStyle style body)+ putStrLn ""++-- | Parsed binds and specs extracted from LH.+data ParsedBinds = ParsedBinds+ { pb_src :: Specs.TargetSrc+ , pb_vars :: [Var]+ , pb_decls :: PData+ , pb_binds :: [CoreBind]+ , pb_specs :: [SpecPair]+ }++getBindsAndSpecs :: Id -> SrcInfo -> ParsedBinds+getBindsAndSpecs modId sinfo = ParsedBinds+ { pb_src = src+ , pb_vars = refls+ , pb_decls = getDataDecls (Specs.gsData specs, Specs.gsName specs)+ , pb_binds = s_cbs sinfo+ , pb_specs = getSpecPairs specs+ }+ where+ Specs.TargetInfo src specs = s_targetInfo sinfo+ refls = Specs.gsReflects $ Specs.gsRefl specs+ getSpecPairs = map (bimap (stripLegalName modId . show) F.val) . Specs.gsTySigs . Specs.gsSig+ getDataDecls (spdata, spnames) = PData (Specs.gsCtors spdata) (Specs.gsTconsP spnames)++getSrcPath :: String -> String -> String -> [String]+getSrcPath moduleId filename workingPath = removeSuffix modulePrefixes folderPath where+ modulePrefixes = init $ split '.' moduleId+ folderPath = splitDirectories $ takeDirectory (workingPath </> filename)++getSrcFolder :: String -> String -> String -> FilePath+getSrcFolder moduleId filename workingPath = joinPath (getSrcPath moduleId filename workingPath)++getModIdsAndImports :: SrcInfo -> [String]+getModIdsAndImports sinfo = map modNameString $ filter (not . isStdLibModule) (s_imports sinfo)+ where+ modNameString = moduleNameString . moduleName+ isStdLibModule m = any (`isPrefixOf` modNameString m) stdLibPrefixes+ stdLibPrefixes = ["GHC.", "Data.", "Control.", "System.", "Prelude", "Foreign.", "Text.", "Numeric.", "Language."]++-- | The defining module name of a type constructor, if any.+tyConPModule :: TyConP -> Maybe ModuleName+tyConPModule tcp = moduleName <$> nameModule_maybe (tyConName (tcpCon tcp))++-- | The defining module name of a variable, if any.+varModule :: Var -> Maybe ModuleName+varModule v = moduleName <$> nameModule_maybe (varName v)++-- | Whether a type constructor is defined in the named module.+tyConPFromModule :: String -> TyConP -> Bool+tyConPFromModule modStr tcp = maybe False ((== modStr) . moduleNameString) (tyConPModule tcp)++-- | Whether a variable is defined in the named module.+varFromModule :: String -> Var -> Bool+varFromModule modStr v = maybe False ((== modStr) . moduleNameString) (varModule v)++filterLocalPData :: ModuleName -> PData -> PData+filterLocalPData modName pd = pd {pdTyCons = filteredTyCons, pdCtors = filteredCtors}+ where+ filteredTyCons = filter isLocalTC (pdTyCons pd)+ filteredCtors = filter (isLocalCtor . fst) (pdCtors pd)+ isLocalTC tcp = maybe True (== modName) (tyConPModule tcp)+ isLocalCtor v = maybe True (== modName) (varModule v)++filterPDataForModule :: String -> PData -> PData+filterPDataForModule modStr pd =+ pd {pdTyCons = filter (tyConPFromModule modStr) (pdTyCons pd), pdCtors = filter (varFromModule modStr . fst) (pdCtors pd)}++mkImportDecl :: Id -> PData -> [(Var, F.Located SpecType)] -> String -> Calc.Decl+mkImportDecl moduleId allPData rawSpecs modName = Calc.Import modName (dataDs ++ defDs)+ where+ dataDs = parsePData moduleId (filterPDataForModule modName allPData)+ defDs = map mkDefStub $ filter (varFromModule modName . fst) rawSpecs+ mkDefStub (v, locSpec) =+ Calc.Definition+ (stripLegalName moduleId (show (varName v)))+ (SLH.transSig moduleId Nothing (F.val locSpec))+ (Calc.Reft (Calc.Var "imported" Nothing Calc.Global))+ False++pairLHDefsWithSigs :: Id -> [CLH.Def] -> M.Map Id Calc.RefType -> [Var] -> [(CLH.Def, Maybe Calc.RefType, Bool)]+pairLHDefsWithSigs modId defs specMap reflectedDecls = map single defs+ where+ reflectedNames :: S.Set Id+ reflectedNames = S.fromList $ map (stripLegalName modId . show . varName) reflectedDecls+ single def = (def, M.lookup (CLH.defName def) specMap, CLH.defName def `S.member` reflectedNames)
+ src/Language/Haskell/Liquid/RefCore/Misc.hs view
@@ -0,0 +1,84 @@+-- | Functions used in the translation from Core and Spec+module Language.Haskell.Liquid.RefCore.Misc where++import Data.List (intercalate, stripPrefix, uncons, unfoldr)+import Data.Maybe (fromMaybe)+import GHC.Core+import Language.Haskell.Liquid.RefCore.Names (Id)++-- * Name manipulation++strip :: Id -> Id+strip s = case split '.' s of+ [] -> ""+ parts -> last parts++split :: Char -> Id -> [Id]+split c = unfoldr go+ where+ go [] = Nothing+ go s = Just (chunk, drop 1 rest)+ where+ (chunk, rest) = break (== c) s++startsWith :: Id -> Char -> Bool+startsWith xs c = maybe False ((== c) . fst) (uncons xs)++-- Get rid of module names.+showStripped :: (Show a) => a -> Id+showStripped = strip . show++-- | Remove character from LH names that are illegal in names for the translation+removeIllegalCharacters :: Id -> Id+removeIllegalCharacters = filter (not . (`elem` illegalChars))++illegalChars :: [Char]+illegalChars = ['$', '#']++-- | Remove illegal characters from LH names and strip their qualifications, unless this produces a built-in name+stripLegalName :: Id -> Id -> Id+stripLegalName moduleId s = removeIllegalCharacters $ if strip s `elem` rocqReservedNames then prefixedS else strip s+ where+ prefS = split '.' s+ -- \| Unfortunately Coq doesn't let us use "." prefixes in names, so we use "__" instead+ prefixedS = if length prefS > 1 then intercalate "__" . drop (length prefS - 2) $ prefS else stripLegalName "" (moduleId ++ "." ++ s) -- error $ "clashing:" ++ s++-- | Whether a String is a built-in datatype+isBuiltinDatatype :: Id -> Bool+isBuiltinDatatype tc = tc == "[]" || tc == "Maybe" || isTuple tc+ where+ isTuple ('(' : ',' : s) = isTuple' s+ isTuple _ = False+ isTuple' (',' : s) = isTuple' s+ isTuple' [')'] = True+ isTuple' _ = False++-- A non-exhaustive list of reserved names+rocqReservedNames :: [Id]+rocqReservedNames = [+ "Z", "bool", "Set", "Type", "Prop",+ "From", "Require", "Import", "Export", "Open", "Scope", "Z_scope", "Int_scope",+ "LiquidPreludeUtil", "Unicode",+ "Inductive", "Fixpoint", "Theorem", "Lemma", "Definition", "Hint",+ "Proof", "Qed", "Defined", "Opaque", "Transparent",+ "Resolve", "Global", "global", "Instance", "Notation", "Rewrite",+ "match", "with", "let", "in", "by", "end", "if", "then", "else"]++-- * GHC Core helpers++-- | tests whether an GHC bind starts with '$' or '?' and should thus not be translated+isIgnoredBind :: (Show b) => Bind b -> Bool+isIgnoredBind bind = name `startsWith` '$' || name == "?"+ where+ name = bindName bind+ bindName (NonRec b _) = showStripped b+ bindName (Rec ((b, _) : _)) = showStripped b+ bindName (Rec []) = "?"++-- * Generic list helpers++removeSuffix :: (Eq a) => [a] -> [a] -> [a]+removeSuffix suffix orig = reverse $ removePrefix (reverse suffix) (reverse orig)++removePrefix :: (Eq a) => [a] -> [a] -> [a]+removePrefix prefix orig = fromMaybe orig $ stripPrefix prefix orig
+ src/Language/Haskell/Liquid/RefCore/Names.hs view
@@ -0,0 +1,43 @@+-- | Collection of names and strings used in the translation+module Language.Haskell.Liquid.RefCore.Names where++import Data.Hashable (hash)+import Data.Set (Set)+import qualified Data.Set as Set+import Text.PrettyPrint.HughesPJClass++-- | Identifiers in both LH and Rocq+type Id = String++-- | return a variable fresh wrt to a set of Id+freshVar :: Id -> Set Id -> Id+freshVar x vars = go x 1+ where+ go n i+ | n `Set.notMember` vars = n+ | otherwise = go (x ++ "_" ++ show (i :: Integer)) (i + 1)++-- | Produce an (almost certainly) unique number string for the given printable object+hashName :: (Pretty a) => a -> Id+hashName e = take 8 $ prettyShow (abs . hash $ prettyShow e)++-- Builtin names++boolTpName :: Id+boolTpName = "Bool"++ttTmName :: Id+ttTmName = "True"++ffTmName :: Id+ffTmName = "False"++unitTpName :: Id+unitTpName = "Unit"++unitTmName :: Id+unitTmName = "unit"++-- | The canonical refinement value variable (the @VV@ in @{VV : tp | …}@).+vvName :: Id+vvName = "VV"
+ src/Language/Haskell/Liquid/RefCore/Parse.hs view
@@ -0,0 +1,144 @@+{-# OPTIONS_GHC -Wall #-}++module Language.Haskell.Liquid.RefCore.Parse+ ( -- ** type aliases for intermediate data+ SpecPair,+ PData (..),++ -- ** "parsers" for the specification data extracted from LH+ parseToSpecPair,+ parsePData,++ -- ** combine "parsed" LH specification data with GHC+ getImportFiles,+ combineDefsAndLemmas,++ -- ** utility function+ signatureToArgsRet,+ )+where++import Control.Monad (filterM)+import Data.Bifunctor (first)+import Data.List (sortOn)+import Data.Set (fromList)+import Data.Tuple.Extra (snd3)+import System.Directory (doesFileExist)+import System.FilePath (joinPath, (<.>), (</>))++import GHC.Types.Var (Var, varName)+import qualified Language.Fixpoint.Types as F (Located (..))+import qualified Language.Haskell.Liquid.Types.RType as LhLib++import Language.Haskell.Liquid.RefCore.Misc+import Language.Haskell.Liquid.RefCore.Names (Id, freshVar)+import qualified Language.Haskell.Liquid.RefCore.Calculus as Calc+import qualified Language.Haskell.Liquid.RefCore.SpecToLH as SLH+import Language.Haskell.Liquid.RefCore.CoreToLH (Def (..))++-- ** LH -> Calculus parsing++type SpecPair = (Id, LhLib.SpecType)++-- | Parsed data declarations extracted from Liquid Haskell+data PData = PData+ { -- | refined types of data constructors+ pdCtors :: [(Var, F.Located LhLib.SpecType)],+ -- | refined types of type constructors+ pdTyCons :: [LhLib.TyConP]+ }++-- , [LhLib.Located DataCon], [F.DataDecl]) -- more data type info, in case they are needed+parseToSpecPair :: Id -> (Var, F.Located LhLib.SpecType) -> SpecPair+parseToSpecPair modId (v, F.Loc _ _ spec) = (stripLegalName modId $ show (varName v), spec)++-- | Parse refined type constructors into Calculus declarations+parsePData :: Id -> PData -> [Calc.Decl]+parsePData modId (PData cs typConstrs) =+ {- trace ("parsePData " ++ modId ++ "\n("++show constrs++", "++show typConstrs++")") $ -}+ map mkData (filter (not . isBuiltinDatatype) typeNames)+ where+ -- translate each branch+ constrs :: [(Id, Calc.RefType)]+ constrs = map (parseSpec . parseToSpecPair modId) cs+ parseSpec (c, sig) =+ let sigT = SLH.transSig modId (Just c) sig+ (args', ret) = signatureToArgsRet sigT+ args_ = map defaultBind args'+ args = mkDistinct args_+ in (c, foldr (\(n, t) acc -> Calc.ArrType n t acc) ret args)+ mkDistinct [] = []+ mkDistinct ((x, xData) : tl) = (x, xData) : mkDistinct (map (first (\y -> if y == x then y ++ "_" else y)) tl)+ -- we translate every type constructor that is not already built-in+ typeNames = map (\(LhLib.TyConP _ con _ _ _ _ _) -> SLH.showppStripped modId con) typConstrs+ -- find the translated branches corresponding to typeName+ getConstrs :: Id -> [(Id, Calc.RefType)]+ getConstrs typeName = filter (isConstrOf typeName . snd3 . snd . Calc.arrs . snd) constrs+ isConstrOf typeName (Calc.TC n) = n == typeName+ isConstrOf _ (Calc.Builtin _) = False+ -- Assemble typeName and the corresponding translated branches+ mkData typeName = Calc.Data typeName (sortOn fst (getConstrs typeName))++-- ** translating the intermediate data structures to 'Calc.Decl's++-- | combine the defs and lemmas into a list of 'Calc.Decl' and sort them in dependency order+combineDefsAndLemmas :: [(Def, Maybe Calc.RefType, Bool)] -> [Calc.Decl]+combineDefsAndLemmas = map parseDef++-- | compute the file path of the module with given name+getImportFile :: FilePath -> String -> FilePath+getImportFile examplesFolder moduleName = examplesFolder </> joinPath (split '.' moduleName) <.> "hs"++-- | filter out only those imported module names that correspond to files in the lhExamples folder+filterImports :: String -> [String] -> IO [String]+filterImports examplesFolder =+ filterM (doesFileExist . getImportFile examplesFolder)++-- | Get the imported filenames and the import declarations for the specified module names+getImportFiles :: String -> [String] -> IO [String]+getImportFiles examplesFolder potentialImports =+ map (getImportFile examplesFolder) <$> filterImports examplesFolder potentialImports++isLemma :: Calc.RefType -> Bool+isLemma = (== "()") . typeName . snd3 . snd . Calc.arrs+ where+ typeName :: Calc.BaseType -> String+ typeName (Calc.Builtin c) = show c+ typeName (Calc.TC n) = n++parseDef :: (Def, Maybe Calc.RefType, Bool) -> Calc.Decl+parseDef (Def dname args body _, Just sig, b) =+ Calc.Definition dname fullTp body b+ where+ sig' = Calc.renameParams args sig+ (sigArgs, sRes) = signatureToArgsRet sig'+ tp =+ if isLemma sig'+ then case sRes of+ Calc.RefType _ _ reft -> Calc.RefType (dname ++ "_claim") Calc.unitTp reft+ _ -> error $ "Lemma " ++ dname ++ " has unexpected arrow return type"+ else sRes++ fullTp = foldr (\(n, t) acc -> Calc.ArrType n t acc) tp (zip args sigArgs)+parseDef (Def dname _ _ _, Nothing, _) = error $ "Top-level definition or lemma " ++ dname ++ " without signature is forbidden."++-- | replace the names of variables v in refinement types {v:A|p} of arguments x by x+signatureToArgsRet :: Calc.RefType -> ([Calc.RefType], Calc.RefType)+signatureToArgsRet sig = (args, ret)+ where+ (sigArgs, (v0, sResTp, sResReft)) = Calc.arrs sig+ names = map fst sigArgs+ v = freshVar v0 (fromList names)+ ret = Calc.RefType v sResTp $ Calc.subst (Calc.mkVar v) v0 sResReft+ args = map renameArg sigArgs+ renameArg (n, Calc.RefType x tp reft) = Calc.RefType m tp (Calc.subst (Calc.mkVar m) x reft)+ where+ m = if n /= "" then n else x+ renameArg (_, arr@Calc.ArrType {}) = arr++-- > defaultBind({x:A | r}) = (x, {x:A | r})+-- > defaultBind(x: Tx -> Y) = (x, (x: Tx -> Y)+defaultBind :: Calc.RefType -> (Id, Calc.RefType)+defaultBind r@(Calc.RefType nm _ _) = (nm, r)+defaultBind a@(Calc.ArrType nm _ _) = (nm, a)+
+ src/Language/Haskell/Liquid/RefCore/Simplify.hs view
@@ -0,0 +1,111 @@+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# OPTIONS_GHC -Wall #-}++module Language.Haskell.Liquid.RefCore.Simplify (simplify) where++import Control.Monad.State.Strict+import Data.Bifunctor (second)+import Data.List (isPrefixOf)+import qualified Data.Map.Strict as M++import GHC.Core+import GHC.Types.Var+-- needed for Show Var instance+import Language.Haskell.Liquid.GHC.Misc ()++import Language.Haskell.Liquid.RefCore.Misc (showStripped)++class Simplifiable a where+ simplify :: a -> a++instance Simplifiable CoreBind where+ simplify (NonRec x e) = NonRec x (simplify e)+ simplify (Rec xes) = Rec (map (second simplify) xes)++instance Simplifiable CoreExpr where+ simplify e =+ let (e', su) = grapANFs e+ in subst su e'++-------------------------------------------------------------------------------++-- | Substitutions ------------------------------------------------------------++-------------------------------------------------------------------------------++binds :: CoreBind -> [Var]+binds (NonRec x _) = [x]+binds (Rec xes) = map fst xes++isANFVar :: Var -> Bool+isANFVar = isPrefixOf "lq_anf" . showStripped++type Subst = M.Map Var CoreExpr++without :: Subst -> [Var] -> Subst+without su = foldr M.delete su++class Subable a where+ subst :: Subst -> a -> a++instance Subable CoreExpr where+ subst su (Var x)+ | Just e <- M.lookup x su = e+ | otherwise = Var x+ subst _ (Lit l) = Lit l+ subst su (App e1 e2) = App (subst su e1) (subst su e2)+ subst su (Lam x e) = Lam x (subst (su `without` [x]) e)+ subst su (Let b e) = Let (subst su b) (subst (su `without` binds b) e)+ subst su (Case e x t alts) = Case (subst su e) x t (subst (su `without` [x]) alts)+ subst su (Cast e c) = Cast (subst su e) c+ subst su (Tick t e) = Tick t (subst su e)+ subst _ (Type t) = Type t+ subst _ (Coercion c) = Coercion c++instance Subable CoreAlt where+ subst su (Alt c xs e) = Alt c xs (subst (su `without` xs) e)++instance (Subable a) => Subable [a] where+ subst su = map (subst su)++instance Subable CoreBind where+ subst su (NonRec x e) = NonRec x (subst (su `without` [x]) e)+ subst su (Rec xes) = Rec (map (second (subst su')) xes)+ where+ su' = su `without` map fst xes++-------------------------------------------------------------------------------++-- | Grap ANF -----------------------------------------------------------------++-------------------------------------------------------------------------------++grapANFs :: CoreExpr -> (CoreExpr, Subst)+grapANFs expr = runState (go expr) M.empty+ where+ go (Let (NonRec x ex) e)+ | isANFVar x = do+ ex' <- go ex+ su <- get+ put $! M.insert x (subst su ex') su+ go e+ | otherwise = do+ ex' <- go ex+ Let (NonRec x ex') <$> go e+ go (Let (Rec xes) e) = do+ xes' <- traverse (traverse go) xes+ Let (Rec xes') <$> go e+ go (App e1 e2) = App <$> go e1 <*> go e2+ go (Lam x e) = Lam x <$> go e+ go (Case e x t alts) = do+ e' <- go e+ Case e' x t <$> traverse goAlt alts+ go (Cast e c) = (`Cast` c) <$> go e+ go (Tick t e) = Tick t <$> go e+ go e@(Type _) = pure e+ go e@(Coercion _) = pure e+ go e@(Lit _) = pure e+ go e@(Var _) = pure e++ goAlt (Alt c xs e) = Alt c xs <$> go e
+ src/Language/Haskell/Liquid/RefCore/SpecToLH.hs view
@@ -0,0 +1,305 @@+{-# OPTIONS_GHC -Wall #-}++module Language.Haskell.Liquid.RefCore.SpecToLH (transSig, transType, showppStripped, bops, builtinDCs, builtinTCs, InternalCont (..)) where++import Control.Monad (filterM)+import Control.Monad.Extra (allM, ifM)+import Control.Monad.Reader (Reader, asks, runReader)+import Data.Char (isUpper)+import Data.List (isInfixOf)+import qualified Data.Map.Strict as M+import Data.Maybe (fromMaybe)++import Language.Fixpoint.Types (PPrint)+import qualified Language.Fixpoint.Types as F+import Language.Haskell.Liquid.Types.RType (PVarBV (PV), RTVar (RTVar), RTyCon (RTyCon), RTyVar (RTV), RTypeBV (..), SpecType, UReft, UReftBV (MkUReft))++import Language.Haskell.Liquid.RefCore.Misc+import Language.Haskell.Liquid.RefCore.Names (Id, ttTmName, ffTmName)+import qualified Language.Haskell.Liquid.RefCore.Calculus as Calc++-- | Helper for unsupported constructs+unsupported :: String -> a+unsupported msg = error $ "[SpecToLH] " ++ msg++-- | Translation of an RTyCon as a builtin or as a type constructor+transCon :: Id -> RTyCon -> Calc.BaseType+transCon modId (RTyCon tc [] _) = M.findWithDefault (Calc.TC name) name builtinTCs+ where+ name = showppStripped modId tc+transCon _ c = unsupported $ "Type constructor with type args not supported (no polymorphism): " ++ show c++showppStripped :: (PPrint a) => Id -> a -> String+showppStripped modId = stripLegalName modId . F.showpp++data InternalCont = ConstrArgsCtx (Maybe Id) [Id]+ deriving (Show)++-- TODO: replace with something that uses notations as defined in liquidhaskell source+internalConstrRef :: (PPrint a) => Id -> a -> Reader InternalCont Bool+internalConstrRef modId s = asks go+ where+ go (ConstrArgsCtx Nothing _) = False+ go (ConstrArgsCtx (Just c) args) = checkPred (parseConstrPred modId s)+ where+ checkPred (Just "is", _) = True+ checkPred _ = checkArg (getFuncArgName modId s)+ checkArg (Just c', _) | stripLegalName modId c' == c = True+ checkArg (Just x, _) | x `elem` args = False+ checkArg (Just c', x) = showppStripped modId c' `elem` c : args && x `elem` args+ checkArg (Nothing, "") = True+ checkArg _ = False++getFuncArgName :: (PPrint a) => Id -> a -> (Maybe Id, Id)+getFuncArgName modId symb = go sym+ where+ -- \| local name generated by parser+ go s | length (filter ('$' ==) s) == 1 && "$db##" `isInfixOf` s = case split '$' s of+ [n, s'] -> (Nothing, stripLegalName modId res)+ where+ res :: Id+ res = case split '#' s' of+ ["db", "", num] -> n ++ num+ _ -> n ++ s'+ _ -> error "Impossible case"+ go s | length (filter ('$' ==) s) > 1 = (Nothing, "")+ go s = case split '#' s of+ [n, "", func] -> (Just (stripLegalName modId n), stripLegalName modId func)+ [func] -> (Nothing, stripLegalName modId func)+ [_, "", n, "", func] -> (Just (stripLegalName modId n), stripLegalName modId func)+ other | length other > 6 -> (Nothing, "") -- go . concat . drop 2 $ split '#' s+ _ -> (Nothing, "")+ sym = F.showpp symb++transVarName :: (PPrint a) => Id -> a -> String+transVarName modId x = case getFuncArgName modId x of+ (Just n, func) -> stripLegalName modId $ func ++ "." ++ n+ (Nothing, "") -> "illegalInternalName"+ (Nothing, func) -> func++parseConstrPred :: (PPrint a) => Id -> a -> (Maybe Id, Id)+parseConstrPred modId symb = case split '$' $ F.showpp symb of+ [n, func] -> (Just (stripLegalName modId n), stripLegalName modId func)+ [func] -> (Nothing, stripLegalName modId func)+ _ -> (Nothing, F.showpp symb)++-- | Translation of a LH SpecType to a refined argument {x: A | r}+--+-- > transType(RVar n ref) = {x: x | transRef(x,ref)} -- where x = showName n+-- > transType({f: (arg -> ret) | ref}) = {f: (x:transType(arg) -> transType(ret)) | transRef(x,ref)} -- where transType(arg) = {x:_ | _}+-- > transType(RAllT (RVar n _) typ ref) = {x:tp | transRef(x,ref)} -- where transType(typ) = {_:tp | _} and x = showName n+-- > transType(PType (PV n _ _ _) typ) = {n:tp | true} -- where transType(typ) = {_:tp | _}+-- > transType(RApp f _ _ reft) = {x: (transCon f) | transRef(x,reft)} -- where reft = {x: _ | _}+transType :: Id -> InternalCont -> SpecType -> Calc.RefType+-- \| Type variables+transType modId intCont (RVar n ref) = case x of+ "()" -> Calc.RefType x Calc.unitTp reft+ _ -> Calc.RefType x (Calc.TC x) reft+ where+ x = showName modId n+ reft = transRef modId intCont x ref+-- \| Functions+transType modId intCont (RFun f _ arg ret _) =+ -- trace ("transType RFun" ++ show (ur_reft ref)) $+ Calc.ArrType x argTp' retTp'+ where+ x = transVarName modId f+ argTp' = transType modId intCont arg+ retTp' = transType modId intCont ret+-- \| Forall?+transType modId intCont (RAllT (RTVar (RTV n) _) typ ref) =+ wrapWith x r (transType modId intCont typ)+ where+ x = showName modId n+ r = transRef modId intCont x ref+-- \| Abstract refinements+transType modId intCont (RAllP (PV n _ _) typ) =+ wrapWith x Calc.ttTm (transType modId intCont typ)+ where+ x = showName modId n+-- \| Application of type constructor/builtin to types+transType modId intCont (RApp f _ _ reft) = Calc.RefType x transT r+ where+ transT = transCon modId f+ x = refVar modId intCont reft+ r = transRef modId intCont x reft+transType _ _ (REx {}) = unsupported "transType: unsupported REx"+transType _ _ (RExprArg {}) = unsupported "transType: unsupported RExprArg"+transType _ _ (RAppTy {}) = unsupported "transType: unsupported RAppTy"+transType _ _ (RRTy {}) = unsupported "transType: unsupported RRTy"+transType _ _ (RHole {}) = unsupported "transType: unsupported RHole"++-- | Re-bind a translated type under the name @x@ with refinement @reft@:+-- on a base type it replaces the refinement, on an arrow it wraps the whole+-- arrow as a unit-typed refined argument.+wrapWith :: Id -> Calc.Reft -> Calc.RefType -> Calc.RefType+wrapWith x reft (Calc.RefType _ tp _) = Calc.RefType x tp reft+wrapWith x reft arr@Calc.ArrType {} = Calc.ArrType x arr (Calc.RefType "_" Calc.unitTp reft)++showName :: (Show a) => Id -> a -> String+showName modId = transVarName modId . show++-- MkUReft (F.Reft (s, tm)) is the representation of {s:_ | tm}+transRefType :: Id -> InternalCont -> UReft -> (F.Symbol, Calc.Reft)+transRefType modId intCont (MkUReft (F.Reft (s, tm)) _) = (s, runReader (transExp modId binder tm) intCont)+ where+ binder = transVarName modId s++transRef :: Id -> InternalCont -> String -> UReft -> Calc.Reft+transRef modId intCont x r =+ let (s, ref') = transRefType modId intCont r+ in Calc.subst (Calc.mkVar x) (transVarName modId s) ref'++refVar :: Id -> InternalCont -> UReft -> String+refVar modId intCont = transVarName modId . fst . transRefType modId intCont++internal :: Id -> F.Expr -> Reader InternalCont Bool+internal modId = go+ where+ go (F.PAtom _ e1 e2) = (||) <$> go e1 <*> go e2+ go (F.EApp f t') = (||) <$> go f <*> go t'+ go (F.EVar sym) = internalConstrRef modId sym+ go (F.PAnd es) = allM go es+ go (F.PNot form) = go form+ go F.EBin {} = pure False+ go _ = pure False++-- | Translation of an LH-fixpoint Types.Expr (predicates used for refinements)+--+-- > transExpr(e) = tt -- if e is internal+-- > transExpr(brel e1 e2) = brel (transExpr e1) (transExpr e2)+-- > transExpr((…(x e1)…) en) = x [transExpr(e1), …, transExpr(en)]+-- > transExpr(x) = x+-- > transExpr(e1 && … && en) = &&_{ei not internal} trans(ei)+-- > transExpr(e1 <=> e2) = transExpr(e1) == transExpr(e2)+-- > transExpr(e1 => e2) = transExpr(e1) => transExpr(e2)+-- > transExpr(sym) = sym+-- > transExpr(i ∈ Int) = i+-- > transExpr(f ∈ Float) = f+-- > transExpr(s ∈ String) = s+-- > transExpr(not e) = not (transExpr e)+-- > transExpr(Ebin f e1 e2) = Ebin (transExpr e1) (transExpr e2)+-- > transExpr(if e1 then e2 else e3) = (e1 && e2) || (not e1 && e3)+-- > transExpr(or [e1,…,en])= ||_{ei} trans(ei)+transExp :: Id -> Id -> F.Expr -> Reader InternalCont Calc.Reft+transExp modId binder = transExpr+ where+ -- Construct a Var or DC depending on whether the name looks like+ -- a Haskell data constructor (starts with uppercase) and is not+ -- the current refinement binder (e.g. "VV").+ mkVarOrDC :: Id -> Calc.Reft+ mkVarOrDC s = M.findWithDefault dflt s builtinDCs+ where+ dflt+ | s /= binder, c : _ <- s, isUpper c = Calc.DC s+ | otherwise = Calc.mkVar s+ transExpr :: F.Expr -> Reader InternalCont Calc.Reft+ transExpr term = ifM (internal modId term) (pure Calc.ttTm) (go term)+ go :: F.Expr -> Reader InternalCont Calc.Reft+ go (F.PAtom brel e1 e2) =+ Calc.Bop (transBrel brel) <$> transExpr e1 <*> transExpr e2+ go app@(F.EApp {}) = goApp (flattenFixApp app)+ go (F.EVar sym) = pure $ mkVarOrDC (transVarName modId sym)+ go (F.PAnd es) = foldAnds <$> (mapM transExpr =<< filterM (fmap not . internalConstrRef modId) es)+ go (F.POr es) = foldOrs <$> mapM transExpr es+ go (F.PIff ante concl) = Calc.Bop Calc.Iff <$> transExpr ante <*> transExpr concl+ go (F.PImp ante concl) = Calc.Bop Calc.Impl <$> transExpr ante <*> transExpr concl+ go (F.ECon (F.I i)) = pure $ Calc.IntLit i+ go (F.ECon (F.R d)) = pure $ Calc.FloatLit d+ go (F.ECon (F.L str _)) = pure . Calc.StringLit $ show str+ go (F.PNot form) = Calc.Neg <$> transExpr form+ go (F.EBin f e1 e2)+ | Just bop <- M.lookup (F.showpp f) bops =+ Calc.Bop bop <$> transExpr e1 <*> transExpr e2+ go (F.EIte cond thenE elseE) = do+ cTm <- transExpr cond+ tTm <- transExpr thenE+ eTm <- transExpr elseE+ pure $ Calc.Bop Calc.Or (Calc.Bop Calc.And cTm tTm) (Calc.Bop Calc.And (Calc.Neg cTm) eTm)+ go (F.ESym sym) = unsupported $ "Uninterpreted symbol encountered: " ++ show sym+ go term = unsupported $ "Undefined expr translation: \n" ++ F.showpp term+ goApp (F.EVar f, ts) = foldl Calc.App (mkVarOrDC (transVarName modId f)) <$> mapM transExpr ts+ goApp (other, _) = unsupported $ "Expected variable at head of application in transExp, got: " ++ F.showpp other+ foldAnds [] = Calc.ttTm+ foldAnds rs = foldl1 (Calc.Bop Calc.And) rs+ foldOrs [] = Calc.ttTm -- TODO: [LP] An empty disjunction should be false no?+ foldOrs rs = foldl1 (Calc.Bop Calc.Or) rs++flattenFixApp :: F.Expr -> (F.Expr, [F.Expr])+flattenFixApp = go []+ where+ go acc v@F.EVar {} = (v, acc)+ go acc (F.EApp f t) = go (t : acc) f+ go _ _ = unsupported "Application expected in flattenFixApp."++-- | Translation of an arrow type+--+-- > transFun({f_1: t1 → {f_2: t_2 → {… → {f_n: t_n → t | _} … } | _} | _}) = ([(f_1, transType t_1), …, (f_n, transType t_n)], transType t) -- where n ≥ 0+-- > -- with some subtleties on the names, that relies on an additional context parameter+transFun :: Id -> Maybe Id -> SpecType -> Calc.RefType+transFun modId fO spTp@(RFun g _ _ _ _) = go spTp [showppStripped modId g]+ where+ go :: SpecType -> [Id] -> Calc.RefType+ -- TODO: put an error or a warning if the ignored refinement is not trivial+ go (RFun f _ tin tout _) vars = Calc.ArrType n (trans tin) (go tout (n : vars))+ where+ (nO, func) = getFuncArgName modId f+ n = fromMaybe func nO+ trans = transType modId (ConstrArgsCtx (Just n) vars)+ go spTp' vars = transType modId (ConstrArgsCtx (Just f) vars) spTp'+ where+ f = maybe (showppStripped modId g) (stripLegalName modId) fO+transFun modId fO spTp = transType modId intCont spTp+ where+ intCont = ConstrArgsCtx (stripLegalName modId <$> fO) []++-- | Translation of a specification of LH SpecType+transSig :: Id -> Maybe Id -> SpecType -> Calc.RefType+transSig = transFun++-- | Trivial translation of binary relations+transBrel :: F.Brel -> Calc.Bop+transBrel F.Eq = Calc.Eq+transBrel F.Ne = Calc.Neq+transBrel F.Ge = Calc.Geq+transBrel F.Le = Calc.Leq+transBrel F.Gt = Calc.Gt+transBrel F.Lt = Calc.Lt+transBrel rel = unsupported $ "Undefined brel translation: " ++ show rel++-- | LH builtin binary operators (on Int) (in Fixpoint, also RTimes (*.) and RDiv (/.), but not in CoreToLogic)+bops :: M.Map String Calc.Bop+bops =+ M.fromList+ [ ("+", Calc.Plus),+ ("-", Calc.Minus),+ ("*", Calc.Times),+ ("/", Calc.Div),+ ("%", Calc.Mod),+ ("==", Calc.Eq),+ ("/=", Calc.Neq),+ (">=", Calc.Geq),+ (">", Calc.Gt),+ ("<=", Calc.Leq),+ ("<", Calc.Lt)+ ]++-- | LH builtin data constructors+builtinDCs :: M.Map String Calc.Reft+builtinDCs =+ M.fromList+ [ ("()", Calc.unitTm),+ ("trivial", Calc.unitTm),+ (ttTmName, Calc.ttTm),+ (ffTmName, Calc.ffTm)+ ]++-- | LH builtin types: the base types and the unit type constructor+builtinTCs :: M.Map String Calc.BaseType+builtinTCs =+ M.fromList+ [ ("Integer", Calc.Builtin Calc.Integer),+ ("Int", Calc.Builtin Calc.Integer),+ ("Float", Calc.Builtin Calc.Double),+ ("()", Calc.unitTp)+ ]
src/Language/Haskell/Liquid/Transforms/ANF.hs view
@@ -9,7 +9,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} -module Language.Haskell.Liquid.Transforms.ANF (anormalize) where+module Language.Haskell.Liquid.Transforms.ANF (anormalize, anormalizeExprBinds) where import Debug.Trace (trace) import Prelude hiding (error)@@ -36,6 +36,7 @@ import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM import GHC.Core.Type (ForAllTyBinder)+import GHC.Types.Id (mkSysLocalM) -------------------------------------------------------------------------------- -- | A-Normalize a module ------------------------------------------------------@@ -47,8 +48,24 @@ where err = panic Nothing "Oops, cannot A-Normalize GHC Core!" act = Misc.concatMapM (normalizeTopBind γ0) (mg_binds modGuts)- γ0 = emptyAnfEnv cfg+ γ0 = emptyAnfEnv cfg False +-- | Put elaborated refinement predicates through the same normalization used+-- for ordinary program expressions. These expressions are produced only after+-- the module's top-level Core has already been normalized.+anormalizeExprBinds :: UX.Config -> HscEnv -> ModGuts -> [CoreExpr] -> IO [CoreBind]+anormalizeExprBinds cfg hscEnv modGuts exprs = do+ fromMaybe err . snd <$> initDsWithModGuts hscEnv modGuts act+ where+ err = panic Nothing "Oops, cannot A-Normalize refinement predicates!"+ act = concat <$> forM exprs (\e -> do+ x <- mkSysLocalM (fsLit "lq_refinement") ManyTy (exprType e)+ normalizeTopBind γ0 (NonRec x e))+ -- Refinement checks need to retain @I# n#@ so constraint generation can+ -- recover the boxed integer's singleton refinement. Ordinary program ANF+ -- keeps its established invariant that application arguments are names.+ γ0 = emptyAnfEnv cfg True+ -------------------------------------------------------------------------------- -- | A-Normalize a @CoreBind@ -------------------------------------------------- --------------------------------------------------------------------------------@@ -214,6 +231,14 @@ e2' <- normalize γ e2 return $ App e1' e2' +-- Keep primitive literals next to their boxing constructor. Besides avoiding+-- a needless ANF binding, this lets constraint generation recognize @I# 2#@+-- as the logical integer constant @2@ rather than the uninterpreted+-- application @I# 2@.+normalize γ (App e1 e2@(Lit _)) | aeKeepBoxedLiterals γ, isIntBox e1+ = do e1' <- normalize γ e1+ return $ App e1' e2+ normalize γ (App e1 e2) = do e1' <- normalize γ e1 n2 <- normalizeName γ e2@@ -226,6 +251,11 @@ normalize _ (Coercion c) = return $ Coercion c +isIntBox :: CoreExpr -> Bool+isIntBox (Var box) = box == dataConWorkId intDataCon+isIntBox (App e (Type _)) = isIntBox e+isIntBox _ = False+ -------------------------------------------------------------------------------- stitch :: AnfEnv -> CoreExpr -> DsMW CoreExpr --------------------------------------------------------------------------------@@ -363,6 +393,7 @@ , aeSrcSpan :: Sp.SpanStack , aeCfg :: UX.Config , aeCaseDepth :: !Int+ , aeKeepBoxedLiterals :: !Bool } -- | A \"stable\" 'Id'. When transforming 'Core' into ANF notation, we need to keep around a mapping between@@ -398,12 +429,13 @@ instance UX.HasConfig AnfEnv where getConfig = aeCfg -emptyAnfEnv :: UX.Config -> AnfEnv-emptyAnfEnv cfg = AnfEnv+emptyAnfEnv :: UX.Config -> Bool -> AnfEnv+emptyAnfEnv cfg keepBoxedLiterals = AnfEnv { aeVarEnv = mempty , aeSrcSpan = Sp.empty , aeCfg = cfg , aeCaseDepth = 1+ , aeKeepBoxedLiterals = keepBoxedLiterals } lookupAnfEnv :: AnfEnv -> Id -> Id -> Id
src/Language/Haskell/Liquid/Transforms/CoreToLogic.hs view
@@ -47,7 +47,6 @@ import Language.Haskell.Liquid.Bare.Types import Language.Haskell.Liquid.Bare.DataType import Language.Haskell.Liquid.Bare.Misc (simpleSymbolVar)-import Language.Haskell.Liquid.GHC.Play import Language.Haskell.Liquid.Types.Errors import Language.Haskell.Liquid.Types.Names import Language.Haskell.Liquid.Types.RefType@@ -204,10 +203,17 @@ = throw $ "Bad alternative" ++ GM.showPpr alt mkDef x ctor _args dx (Just dtss) (Just e) = do- eDef <- ctor <$> coreToLg e- -- let ys = toArgs id args+ e0 <- coreToLg e let dxt = Just (varRType dx)- return [ Def x {- ys -} d dxt (defArgs x ts) eDef | (d, _, ts) <- dtss ]+ -- The DEFAULT body may mention the scrutinee @dx@; for each data+ -- constructor @d@ covered by the default alternative, we re-express it as+ -- @d@ applied to the fresh field arguments, mirroring 'mkAlt'. Without+ -- this substitution the scrutinee would remain unbound.+ let mkOne (d, _, ts) =+ let args = defArgs x ts+ su = (F.symbol dx, F.mkEApp (GM.namedLocSymbol d) (F.eVar . fst <$> args))+ in Def x d dxt args (ctor (e0 `subst1` su))+ return (mkOne <$> dtss) mkDef _ _ _ _ _ _ = return []@@ -303,6 +309,17 @@ coreToLg (C.Lit l) = case mkLit l of Nothing -> throw $ "Bad Literal in measure definition" ++ GM.showPpr l Just i -> return i+coreToLg (C.Cast e c)+ | Just (dc, ntCo) <- newtypeCoercionDataCon c+ = do e' <- coreToLg e+ case ntCo of+ -- @e |> (Rep ~ NT)@ is the newtype constructor applied to @e@.+ WrapCoercion ->+ return $ F.mkEApp (GM.namedLocSymbol dc) [e']+ -- @e |> (NT ~ Rep)@ is the newtype field selector applied to @e@.+ UnwrapCoercion -> do+ dm <- reader lsDCMap+ return $ EApp (EVar (makeDataConSelector (Just dm) dc 1)) e' coreToLg (C.Cast e c) = do (s, t) <- coerceToLg c e' <- coreToLg e return (ECoerc s t e')@@ -319,6 +336,49 @@ coerceToLg :: Coercion -> LogicM (Sort, Sort) coerceToLg = typeEqToLg . coercionTypeEq +data NewtypeCoercion = WrapCoercion | UnwrapCoercion+ deriving (Eq, Show)++-- | @newtypeCoercionDataCon co@ recognises the representational coercions that+-- GHC inserts to wrap and unwrap @newtype@ values.+--+-- Given a newtype declaration+--+-- > newtype NT = MkT (unwrap :: Rep)+--+-- an expression @Cast e co@, could stand for a wrap coercion @MkT e@, or an+-- unwrap coercion @unwrap e@, or something else. And this function must+-- distinguish between the three cases.+--+-- @Cast e (NT ~ Rep)@ is an unwrap coercion, and @Cast e (Rep ~ NT)@ is a+-- wrap coercion.+--+-- If this is a newtype coercion, it returns the newtype's 'DataCon' together+-- with a flag indicating the kind of coercion.+--+-- See note [Newtype checking] in "Language.Haskell.Liquid.Constraint.Generate".+newtypeCoercionDataCon :: Coercion -> Maybe (DataCon, NewtypeCoercion)+newtypeCoercionDataCon co+ | Ghc.Pair s t <- coercionKind co+ = case (asNewtypeRep t s, asNewtypeRep s t) of+ (Just dc, _) -> Just (dc, WrapCoercion)+ (_, Just dc) -> Just (dc, UnwrapCoercion)+ _ -> Nothing+ where+ -- @asNewtypeRep nt rep@ returns the newtype's 'DataCon' when @nt@ is a+ -- fully-applied non-recursive newtype whose instantiated representation+ -- type is @rep@.+ asNewtypeRep nt rep+ | Just (tc, args) <- splitTyConApp_maybe nt+ , isNewTyCon tc+ , args `lengthAtLeast` newTyConEtadArity tc+ , Just dc <- tyConSingleDataCon_maybe tc+ , newTyConInstRhs tc args `eqType` rep+ = Just dc+ | otherwise+ = Nothing++ coercionTypeEq :: Coercion -> (Type, Type) coercionTypeEq co | Ghc.Pair s t <- -- GM.tracePpr ("coercion-type-eq-1: " ++ GM.showPpr co) $@@ -417,8 +477,12 @@ = PAnd <$> mapM coreToLg [e1, e2] | f == symbol ("Language.Haskell.Liquid.Prelude.==>" :: String) = PImp <$> coreToLg e1 <*> coreToLg e2+ | GM.dropModuleUnique f == symbol ("==>" :: String)+ = PImp <$> coreToLg e1 <*> coreToLg e2 | f == symbol ("Language.Haskell.Liquid.Prelude.<=>" :: String) = PIff <$> coreToLg e1 <*> coreToLg e2+ | GM.dropModuleUnique f == symbol ("<=>" :: String)+ = PIff <$> coreToLg e1 <*> coreToLg e2 | f == symbol (show 'const) = coreToLg e1 go (Just f, [es])@@ -550,6 +614,7 @@ mkLit (LitDouble n) = mkR n mkLit (LitString s) = Just (mkS s) mkLit (LitChar c) = mkC c+mkLit LitNullAddr = mkI 0 mkLit _ = Nothing -- ELit sym sort mkI :: Integer -> Maybe Expr@@ -690,7 +755,7 @@ = C.Let (C.Rec (map (fmap go) xes)) (go e) go (C.Case e x _t alts@[Alt _ _ ee,_,_]) | isBangInteger alts- = sub (M.singleton x (go e)) (go ee)+ = sub x (go e) (go ee) go (C.Case e x t alts) = C.Case (go e) x t $ filter@@ -705,9 +770,22 @@ go (C.Type t) = C.Type t +-- | Substitute variable bindings in a CoreExpr using GHC's capture-avoiding+-- substExpr.+--+-- TODO: This implementation is a bit wastful since it collects the free+-- variables of both expressions every time, we could pass a superset of the+-- free variables instead. But the overhead is not observable in our tests.+sub :: CoreBndr -> CoreExpr -> CoreExpr -> CoreExpr+sub x e0 e = Ghc.substExpr su e+ where+ fvs = Ghc.exprFreeVars e `Ghc.unionVarSet` Ghc.exprFreeVars e0+ inScope = Ghc.mkInScopeSet fvs+ su = Ghc.extendIdSubst (Ghc.mkEmptySubst inScope) x e0+ inlineCoreExpr :: (Id -> Bool) -> CoreExpr -> CoreExpr inlineCoreExpr p (C.Let (C.NonRec x ex) e)- | p x = sub (M.singleton x (inlineCoreExpr p ex)) (inlineCoreExpr p e)+ | p x = sub x (inlineCoreExpr p ex) (inlineCoreExpr p e) | otherwise = C.Let (C.NonRec x (inlineCoreExpr p ex)) (inlineCoreExpr p e) inlineCoreExpr p (C.Let (C.Rec xes) e) = C.Let (C.Rec (map (fmap (inlineCoreExpr p)) xes)) (inlineCoreExpr p e) inlineCoreExpr p (C.App e1 e2) = C.App (inlineCoreExpr p e1) (inlineCoreExpr p e2)
src/Language/Haskell/Liquid/Transforms/InlineAux.hs view
@@ -11,9 +11,23 @@ as GM import qualified Data.HashMap.Strict as M +-- | Inline auxiliary class method implementations in a 'CoreProgram'.+--+-- When GHC compiles a typeclass instance, it generates:+-- * a dictionary function (dfun), e.g. @$fShowInt@+-- * auxiliary functions for each method, e.g. @$cshow@ for 'show'+--+-- A call like @show $fShowInt x@ dispatches through the dictionary.+-- This pass rewrites such calls to bypass the dictionary and call the+-- auxiliary directly: @$cshow x@.+--+-- This transformation is only applied when 'UX.auxInline' is enabled in the+-- config. After inlining, 'occurAnalysePgm' is run to clean up dead bindings. inlineAux :: UX.Config -> Module -> CoreProgram -> CoreProgram inlineAux cfg m cbs = if UX.auxInline cfg then occurAnalysePgm m (const False) (const False) [] (map f cbs) else cbs where+ -- For each binding that is itself an auxiliary (i.e. it appears as a free+ -- variable inside some dfun body), rewrite its RHS using 'inlineAuxExpr'. f :: CoreBind -> CoreBind f all'@(NonRec x e) | Just (dfunId, methodToAux) <- M.lookup x auxToMethodToAux = NonRec@@ -27,39 +41,69 @@ = (x, inlineAuxExpr dfunId methodToAux e) | otherwise = all'+ -- Build the combined map from every dfun found in the program.+ -- Maps each auxiliary Id to (its dfun, the method->aux map for that dfun). auxToMethodToAux = mconcat $ fmap (uncurry dfunIdSubst) (grepDFunIds cbs) ---- inlineDFun :: DynFlags -> CoreProgram -> IO CoreProgram--- inlineDFun df cbs = mapM go cbs--- where--- go orig@(NonRec x e) | isDFunId x = do--- -- e''' <- simplifyExpr df e''--- let newBody = mkCoreApps (GM.tracePpr ("substituted type:" ++ GM.showPpr (exprType (mkCoreApps e' (Var <$> binders)))) e') (fmap Var binders)--- bind = NonRec (mkWildValBinder (exprType newBody)) newBody--- pure $ NonRec x (mkLet bind e)--- | otherwise = pure orig--- where--- -- wcBinder = mkWildValBinder t--- (binders, _) = GM.tracePpr "collectBinders"$ collectBinders e--- e' = substExprAll empty subst e--- go recs = pure recs--- subst = buildDictSubst cbs---- grab the dictionaries+-- | Collect all dictionary-function bindings from a 'CoreProgram'.+--+-- A dfun is the implementation record GHC generates for a typeclass instance.+-- For example, @instance Show Int@ produces @$fShowInt :: Show Int@.+--+-- Example: given bindings for @[$fShowInt, foo, $fOrdInt]@, this returns+-- @[($fShowInt, <its RHS>), ($fOrdInt, <its RHS>)]@. grepDFunIds :: CoreProgram -> [(DFunId, CoreExpr)] grepDFunIds = filter (isDFunId . fst) . flattenBinds +-- | Check whether an 'OccName' is a GHC-generated class-op auxiliary name.+--+-- GHC names auxiliary class method implementations with the prefix @$c@.+-- For example, the auxiliary for 'show' in @instance Show Int@ is @$cshow@.+--+-- Examples:+-- isClassOpAuxOccName "$cshow" == True+-- isClassOpAuxOccName "show" == False+-- isClassOpAuxOccName "$fShowInt" == False isClassOpAuxOccName :: OccName -> Bool isClassOpAuxOccName occ = case occNameString occ of '$' : 'c' : _ -> True _ -> False +-- | Check whether @aux@ is the class-op auxiliary implementation of @method@.+--+-- @aux `isClassOpAuxOf` method@ holds when @aux@ has a @$c@-prefixed name+-- whose suffix matches @method@'s unqualified name.+--+-- Example:+-- -- aux = "$cshow" (OccName for the Show Int auxiliary)+-- -- method = "show" (OccName for the 'show' selector)+-- "$cshow" `isClassOpAuxOf` "show" == True+-- "$cshow" `isClassOpAuxOf` "eq" == False isClassOpAuxOf :: Id -> Id -> Bool isClassOpAuxOf aux method = case occNameString $ getOccName aux of '$' : 'c' : rest -> rest == occNameString (getOccName method) _ -> False +-- | Build a substitution map from a single dfun and its Core body.+--+-- For each auxiliary Id @aux@ that appears free in the dfun's body, and for+-- each class method @m@ such that @aux `isClassOpAuxOf` m@, the resulting map+-- contains an entry:+--+-- @ aux -> (dfunId, { m -> aux, ... }) @+--+-- This lets 'inlineAuxExpr' know that, inside the body of @aux@, calls to+-- method @m@ dispatched through @dfunId@ can be replaced by direct calls to+-- the corresponding auxiliary.+--+-- Example: for @$fShowInt@ whose body mentions @$cshow@ and @$cshowList@:+--+-- @+-- dfunIdSubst $fShowInt <body> ==+-- { $cshow -> ($fShowInt, { show -> $cshow, showList -> $cshowList })+-- , $cshowList -> ($fShowInt, { show -> $cshow, showList -> $cshowList })+-- }+-- @ dfunIdSubst :: DFunId -> CoreExpr -> M.HashMap Id (Id, M.HashMap Id Id) dfunIdSubst dfunId e = M.fromList [(auxId, (dfunId, methodToAux)) | auxId <- auxIds] where@@ -69,6 +113,36 @@ auxIds = filter (isClassOpAuxOccName . getOccName) (exprFreeVarsList e) methods = classAllSelIds cls +-- | Rewrite a Core expression by replacing indirect method calls that go+-- through a dictionary with direct calls to the corresponding auxiliary.+--+-- The key rewrite rule (the last @go@ case before the @App@ fall-through) is:+--+-- @+-- m @T1 .. @Tn ($fC args..) x1 .. xk+-- -- where M.lookup m methodToAux == Just aux+-- ==>+-- aux args.. (go x1) .. (go xk)+-- @+--+-- In other words: a call to method @m@ whose first value argument is an+-- application of @dfunId@ is rewritten to call the auxiliary @aux@ directly,+-- passing the dfun's own arguments followed by the remaining method arguments.+--+-- All other sub-expressions are traversed recursively.+-- Dict-only let-bindings (@let x = dict in ...@) are substituted away eagerly+-- so that the main rewrite rule can fire on the resulting expression.+--+-- Example (schematic Core):+-- @+-- -- Before:+-- $cshow = \dict_arg ->+-- let d = $fShowInt in show @Int d 42+--+-- -- After inlineAuxExpr $fShowInt { show -> $cshow } on the RHS:+-- $cshow = \dict_arg ->+-- $cshow 42+-- @ inlineAuxExpr :: DFunId -> M.HashMap Id Id -> CoreExpr -> CoreExpr inlineAuxExpr dfunId methodToAux = go where@@ -93,10 +167,18 @@ go e = e --- modified from Rec.hs+-- | Apply a transformation to the RHS expression(s) of a 'Bind'.+--+-- Example:+-- mapBnd go (NonRec x e) == NonRec x (go e)+-- mapBnd go (Rec [(x,e)]) == Rec [(x, go e)] mapBnd :: (Expr b -> Expr b) -> Bind b -> Bind b mapBnd f (NonRec b e) = NonRec b (f e) mapBnd f (Rec bs ) = Rec (map (second f) bs) +-- | Apply a transformation to the body expression of a 'Case' alternative.+--+-- Example:+-- mapAlt go (Alt DataAlt [b] e) == Alt DataAlt [b] (go e) mapAlt :: (Expr b -> Expr b) -> Alt b -> Alt b mapAlt f (Alt d bs e) = Alt d bs (f e)
src/Language/Haskell/Liquid/Transforms/QuestionMark.hs view
@@ -1,5 +1,6 @@ {-# LANGUAGE PatternGuards #-}--- | Eliminate applications of the '?' operator from Core after ANF.+{-# LANGUAGE TemplateHaskellQuotes #-}+-- | Eliminate applications of the '?' operator and 'const' from Core after ANF. -- -- After ANF, @e ? s@ becomes: --@@ -13,38 +14,73 @@ -- are introduced in the signature of @?@. The binding @a2 = s@ remains in -- scope, so the lemma's postcondition still enters the environment during -- constraint generation.+--+-- This pass fixes #2544.+--+-- Eliminating applications of 'const' is convenient when importing modules from+-- liquid-prelude is unwanted and therefore `?` is unavailable. module Language.Haskell.Liquid.Transforms.QuestionMark (eliminateQuestionMark) where +import qualified Language.Haskell.TH.Syntax as TH (nameModule) import Liquid.GHC.API as Ghc --- | Look up the '?' operator in the 'GlobalRdrEnv'. If found, eliminate all--- its applications from the Core program. If not found (module doesn't import--- ProofCombinators), return the bindings unchanged.+-- | Look up the 'FunctionNames' in the 'GlobalRdrEnv'. If found, eliminate all+-- their applications from the Core program. If not found, return the bindings unchanged. eliminateQuestionMark :: GlobalRdrEnv -> [CoreBind] -> [CoreBind] eliminateQuestionMark rdrEnv cbs =- case lookupQuestionMark rdrEnv of- Nothing -> cbs- Just name -> map (goBind name) cbs+ case lookupFunctionNames rdrEnv of+ Nothing -> cbs+ Just names -> map (goBind names) cbs+-- | A record of function names whose applications are to be removed form the core program.+data FunctionNames = FunctionNames+ { questionMarkName :: Maybe Name+ , constName :: Maybe Name+ } +lookupFunctionNames :: GlobalRdrEnv -> Maybe FunctionNames+lookupFunctionNames rdrEnv =+ case (lookupQuestionMark rdrEnv, lookupConst rdrEnv) of+ (Nothing, Nothing) -> Nothing+ (n0, n1) -> Just (FunctionNames n0 n1)+ -- | Find the 'Name' of '?' from @Language.Haskell.Liquid.ProofCombinators@ -- in the renamer environment. lookupQuestionMark :: GlobalRdrEnv -> Maybe Name lookupQuestionMark rdrEnv =- case lookupGRE rdrEnv (LookupRdrName rdrName SameNameSpace) of- [gre] -> Just (greName gre)+ let m = "Language.Haskell.Liquid.ProofCombinators"+ in case filter (nameModuleIs m . greName) $+ lookupGRE rdrEnv (LookupOccName (mkVarOcc "?") SameNameSpace) of+ [gre] -> Just (greName gre)+ _ -> Nothing++-- | Find the 'Name' of 'const' from @base@ in the renamer environment.+lookupConst :: GlobalRdrEnv -> Maybe Name+lookupConst rdrEnv = do+ m <- TH.nameModule 'const+ case filter (nameModuleIs m . greName) $+ lookupGRE rdrEnv (LookupOccName (mkVarOcc "const") SameNameSpace) of+ [gre] -> do+ Just (greName gre) _ -> Nothing- where- rdrName = mkRdrQual (mkModuleName "Language.Haskell.Liquid.ProofCombinators")- (mkVarOcc "?") -goBind :: Name -> CoreBind -> CoreBind+nameModuleIs :: String -> Name -> Bool+nameModuleIs m n = case nameModule_maybe n of+ Just m' -> moduleNameString (moduleName m') == m+ Nothing -> False++goBind :: FunctionNames -> CoreBind -> CoreBind goBind n (NonRec x e) = NonRec x (goExpr n e) goBind n (Rec xes) = Rec [(x, goExpr n e) | (x, e) <- xes] -goExpr :: Name -> CoreExpr -> CoreExpr+goExpr :: FunctionNames -> CoreExpr -> CoreExpr goExpr n e- | Just firstArg <- isQuestionMarkApp n e = goExpr n firstArg+ | Just qmName <- questionMarkName n+ , Just firstArg <- isQuestionMarkApp qmName e =+ goExpr n firstArg+ | Just cName <- constName n+ , Just firstArg <- isQuestionMarkApp cName e =+ goExpr n firstArg goExpr n (Lam x e) = Lam x (goExpr n e) goExpr n (Let b e) = Let (goBind n b) (goExpr n e) goExpr n (Case s x t alts) = Case (goExpr n s) x t [goAlt n a | a <- alts]@@ -53,10 +89,10 @@ goExpr n (App f a) = App (goExpr n f) (goExpr n a) goExpr _ e = e -- Var, Lit, Type, Coercion -goAlt :: Name -> CoreAlt -> CoreAlt+goAlt :: FunctionNames -> CoreAlt -> CoreAlt goAlt n (Alt con bs e) = Alt con bs (goExpr n e) --- | Detect a fully-saturated application of '?': four arguments total+-- | Detect a fully-saturated application of '?' or `const`: four arguments total -- (two types + two values), possibly wrapped in ticks. -- Returns @Just arg1@ (the first value argument). isQuestionMarkApp :: Name -> CoreExpr -> Maybe CoreExpr
src/Language/Haskell/Liquid/Transforms/Rewrite.hs view
@@ -24,17 +24,15 @@ ) where -import Liquid.GHC.API as Ghc hiding (get, showPpr, substExpr)+import Liquid.GHC.API as Ghc hiding (get, showPpr) import Language.Haskell.Liquid.GHC.TypeRep () import Data.Maybe (fromMaybe, isJust, mapMaybe) import Control.Monad.State hiding (lift) import Language.Haskell.Liquid.Misc (Nat)-import Language.Haskell.Liquid.GHC.Play (sub, substExpr) import Language.Haskell.Liquid.GHC.Misc (unTickExpr, isTupleId, mkAlive) import Language.Haskell.Liquid.Types.Errors (impossible) import Language.Haskell.Liquid.UX.Config (Config, noSimplifyCore) import qualified Data.List as L-import qualified Data.HashMap.Strict as M -------------------------------------------------------------------------------- -- | Top-level rewriter --------------------------------------------------------@@ -283,7 +281,11 @@ -- | `substTuple xs ys e'` returns e' [y1 := x1,...,yn := xn] -------------------------------------------------------------------------------- substTuple :: [Var] -> [Var] -> CoreExpr -> CoreExpr-substTuple xs ys = substExpr (M.fromList $ zip ys xs)+substTuple xs ys e = Ghc.substExpr subst e+ where+ inScope = Ghc.mkInScopeSet (Ghc.exprFreeVars e `extendVarSetList` xs)+ subst = Ghc.extendIdSubstList (Ghc.mkEmptySubst inScope)+ [ (v, Var v') | (v, v') <- zip ys xs ] -- | Yields the tuple of variables at the end of nested cases with -- a single alternative each.@@ -339,7 +341,11 @@ inlineLoopBreaker (NonRec x e) | Just (lbx, lbe, lbargs) <- hasLoopBreaker be = let asPrefix = take (length as - length lbargs) as- lbe' = sub (M.singleton lbx (ecall asPrefix)) lbe+ inScope =+ Ghc.mkInScopeSet $+ Ghc.exprFreeVars (ecall asPrefix) `unionVarSet` Ghc.exprFreeVars lbe+ subst = Ghc.extendIdSubst (Ghc.mkEmptySubst inScope) lbx (ecall asPrefix)+ lbe' = Ghc.substExpr subst lbe in Rec [(x, mkLams (αs ++ asPrefix) (mkLets nrbinds lbe'))] where (αs, as, e') = collectTyAndValBinders e
src/Language/Haskell/Liquid/Types/Equality.hs view
@@ -67,7 +67,7 @@ instance REq t2 => REq (Ref t1 t2) where (RProp _ t1) =*= (RProp _ t2) = t1 =*= t2 -instance REq (UReft F.Reft) where+instance REq UReft where (MkUReft r1 p1) =*= (MkUReft r2 p2) = r1 =*= r2 && p1 == p2
src/Language/Haskell/Liquid/Types/Errors.hs view
@@ -479,6 +479,11 @@ , msg :: !Doc } + | ErrPleDisabled { pos :: !SrcSpan+ , var :: !Doc+ } -- ^ 'ple' or 'automatic-instances' annotation in a module+ -- that enables neither --ple-local nor --ple+ | ErrPosTyCon { pos :: SrcSpan , tc :: !Doc , dc :: !Doc@@ -521,6 +526,11 @@ } -- ^ Type was declared stratified but one of its constructors has a recursive -- occurence whose index type is not a smaller+ | ErrBadIgnore { pos :: !SrcSpan+ , var :: !Doc+ , msg :: !Doc+ } -- ^ Bad {-@ ignore @-} annotation+ | ErrOther { pos :: SrcSpan , msg :: !Doc } -- ^ Sigh. Other.@@ -1061,6 +1071,11 @@ , hint err ] +ppError' _ dCtx (ErrBadIgnore _ v msg)+ = (text "Cannot ignore" <+> ppTicks v)+ $+$ dCtx+ $+$ nest 4 msg+ ppError' _ dCtx (ErrOther _ s) = text "Uh oh." $+$ dCtx@@ -1106,6 +1121,14 @@ = text "Rewrite error" $+$ dCtx $+$ nest 4 msg++ppError' _ dCtx (ErrPleDisabled _ v)+ = text "PLE is not enabled for" <+> ppTicks v+ $+$ dCtx+ $+$ nest 4 (vcat+ [ text "Add {-@ LIQUID \"--ple-local\" @-} to run PLE on the annotated binders,"+ , text "or {-@ LIQUID \"--ple\" @-} to run it on the whole module."+ ]) ppError' _ dCtx (ErrPosTyCon _ tc dc) = text "Negative occurence of" <+> tc <+> "in" <+> dc
src/Language/Haskell/Liquid/Types/Names.hs view
@@ -53,7 +53,7 @@ import Data.Data (Data, gmapM, gmapT) import Data.Generics (extM, extT) import Data.Hashable-import Data.Maybe (isNothing)+import Data.Maybe (fromMaybe, isNothing) import Data.String (fromString) import qualified Data.Text as Text import GHC.Generics@@ -88,9 +88,13 @@ instance CompatibleBinder Symbol (Located Symbol) where coerceBinder (Loc _ _ s) = s --- RJ: Please add docs+-- | The size measure applied to values of a type marked @{-@ autosize T @-}@.+--+-- It is declared in @GHC.Base_LHAssumptions@, so it must be spelled with that+-- qualification here: the solver only knows the resolved name, and an+-- unqualified occurrence is rejected as a free variable. lenLocSymbol :: Located Symbol-lenLocSymbol = dummyLoc $ symbol ("autolen" :: String)+lenLocSymbol = dummyLoc $ symbol ("GHC.Base_LHAssumptions.autolen" :: String) anyTypeSymbol :: Symbol anyTypeSymbol = symbol (show ''Any)@@ -377,7 +381,7 @@ -- Otherwise, LH would fail to link the two at various places where it is needed. lhNameToResolvedSymbol :: LHName -> Symbol lhNameToResolvedSymbol (LHNResolved (LHRLogic (LogicName s om mReflectionOf)) _) =- let m = maybe om GHC.nameModule mReflectionOf+ let m = maybe om (\n -> fromMaybe om (GHC.nameModule_maybe n)) mReflectionOf msymbol = Text.pack $ GHC.moduleNameString $ GHC.moduleName m in symbol $ mconcat [msymbol, ".", symbolText s] {-
src/Language/Haskell/Liquid/Types/PredType.hs view
@@ -72,8 +72,19 @@ where tcM = M.fromList [(tcpCon tcp, mkRTyCon tcp) | tcp <- tcps ] tcInstM = mkFInstRTyCon tce fiTcs tcM- arities = safeFromList "makeTyConInfo" [ (c, length ts) | (c, ts) <- M.keys tcInstM ]+ arities =+ foldr+ (\(c, a) -> M.insertWith (checkEqValues c) c a)+ M.empty+ [ (c, length ts) | (c, ts) <- M.keys tcInstM ] + checkEqValues c v0 v1 =+ if v0 == v1 then v0+ else+ panic Nothing $+ "makeTyConInfo: Conflicting arities for TyCon: " +++ showPpr c ++ " " ++ showPpr v0 ++ " " ++ showPpr v1+ mkFInstRTyCon :: F.TCEmb Ghc.TyCon -> [Ghc.TyCon] -> M.HashMap Ghc.TyCon RTyCon -> M.HashMap (Ghc.TyCon, [F.Sort]) RTyCon mkFInstRTyCon tce fiTcs tcm = M.fromList [ ((c, typeSort tce <$> ts), rtc)@@ -198,7 +209,7 @@ ts' = map ("" , classRFInfo allowTC , , mempty) cs ++ yts' subst = F.mkSubst [(x, F.EVar y) | (x, y) <- zip as1 bs] rt' = F.subst subst rt- makeVars = filter (`elem` fvs) $ zipWith (\v a -> RTVar v (rTVarInfo a :: RTVInfo RSort)) vs (fst $ splitForAllTyCoVars $ dataConRepType dc)+ makeVars = filter (`elem` fvs) $ zipWith (\v a -> RTVar v (rTVarInfo a)) vs (fst $ splitForAllTyCoVars $ dataConRepType dc) makeVars' = map (, mempty) makeVars fvs = freeTyVars $ mkArrow [] ps ts' rt' @@ -219,8 +230,8 @@ ---------------------------------------------------------------------------- -- | Interface: Replace Predicate With Uninterpreted Function Symbol ------- -----------------------------------------------------------------------------replacePredsWithRefs :: (UsedPVar, (F.Symbol, [((), F.Symbol, F.Expr)]) -> F.Expr)- -> UReft F.Reft -> UReft F.Reft+replacePredsWithRefs :: (UsedPVar, (F.Symbol, [(NoReft, F.Symbol, F.Expr)]) -> F.Expr)+ -> UReft -> UReft replacePredsWithRefs (p, r) (MkUReft (F.Reft(v, rs)) (Pr ps)) = MkUReft (F.Reft (v, rs'')) (Pr ps2) where@@ -246,7 +257,7 @@ ----------------------------------------------------------------------- pvarRType :: (PPrint r, IsReft r) => PVar RSort -> RRType r ------------------------------------------------------------------------pvarRType (PV _ k {- (PVProp τ) -} _ args) = rpredType k (fst3 <$> args) -- (ty:tys)+pvarRType (PV _ k {- (PVProp τ) -} args) = rpredType k (fst3 <$> args) -- (ty:tys) -- where -- ty = uRTypeGen τ -- tys = uRTypeGen . fst3 <$> args@@ -366,8 +377,9 @@ SubsTy tv (RType RTyCon tv NoReft) (RType RTyCon tv NoReft), SubsTy tv (RType RTyCon tv NoReft) RTyCon, SubsTy tv (RType RTyCon tv NoReft) tv,- SubsTy tv (RType RTyCon tv NoReft) (RTVar tv (RType RTyCon tv NoReft)),+ SubsTy tv (RType RTyCon tv NoReft) (RTVar F.Symbol F.Symbol RTyCon tv), FreeVar RTyCon tv,+ Meet r, Meet (RType RTyCon tv r)) => [Char] -> (t, Ref RSort (RType RTyCon tv r))@@ -415,13 +427,13 @@ -- su = mkSubst (zip (fst <$> ss) (EVar . fst <$> ss')) -splitRPvar :: PVar t -> UReft r -> (UReft r, [UsedPVar])+splitRPvar :: PVar t -> UReft -> (UReft, [UsedPVar]) splitRPvar pv (MkUReft x (Pr pvs)) = (MkUReft x (Pr pvs'), epvs) where (epvs, pvs') = L.partition (uPVar pv ==) pvs -- TODO: rewrite using foldReft-freeArgsPs :: PVar (RType t t1 NoReft) -> RType t t1 (UReft t2) -> [F.Symbol]+freeArgsPs :: PVar (RType t t1 NoReft) -> RType t t1 UReft -> [F.Symbol] freeArgsPs p (RVar _ r) = freeArgsPsRef p r freeArgsPs p (RFun _ _ t1 t2 r)@@ -444,7 +456,7 @@ freeArgsPs p (RRTy env r _ t) = L.nub $ concatMap (freeArgsPs p . snd) env ++ freeArgsPsRef p r ++ freeArgsPs p t -freeArgsPsRef :: PVar t1 -> UReft t -> [F.Symbol]+freeArgsPsRef :: PVar t1 -> UReft -> [F.Symbol] freeArgsPsRef p (MkUReft _ (Pr ps)) = [x | (_, x, w) <- concatMap pargs ps', F.EVar x == w] where ps' = f <$> filter (uPVar p ==) ps@@ -454,12 +466,21 @@ => t (PVar t1) -> [(F.Symbol, RSort)] -> b -> b -> b meetListWithPSubs πs ss r1 r2 = L.foldl' (meetListWithPSub ss r1) r2 πs -meetListWithPSubsRef :: (Foldable t, Meet (RType c tv r), TyConable c, IsReft r, F.Subable r, F.Variable r ~ F.Symbol, ReftBind r ~ F.Symbol)- => t (PVar t4)- -> [(F.Symbol, b)]- -> Ref τ (RType c tv r)- -> Ref τ (RType c tv r)- -> Ref τ (RType c tv r)+meetListWithPSubsRef+ :: ( Foldable t+ , Meet (RType c tv r)+ , TyConable c+ , IsReft r+ , F.Subable r+ , F.Variable r ~ F.Symbol+ , ReftBind r ~ F.Symbol+ , ReftVar r ~ F.Symbol+ )+ => t (PVar t4)+ -> [(F.Symbol, b)]+ -> Ref τ (RType c tv r)+ -> Ref τ (RType c tv r)+ -> Ref τ (RType c tv r) meetListWithPSubsRef πs ss r1 r2 = L.foldl' (meetListWithPSubRef ss r1) r2 πs meetListWithPSub :: (PPrint t, F.Subable r, F.Variable r ~ F.Symbol, Meet r) => [(F.Symbol, RSort)]-> r -> r -> PVar t -> r@@ -473,12 +494,20 @@ where su = F.mkSubst [(x, y) | (x, (_, _, y)) <- zip (fst <$> ss) (pargs π)] -meetListWithPSubRef :: (Meet (RType c tv r), TyConable c, IsReft r, F.Subable r, F.Variable r ~ F.Symbol, ReftBind r ~ F.Symbol)- => [(F.Symbol, b)]- -> Ref τ (RType c tv r)- -> Ref τ (RType c tv r)- -> PVar t3- -> Ref τ (RType c tv r)+meetListWithPSubRef+ :: ( Meet (RType c tv r)+ , TyConable c+ , IsReft r+ , F.Subable r+ , F.Variable r ~ F.Symbol+ , ReftBind r ~ F.Symbol+ , ReftVar r ~ F.Symbol+ )+ => [(F.Symbol, b)]+ -> Ref τ (RType c tv r)+ -> Ref τ (RType c tv r)+ -> PVar t3+ -> Ref τ (RType c tv r) meetListWithPSubRef _ (RProp _ (RHole _)) _ _ -- TODO: Is this correct? = panic Nothing "PredType.meetListWithPSubRef called with invalid input" meetListWithPSubRef _ _ (RProp _ (RHole _)) _
src/Language/Haskell/Liquid/Types/PrettyPrint.hs view
@@ -42,6 +42,7 @@ ) where +import Control.Monad (unless) import qualified Data.HashMap.Strict as M import qualified Data.List as L -- (sort) import qualified Data.Set as Set@@ -374,7 +375,7 @@ dπs False _ = empty dπs True πs = angleBrackets $ intersperse comma $ pprPvarDef bb p <$> πs -pprRtvarDef :: (PPrint tv) => [RTVar tv (RTypeBV b v c tv (NoReftB b))] -> Doc+pprRtvarDef :: (PPrint tv) => [RTVar b v c tv] -> Doc pprRtvarDef = sep . map (pprint . ty_var_value) pprCls@@ -389,7 +390,7 @@ pprPvarDef :: (OkRTBV b v c tv (NoReftB b)) => PPEnv -> Prec -> PVarBV b v (RTypeBV b v c tv (NoReftB b)) -> Doc-pprPvarDef bb p (PV s t _ xts)+pprPvarDef bb p (PV s t xts) = pprint s <+> dcolon <+> intersperse arrow dargs <+> pprPvarKind bb p t where dargs = [pprPvarSort bb p xt | (xt,_,_) <- xts]@@ -422,7 +423,7 @@ ppTy :: ( Ord (ReftBind r), F.Fixpoint (ReftBind r), PPrint (ReftBind r) , Ord (ReftVar r), F.Fixpoint (ReftVar r), PPrint (ReftVar r)- , ToReft r+ , IsReft r ) => PPEnv -> r -> Doc -> Doc ppTy bb r0 t = doc where@@ -436,10 +437,10 @@ | not (ppPs bb) = t | otherwise = t <-> angleBrackets (pprint p) -instance (PPrint (PredicateBV b v), ToReft (PredicateBV b v), PPrint r, ToReft r) => PPrint (UReftBV b v r) where+instance (IsReft (F.ReftBV b v), Eq v, PPrint (PredicateBV b v), PPrint (F.ReftBV b v)) => PPrint (UReftBV b v) where pprintTidy k (MkUReft r p) | isTauto r = pprintTidy k p- | isTauto p = pprintTidy k r+ | null (pvars p) = pprintTidy k r | otherwise = pprintTidy k p <-> text " & " <-> pprintTidy k r --------------------------------------------------------------------------------@@ -456,14 +457,12 @@ -- are unexpected errors, or will call @continue@ otherwise. -- -- An error is expected if there is any filter that matches it.-filterReportErrors :: forall e' a. F.PPrint e' => FilePath -> Ghc.TcRn a -> Ghc.TcRn a -> [Filter] -> F.Tidy -> [TError e'] -> Ghc.TcRn a-filterReportErrors path failure continue filters k =+filterReportErrors :: forall e'. F.PPrint e' => FilePath -> [Filter] -> F.Tidy -> [TError e'] -> Ghc.TcRn ()+filterReportErrors path filters k = filterReportErrorsWith FilterReportErrorsArgs { errorReporter = \errs -> addTcRnUnknownMessages [(pos err, ppError k empty err) | err <- errs] , filterReporter = defaultFilterReporter path- , failure = failure- , continue = continue , matchingFilters = reduceFilters renderer filters , filters = filters }@@ -491,7 +490,7 @@ stringMatch filter' str = filter' `L.isInfixOf` str -- | Used in `filterReportErrorsWith'`-data FilterReportErrorsArgs m filter msg e a =+data FilterReportErrorsArgs m filter msg e = FilterReportErrorsArgs { -- | Report the @msgs@ to the monad (usually IO)@@ -500,12 +499,6 @@ -- | Report unmatched @filters@ to the monad filterReporter :: [filter] -> m () ,- -- | Continuation for when there are unmatched filters or unmatched errors- failure :: m a- ,- -- | Continuation for when there are no unmatched errors or filters- continue :: m a- , -- | Yields the filters that map a given error. Must only yield -- filters in the @filters@ field. matchingFilters :: e -> [filter]@@ -516,7 +509,7 @@ -- | Calls the continuations in FilterReportErrorsArgs depending on whethere there -- are unmatched errors, unmatched filters or none.-filterReportErrorsWith :: (Monad m, Ord filter) => FilterReportErrorsArgs m filter msg e a -> [e] -> m a+filterReportErrorsWith :: (Monad m, Ord filter) => FilterReportErrorsArgs m filter msg e -> [e] -> m () filterReportErrorsWith FilterReportErrorsArgs {..} errs = let (unmatchedErrors, matchedFilters) =@@ -525,14 +518,10 @@ Set.fromList filters `Set.difference` Set.fromList (concatMap snd matchedFilters) in if null unmatchedErrors then- if null unmatchedFilters then- continue- else do+ unless (null unmatchedFilters) $ filterReporter unmatchedFilters- failure- else do+ else errorReporter $ map fst unmatchedErrors- failure -- | Report errors via GHC's API stating the given `Filter`s did not get -- matched. Does nothing if the list of filters is empty.
src/Language/Haskell/Liquid/Types/RType.hs view
@@ -4,6 +4,7 @@ {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE GADTs #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-}@@ -12,8 +13,11 @@ {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE TupleSections #-}+{-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-}+{-# LANGUAGE RoleAnnotations #-}+{-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -Wno-orphans #-}@@ -46,18 +50,18 @@ -- * Type Variables , RTVar (..), RTVInfo (..)- , makeRTVar, mapTyVarValue- , dropTyVarInfo, rTVarToBind+ , makeRTVar+ , rTVarToBind , setRtvPol -- * Predicate Variables , PVar , PVarV- , PVarBV (PV, pname, parg, ptype, pargs), pvType+ , PVarBV (PV, pname, ptype, pargs), pvType , Predicate , PredicateV , PredicateBV(..)- , PredicateCompat(..)+ , pappV -- * Expression Arguments , notExprArg@@ -78,7 +82,8 @@ , mapUReftV , emapUReftVM , NoReft- , NoReftB(..)+ , NoReftB+ , NoReftBV(..) -- * Parse-time entities describing refined data types , SizeFun, SizeFunV (..), szFun@@ -114,11 +119,15 @@ , RFInfo(..), defRFInfo, mkRFInfo, classRFInfo -- * Converting to and from refinements- , ToReft(..)+ , ConcreteReft(..) , Meet(..) , Top(..) , IsReft(..) , isTauto+ , mapReftField+ , ofReft+ , toReft+ , toUReft , trueReft ) where@@ -149,7 +158,6 @@ ) import Data.String import GHC.Generics-import Prelude hiding (error) import Control.DeepSeq import Data.Traversable (forAccumM)@@ -160,7 +168,7 @@ import qualified Data.List as L import Data.Maybe (mapMaybe) import Data.List as L (nub)-import Data.Proxy (Proxy(..))+import qualified Data.HashSet as S import Text.PrettyPrint.HughesPJ hiding (first, (<>)) import Language.Fixpoint.Misc @@ -290,19 +298,13 @@ -- @{-\@ foo :: forall a \<p :: x:a -> z:a -> Bool\>. y:a -> a\<p y\> \@-}@ -- -- * At the __binder__ (inside 'RAllP'):--- @PV{pname="p", ptype=a, parg="LIQUID$dummy", pargs=[(a, "x", EVar "x")]}@+-- @PV{pname="p", ptype=a, pargs=[(a, "x", EVar "x")]}@ -- * At the __use site__ @a\<p y\>@ (inside 'ur_pred'):--- @PV{pname="p", ptype=a, parg="LIQUID$dummy", pargs=[(a, "x", EVar "y")]}@+-- @PV{pname="p", ptype=a, pargs=[(a, "x", EVar "y")]}@ -- -- * @pname@ is the name of the predicate variable, e.g. @p@ -- * @ptype@ is the type of the last (value) argument, i.e. the type being -- constrained, e.g. @a@--- * @parg@ is an internal dummy binder — always @"LIQUID$dummy"@. It is used--- by 'pToRef' as the value-position variable in the uninterpreted function--- call @papp_n(p, parg, e1, ..., en)@ when converting a standalone--- 'PredicateBV' to a 'F.Reft' via 'toReft'. In the main constraint--- generation path ('replacePredsWithRefs' / 'pVartoRConc'), the @ur_reft@--- binder is used instead. -- * @pargs@ is the list of non-value arguments (excluding the last one). -- Each triple is @(type, formal-binder, actual-expr)@. -- The __formal-binder__ always comes from the predicate declaration site@@ -317,7 +319,6 @@ data PVarBV b v t = PV { pname :: !b , ptype :: !t- , parg :: !b , pargs :: ![(t, b, F.ExprBV b v)] } deriving (Generic, Data, Show, Functor) deriving B.Binary via Generically (PVarBV b v t)@@ -344,12 +345,12 @@ pv == pv' = pname pv == pname pv' {- UNIFY: What about: && eqArgs pv pv' -} instance Ord b => Ord (PVarBV b v t) where- compare (PV n _ _ _) (PV n' _ _ _) = compare n n'+ compare (PV n _ _) (PV n' _ _) = compare n n' instance (NFData b, NFData v, NFData t) => NFData (PVarBV b v t) instance Hashable b => Hashable (PVarBV b v a) where- hashWithSalt i (PV n _ _ _) = hashWithSalt i n+ hashWithSalt i (PV n _ _) = hashWithSalt i n pvType :: PVarBV b v t -> t pvType = ptype@@ -358,7 +359,7 @@ pprintTidy _ = pprPvar pprPvar :: (Ord b, F.Fixpoint b, Hashable b, F.PPrint b, Ord v, F.Fixpoint v, F.PPrint v) => PVarBV b v a -> Doc-pprPvar (PV s _ _ xts) = F.pprint s <+> hsep (F.pprint . thd3 <$> xts)+pprPvar (PV s _ xts) = F.pprint s <+> hsep (F.pprint . thd3 <$> xts) -- | A map traversal that collects the local variables in scope emapExprVM :: (Monad m, Hashable b) => ([b] -> v -> m v') -> ExprBV b v -> m (ExprBV b v')@@ -399,7 +400,7 @@ type UsedPVar = UsedPVarV Symbol type UsedPVarV v = UsedPVarBV Symbol v-type UsedPVarBV b v = PVarBV b v ()+type UsedPVarBV b v = PVarBV b v (NoReftBV b v) type Predicate = PredicateV Symbol type PredicateV v = PredicateBV Symbol v@@ -408,11 +409,11 @@ deriving (B.Binary, Hashable) via Generically (PredicateBV b v) mapPredicateV :: (v -> v') -> PredicateV v -> PredicateV v'-mapPredicateV f (Pr xs) = Pr (map (mapPVarV f (const ())) xs)+mapPredicateV f (Pr xs) = Pr (map (mapPVarV f (const NoReft)) xs) -- | A map traversal that collects the local variables in scope emapPredicateVM :: Monad m => ([Symbol] -> v -> m v') -> PredicateV v -> m (PredicateV v')-emapPredicateVM f (Pr xs) = Pr <$> mapM (emapPVarVM f (\_ _ -> pure ())) xs+emapPredicateVM f (Pr xs) = Pr <$> mapM (emapPVarVM f (\_ _ -> pure NoReft)) xs instance (Ord b, Ord v) => Eq (PredicateBV b v) where (Pr vs) == (Pr ws)@@ -435,10 +436,10 @@ pprintTidy _ (Pr []) = text "True" pprintTidy k (Pr pvs) = hsep $ punctuate (text "&") (F.pprintTidy k <$> pvs) -instance (Semigroup a, Eq b) => Semigroup (UReftBV b v a) where+instance (Semigroup (F.ReftBV b v), Eq b) => Semigroup (UReftBV b v) where MkUReft x y <> MkUReft x' y' = MkUReft (x <> x') (y <> y') -instance (Monoid a) => Monoid (UReft a) where+instance Monoid UReft where mempty = MkUReft mempty mempty mappend = (<>) @@ -452,22 +453,18 @@ pvars :: PredicateBV b v -> [UsedPVarBV b v] pvars (Pr pvs) = pvs -instance Hashable v => F.Subable (UsedPVarBV v v) where+instance (Hashable v, F.Refreshable v) => F.Subable (UsedPVarBV v v) where type Variable (UsedPVarBV v v) = v- syms pv = [ y | (_, x, F.EVar y) <- pargs pv, x /= y ]- subst s pv = pv { pargs = mapThd3 (F.subst s) <$> pargs pv }- substf f pv = pv { pargs = mapThd3 (F.substf f) <$> pargs pv }- substa f pv = pv { pargs = mapThd3 (F.substa f) <$> pargs pv }+ syms pv = F.syms [ e | (_, _x, e) <- pargs pv ]+ substr ns s pv = pv { pargs = mapThd3 (F.substr ns s) <$> pargs pv } -instance Hashable v => F.Subable (PredicateBV v v) where+instance (Hashable v, F.Refreshable v) => F.Subable (PredicateBV v v) where type Variable (PredicateBV v v) = v- syms (Pr pvs) = concatMap F.syms pvs- subst s (Pr pvs) = Pr (F.subst s <$> pvs)- substf f (Pr pvs) = Pr (F.substf f <$> pvs)- substa f (Pr pvs) = Pr (F.substa f <$> pvs)+ syms (Pr pvs) = F.syms pvs+ substr ns s (Pr pvs) = Pr (F.substr ns s <$> pvs) -instance NFData r => NFData (UReft r)+instance NFData UReft newtype BTyVar = BTV F.LocSymbol deriving (Show, Generic, Data)@@ -704,7 +701,7 @@ LHRIndex i -> text $ "(Unknown LHRIndex " ++ show i ++ ")" LHRLogic _ -> text $ F.symbolString $ lhNameToResolvedSymbol $ F.val $ btc_tc b -instance F.PPrint v => F.PPrint (RTVar v s) where+instance F.PPrint v => F.PPrint (RTVar b v c v) where pprintTidy k (RTVar x _) = F.pprintTidy k x instance F.Loc BTyCon where@@ -744,22 +741,24 @@ type RTVU c tv = RTVUV Symbol c tv type RTVUV v c tv = RTVUBV Symbol v c tv-type RTVUBV b v c tv = RTVar tv (RTypeBV b v c tv (NoReftB b))+type RTVUBV b v c tv = RTVar b v c tv type PVU c tv = PVUV Symbol c tv type PVUV v c tv = PVarV v (RTypeV v c tv NoReft)-type PVUBV b v c tv = PVarBV b v (RTypeBV b v c tv (NoReftB b))+type PVUBV b v c tv = PVarBV b v (RTypeBV b v c tv (NoReftBV b v)) type RType c tv r = RTypeV Symbol c tv r type RTypeV v c tv = RTypeBV Symbol v c tv+ -- | A refinement type -- -- * @b@ is the type of bindings -- * @v@ is the type of variables appearing in expressions -- * @c@ is the type of type constructors -- * @tv@ is the type of type variables--- * @r@ is the type of refinements+-- * @r@ is the type of refinements. Must instance the 'IsReft' class. There are+-- only three instances of 'IsReft': 'ReftBV', 'NoReftBV', and 'UReftBV'. ----- A refinement might be missing (e.g. @r@ is @()@), if the RTypeBV is used to+-- A refinement might be missing (e.g. @r@ is @NoReft@), if the RTypeBV is used to -- represent the type of an entity that can't use refinements, e.g. the type of -- an abstract predicate. data RTypeBV b v c tv r@@ -948,16 +947,102 @@ -- or termination metric). It wraps an actual type @rt_ty@ with auxiliary -- information for constraint generation. --- -- Example (OCons): the type @{x:Int |- {v:Int | v > 0} \<: {v:Int | v > x}} => Int -> Int@+ -- For the invariant and termination obligations, the wrapping is done after+ -- parsing. In the case of termination, it is done in constraint generation+ -- and depends on the part of the code for which constraints are being+ -- generated. That is, different locations of the code have available different+ -- variations of the type representation.+ --+ -- === Example (OCons)+ --+ -- The type+ --+ -- > {x:Int |- {v:Int | v > 0} \<: {v:Int | v > x}} => Int -> Int+ -- -- is represented as:- -- @RRTy [("x", Int), (dummySymbol, {v:Int | v > 0}), (dummySymbol, {v:Int | v > x})]@- -- @trueReft OCons (Int -> Int)@ --+ -- > RRTy+ -- > [("x", Int), (dummySymbol, {v:Int | v > 0}), (dummySymbol, {v:Int | v > x})]+ -- > trueReft+ -- > OCons+ -- > (Int -> Int)+ --+ -- === Example (OInv)+ --+ -- Given+ --+ -- > {-@ invariant {v:Peano | toInt v >= 0} @-}+ -- > {-@ add :: Peano -> Peano -> Peano @-}+ --+ -- the invariant obligation generated for @add@ is represented as:+ --+ -- > RFun "lq1" -- first arg binder+ -- > defRFInfo+ -- > (RApp Peano [] [] trueReft) -- Peano (first arg type)+ -- > (RFun "lq2" -- second arg binder+ -- > defRFInfo+ -- > (RApp Peano [] [] trueReft) -- Peano (second arg type)+ -- > (RRTy -- ← invariant obligation wraps the RESULT+ -- > [("xInv", RApp Peano [] [] trueReft)] -- rt_env: bind scrutinee+ -- > (MkUReft -- rt_ref: NON-TRIVIAL+ -- > (Reft ("v", -- binder "v" is bound HERE in the Reft+ -- > PIff (EVar "v") -- v ⟺ (toInt xInv >= 0)[xInv/v]+ -- > (PAtom Ge (EApp "toInt" (EVar "xInv"))+ -- > (ECon (I 0)))))+ -- > (Pr []))+ -- > OInv -- rt_obl: invariant+ -- > (RApp Peano [] [] trueReft)) -- rt_ty: actual result type+ -- > trueReft)+ -- > trueReft+ --+ -- === Example (OTerm)+ --+ -- Given+ --+ -- > {-@ fib :: n:Nat -> Nat / [n] @-}+ -- > fib :: Int -> Int+ -- > fib 0 = 0+ -- > fib 1 = 1+ -- > fib n = fib (n - 1) + fib (n - 2)+ --+ -- The type represenation available when checking the recursive calls is:+ --+ -- > RFun "n" -- binder for the argument+ -- > defRFInfo+ -- > (RApp Int [] [] -- Nat = {v:Int | v >= 0}+ -- > (MkUReft (Reft ("v", PAtom Ge (EVar "v") (ECon (I 0)))) (Pr [])))+ -- > (RRTy -- ← termination obligation wraps RESULT+ -- > [] -- rt_env: empty+ -- > (MkUReft -- rt_ref: NON-TRIVIAL+ -- > (Reft ("vvRec", -- "vvRec" bound HERE in the Reft+ -- > PIff (EVar "vvRec") -- vvRec ⟺ (n' < n ∧ n' >= 0)+ -- > (PAnd [ PAtom Lt (EVar "n'") (EVar "n")+ -- > , PAtom Ge (EVar "n'") (ECon (I 0))+ -- > ])))+ -- > (Pr []))+ -- > OTerm -- rt_obl: termination+ -- > (RApp Int [] [] -- rt_ty: actual result type (Nat)+ -- > (MkUReft (Reft ("v", PAtom Ge (EVar "v") (ECon (I 0)))) (Pr []))))+ -- > trueReft+ --+ -- The binding @n'@ is instantiated at different places with the argument of+ -- the recursive call, e.g. @n - 1@ and @n - 2@.+ --+ -- === Fields+ -- -- * @rt_env@ is the typing environment and subtyping pair. For @OCons@, -- the last two entries are the LHS and RHS of the subtyping obligation;- -- preceding entries form the local typing environment.+ -- preceding entries form the local typing environment. For @OTerm@ the+ -- environment is empty, and for @OInv@ it contains a single binding.+ -- -- * @rt_ref@ is the refinement predicate (for @OInv@ and @OTerm@ this- -- carries the invariant or termination metric).+ -- carries the invariant or termination metric). For @OCon@s, this is always+ -- @trueReft@, akin to leaving the field unused. For @OInv@, the+ -- refinement is an encoding of the invariant predicate, and for @OTerm@+ -- it contains the termination constraint (the metric on the argument of+ -- the recursive call must be non-negative and smaller than the metric on+ -- the initial argument.+ -- -- * @rt_obl@ is the kind of obligation: -- - @OCons@: subtyping constraint, parsed from -- @{env |- t1 \<: t2} => TYPE@@@ -968,6 +1053,10 @@ -- In all cases, the obligation is discharged as a side-effect during -- constraint generation, and @rt_ty@ is the type used for further checking. --+ -- Unlike in other data constructors of @RTypeBV@, the bind of @rt_ref@+ -- does not scope over other fields. As can be seen in the example of @OInv@,+ -- @rt_env@ binds scope over @rt_ref@.+ -- | RRTy { rt_env :: ![(b, RTypeBV b v c tv r)] , rt_ref :: !r@@ -990,56 +1079,50 @@ deriving (Eq, Generic, Data, Functor, Foldable, Show, Traversable) deriving (B.Binary, Hashable) via Generically (RTypeBV b v c tv r) -instance (NFData c, NFData tv, NFData r) => NFData (RType c tv r)+instance (NFData b, NFData v, NFData c, NFData tv, NFData r) => NFData (RTypeBV b v c tv r) -makeRTVar :: tv -> RTVar tv s+makeRTVar :: tv -> RTVar b v c tv makeRTVar a = RTVar a (RTVNoInfo True) notExprArg :: RTypeV v c tv r -> Bool notExprArg (RExprArg _) = False notExprArg _ = True -instance (Eq tv) => Eq (RTVar tv s) where+instance (Eq tv) => Eq (RTVar b v c tv) where t1 == t2 = ty_var_value t1 == ty_var_value t2 -- | @RTVar@ is the type of type variables in the refinement type system. It -- contains a type variable, optionally a kind, and information about how to -- instantiate it (polymorphic vs. monomorphic refinements).-data RTVar tv s = RTVar+data RTVar b v c tv = RTVar { ty_var_value :: tv- , ty_var_info :: RTVInfo s- } deriving (Generic, Data, Functor, Foldable, Show, Traversable)- deriving (B.Binary, Hashable) via Generically (RTVar tv s)--mapTyVarValue :: (tv1 -> tv2) -> RTVar tv1 s -> RTVar tv2 s-mapTyVarValue f v = v {ty_var_value = f $ ty_var_value v}--dropTyVarInfo :: RTVar tv s1 -> RTVar tv s2-dropTyVarInfo v = v{ty_var_info = RTVNoInfo True }+ , ty_var_info :: RTVInfo b v c tv+ } deriving (Generic, Data, Show)+ deriving (B.Binary, Hashable) via Generically (RTVar b v c tv) -data RTVInfo s+data RTVInfo b v c tv = RTVNoInfo { rtv_is_pol :: Bool }- | RTVInfo { rtv_name :: Symbol- , rtv_kind :: s+ | RTVInfo { rtv_name :: b+ , rtv_kind :: RTypeBV b v c tv (NoReftBV b v) , rtv_is_val :: Bool , rtv_is_pol :: Bool -- true iff the type variable gets instantiated with -- any refinement (ie is polymorphic on refinements), -- false iff instantiation is with true refinement- } deriving (Generic, Data, Functor, Eq, Foldable, Show, Traversable)- deriving (B.Binary, Hashable) via Generically (RTVInfo s)+ } deriving (Generic, Data, Eq, Show)+ deriving (B.Binary, Hashable) via Generically (RTVInfo b v c tv) -setRtvPol :: RTVar tv a -> Bool -> RTVar tv a+setRtvPol :: RTVar b v c tv -> Bool -> RTVar b v c tv setRtvPol (RTVar a i) b = RTVar a (i{rtv_is_pol = b}) -rTVarToBind :: RTVar RTyVar s -> Maybe (Symbol, s)+rTVarToBind :: RTVar b v c tv -> Maybe (b, RTypeBV b v c tv (NoReftBV b v)) rTVarToBind = go . ty_var_info where go RTVInfo{..} | rtv_is_val = Just (rtv_name, rtv_kind) go _ = Nothing -instance (NFData tv, NFData s) => NFData (RTVar tv s)-instance (NFData s) => NFData (RTVInfo s)+instance (NFData b, NFData v, NFData c, NFData tv) => NFData (RTVar b v c tv)+instance (NFData b, NFData v, NFData c, NFData tv) => NFData (RTVInfo b v c tv) type Ref τ t = RefB Symbol τ t @@ -1058,7 +1141,7 @@ } deriving (Eq, Generic, Data, Functor, Foldable, Show, Traversable) deriving (B.Binary, Hashable) via Generically (RefB b τ t) -instance (NFData τ, NFData t) => NFData (Ref τ t)+instance (NFData b, NFData τ, NFData t) => NFData (RefB b τ t) rPropP :: [(b, τ)] -> r -> RefB b τ (RTypeV v c tv r) rPropP τ r = RProp τ (RHole r)@@ -1067,10 +1150,10 @@ -- In general, perhaps we need not expose @Ref@ directly at all. type RTProp c tv r = RTPropV Symbol c tv r type RTPropV v c tv r = RTPropBV Symbol v c tv r-type RTPropBV b v c tv r = RefB b (RTypeBV b v c tv (NoReftB b)) (RTypeBV b v c tv r)+type RTPropBV b v c tv r = RefB b (RTypeBV b v c tv (NoReftBV b v)) (RTypeBV b v c tv r) -type UReft r = UReftV F.Symbol r-type UReftV v r = UReftBV F.Symbol v r+type UReft = UReftV F.Symbol+type UReftV v = UReftBV F.Symbol v -- | A combined refinement carrying both a first-order predicate and a -- conjunction of abstract-refinement (predicate-variable) applications.@@ -1087,7 +1170,6 @@ -- { ur_reft = F.Reft ("VV", PTrue) -- no first-order constraint -- , ur_pred = Pr [ PV { pname = "p" -- , ptype = intSort--- , parg = "LIQUID$dummy" -- , pargs = [(intSort, "x", EVar "m")] } ] -- } -- @@@ -1102,69 +1184,69 @@ -- * @ur_pred@ is the abstract-refinement part: a 'PredicateBV' (= @Pr [UsedPVarBV]@), -- i.e. a conjunction of predicate-variable applications. -- Each 'UsedPVarBV' records which predicate variable is used (via @pname@),--- the internal dummy binder (@parg = "LIQUID$dummy"@), and the actual--- argument expressions (@pargs@) at this use site (see 'PVarBV').+-- and the actual argument expressions (@pargs@) at this use site (see 'PVarBV'). -- -- During constraint generation, @ur_pred@ is eliminated by -- 'replacePredsWithRefs': each predicate-variable application is converted -- to an uninterpreted function call @papp_n(p, VV, e1, ..., en)@ via--- 'pVartoRConc' (using the @ur_reft@ binder @VV@, __not__ @parg@) and+-- 'pVartoRConc' (using the @ur_reft@ binder @VV@) and -- conjoined into @ur_reft@, producing a pure 'F.Reft' understood by the SMT -- solver. After this step, @ur_pred@ becomes @Pr []@. -- -- 'toReft' on a 'UReftBV' discards @ur_pred@ entirely and returns only -- @ur_reft@; it must therefore be called only after predicate-replacement. ---data UReftBV b v r = MkUReft- { ur_reft :: !r+data UReftBV b v = MkUReft+ { ur_reft :: !(F.ReftBV b v) , ur_pred :: !(PredicateBV b v) }- deriving (Eq, Generic, Data, Functor, Foldable, Show, Traversable)- deriving (B.Binary, Hashable) via Generically (UReftBV b v r)+ deriving (Eq, Generic, Data)+ deriving (B.Binary, Hashable) via Generically (UReftBV b v) -mapUReftV :: (v -> v') -> (r -> r') -> UReftV v r -> UReftV v' r'+deriving instance (Show (F.ReftBV b v), Show (PredicateBV b v)) => Show (UReftBV b v)++mapUReftV :: (v -> v') -> (F.ReftV v -> F.ReftV v') -> UReftV v -> UReftV v' mapUReftV f g (MkUReft r p) = MkUReft (g r) (mapPredicateV f p) emapUReftVM :: Monad m- => ([Symbol] -> v -> m v') -> (r -> m r') -> UReftV v r -> m (UReftV v' r')+ => ([Symbol] -> v -> m v') -> (F.ReftV v -> m (F.ReftV v')) -> UReftV v -> m (UReftV v') emapUReftVM f g (MkUReft r p) = MkUReft <$> g r <*> emapPredicateVM f p +type role NoReftBV phantom phantom type NoReft = NoReftB Symbol-data NoReftB b = NoReft+type NoReftB b = NoReftBV b Symbol+data NoReftBV b v = NoReft deriving (Eq, Generic, Data, Functor, Foldable, Show, Traversable)- deriving (B.Binary, Hashable) via Generically (NoReftB b)+ deriving (B.Binary, Hashable) via Generically (NoReftBV b v) -instance NFData (NoReftB b)+instance NFData (NoReftBV b v) -instance F.PPrint (NoReftB b) where+instance F.PPrint (NoReftBV b v) where pprintTidy _ _ = text $ show () -instance Hashable b => F.Subable (NoReftB b) where- type Variable (NoReftB b) = b- syms _ = []- substa _ = id- substf _ = id- subst _ = id- subst1 r = const r+instance Hashable b => F.Subable (NoReftBV b v) where+ type Variable (NoReftBV b v) = b+ syms _ = S.empty+ substr _ _ = id -instance Semigroup (NoReftB b) where+instance Semigroup (NoReftBV b v) where _ <> _ = NoReft -instance Monoid (NoReftB b) where+instance Monoid (NoReftBV b v) where mempty = NoReft type BRType = RTypeV Symbol BTyCon BTyVar -- ^ "Bare" parsed version type BRTypeV v = RTypeV v BTyCon BTyVar -- ^ "Bare" parsed version type RRType = RTypeV Symbol RTyCon RTyVar -- ^ "Resolved" version type BSort = BRType NoReft-type BSortV v = BRTypeV v NoReft+type BSortV v = BRTypeV v (NoReftBV Symbol v) type RSort = RRType NoReft type BPVar = PVar BSort type RPVar = PVar RSort type RReft = RReftV F.Symbol type RReftV v = RReftBV Symbol v-type RReftBV b v = UReftBV b v (F.ReftBV b v)+type RReftBV b v = UReftBV b v type BareType = BareTypeV F.Symbol type BareTypeParsed = BareTypeV F.LocSymbol type BareTypeLHName = BareTypeV LHName@@ -1174,7 +1256,7 @@ type RRProp r = Ref RSort (RRType r) type BRProp r = BRPropV Symbol r type BRPropV v r = Ref (BSortV v) (BRTypeV v r)-type SpecRTVar = RTVar RTyVar RSort+type SpecRTVar = RTVar Symbol Symbol RTyCon RTyVar @@ -1219,7 +1301,7 @@ ( TyConable c , F.PPrint tv, F.PPrint c, F.PPrint r, F.PPrint (ReftVar r) , F.Fixpoint (ReftVar r)- , ToReft r+ , IsReft r , ReftBind r ~ F.Symbol , Eq c, Eq tv, Ord (ReftVar r) , Hashable tv@@ -1230,21 +1312,13 @@ , F.PPrint b, F.PPrint v, F.PPrint tv, F.PPrint c, F.PPrint r, F.PPrint (ReftVar r) , F.Fixpoint b, F.Fixpoint v, F.Fixpoint (ReftVar r) , F.Binder b- , ToReft r+ , IsReft r , ReftBind r ~ b+ , v ~ F.Symbol , Eq c, Eq tv, Ord b, Ord v, Ord (ReftVar r) , Hashable tv ) --- | Types that have one associated refinement representible by a 'F.ReftBV'-class (F.Binder (ReftBind r), Eq (ReftVar r)) => ToReft r where- type ReftVar r- type ReftBind r- type ReftBind r = Symbol- toReft :: r -> F.ReftBV (ReftBind r) (ReftVar r)- toUReft :: r -> UReftBV (ReftBind r) (ReftVar r) (F.ReftBV (ReftBind r) (ReftVar r))- toUReft r = MkUReft (toReft r) pdTrue- -- | Types that can be combined conjunctively in some sense class Semigroup r => Meet r where meet :: r -> r -> r@@ -1254,127 +1328,123 @@ class Top r where top :: r -> r --- | Types that can be constructed from a 'F.ReftBV'-class (ToReft r, Meet r, Top r) => IsReft r where- ofReft :: F.ReftBV (ReftBind r) (ReftVar r) -> r--trueReft :: IsReft r => r-trueReft = ofReft F.trueReft--isTauto :: ToReft r => r -> Bool-isTauto r0 = F.isTautoReft r && null ps- where- MkUReft r (Pr ps) = toUReft r0+-- | The universe of refinement types that can be used in RTypes.+data ConcreteReft r b v where+ ConcreteNoReft :: ConcreteReft (NoReftBV b v) b v+ ConcreteReft :: F.ReftBV b v -> ConcreteReft (F.ReftBV b v) b v+ ConcreteUReft :: UReftBV b v -> ConcreteReft (UReftBV b v) b v -instance (ToReft r, ReftBind r ~ b, ReftVar r ~ v) => ToReft (UReftBV b v r) where- type ReftVar (UReftBV b v r) = ReftVar r- type ReftBind (UReftBV b v r) = ReftBind r- toReft = toReft . ur_reft- toUReft (MkUReft r p) = MkUReft (toReft r) p+-- | Types that can be constructed from a 'F.ReftBV'.+--+-- Only three types can be 'IsReft': 'NoReftBV', 'F.ReftBV', and 'UReftBV'.+--+-- 'ofConcreteReft' and 'toConcreteReft' must be inverses of each other.+--+-- In order to allow distinguishing the @r@ type when no value is present+-- (e.g. in @ofReft@ or @trueReft@), 'toConcreteReft' must be non-strict.+--+class (F.Binder (ReftBind r), Top r) => IsReft r where+ type ReftVar r+ type ReftBind r+ ofConcreteReft :: ConcreteReft r (ReftBind r) (ReftVar r) -> r+ toConcreteReft :: r -> ConcreteReft r (ReftBind r) (ReftVar r) -instance Top r => Top (UReftBV b v r) where- top (MkUReft r _) = MkUReft (top r) pdTrue+ofReft :: forall r. IsReft r => F.ReftBV (ReftBind r) (ReftVar r) -> r+ofReft r = case toConcreteReft @r (error "ofReft") of+ ConcreteNoReft -> NoReft+ ConcreteReft _ -> r+ ConcreteUReft _ -> MkUReft r pdTrue -instance (IsReft r, F.Binder v, ReftBind r ~ v, ReftVar r ~ v) => IsReft (UReftBV v v r) where- ofReft r = MkUReft (ofReft r) pdTrue+toReft :: IsReft r => r -> F.ReftBV (ReftBind r) (ReftVar r)+toReft r0 = case toConcreteReft r0 of+ ConcreteNoReft -> F.trueReft+ ConcreteReft r -> r+ ConcreteUReft (MkUReft r _) -> r -instance (F.Binder b, Eq v) => ToReft (F.ReftBV b v) where- type ReftVar (F.ReftBV b v) = v- type ReftBind (F.ReftBV b v) = b- toReft = id+toUReft :: IsReft r => r -> UReftBV (ReftBind r) (ReftVar r)+toUReft r0 = case toConcreteReft r0 of+ ConcreteNoReft -> MkUReft F.trueReft pdTrue+ ConcreteReft r -> MkUReft r pdTrue+ ConcreteUReft r -> r -instance (F.Binder b) => Top (F.ReftBV b v) where+instance Top (NoReftBV b v) where+ top _ = NoReft+instance F.Binder b => Top (F.ReftBV b v) where top _ = F.trueReft--instance (F.Binder v, F.Fixpoint v) => Meet (F.ReftBV v v) where--instance (F.Binder v, F.Fixpoint v, Eq v) => IsReft (F.ReftBV v v) where- ofReft = id+instance F.Binder b => Top (UReftBV b v) where+ top _ = MkUReft F.trueReft pdTrue -instance ToReft () where- type ReftVar () = Symbol- toReft _ = F.trueReft+-- | A refinement type that accepts all elements of its base type.+--+-- This is a generalization of 'F.trueReft' for the other types that instantiate+-- 'IsReft'.+trueReft :: forall r. IsReft r => r+trueReft = case toConcreteReft @r (error "trueReft") of+ ConcreteNoReft -> top (error "trueReft: ConcreteNoReft")+ ConcreteReft _ -> top (error "trueReft: ConcreteReft")+ ConcreteUReft _ -> top (error "trueReft: ConcreteUReft") -instance Top () where- top _ = ()+isTauto :: (IsReft r, Eq (ReftVar r)) => r -> Bool+isTauto r0 = case toConcreteReft r0 of+ ConcreteNoReft -> True+ ConcreteReft r -> F.isTautoReft r+ ConcreteUReft (MkUReft r (Pr ps)) -> F.isTautoReft r && null ps -instance IsReft () where- ofReft _ = ()+mapReftField :: IsReft r => (F.ReftBV (ReftBind r) (ReftVar r) -> F.ReftBV (ReftBind r) (ReftVar r)) -> r -> r+mapReftField f r0 = case toConcreteReft r0 of+ ConcreteNoReft -> ofConcreteReft ConcreteNoReft+ ConcreteReft r -> ofConcreteReft (ConcreteReft (f r))+ ConcreteUReft (MkUReft r p) -> ofConcreteReft (ConcreteUReft (MkUReft (f r) p)) -instance F.Binder b => ToReft (NoReftB b) where- type ReftVar (NoReftB b) = Symbol- type ReftBind (NoReftB b) = b- toReft _ = F.trueReft+instance F.Binder b => IsReft (UReftBV b v) where+ type ReftVar (UReftBV b v) = v+ type ReftBind (UReftBV b v) = b+ ofConcreteReft (ConcreteUReft r) = r+ toConcreteReft = ConcreteUReft -instance Top (NoReftB b) where- top _ = NoReft+instance (F.Binder v, F.Fixpoint v, F.Refreshable v) => Meet (F.ReftBV v v) where -instance F.Binder b => IsReft (NoReftB b) where- ofReft _ = NoReft+instance F.Binder b => IsReft (F.ReftBV b v) where+ type ReftVar (F.ReftBV b v) = v+ type ReftBind (F.ReftBV b v) = b+ toConcreteReft = ConcreteReft+ ofConcreteReft (ConcreteReft r) = r -instance ToReft t => ToReft (RefB b τ t) where- type ReftVar (RefB b τ t) = ReftVar t- type ReftBind (RefB b τ t) = ReftBind t- toReft (RProp _ t) = toReft t+instance F.Binder b => IsReft (NoReftBV b v) where+ type ReftVar (NoReftBV b v) = v+ type ReftBind (NoReftBV b v) = b+ toConcreteReft _ = ConcreteNoReft+ ofConcreteReft ConcreteNoReft = NoReft instance Top t => Top (RefB b τ t) where top (RProp args t) = RProp args (top t) -instance (F.Binder b, Ord v, PredicateCompat b v) => ToReft (PredicateBV b v) where- type ReftVar (PredicateBV b v) = v- type ReftBind (PredicateBV b v) = b- toReft (Pr []) = F.trueReft- toReft (Pr ps@(p:_)) = F.Reft (parg p, F.pAnd $ pToRef <$> ps)- toUReft p = MkUReft F.trueReft p- instance Top (PredicateBV b v) where top _ = pdTrue -instance (F.Binder v, F.Fixpoint v) => Semigroup (F.ReftBV v v) where+instance (F.Binder v, F.Fixpoint v, F.Refreshable v) => Semigroup (F.ReftBV v v) where (<>) = F.meetReft instance Monoid F.Reft where mempty = F.trueReft mappend = (<>) -instance Meet ()--instance Meet (NoReftB b)--instance (Meet r, Eq v) => Meet (UReftBV v v r)+instance Meet (NoReftBV b v) -instance (F.Subable r, F.Variable r ~ v) => F.Subable (UReftBV v v r) where- type Variable (UReftBV v v r) = v- syms (MkUReft r p) = F.syms r ++ F.syms p- subst s (MkUReft r z) = MkUReft (F.subst s r) (F.subst s z)- substf f (MkUReft r z) = MkUReft (F.substf f r) (F.substf f z)- substa f (MkUReft r z) = MkUReft (F.substa f r) (F.substa f z)+instance (Semigroup (F.ReftBV b v), Eq b, Eq v) => Meet (UReftBV b v) -instance F.Expression (UReft ()) where- expr = F.expr . toReft+instance (F.Refreshable v, Hashable v) => F.Subable (UReftBV v v) where+ type Variable (UReftBV v v) = v+ syms (MkUReft r p) = F.syms r `S.union` F.syms p+ substr ns s (MkUReft r z) = MkUReft (F.substr ns s r) (F.substr ns s z) instance Meet Predicate -pToRef :: PredicateCompat b v => PVarBV b v a -> F.ExprBV b v-pToRef p = pApp (pnameV p) $ F.EVar (pargV p) : (thd3 <$> pargs p)--pApp :: forall b v . PredicateCompat b v => v -> [ExprBV b v] -> ExprBV b v+pApp :: Symbol -> [Expr] -> Expr pApp p es = F.mkEApp fn (F.EVar p:es) where- fn = F.dummyLoc (pappV (Proxy :: Proxy b) n)+ fn = F.dummyLoc $ F.symbol (pappV n) n = length es -class PredicateCompat b v where- pappV :: Proxy b -> Int -> v- pnameV :: PVarBV b v a -> v- pargV :: PVarBV b v a -> v--instance PredicateCompat Symbol Symbol where- pappV _ n = F.symbol $ "papp" ++ show n- pnameV p = pname p- pargV p = parg p--instance PredicateCompat Symbol F.LocSymbol where- pappV _ n = F.dummyLoc $ F.symbol $ "papp" ++ show n- pnameV p = F.dummyLoc $ pname p- pargV p = F.dummyLoc $ parg p+pappV :: Int -> Symbol+pappV n = F.symbol $ "papp" ++ show n
src/Language/Haskell/Liquid/Types/RTypeOp.hs view
@@ -38,6 +38,7 @@ , mapRTypeVM , mapDataDeclV , mapDataDeclVM+ , mapRBase , emapDataDeclM , emapDataCtorTyM , emapBareTypeVM@@ -71,7 +72,10 @@ import Control.Monad (liftM2, liftM3, liftM4) import Data.Bifunctor (bimap)+import Data.Coerce (coerce) import Data.Hashable (Hashable)+import qualified Data.HashSet as S+import qualified Data.List as List import qualified Language.Fixpoint.Types as F import Language.Fixpoint.Types (ExprBV, Symbol)@@ -102,8 +106,8 @@ type RTypeRep = RTypeRepV Symbol type RTypeRepV = RTypeRepBV Symbol data RTypeRepBV b v c tv r = RTypeRep- { ty_vars :: [(RTVar tv (RTypeBV b v c tv (NoReftB b)), r)]- , ty_preds :: [PVarBV b v (RTypeBV b v c tv (NoReftB b))]+ { ty_vars :: [(RTVar b v c tv, r)]+ , ty_preds :: [PVarBV b v (RTypeBV b v c tv (NoReftBV b v))] , ty_binds :: [b] , ty_info :: [RFInfo] , ty_refts :: [r]@@ -130,8 +134,8 @@ (αs, πs, t') = bkUniv t ((xs, is, ts, rs), t'') = bkArrow t' -mkArrow :: [(RTVar tv (RTypeBV b v c tv (NoReftB b)), r)]- -> [PVarBV b v (RTypeBV b v c tv (NoReftB b))]+mkArrow :: [(RTVar b v c tv, r)]+ -> [PVarBV b v (RTypeBV b v c tv (NoReftBV b v))] -> [(b, RFInfo, RTypeBV b v c tv r, r)] -> RTypeBV b v c tv r -> RTypeBV b v c tv r@@ -166,8 +170,8 @@ safeBkArrow t = bkArrow t mkUnivs :: (Foldable t, Foldable t1)- => t (RTVar tv (RTypeBV b v c tv (NoReftB b)), r)- -> t1 (PVarBV b v (RTypeBV b v c tv (NoReftB b)))+ => t (RTVar b v c tv, r)+ -> t1 (PVarBV b v (RTypeBV b v c tv (NoReftBV b v))) -> RTypeBV b v c tv r -> RTypeBV b v c tv r mkUnivs αs πs rt = foldr (\(a,r) t -> RAllT a t r) (foldr RAllP rt πs) αs@@ -179,7 +183,7 @@ (cs, t2) = bkClass t1 -bkUniv :: RTypeBV b v tv c r -> ([(RTVar c (RTypeBV b v tv c (NoReftB b)), r)], [PVarBV b v (RTypeBV b v tv c (NoReftB b))], RTypeBV b v tv c r)+bkUniv :: RTypeBV b v c tv r -> ([(RTVar b v c tv, r)], [PVarBV b v (RTypeBV b v c tv (NoReftBV b v))], RTypeBV b v c tv r) bkUniv (RAllT α t r) = let (αs, πs, t') = bkUniv t in ((α, r):αs, πs, t') bkUniv (RAllP π t) = let (αs, πs, t') = bkUniv t in (αs, π:πs, t') bkUniv t = ([], [], t)@@ -245,63 +249,223 @@ F.Reft(v, rv) = ur_reft r' -instance (IsReft r, F.Subable r, TyConable c, F.Binder v, F.Variable r ~ v, ReftBind r ~ v) => F.Subable (RTPropBV v v c tv r) where- type Variable (RTPropBV v v c tv r) = v- syms (RProp ss r) = (fst <$> ss) ++ F.syms r-- subst su (RProp ss (RHole r)) = RProp ss (RHole (F.subst su r))- subst su (RProp ss t) = RProp ss (F.subst su <$> t)-- substf f (RProp ss (RHole r)) = RProp ss (RHole (F.substf f r))- substf f (RProp ss t) = RProp ss (F.substf f <$> t)+instance ( IsReft r+ , F.Subable r+ , F.Subable t+ , TyConable c+ , F.Binder v+ , F.Refreshable v+ , F.Variable r ~ v+ , F.Variable t ~ v+ , ReftBind r ~ v+ , ReftVar r ~ v+ ) =>+ F.Subable (RefB v (RTypeBV v v c tv r) t) where+ type Variable (RefB v (RTypeBV v v c tv r) t) = v+ syms (RProp ss r) =+ let (bs, tss) =+ List.mapAccumL+ (\bs0 (b, tb) -> (S.insert b bs0, F.syms tb `S.difference` bs0))+ S.empty+ ss+ in+ S.unions $ (F.syms r `S.difference` bs) : tss - substa f (RProp ss (RHole r)) = RProp ss (RHole (F.substa f r))- substa f (RProp ss t) = RProp ss (F.substa f <$> t)+ substr ns0 su0 (RProp ss0 t0) =+ let ((bs', ns', su'), ts) = substInArgs ss0 ns0 su0+ ss' = zip bs' ts+ in RProp ss' (F.substr ns' su' t0)+ where+ substInArgs ss1 ns1 su1 =+ List.mapAccumR+ (\(bs, ns, su) (x, t) ->+ let (ns', x') = F.freshInNS x ns+ su' = F.extendSubstWithVar su x x'+ in+ ( (x' : bs, ns', su')+ , F.substr ns su t+ )+ )+ ([], ns1, su1)+ ss1 -instance (F.Subable r, IsReft r, TyConable c, F.Binder v, F.Variable r ~ v, ReftBind r ~ v) => F.Subable (RTypeBV v v c tv r) where+instance ( F.Subable r+ , IsReft r+ , TyConable c+ , F.Binder v+ , F.Refreshable v+ , F.Variable r ~ v+ , ReftBind r ~ v+ , ReftVar r ~ v+ ) => F.Subable (RTypeBV v v c tv r) where type Variable (RTypeBV v v c tv r) = v- syms = foldReft False (\_ r acc -> F.syms r ++ acc) []- -- 'substa' will substitute bound vars- substa f = emapExprArg (\_ -> F.substa f) [] . mapReft (F.substa f)- -- 'substf' will NOT substitute bound vars- substf f = emapExprArg (\_ -> F.substf f) [] . emapReft (F.substf . F.substfExcept f) []- subst su = emapExprArg (\_ -> F.subst su) [] . emapReft (F.subst . F.substExcept su) []- subst1 t su = emapExprArg (\_ e -> F.subst1 e su) [] $ emapReft (\xs r -> F.subst1Except xs r su) [] t+ syms = go+ where+ deletev r0 = case toConcreteReft r0 of+ ConcreteNoReft -> id+ ConcreteReft r -> S.delete (F.reftBind r)+ ConcreteUReft (MkUReft r _) -> S.delete (F.reftBind r) + go :: RTypeBV v v c tv r -> S.HashSet v+ go (RVar _ r) = F.syms r+ go (RFun x _ t1 t2 r) =+ -- x scopes over t1, t2, and r+ deletev r (S.delete x $ F.syms t1 `S.union` F.syms t2)+ `S.union` F.syms r+ go (RAllT α t r) =+ let kindSyms = maybe S.empty (F.syms . snd) (rTVarToBind α)+ deleteα = maybe id (S.delete . fst) (rTVarToBind α)+ in+ deletev r (kindSyms `S.union` deleteα (F.syms t))+ `S.union` F.syms r+ go (RAllP pb t) =+ S.delete (pname pb) (F.syms t) `S.union` symsPVar pb+ where+ symsPVar p =+ let (bs, tss) =+ List.mapAccumL+ (\bs0 (tb, b, _) -> (S.insert b bs0, F.syms tb `S.difference` bs0))+ S.empty+ (pargs p)+ in+ S.unions $ (F.syms (ptype p) `S.difference` bs) : tss ------------------------------------------------------------------------------------ | Visitors ----------------------------------------------------------------------------------------------------------------------------------------------------mapExprReft :: (b -> ExprBV b v -> ExprBV b v) -> RTypeBV b v c tv (RReftBV b v) -> RTypeBV b v c tv (RReftBV b v)-mapExprReft f = mapReft g- where- g (MkUReft (F.Reft (x, e)) p) = MkUReft (F.Reft (x, f x e)) p+ go (RApp _ ts ps r) =+ deletev r (F.syms ts `S.union` F.syms ps)+ `S.union` F.syms r+ go (REx x t1 t2) =+ -- x scopes over t2 only+ F.syms t1 `S.union` S.delete x (F.syms t2)+ go (RExprArg e) = F.syms e+ go (RAppTy t1 t2 r) =+ deletev r (F.syms t1 `S.union` F.syms t2)+ `S.union` F.syms r+ go (RRTy env r _ t) =+ -- env scopes over the refinement type+ let (bs, envSyms) = symsEnv env+ rsyms = F.syms r `S.difference` bs+ in+ envSyms `S.union` rsyms `S.union` F.syms t+ where+ symsEnv = foldl'+ (\(s, env') (x, xt) ->+ let s' = S.insert x s+ in (s', (F.syms xt `S.difference` s) `S.union` env')+ )+ (S.empty, S.empty) -data OrReftBV r = LeftReftBV (F.ReftBV (ReftBind r) (ReftVar r)) | RightR r+ go (RHole r) = F.syms r -instance ToReft r => ToReft (OrReftBV r) where- type ReftBind (OrReftBV r) = ReftBind r- type ReftVar (OrReftBV r) = ReftVar r- toReft (LeftReftBV r) = r- toReft (RightR r) = toReft r- toUReft (LeftReftBV r) = MkUReft r (Pr [])- toUReft (RightR r) = toUReft r+ substr = go+ where+ -- Given a reft 'r' and the nameset 's' that will be passed to+ -- 'F.substr' for 'r', compute the fresh reft-binder 'v0'' and return+ -- the updated nameset and substitution for sub-fields that have 'v0'+ -- in scope (i.e. all fields of the same constructor other than 'r').+ substReft :: r -> S.HashSet v -> F.SubstV v -> (S.HashSet v, F.SubstV v, r)+ substReft r s su =+ case toConcreteReft r of+ ConcreteNoReft -> (s, su, r)+ ConcreteReft (F.Reft (v0, e)) ->+ let (s', v0') = F.freshInNS v0 s+ su' = F.extendSubstWithVar su v0 v0'+ in (s', su', F.Reft (v0', F.substr s' su' e))+ ConcreteUReft (MkUReft (F.Reft (v0, e)) ps) ->+ let (s', v0') = F.freshInNS v0 s+ su' = F.extendSubstWithVar su v0 v0'+ e' = F.substr s' su' e+ ps' = F.substr s su ps+ ur' = MkUReft (F.Reft (v0', e')) ps'+ in (s', su', ur') -instance ToReft r => Semigroup (OrReftBV r) where- _ <> _ = Prelude.error "Meet OrReftBV"+ go :: S.HashSet v -> F.SubstV v -> RTypeBV v v c tv r -> RTypeBV v v c tv r+ go s su (RFun x i t1 t2 r) =+ -- x scopes over t1 and t2; v0 (reft binder of r) scopes over t1 and t2.+ let (s_x, x') = F.freshInNS x s+ su_x = F.extendSubstWithVar su x x'+ (s_xv, su_xv, r') = substReft r s_x su_x -- nameset/subst for t1, t2+ in RFun x' i (go s_xv su_xv t1) (go s_xv su_xv t2) r'+ go s su (REx x t1 t2) =+ -- x scopes over t2 only; no reft field.+ let (s', x') = F.freshInNS x s+ su' = F.extendSubstWithVar su x x'+ in REx x' (go s su t1) (go s' su' t2)+ go s su (RAllT α t r) =+ -- v0 (reft binder of r) scopes over the kind inside α and over t.+ let (s', su', r') = substReft r s su+ (s'', su'', α') = αScope s' su' α+ in RAllT α' (go s'' su'' t) r'+ where+ αScope s0 su0 rtv@(RTVar _tv (RTVNoInfo _)) = (s0, su0, rtv)+ αScope s0 su0 (RTVar tv (RTVInfo b k v pol)) =+ let (s1, b') = F.freshInNS b s0+ su1 = F.extendSubstWithVar su0 b b'+ k' = F.substr s0 su0 k+ in (s1, su1, RTVar tv (RTVInfo b' k' v pol)) -instance ToReft r => Meet (OrReftBV r) where+ go s su (RAllP π t) =+ let (ns_p, pname') = F.freshInNS (pname π) s+ su_p = F.extendSubstWithVar su (pname π) pname'+ π' = (substPVar s su π) { pname = pname' }+ in+ RAllP π' (go ns_p su_p t)+ where+ substPVar s0 su0 π0 =+ let ((ns_pargs, su_pargs), pargs') =+ List.mapAccumR+ (\(ns', su') (tb, b, e) ->+ let (ns'', b') = F.freshInNS b ns'+ su'' = F.extendSubstWithVar su' b b'+ -- b must be in scope for substituting into e (which is typically EVar b)+ nsE = S.insert b ns'+ e' = F.substr nsE su' e+ in ((ns'', su''), (F.substr ns' su' tb, b', e'))+ )+ (s0, su0)+ (pargs π)+ in+ PV { pname = pname π0+ , ptype = F.substr ns_pargs su_pargs (ptype π0)+ , pargs = pargs'+ } -instance F.Binder (ReftBind r) => Top (OrReftBV r) where- top _ = LeftReftBV F.trueReft+ go s su (RVar α r) = RVar α (F.substr s su r)+ go s su (RApp c ts ps r) =+ -- v0 (reft binder of r) scopes over ts and ps.+ let (s', su', r') = substReft r s su+ in RApp c (go s' su' <$> ts) (F.substr s' su' ps) r'+ go s su (RAppTy t1 t2 r) =+ -- v0 (reft binder of r) scopes over t1 and t2.+ let (s', su', r') = substReft r s su+ in RAppTy (go s' su' t1) (go s' su' t2) r'+ go s su (RExprArg e) = RExprArg (F.substr s su <$> e)+ go s su (RRTy env r o t) =+ let ((s', su'), env') = substEnv s su env+ in+ RRTy env' (F.substr s' su' r) o (go s su t)+ where+ substEnv s0 su0 env0 =+ List.mapAccumL+ (\(s', su') (x, xt) ->+ let (s'', x') = F.freshInNS x s'+ su'' = F.extendSubstWithVar su' x x'+ xt' = F.substr s' su' xt+ in ((s'', su''), (x', xt'))+ )+ (s0, su0)+ env0 -instance ToReft r => IsReft (OrReftBV r) where- ofReft r = LeftReftBV r+ go s su (RHole r) = RHole (F.substr s su r) -isTrivial :: (ToReft r, TyConable c, F.Binder b, ReftBind r ~ b) => RTypeBV b v c tv r -> Bool-isTrivial = foldReft False (\_ r b -> isTauto r && b) True . fmap RightR+mapExprReft :: (b -> ExprBV b v -> ExprBV b v) -> RTypeBV b v c tv (RReftBV b v) -> RTypeBV b v c tv (RReftBV b v)+mapExprReft f = mapReft g+ where+ g (MkUReft (F.Reft (x, e)) p) = MkUReft (F.Reft (x, f x e)) p +isTrivial :: (IsReft r, IsReft r, TyConable c, F.Binder b, ReftBind r ~ b, Eq (ReftVar r)) => RTypeBV b v c tv r -> Bool+isTrivial = foldReft False (\_ r b -> isTauto r && b) True+ mapReft :: (r1 -> r2) -> RTypeBV b v c tv r1 -> RTypeBV b v c tv r2 mapReft f = emapReft (const f) [] @@ -325,12 +489,16 @@ emapRef f γ (RProp s (RHole r)) = RProp s $ RHole (f γ r) emapRef f γ (RProp s t) = RProp s $ emapReft f γ t +mapRTVarV :: (v -> v') -> RTVar b v c tv -> RTVar b v' c tv+mapRTVarV _ (RTVar tv (RTVNoInfo p)) = RTVar tv (RTVNoInfo p)+mapRTVarV f (RTVar tv ri@RTVInfo{rtv_kind=k}) = RTVar tv ri{rtv_kind = coerce (mapRTypeV f k)}+ mapRTypeV :: (v -> v') -> RTypeBV b v c tv r -> RTypeBV b v' c tv r mapRTypeV _ (RVar α r) = RVar α r-mapRTypeV f (RAllT α t r) = RAllT (fmap (mapRTypeV f) α) (mapRTypeV f t) r-mapRTypeV f (RAllP π t) = RAllP (mapPVarV f (mapRTypeV f) π) (mapRTypeV f t)+mapRTypeV f (RAllT α t r) = RAllT (mapRTVarV f (coerce α)) (mapRTypeV f t) r+mapRTypeV f (RAllP π t) = RAllP (mapPVarV f (mapRTypeV f) $ coerce π) (mapRTypeV f t) mapRTypeV f (RFun x i t t' r) = RFun x i (mapRTypeV f t) (mapRTypeV f t') r-mapRTypeV f (RApp c ts rs r) = RApp c (mapRTypeV f <$> ts) (mapRefV <$> rs) r+mapRTypeV f (RApp c ts rs r) = RApp c (mapRTypeV f <$> ts) (mapRefV <$> coerce rs) r where mapRefV (RProp ss t) = RProp (map (fmap (mapRTypeV f)) ss) (mapRTypeV f t) mapRTypeV f (REx z t t') = REx z (mapRTypeV f t) (mapRTypeV f t')@@ -339,12 +507,18 @@ mapRTypeV f (RRTy e r o t) = RRTy (fmap (mapRTypeV f) <$> e) r o (mapRTypeV f t) mapRTypeV _ (RHole r) = RHole r +mapRTVarVM :: (Hashable b, Monad m) => (v -> m v') -> RTVar b v c tv -> m (RTVar b v' c tv)+mapRTVarVM _ (RTVar tv (RTVNoInfo p)) = pure $ RTVar tv (RTVNoInfo p)+mapRTVarVM f (RTVar tv ri@RTVInfo{rtv_kind=k}) = do+ k' <- mapRTypeVM f k+ pure $ RTVar tv ri{rtv_kind = coerce k'}+ mapRTypeVM :: (Hashable b, Monad m) => (v -> m v') -> RTypeBV b v c tv r -> m (RTypeBV b v' c tv r) mapRTypeVM _ (RVar α r) = return $ RVar α r-mapRTypeVM f (RAllT α t r) = RAllT <$> traverse (mapRTypeVM f) α <*> mapRTypeVM f t <*> pure r-mapRTypeVM f (RAllP π t) = RAllP <$> emapPVarVM (const f) (const (mapRTypeVM f)) π <*> mapRTypeVM f t+mapRTypeVM f (RAllT α t r) = RAllT <$> mapRTVarVM f (coerce α) <*> mapRTypeVM f t <*> pure r+mapRTypeVM f (RAllP π t) = RAllP <$> emapPVarVM (const f) (const (mapRTypeVM f)) (coerce π) <*> mapRTypeVM f t mapRTypeVM f (RFun x i t t' r) = RFun x i <$> mapRTypeVM f t <*> mapRTypeVM f t' <*> pure r-mapRTypeVM f (RApp c ts rs r) = RApp c <$> mapM (mapRTypeVM f) ts <*> mapM mapRefVM rs <*> pure r+mapRTypeVM f (RApp c ts rs r) = RApp c <$> mapM (mapRTypeVM f) ts <*> mapM mapRefVM (coerce rs) <*> pure r where mapRefVM (RProp ss t) = RProp <$> mapM (traverse (mapRTypeVM f)) ss <*> mapRTypeVM f t mapRTypeVM f (REx z t t') = REx z <$> mapRTypeVM f t <*> mapRTypeVM f t'@@ -358,7 +532,7 @@ -- The first parameter corresponds to the bscope config setting emapReftM- :: (Monad m, ToReft r1, F.Binder b, CompatibleBinder b tv, ReftBind r1 ~ b)+ :: forall m b v1 v2 c tv r1 r2. (Monad m, IsReft r1, F.Binder b, CompatibleBinder b tv, ReftBind r1 ~ b) => Bool -> ([b] -> v1 -> m v2) -> ([b] -> r1 -> m r2)@@ -367,9 +541,16 @@ -> m (RTypeBV b v2 c tv r2) emapReftM bscp vf f = go where+ emapRTVarM :: (RTypeBV b v1 c tv (NoReftBV b v1) -> m (RTypeBV b v2 c tv (NoReftBV b v1))) -> RTVar b v1 c tv -> m (RTVar b v2 c tv)+ emapRTVarM _ (RTVar tv (RTVNoInfo p)) = pure $ RTVar tv (RTVNoInfo p)+ emapRTVarM rf (RTVar tv ri@RTVInfo{rtv_kind=k}) = do+ t' <- rf k+ pure $ RTVar tv ri{rtv_kind = coerce t'}++ go :: [b] -> RTypeBV b v1 c tv r1 -> m (RTypeBV b v2 c tv r2) go γ (RVar α r) = RVar α <$> f γ r- go γ (RAllT α t r) = RAllT <$> traverse (emapReftM bscp vf (const pure) γ) α <*> go (coerceBinder (ty_var_value α) : γ) t <*> f γ r- go γ (RAllP π t) = RAllP <$> emapPVarVM vf (emapReftM bscp vf (const pure)) π <*> go γ t+ go γ (RAllT α t r) = RAllT <$> emapRTVarM (emapReftM bscp vf (const pure) γ) (coerce α) <*> go (coerceBinder (ty_var_value α) : γ) t <*> f γ r+ go γ (RAllP π t) = RAllP <$> emapPVarVM vf (emapReftM bscp vf (const pure)) (coerce π) <*> go γ t go γ (RFun x i t t' r) = RFun x i <$> go (x:γ) t <*> go (x:γ) t' <*> f (x:γ) r go γ (RApp c ts rs r) = let γ' = if bscp then F.reftBind (toReft r) : γ else γ@@ -382,7 +563,7 @@ go γ (RHole r) = RHole <$> f γ r emapRefM- :: (Monad m, ToReft t, F.Binder b, CompatibleBinder b tv, ReftBind t ~ b)+ :: (Monad m, IsReft t, F.Binder b, CompatibleBinder b tv, ReftBind t ~ b) => Bool -> ([b] -> v -> m v') -> ([b] -> t -> m s)@@ -394,11 +575,11 @@ mapAccumM (\γ (s, t) -> (s:γ,) . (s,) <$> emapReftM bscp vf (const pure) γ t) γ0- ss+ (coerce ss) <*> emapReftM bscp vf f (map fst ss ++ γ0) t0 emapBareTypeVM- :: (Monad m, Ord v1)+ :: Monad m => Bool -> ([Symbol] -> v1 -> m v2) -> [Symbol]@@ -413,7 +594,7 @@ mapDataDeclV :: (v -> v') -> DataDeclP v ty -> DataDeclP v' ty mapDataDeclV f DataDecl {..} = DataDecl- { tycPVars = map (mapPVarV f (mapRTypeV f)) tycPVars+ { tycPVars = map (mapPVarV f (mapRTypeV f)) (coerce tycPVars) , tycSFun = fmap (fmap f) tycSFun , .. }@@ -433,7 +614,7 @@ tycDCons <- traverse (mapM (emapDataCtorTyM f)) (tycDCons d) tycSFun <- traverse (traverse (vf [])) (tycSFun d) tycPropTy <- traverse (f []) $ tycPropTy d- return d{tycDCons, tycPVars, tycSFun, tycPropTy}+ return d{tycDCons, tycPVars = coerce tycPVars, tycSFun, tycPropTy} emapDataCtorTyM :: Monad m@@ -446,23 +627,6 @@ dcFields <- snd <$> mapAccumM (\γ (s, t) -> (lhNameToUnqualifiedSymbol s:γ,) . (s,) <$> f γ t) [] (dcFields d) return d{dcTheta, dcFields, dcResult} -emapExprArg :: ([b] -> ExprBV b v -> ExprBV b v) -> [b] -> RTypeBV b v c tv r -> RTypeBV b v c tv r-emapExprArg f = go- where- go _ t@RVar{} = t- go _ t@RHole{} = t- go γ (RAllT α t r) = RAllT α (go γ t) r- go γ (RAllP π t) = RAllP π (go γ t)- go γ (RFun x i t t' r) = RFun x i (go γ t) (go (x:γ) t') r- go γ (RApp c ts rs r) = RApp c (go γ <$> ts) (mo γ <$> rs) r- go γ (REx z t t') = REx z (go γ t) (go γ t')- go γ (RExprArg e) = RExprArg (f γ <$> e) -- <---- actual substitution- go γ (RAppTy t t' r) = RAppTy (go γ t) (go γ t') r- go γ (RRTy e r o t) = RRTy (fmap (go γ) <$> e) r o (go γ t)-- mo _ t@(RProp _ RHole{}) = t- mo γ (RProp s t) = RProp s (go γ t)- parsedToBareType :: BareTypeParsed -> BareType parsedToBareType = mapRTypeV F.val . mapReft (mapUReftV F.val (fmap F.val)) @@ -570,20 +734,20 @@ (\_ γ -> γ) F.emptySEnv -tyVarIsVal :: RTVar tv s -> Bool+tyVarIsVal :: RTVar b v c tv -> Bool tyVarIsVal = rtvinfoIsVal . ty_var_info -rtvinfoIsVal :: RTVInfo s -> Bool+rtvinfoIsVal :: RTVInfo b v c tv -> Bool rtvinfoIsVal RTVNoInfo{} = False rtvinfoIsVal RTVInfo{..} = rtv_is_val efoldReft :: (IsReft r, TyConable c, F.Binder b, ReftBind r ~ b) => BScope -> (c -> [RTypeBV b v c tv r] -> [(b, a)])- -> (RTVar tv (RTypeBV b v c tv (NoReftB b)) -> [(b, a)])+ -> (RTVar b v c tv -> [(b, a)]) -> (RTypeBV b v c tv r -> a) -> (F.SEnvB b a -> Maybe (RTypeBV b v c tv r) -> r -> z -> z)- -> (PVarBV b v (RTypeBV b v c tv (NoReftB b)) -> F.SEnvB b a -> F.SEnvB b a)+ -> (PVarBV b v (RTypeBV b v c tv (NoReftBV b v)) -> F.SEnvB b a -> F.SEnvB b a) -> F.SEnvB b a -> z -> RTypeBV b v c tv r@@ -670,16 +834,16 @@ mapT (RTVar tv i) = RTVar tv (mapI i) mapS = mapReft (\NoReft -> NoReft) . mapBind f mapI RTVNoInfo{..} = RTVNoInfo{..}- mapI RTVInfo{..} = RTVInfo { rtv_kind = mapS rtv_kind, .. }- mapP (PV n τ a as) = PV (f n) (mapS τ) (f a) (mapA <$> as)+ mapI RTVInfo{..} = RTVInfo {rtv_name = f rtv_name, rtv_kind = mapS rtv_kind, .. }+ mapP (PV n τ as) = PV (f n) (mapS τ) (mapA <$> as) mapA (τ, b, e) = (mapS τ, f b, F.mapBindExpr f e) mapR (RProp as t) = RProp (bimap f mapS <$> as) (go t) ---------------------------------------------------ofRSort :: IsReft r => RTypeBV b v c tv (NoReftB b) -> RTypeBV b v c tv r+ofRSort :: IsReft r => RTypeBV b v c tv (NoReftBV b v) -> RTypeBV b v c tv r ofRSort = fmap (const trueReft) -toRSort :: F.Binder b => RTypeBV b v c tv r -> RTypeBV b v c tv (NoReftB b)+toRSort :: F.Binder b => RTypeBV b v c tv r -> RTypeBV b v c tv (NoReftBV b v) toRSort = stripAnnotations . mapBind (const F.wildcard) . (NoReft <$) stripAnnotations :: RTypeBV b v c tv r -> RTypeBV b v c tv r@@ -702,10 +866,10 @@ insertsSEnv :: (Eq b, Hashable b) => F.SEnvB b a -> [(b, a)] -> F.SEnvB b a insertsSEnv = foldr (\(x, t) γ -> insertSEnv x t γ) -rTypeValueVar :: (ToReft r, F.Binder (ReftBind r)) => RTypeBV b v c tv r -> ReftBind r+rTypeValueVar :: (IsReft r, F.Binder (ReftBind r)) => RTypeBV b v c tv r -> ReftBind r rTypeValueVar t = vv where F.Reft (vv,_) = rTypeReft t -rTypeReft :: (ToReft r, F.Binder (ReftBind r)) => RTypeBV b v c tv r -> F.ReftBV (ReftBind r) (ReftVar r)+rTypeReft :: (IsReft r, F.Binder (ReftBind r)) => RTypeBV b v c tv r -> F.ReftBV (ReftBind r) (ReftVar r) rTypeReft = maybe F.trueReft toReft . stripRTypeBase -- stripRTypeBase :: RType a -> Maybe a@@ -725,4 +889,5 @@ mapRBase f (RVar a r) = RVar a $ f r mapRBase f (RFun x i t1 t2 r) = RFun x i t1 t2 $ f r mapRBase f (RAppTy t1 t2 r) = RAppTy t1 t2 $ f r+mapRBase f (RAllT b t r) = RAllT b t (f r) mapRBase _ t = t
src/Language/Haskell/Liquid/Types/RefType.hs view
@@ -103,7 +103,6 @@ import qualified Data.HashMap.Strict as M import qualified Data.HashSet as S import qualified Data.List as L-import Control.Monad (void) import Text.Printf import Text.PrettyPrint.HughesPJ hiding ((<>), first) import Language.Fixpoint.Misc@@ -120,7 +119,7 @@ import Language.Haskell.Liquid.Misc import Language.Haskell.Liquid.Types.Names import qualified Language.Haskell.Liquid.GHC.Misc as GM-import Language.Haskell.Liquid.GHC.Play (mapType, stringClassArg, isRecursivenewTyCon)+import Language.Haskell.Liquid.GHC.Play (mapType, stringClassArg) import Liquid.GHC.API as Ghc hiding ( Expr, get , Located , tyConName@@ -170,29 +169,29 @@ pdVar v = Pr [uPVar v] findPVar :: [PVar (RType c tv NoReft)] -> UsedPVar -> PVar (RType c tv NoReft)-findPVar ps upv = PV name ty v (zipWith (\(_, _, e) (t, s, _) -> (t, s, e)) (pargs upv) args)+findPVar ps upv = PV name ty (zipWith (\(_, _, e) (t, s, _) -> (t, s, e)) (pargs upv) args) where- PV name ty v args = fromMaybe (msg upv) $ L.find ((== pname upv) . pname) ps+ PV name ty args = fromMaybe (msg upv) $ L.find ((== pname upv) . pname) ps msg p = panic Nothing $ "RefType.findPVar" ++ showpp p ++ "not found" -- | Various functions for converting vanilla `Reft` to `Spec` -uRType :: RType c tv a -> RType c tv (UReft a)+uRType :: RType c tv Reft -> RType c tv UReft uRType = fmap uTop -uRType' :: RType c tv (UReft a) -> RType c tv a+uRType' :: RType c tv UReft -> RType c tv Reft uRType' = fmap ur_reft uRTypeGen :: IsReft b => RType c tv a -> RType c tv b uRTypeGen = fmap $ const trueReft uPVar :: PVarV v t -> UsedPVarV v-uPVar = void+uPVar = fmap (const NoReft) -uReft :: (Symbol, Expr) -> UReft Reft+uReft :: (Symbol, Expr) -> UReft uReft = uTop . Reft -uTop :: r -> UReftV v r+uTop :: ReftV v -> UReftV v uTop r = MkUReft r (Pr []) --------------------------------------------------------------------@@ -209,10 +208,13 @@ , Subable r , F.Variable r ~ v , ReftBind r ~ v+ , ReftVar r ~ v , IsReft r+ , Meet r+ , F.Refreshable v , SubsTy tv (RTypeBV v v c tv (NoReftB v)) r , SubsTy tv (RTypeBV v v c tv (NoReftB v)) tv- , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar tv (RTypeBV v v c tv (NoReftB v)))+ , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar v v c tv) ) => Semigroup (RTypeBV v v c tv r) where (<>) = strengthenRefType@@ -225,10 +227,13 @@ , Subable r , F.Variable r ~ v , ReftBind r ~ v+ , ReftVar r ~ v , IsReft r+ , Meet r+ , F.Refreshable v , SubsTy tv (RTypeBV v v c tv (NoReftB v)) r , SubsTy tv (RTypeBV v v c tv (NoReftB v)) tv- , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar tv (RTypeBV v v c tv (NoReftB v)))+ , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar v v c tv) ) => Monoid (RTypeBV v v c tv r) where mempty = panic Nothing "mempty: RType"@@ -238,13 +243,16 @@ , OkRTBV v v c tv r , Variable r ~ v , ReftBind r ~ v+ , ReftVar r ~ v , IsReft r+ , Meet r , FreeVar c tv , Subable r+ , F.Refreshable v , SubsTy tv (RTypeBV v v c tv (NoReftB v)) r , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTypeBV v v c tv (NoReftB v)) , SubsTy tv (RTypeBV v v c tv (NoReftB v)) tv- , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar tv (RTypeBV v v c tv (NoReftB v)))+ , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar v v c tv) ) => Semigroup (RTPropBV v v c tv r) where (<>) (RProp s1 (RHole r1)) (RProp s2 (RHole r2))@@ -263,13 +271,16 @@ , OkRTBV v v c tv r , Variable r ~ v , ReftBind r ~ v+ , ReftVar r ~ v , IsReft r+ , Meet r , FreeVar c tv , Subable r+ , F.Refreshable v , SubsTy tv (RTypeBV v v c tv (NoReftB v)) r , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTypeBV v v c tv (NoReftB v)) , SubsTy tv (RTypeBV v v c tv (NoReftB v)) tv- , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar tv (RTypeBV v v c tv (NoReftB v)))+ , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar v v c tv) ) => Meet (RTPropBV v v c tv r) where @@ -278,46 +289,23 @@ , OkRTBV v v c tv r , Variable r ~ v , ReftBind r ~ v+ , ReftVar r ~ v , IsReft r+ , Meet r , FreeVar c tv , Subable r+ , F.Refreshable v , SubsTy tv (RTypeBV v v c tv (NoReftB v)) r , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTypeBV v v c tv (NoReftB v)) , SubsTy tv (RTypeBV v v c tv (NoReftB v)) tv- , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar tv (RTypeBV v v c tv (NoReftB v)))+ , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar v v c tv) ) => Monoid (RTPropBV v v c tv r) where mempty = panic Nothing "mempty: RTProp" mappend = (<>) -instance Meet (RTProp RTyCon RTyVar (UReft Reft))-instance Meet (RTProp RTyCon RTyVar NoReft)-instance Meet (RTProp BTyCon BTyVar (UReft Reft))-instance Meet (RTProp BTyCon BTyVar NoReft)-instance Meet (RTProp RTyCon RTyVar Reft)- instance Semigroup (RType RTyCon RTyVar r) => Meet (RType RTyCon RTyVar r) where-instance Meet (RType BTyCon BTyVar (UReft Reft)) -------------------------------------------------------------------------------- | Subable Instances ------------------------------------------------------------------------------------------------------------------------------------instance Subable (RRProp Reft) where- syms (RProp ss (RHole r)) = (fst <$> ss) ++ syms r- syms (RProp ss t) = (fst <$> ss) ++ syms t--- subst su (RProp ss (RHole r)) = RProp (fmap (subst su) <$> ss) $ RHole $ subst su r- subst su (RProp ss r) = RProp (fmap (subst su) <$> ss) $ subst su r--- substf f (RProp ss (RHole r)) = RProp (fmap (substf f) <$> ss) $ RHole $ substf f r- substf f (RProp ss r) = RProp (fmap (substf f) <$> ss) $ substf f r-- substa f (RProp ss (RHole r)) = RProp (fmap (substa f) <$> ss) $ RHole $ substa f r- substa f (RProp ss r) = RProp (fmap (substa f) <$> ss) $ substa f r- -- MOVE TO TYPES instance Fixpoint String where toFix = text@@ -409,22 +397,24 @@ rTyVar :: TyVar -> RTyVar rTyVar = RTV -updateRTVar :: IsReft r => RTVar RTyVar i -> RTVar RTyVar (RType RTyCon RTyVar r)-updateRTVar (RTVar (RTV a) _) = RTVar (RTV a) (rTVarInfo a)+-- | Compute 'RTVarInfo' for an 'RTVar' if the info is not already present.+updateRTVar :: SpecRTVar -> SpecRTVar+updateRTVar (RTVar (RTV a) RTVNoInfo{}) = RTVar (RTV a) (rTVarInfo a)+updateRTVar v = v -rTVar :: IsReft r => TyVar -> RTVar RTyVar (RRType r)+rTVar :: TyVar -> RTVar Symbol Symbol RTyCon RTyVar rTVar a = RTVar (RTV a) (rTVarInfo a) -bTVar :: IsReft r => TyVar -> RTVar BTyVar (BRType r)+bTVar :: TyVar -> RTVar Symbol Symbol BTyCon BTyVar bTVar a = RTVar (BTV (symbol <$> GM.locNamedThing a)) (bTVarInfo a) -bTVarInfo :: IsReft r => TyVar -> RTVInfo (BRType r)+bTVarInfo :: TyVar -> RTVInfo Symbol Symbol BTyCon BTyVar bTVarInfo = mkTVarInfo kindToBRType -rTVarInfo :: IsReft r => TyVar -> RTVInfo (RRType r)+rTVarInfo :: TyVar -> RTVInfo Symbol Symbol RTyCon RTyVar rTVarInfo = mkTVarInfo kindToRType -mkTVarInfo :: (Kind -> s) -> TyVar -> RTVInfo s+mkTVarInfo :: (Kind -> RTypeBV Symbol v c tv (NoReftBV Symbol v)) -> TyVar -> RTVInfo Symbol v c tv mkTVarInfo k2t a = RTVInfo { rtv_name = symbol $ varName a , rtv_kind = k2t $ tyVarKind a@@ -485,7 +475,7 @@ (rPropP [] . pdVarReft <$> πs) mempty -pdVarReft :: PVar t -> UReft Reft+pdVarReft :: PVar t -> UReft pdVarReft = (\p -> MkUReft mempty p) . pdVar tyConRTyCon :: TyCon -> RTyCon@@ -540,13 +530,16 @@ , Subable r , F.Variable r ~ v , ReftBind r ~ v+ , ReftVar r ~ v , IsReft r+ , Meet r+ , F.Refreshable v , FreeVar c tv , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTypeBV v v c tv (NoReftB v)) , SubsTy tv (RTypeBV v v c tv (NoReftB v)) c , SubsTy tv (RTypeBV v v c tv (NoReftB v)) r , SubsTy tv (RTypeBV v v c tv (NoReftB v)) tv- , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar tv (RTypeBV v v c tv (NoReftB v)))+ , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar v v c tv) ) => RTypeBV v v c tv r -> RTypeBV v v c tv r -> RTypeBV v v c tv r strengthenRefType_ ::@@ -554,19 +547,22 @@ , Subable r , F.Variable r ~ v , ReftBind r ~ v+ , ReftVar r ~ v , IsReft r+ , Meet r+ , F.Refreshable v , FreeVar c tv , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTypeBV v v c tv (NoReftB v)) , SubsTy tv (RTypeBV v v c tv (NoReftB v)) c , SubsTy tv (RTypeBV v v c tv (NoReftB v)) r- , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar tv (RTypeBV v v c tv (NoReftB v)))+ , SubsTy tv (RTypeBV v v c tv (NoReftB v)) (RTVar v v c tv) , SubsTy tv (RTypeBV v v c tv (NoReftB v)) tv ) => (RTypeBV v v c tv r -> RTypeBV v v c tv r -> RTypeBV v v c tv r) -> RTypeBV v v c tv r -> RTypeBV v v c tv r -> RTypeBV v v c tv r strengthenRefTypeGen = strengthenRefType_ f where- f :: (OkRTBV v v c tv r, IsReft r) => RTypeBV v v c tv r -> RTypeBV v v c tv r -> RTypeBV v v c tv r+ f :: (OkRTBV v v c tv r, IsReft r, Meet r) => RTypeBV v v c tv r -> RTypeBV v v c tv r -> RTypeBV v v c tv r f (RVar v1 r1) t = RVar v1 (r1 `meet` fromMaybe trueReft (stripRTypeBase t)) f t (RVar _ r1) = t `strengthen` r1 f t1 t2 = panic Nothing $ printf "strengthenRefTypeGen on differently shaped types \nt1 = %s [shape = %s]\nt2 = %s [shape = %s]"@@ -667,7 +663,7 @@ go t _ = t -quantifyRTy :: (Monoid r, Eq tv) => [RTVar tv (RTypeV v c tv NoReft)] -> RTypeV v c tv r -> RTypeV v c tv r+quantifyRTy :: (Monoid r, Eq tv) => [RTVar Symbol v c tv] -> RTypeV v c tv r -> RTypeV v c tv r quantifyRTy tvs ty = foldr rAllT ty tvs where rAllT a t = RAllT a t mempty @@ -676,7 +672,7 @@ --------------------------------------------------------------------------addTyConInfo :: (PPrint r, ToReft r, SubsTy RTyVar RSort r, Variable r ~ Symbol, ReftBind r ~ Symbol, ReftVar r ~ Symbol, IsReft r)+addTyConInfo :: (PPrint r, IsReft r, SubsTy RTyVar RSort r, Variable r ~ Symbol, ReftBind r ~ Symbol, ReftVar r ~ Symbol, IsReft r, Meet r) => TCEmb TyCon -> TyConMap -> RRType r@@ -685,7 +681,7 @@ addTyConInfo tce tyi = mapBot (expandRApp tce tyi) --------------------------------------------------------------------------expandRApp :: (PPrint r, ToReft r, SubsTy RTyVar RSort r, Variable r ~ Symbol, ReftBind r ~ Symbol, ReftVar r ~ Symbol, IsReft r)+expandRApp :: (PPrint r, IsReft r, SubsTy RTyVar RSort r, Variable r ~ Symbol, ReftBind r ~ Symbol, ReftVar r ~ Symbol, IsReft r, Meet r) => TCEmb TyCon -> TyConMap -> RRType r -> RRType r ------------------------------------------------------------------------- expandRApp tce tyi t@RApp{} = RApp rc' ts rs' r@@ -713,18 +709,20 @@ SubsTy tv (RType c tv NoReft) c, SubsTy tv (RType c tv NoReft) r, SubsTy tv (RType c tv NoReft) (RType c tv NoReft), FreeVar c tv, SubsTy tv (RType c tv NoReft) tv,- SubsTy tv (RType c tv NoReft) (RTVar tv (RType c tv NoReft)))+ SubsTy tv (RType c tv NoReft) (RTVar Symbol Symbol c tv)) => PVar (RType c tv NoReft) -> Ref (RType c tv NoReft) (RType c tv r) rtPropTop pv = RProp (pvArgs pv) $ ofRSort $ ptype pv -rtPropPV :: (Fixpoint a, IsReft r)+rtPropPV :: (Fixpoint a, IsReft r, Meet r) => a -> [PVar (RType c tv NoReft)] -> [Ref (RType c tv NoReft) (RType c tv r)] -> [Ref (RType c tv NoReft) (RType c tv r)] rtPropPV _rc = zipWith mkRTProp -mkRTProp :: IsReft r+-- | Eliminates top-level RHoles. See @goRProps@ inside 'goPlugged' in+-- Plugged.hs for the handling of nested RHoles.+mkRTProp :: (IsReft r, Meet r) => PVar (RType c tv NoReft) -> Ref (RType c tv NoReft) (RType c tv r) -> Ref (RType c tv NoReft) (RType c tv r)@@ -870,7 +868,7 @@ vs' = freeTyVars t -freeTyVars :: Eq tv => RTypeV v c tv r -> [RTVar tv (RTypeV v c tv NoReft)]+freeTyVars :: Eq tv => RTypeV v c tv r -> [RTVar Symbol v c tv] freeTyVars (RAllP _ t) = freeTyVars t freeTyVars (RAllT α t _) = freeTyVars t L.\\ [α] freeTyVars (RFun _ _ t t' _) = freeTyVars t `L.union` freeTyVars t'@@ -905,84 +903,84 @@ -------------------------------------------------------------------------------- subsTyVarsMeet- :: (Eq tv, Foldable t, Hashable tv, IsReft r, TyConable c, Binder b,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) c, SubsTy tv (RTypeBV b v c tv (NoReftB b)) r,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTypeBV b v c tv (NoReftB b)), FreeVar c tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTVar tv (RTypeBV b v c tv (NoReftB b))))- => t (tv, RTypeBV b v c tv (NoReftB b), RTypeBV b v c tv r) -> RTypeBV b v c tv r -> RTypeBV b v c tv r+ :: (Eq tv, Foldable t, Hashable tv, IsReft r, Eq (ReftVar r), TyConable c, Binder b, Meet r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) c, SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTypeBV b v c tv (NoReftBV b v)), FreeVar c tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTVar b v c tv))+ => t (tv, RTypeBV b v c tv (NoReftBV b v), RTypeBV b v c tv r) -> RTypeBV b v c tv r -> RTypeBV b v c tv r subsTyVarsMeet = subsTyVars True subsTyVarsNoMeet- :: (Eq tv, Foldable t, Hashable tv, IsReft r, TyConable c, Binder b,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) c, SubsTy tv (RTypeBV b v c tv (NoReftB b)) r,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTypeBV b v c tv (NoReftB b)), FreeVar c tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTVar tv (RTypeBV b v c tv (NoReftB b))))- => t (tv, RTypeBV b v c tv (NoReftB b), RTypeBV b v c tv r) -> RTypeBV b v c tv r -> RTypeBV b v c tv r+ :: (Eq tv, Foldable t, Hashable tv, IsReft r, Eq (ReftVar r), TyConable c, Binder b, Meet r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) c, SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTypeBV b v c tv (NoReftBV b v)), FreeVar c tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTVar b v c tv))+ => t (tv, RTypeBV b v c tv (NoReftBV b v), RTypeBV b v c tv r) -> RTypeBV b v c tv r -> RTypeBV b v c tv r subsTyVarsNoMeet = subsTyVars False subsTyVarNoMeet- :: (Eq tv, Hashable tv, IsReft r, TyConable c, Binder b,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) c, SubsTy tv (RTypeBV b v c tv (NoReftB b)) r,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTypeBV b v c tv (NoReftB b)), FreeVar c tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTVar tv (RTypeBV b v c tv (NoReftB b))))- => (tv, RTypeBV b v c tv (NoReftB b), RTypeBV b v c tv r) -> RTypeBV b v c tv r -> RTypeBV b v c tv r+ :: (Eq tv, Hashable tv, IsReft r, Eq (ReftVar r), TyConable c, Binder b, Meet r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) c, SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTypeBV b v c tv (NoReftBV b v)), FreeVar c tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTVar b v c tv))+ => (tv, RTypeBV b v c tv (NoReftBV b v), RTypeBV b v c tv r) -> RTypeBV b v c tv r -> RTypeBV b v c tv r subsTyVarNoMeet = subsTyVar False subsTyVarMeet- :: (Eq tv, Hashable tv, IsReft r, TyConable c, Binder b,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) c, SubsTy tv (RTypeBV b v c tv (NoReftB b)) r,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTypeBV b v c tv (NoReftB b)), FreeVar c tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTVar tv (RTypeBV b v c tv (NoReftB b))))- => (tv, RTypeBV b v c tv (NoReftB b), RTypeBV b v c tv r) -> RTypeBV b v c tv r -> RTypeBV b v c tv r+ :: (Eq tv, Hashable tv, IsReft r, Eq (ReftVar r), TyConable c, Binder b, Meet r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) c, SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTypeBV b v c tv (NoReftBV b v)), FreeVar c tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTVar b v c tv))+ => (tv, RTypeBV b v c tv (NoReftBV b v), RTypeBV b v c tv r) -> RTypeBV b v c tv r -> RTypeBV b v c tv r subsTyVarMeet = subsTyVar True subsTyVarMeet'- :: (Eq tv, Hashable tv, IsReft r, TyConable c, Binder b,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) c, SubsTy tv (RTypeBV b v c tv (NoReftB b)) r,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTypeBV b v c tv (NoReftB b)), FreeVar c tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTVar tv (RTypeBV b v c tv (NoReftB b))))+ :: (Eq tv, Hashable tv, IsReft r, Eq (ReftVar r), TyConable c, Binder b, Meet r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) c, SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTypeBV b v c tv (NoReftBV b v)), FreeVar c tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTVar b v c tv)) => (tv, RTypeBV b v c tv r) -> RTypeBV b v c tv r -> RTypeBV b v c tv r subsTyVarMeet' (α, t) = subsTyVarMeet (α, toRSort t, t) subsTyVars- :: (Eq tv, Foldable t, Hashable tv, IsReft r, TyConable c, Binder b,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) c, SubsTy tv (RTypeBV b v c tv (NoReftB b)) r,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTypeBV b v c tv (NoReftB b)), FreeVar c tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTVar tv (RTypeBV b v c tv (NoReftB b))))+ :: (Eq tv, Foldable t, Hashable tv, IsReft r, Eq (ReftVar r), TyConable c, Binder b, Meet r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) c, SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTypeBV b v c tv (NoReftBV b v)), FreeVar c tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTVar b v c tv)) => Bool- -> t (tv, RTypeBV b v c tv (NoReftB b), RTypeBV b v c tv r)+ -> t (tv, RTypeBV b v c tv (NoReftBV b v), RTypeBV b v c tv r) -> RTypeBV b v c tv r -> RTypeBV b v c tv r subsTyVars meet' ats t = foldl' (flip (subsTyVar meet')) t ats subsTyVar- :: (Eq tv, Hashable tv, IsReft r, TyConable c, Binder b,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) c, SubsTy tv (RTypeBV b v c tv (NoReftB b)) r,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTypeBV b v c tv (NoReftB b)), FreeVar c tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTVar tv (RTypeBV b v c tv (NoReftB b))))+ :: (Eq tv, Hashable tv, IsReft r, Eq (ReftVar r), TyConable c, Binder b, Meet r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) c, SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTypeBV b v c tv (NoReftBV b v)), FreeVar c tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTVar b v c tv)) => Bool- -> (tv, RTypeBV b v c tv (NoReftB b), RTypeBV b v c tv r)+ -> (tv, RTypeBV b v c tv (NoReftBV b v), RTypeBV b v c tv r) -> RTypeBV b v c tv r -> RTypeBV b v c tv r subsTyVar meet' = subsFree meet' S.empty subsFree- :: (Eq tv, Hashable tv, IsReft r, TyConable c, Binder b,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) c, SubsTy tv (RTypeBV b v c tv (NoReftB b)) r,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTypeBV b v c tv (NoReftB b)), FreeVar c tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTVar tv (RTypeBV b v c tv (NoReftB b)))+ :: (Eq tv, Hashable tv, IsReft r, Eq (ReftVar r), TyConable c, Binder b, Meet r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) c, SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTypeBV b v c tv (NoReftBV b v)), FreeVar c tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTVar b v c tv) ) => Bool -> S.HashSet tv- -> (tv, RTypeBV b v c tv (NoReftB b), RTypeBV b v c tv r)+ -> (tv, RTypeBV b v c tv (NoReftBV b v), RTypeBV b v c tv r) -> RTypeBV b v c tv r -> RTypeBV b v c tv r subsFree m s z@(α, τ,_) (RAllP π t)@@ -1013,26 +1011,26 @@ = RHole (subt (α, τ) r) subsFrees- :: (Eq tv, Hashable tv, IsReft r, TyConable c, Binder b,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) c, SubsTy tv (RTypeBV b v c tv (NoReftB b)) r,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTypeBV b v c tv (NoReftB b)), FreeVar c tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTVar tv (RTypeBV b v c tv (NoReftB b))))+ :: (Eq tv, Hashable tv, IsReft r, Eq (ReftVar r), TyConable c, Binder b, Meet r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) c, SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTypeBV b v c tv (NoReftBV b v)), FreeVar c tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTVar b v c tv)) => Bool -> S.HashSet tv- -> [(tv, RTypeBV b v c tv (NoReftB b), RTypeBV b v c tv r)]+ -> [(tv, RTypeBV b v c tv (NoReftBV b v), RTypeBV b v c tv r)] -> RTypeBV b v c tv r -> RTypeBV b v c tv r subsFrees m s zs t = foldl' (flip (subsFree m s)) t zs -- GHC INVARIANT: RApp is Type Application to something other than TYCon subsFreeRAppTy- :: (Eq tv, Hashable tv, IsReft r, TyConable c, Binder b,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) c, SubsTy tv (RTypeBV b v c tv (NoReftB b)) r,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTypeBV b v c tv (NoReftB b)),+ :: (Eq tv, Hashable tv, IsReft r, Eq (ReftVar r), TyConable c, Binder b, Meet r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) c, SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTypeBV b v c tv (NoReftBV b v)), FreeVar c tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTVar tv (RTypeBV b v c tv (NoReftB b))))+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTVar b v c tv)) => Bool -> S.HashSet tv -> RTypeBV b v c tv r@@ -1051,11 +1049,11 @@ -- parameters come from the "levity polymorphism" changes in GHC 8.6 (?) -- See [NOTE:Levity-Polymorphism] -mkRApp :: (Eq tv, Hashable tv, IsReft r, TyConable c, Binder b,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) c, SubsTy tv (RTypeBV b v c tv (NoReftB b)) r,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTypeBV b v c tv (NoReftB b)), FreeVar c tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTVar tv (RTypeBV b v c tv (NoReftB b))))+mkRApp :: (Eq tv, Hashable tv, IsReft r, Eq (ReftVar r), TyConable c, Binder b, Meet r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) c, SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTypeBV b v c tv (NoReftBV b v)), FreeVar c tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTVar b v c tv)) => Bool -> S.HashSet tv -> c@@ -1114,20 +1112,20 @@ • and other links from https://stackoverflow.com/a/35320729/946226 (edited) -} -refAppTyToFun :: ToReft r => r -> r+refAppTyToFun :: (IsReft r, Eq (ReftVar r)) => r -> r refAppTyToFun r | isTauto r = r | otherwise = panic Nothing "RefType.refAppTyToFun" subsFreeRef- :: (Eq tv, Hashable tv, IsReft r, TyConable c, Binder b,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) c, SubsTy tv (RTypeBV b v c tv (NoReftB b)) r,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTypeBV b v c tv (NoReftB b)), FreeVar c tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) tv,- SubsTy tv (RTypeBV b v c tv (NoReftB b)) (RTVar tv (RTypeBV b v c tv (NoReftB b))))+ :: (Eq tv, Hashable tv, IsReft r, Eq (ReftVar r), TyConable c, Binder b, Meet r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) c, SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) r,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTypeBV b v c tv (NoReftBV b v)), FreeVar c tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) tv,+ SubsTy tv (RTypeBV b v c tv (NoReftBV b v)) (RTVar b v c tv)) => Bool -> S.HashSet tv- -> (tv, RTypeBV b v c tv (NoReftB b), RTypeBV b v c tv r)+ -> (tv, RTypeBV b v c tv (NoReftBV b v), RTypeBV b v c tv r) -> RTPropBV b v c tv r -> RTPropBV b v c tv r subsFreeRef _ _ (α', τ', _) (RProp ss (RHole r))@@ -1149,7 +1147,7 @@ subt _ v = v -instance SubsTy RTyVar (RType RTyCon RTyVar NoReft) (RTVar RTyVar (RType RTyCon RTyVar NoReft)) where+instance SubsTy RTyVar (RType RTyCon RTyVar NoReft) (RTVar Symbol Symbol RTyCon RTyVar) where -- NV TODO: update kind subt su rty = rty { ty_var_value = subt su $ ty_var_value rty } @@ -1157,7 +1155,7 @@ instance SubsTy BTyVar (RType c BTyVar NoReft) BTyVar where subt _ = id -instance SubsTy BTyVar (RType c BTyVar NoReft) (RTVar BTyVar (RType c BTyVar NoReft)) where+instance SubsTy BTyVar (RType c BTyVar NoReft) (RTVar Symbol Symbol c BTyVar) where subt _ = id instance SubsTy tv ty NoReft where@@ -1235,7 +1233,7 @@ subt _ s = s instance (SubsTy tv ty ty) => SubsTy tv ty (PVarBV b v ty) where- subt su (PV n pvk v xts) = PV n (subt su pvk) v [(subt su t, x, y) | (t,x,y) <- xts]+ subt su (PV n pvk xts) = PV n (subt su pvk) [(subt su t, x, y) | (t,x,y) <- xts] instance SubsTy RTyVar RSort RTyCon where subt z c = RTyCon tc ps' i@@ -1260,7 +1258,7 @@ instance SubsTy tv RSort Predicate where subt _ = id -- NV TODO -instance (SubsTy tv ty r) => SubsTy tv ty (UReft r) where+instance SubsTy tv ty Reft => SubsTy tv ty UReft where subt su r = r {ur_reft = subt su $ ur_reft r} -- Here the "String" is a Bare-TyCon. TODO: wrap in newtype@@ -1270,11 +1268,11 @@ instance SubsTy BTyVar BSort BSort where subt (α, τ) = subsTyVarMeet (α, τ, ofRSort τ) -instance (SubsTy tv ty (UReft r), SubsTy tv ty (RType c tv NoReft)) => SubsTy tv ty (RTProp c tv (UReft r)) where+instance (SubsTy tv ty UReft, SubsTy tv ty (RType c tv NoReft)) => SubsTy tv ty (RTProp c tv UReft) where subt m (RProp ss (RHole p)) = RProp (fmap (subt m) <$> ss) $ RHole $ subt m p subt m (RProp ss t) = RProp (fmap (subt m) <$> ss) $ fmap (subt m) t -subvUReft :: (UsedPVar -> UsedPVar) -> UReft Reft -> UReft Reft+subvUReft :: (UsedPVar -> UsedPVar) -> UReft -> UReft subvUReft f (MkUReft r p) = MkUReft r (subvPredicate f p) subvPredicate :: (UsedPVar -> UsedPVar) -> Predicate -> Predicate@@ -1336,7 +1334,7 @@ data TyConv c tv r = TyConv { tcFVar :: TyVar -> RType c tv r- , tcFTVar :: TyVar -> RTVar tv (RType c tv NoReft)+ , tcFTVar :: TyVar -> RTVar Symbol Symbol c tv , tcFApp :: TyCon -> [RType c tv r] -> RType c tv r , tcFLit :: TyLit -> RType c tv r }@@ -1386,7 +1384,7 @@ isBaseTy (CoercionTy _) = False -dataConMsReft :: (ToReft r, ReftBind r ~ v, ReftVar r ~ v, F.Refreshable v) => RTypeBV v v c tv r -> [v] -> ReftBV v v+dataConMsReft :: (IsReft r, ReftBind r ~ v, ReftVar r ~ v, F.Refreshable v) => RTypeBV v v c tv r -> [v] -> ReftBV v v dataConMsReft ty ys = subst su (rTypeReft (ignoreOblig $ ty_res trep)) where trep = toRTypeRep ty@@ -1497,7 +1495,8 @@ where txK (PKVar k _tsu su) | Just p' <- f k =- rapierSubstExpr (substSymbolsSet $ substFromKSubst su) (renameDomain k su) p'+ let su' = renameDomain k su+ in rapierSubstExpr (substSymbolsSet su' `S.union` syms p') su' p' txK p = p -- The parameters of kvars all seem to have prefix $ and suffix ##k_@@ -1511,23 +1510,23 @@ -------------------------------------------------------------------------------- -- shiftVV :: Int -- SpecType -> Symbol -> SpecType-shiftVV :: (TyConable c, IsReft (f Reft), Functor f, Subable (f Reft),- Variable (f Reft) ~ Variable Reft, ReftBind (f Reft) ~ ReftBind Reft)- => RType c tv (f Reft) -> Symbol -> RType c tv (f Reft)+shiftVV :: (TyConable c, IsReft r, Subable r, Variable r ~ Symbol,+ ReftBind r ~ Symbol, ReftVar r ~ Symbol)+ => RType c tv r -> Symbol -> RType c tv r -------------------------------------------------------------------------------- shiftVV t@(RApp _ ts rs r) vv' = t { rt_args = subst1 ts (rTypeValueVar t, EVar vv') } { rt_pargs = subst1 rs (rTypeValueVar t, EVar vv') }- { rt_reft = (`F.shiftVV` vv') <$> r }+ { rt_reft = mapReftField (`F.shiftVV` vv') r } shiftVV t@(RFun _ _ _ _ r) vv'- = t { rt_reft = (`F.shiftVV` vv') <$> r }+ = t { rt_reft = mapReftField (`F.shiftVV` vv') r } shiftVV t@(RAppTy _ _ r) vv'- = t { rt_reft = (`F.shiftVV` vv') <$> r }+ = t { rt_reft = mapReftField (`F.shiftVV` vv') r } shiftVV t@(RVar _ r) vv'- = t { rt_reft = (`F.shiftVV` vv') <$> r }+ = t { rt_reft = mapReftField (`F.shiftVV` vv') r } shiftVV t _ = t -- errorstar $ "shiftVV: cannot handle " ++ showpp t@@ -1556,15 +1555,15 @@ go τ@(ForAllTy _ _) = typeSortForAll tce τ -- go (TyConApp c τs) = fApp (tyConFTyCon tce c) (go <$> τs) go (TyConApp c τs)- | isNewTyCon c- , not (isRecursivenewTyCon c)- , τs `lengthAtLeast` newTyConEtadArity c- = go (Ghc.newTyConInstRhs c τs)+ | Ghc.isFamilyTyCon c+ , Ghc.piResultTys (Ghc.tyConKind c) τs `Ghc.eqType` naturalTy+ = FInt | otherwise = tyConFTyCon tce c (go <$> τs) go (AppTy t1 t2) = fApp (go t1) [go t2] go (TyVarTy tv) = tyVarSort tv go (CastTy t _) = go t+ go (LitTy (NumTyLit _)) = FInt go τ = FObj (typeUniqueSymbol τ) tyConFTyCon :: TCEmb TyCon -> TyCon -> [Sort] -> Sort@@ -1727,8 +1726,8 @@ makeDecrType :: Symbolic a => S.HashSet TyCon- -> Maybe (a, (Symbol, RType RTyCon t (UReft Reft)))- -> Either (Symbol, RType RTyCon t (UReft Reft)) String+ -> Maybe (a, (Symbol, RType RTyCon t UReft))+ -> Either (Symbol, RType RTyCon t UReft) String makeDecrType autoenv (Just (v, (x, t))) = Left (x, t `strengthen` tr) where@@ -1761,7 +1760,7 @@ = pAnd [PAtom Lt (g x) (g v), PAtom Ge (g x) zero] where zero = ECon $ I 0 -makeLexRefa :: [Located Expr] -> [Located Expr] -> UReft Reft+makeLexRefa :: [Located Expr] -> [Located Expr] -> UReft makeLexRefa es' es = uTop $ Reft (vv', PIff (EVar vv') $ pOr rs) where rs = makeLexReft [] [] (val <$> es) (val <$> es')
src/Language/Haskell/Liquid/Types/Specs.hs view
@@ -45,6 +45,7 @@ , Spec(..) , GhcSpecVars(..) , GhcSpecSig(..)+ , RefinementCheck(..) , GhcSpecNames(..) , GhcSpecTerm(..) , GhcSpecRefl(..)@@ -186,6 +187,7 @@ , gsFiTcs :: ![TyCon] -- ^ Family instance TyCons , gsFiDcs :: ![(F.Symbol, DataCon)] -- ^ Family instance DataCons , gsPrimTcs :: ![TyCon] -- ^ Primitive GHC TyCons (from TysPrim.primTyCons)+ , giInstSpans :: ![SrcSpan] -- ^ Full source spans of instance declarations } -- | 'QImports' is a map of qualified imports.@@ -254,9 +256,32 @@ , gsTexprs :: ![(Var, LocSpecType, [F.Located F.Expr])] -- ^ Lexicographically ordered expressions for termination , gsRelation :: ![(Var, Var, LocSpecType, LocSpecType, RelExpr, RelExpr)] , gsAsmRel :: ![(Var, Var, LocSpecType, LocSpecType, RelExpr, RelExpr)]+ , gsReftChecks :: ![RefinementCheck] -- ^ Synthetic Core checks for refinement predicates } deriving Show +-- | Checking that the predicates of the refinements do not violate their specifications.+--+-- Since constraint generation is only done by analyzing Core, checking+-- predicates of refinement types requires translating them to Core.+--+-- For each refinement that can be translated to Haskell, elaboration produces+-- a synthetic function whose arguments are the values in scope at the point of+-- the refinement and whose result is the predicate as a 'Bool'. For example,+-- the refinement @x:Int -> {v:Int | v > x}@ generates @\x v -> v > x@.+-- Elaboration is implemented in 'Language.Haskell.Liquid.Bare.Elaborate.elaborateSpecTypeWith'.+--+-- 'refinementCheckExpr' stores that function as GHC Core and+-- 'refinementCheckType' is the original Liquid signature.++data RefinementCheck = RefinementCheck+ { refinementCheckExpr :: !CoreExpr+ , refinementCheckType :: !LocSpecType+ }++instance Show RefinementCheck where+ show _ = "<refinement-check>"+ instance Semigroup GhcSpecSig where x <> y = SpSig { gsTySigs = gsTySigs x <> gsTySigs y@@ -271,6 +296,7 @@ , gsTexprs = gsTexprs x <> gsTexprs y , gsRelation = gsRelation x <> gsRelation y , gsAsmRel = gsAsmRel x <> gsAsmRel y+ , gsReftChecks = gsReftChecks x <> gsReftChecks y } @@ -280,7 +306,7 @@ instance Monoid GhcSpecSig where- mempty = SpSig mempty mempty mempty mempty mempty mempty mempty mempty mempty mempty mempty mempty+ mempty = SpSig mempty mempty mempty mempty mempty mempty mempty mempty mempty mempty mempty mempty mempty data GhcSpecData = SpData { gsCtors :: ![(Var, LocSpecType)] -- ^ Data Constructor Measure Sigs@@ -427,7 +453,7 @@ , usedDataCons :: S.HashSet LHName -- ^ Data constructors used in specs } deriving (Data, Generic) -instance (F.PPrint lname, F.PPrint ty, PredicateCompat F.Symbol lname, F.Fixpoint lname, Ord lname) => F.PPrint (Spec lname ty) where+instance (F.PPrint ty) => F.PPrint (Spec F.Symbol ty) where pprintTidy k sp = text "dataDecls = " <+> pprintTidy k (dataDecls sp) HughesPJ.$$ text "classes = " <+> pprintTidy k (classes sp)@@ -440,25 +466,36 @@ -- -- emapSpecM- :: (Monad m, Ord lname0)+ :: Monad m => -- | The bscope setting, which affects which names -- are considered to be in scope in refinement types. Bool -- | For names that have a local environment return the names in scope. -> (LHName -> [F.Symbol])- -- | The first parameter of the function argument are the variables in scope.- -> ([F.Symbol] -> lname0 -> m lname1)- -> ([F.Symbol] -> ty0 -> m ty1)+ -- | The first parameter of the function argument is the name of the+ -- definition whose specification is being traversed, if there is one.+ -- The second parameter are the variables in scope.+ -> (Maybe LHName -> [F.Symbol] -> lname0 -> m lname1)+ -> (Maybe LHName -> [F.Symbol] -> ty0 -> m ty1) -> Spec lname0 ty0 -> m (Spec lname1 ty1)-emapSpecM bscp lenv vf f sp = do+emapSpecM bscp lenv vfn fn sp = do measures <- mapM (emapMeasureM vf (traverse . f)) (measures sp) expSigs <- sequence [ (,s) <$> vf [] n | (n, s) <- expSigs sp ]- asmSigs <- mapM (\p -> traverse (traverse (f $ lenv $ val $ fst p)) p) (asmSigs sp)+ asmSigs <-+ mapM+ (\p -> do+ let n = val $ fst p+ traverse (traverse (fn (Just n) (lenv n))) p+ )+ (asmSigs sp) sigs <- mapM- (\p -> traverse (traverse (emapBareTypeVM bscp vf (lenv $ val $ fst p))) p)+ (\p -> do+ let n = val $ fst p+ traverse (traverse (emapBareTypeVM bscp (vfn (Just n)) (lenv n))) p+ ) (sigs sp) invariants <- mapM (traverse (traverse fnull)) (invariants sp) ialiases <- mapM (bimapM (traverse fnull) (traverse fnull)) (ialiases sp)@@ -477,10 +514,11 @@ termexprs <- mapM (\p -> do- let bs0 = lenv $ val $ fst p- mbs = M.findWithDefault [] (val $ fst p) mbinds+ let n = val $ fst p+ bs0 = lenv n+ mbs = M.findWithDefault [] n mbinds traverse- (mapM (traverse (emapExprVM (vf . (++ (mbs ++ bs0))))))+ (mapM (traverse (emapExprVM (vfn (Just n) . (++ (mbs ++ bs0)))))) p ) (termexprs sp)@@ -518,6 +556,8 @@ , defines } where+ vf = vfn Nothing+ f = fn Nothing fnull = f [] emapRelationalM vf1 (n0, n1, t0, t1, e0, e1) = do t0' <- traverse (emapBareTypeVM bscp vf1 []) t0@@ -885,6 +925,7 @@ , _gsFiTcs :: ![TyCon] -- ^ Family instance TyCons , _gsFiDcs :: ![(F.Symbol, DataCon)] -- ^ Family instance DataCons , _gsPrimTcs :: ![TyCon] -- ^ Primitive GHC TyCons (from TysPrim.primTyCons)+ , _giInstSpans :: ![SrcSpan] -- ^ Full source spans of instance declarations } data GhcSpec = SP@@ -919,6 +960,7 @@ , gsFiTcs = _gsFiTcs a , gsFiDcs = _gsFiDcs a , gsPrimTcs = _gsPrimTcs a+ , giInstSpans = _giInstSpans a } fromTargetSrc :: TargetSrc -> GhcSrc@@ -936,6 +978,7 @@ , _gsFiTcs = gsFiTcs a , _gsFiDcs = gsFiDcs a , _gsPrimTcs = gsPrimTcs a+ , _giInstSpans = giInstSpans a } toTargetSpec :: GhcSpec -> TargetSpec
src/Language/Haskell/Liquid/Types/Types.hs view
@@ -791,44 +791,30 @@ instance F.Subable (Measure ty ctor) where- syms m = concatMap F.syms (msEqns m)- substa f m = m { msEqns = F.substa f <$> msEqns m }- substf f m = m { msEqns = F.substf f <$> msEqns m }- subst su m = m { msEqns = F.subst su <$> msEqns m }- -- substa f (M n s es _) = M n s (F.substa f <$> es) k- -- substf f (M n s es _) = M n s $ F.substf f <$> es- -- subst su (M n s es _) = M n s $ F.subst su <$> es+ syms m = F.syms (msEqns m)+ substr ns su m = m { msEqns = F.substr ns su <$> msEqns m } instance F.Subable (Def ty ctor) where- syms (Def _ _ _ sb bd) = (fst <$> sb) ++ F.syms bd- substa f (Def m c t b bd) = Def m c t b $ F.substa f bd- substf f (Def m c t b bd) = Def m c t b $ F.substf f bd- subst su (Def m c t b bd) = Def m c t b $ F.subst su bd+ syms (Def _ _ _ sb bd) = S.fromList (fst <$> sb) `S.union` F.syms bd+ substr ns su (Def m c t b bd) = Def m c t b $ F.substr ns su bd instance F.Subable Body where syms (E e) = F.syms e syms (P e) = F.syms e- syms (R s e) = s : F.syms e-- substa f (E e) = E (F.substa f e)- substa f (P e) = P (F.substa f e)- substa f (R s e) = R s (F.substa f e)-- substf f (E e) = E (F.substf f e)- substf f (P e) = P (F.substf f e)- substf f (R s e) = R s (F.substf f e)+ syms (R s e) = S.delete s (F.syms e) - subst su (E e) = E (F.subst su e)- subst su (P e) = P (F.subst su e)- subst su (R s e) = R s (F.subst su e)+ substr ns su (E e) = E (F.substr ns su e)+ substr ns su (P e) = P (F.substr ns su e)+ substr ns su (R s e) =+ let (ns', s') = F.freshInNS s ns+ su' = F.extendSubstWithVar su s s'+ in R s' (F.substr ns' su' e) instance F.Subable t => F.Subable (WithModel t) where type Variable (WithModel t) = F.Variable t syms (NoModel t) = F.syms t syms (WithModel _ t) = F.syms t- substa f = fmap (F.substa f)- substf f = fmap (F.substf f)- subst su = fmap (F.subst su)+ substr ns su = fmap (F.substr ns su) data RClass ty = RClass { rcName :: BTyCon@@ -986,7 +972,7 @@ isHole (F.PKVar "HOLE" _ _) = True isHole _ = False -hasHole :: (ToReft r, ReftBind r ~ Symbol, ReftVar r ~ Symbol) => r -> Bool+hasHole :: (IsReft r, ReftBind r ~ Symbol, ReftVar r ~ Symbol) => r -> Bool hasHole = any isHole . F.conjuncts . F.reftPred . toReft instance F.Symbolic DataCon where
src/Language/Haskell/Liquid/UX/Annotate.hs view
@@ -76,17 +76,18 @@ -- | @output@ creates the pretty printed output+-- NOTE: for Refcore, we want to get the inferred types before they get printed to Doc ---------------------------------------------------------------------------------------------mkOutput :: Config -> ErrorResult -> FInfo a -> FixDelayedSolution -> AnnInfo (Annot SpecType) -> Output Doc+mkOutput :: Config -> ErrorResult -> FInfo a -> FixDelayedSolution -> AnnInfo (Annot SpecType) -> (Output Doc, AnnInfo SpecType) -------------------------------------------------------------------------------------------- mkOutput cfg res si sol anna- = O { o_vars = Nothing+ = (O { o_vars = Nothing -- , o_errors = [] , o_types = toDoc <$> annTy , o_templs = toDoc <$> annTmpl , o_bots = mkBots annTy , o_result = res- }+ }, annTy) where annTmpl = closeAnnots anna annTy = tidySpecType Lossy <$> applySolution si sol annTmpl@@ -126,7 +127,7 @@ jsonF = extFileName Json srcF vimF = extFileName Vim srcF -mkBots :: ToReft r => AnnInfo (RType c tv r) -> [GHC.SrcSpan]+mkBots :: IsReft r => AnnInfo (RType c tv r) -> [GHC.SrcSpan] mkBots (AI m) = [ src | (src, (Just _, t) : _) <- sortBy (ordSrcSpan `on` fst) $ M.toList m , isFalse (rTypeReft t) ]
src/Language/Haskell/Liquid/UX/CmdLine.hs view
@@ -35,6 +35,9 @@ -- * Diff check mode , diffcheck + -- * Shell-word splitting (used by LIQUIDHASKELL_OPTS parsing)+ , shellWords+ ) where import Prelude hiding (error)@@ -42,7 +45,7 @@ import Control.Monad import Control.Monad.IO.Class-import Data.Char (toLower)+import Data.Char (isSpace, toLower) import Data.Maybe import Data.Functor ((<&>)) import Data.Aeson (encode)@@ -113,7 +116,6 @@ , totalHaskell = False , nowarnings = False , noannotations = False- , checkDerived = False , caseExpandDepth = 2 , notruetypes = False , nototality = False@@ -151,6 +153,7 @@ , reflection = False , compileSpec = False , typeclass = False+ , checkRefinements = False , auxInline = False , rwTerminationCheck = False , skipModule = False@@ -167,6 +170,8 @@ , ddumpTimings = False , modern = False , warnOnTermHoles = False+ , refcore = False+ , refcoreText = False } -- | A flag is either a config transformer or a request for --help/--version.@@ -250,8 +255,6 @@ "Don't display warnings, only show errors" , opt [] ["no-annotations"] (NoArg $ fm $ \c -> c { noannotations = True }) "Don't create intermediate annotation files"- , opt [] ["check-derived"] (NoArg $ fm $ \c -> c { checkDerived = True })- "Check GHC generated binders (e.g. Read, Show instances)" , opt [] ["max-case-expand"] (ReqArg (fm . setCaseExpandDepth) "N") "Maximum depth at which to expand DEFAULT in case-of (default=2)" , opt [] ["no-true-types"] (NoArg $ fm $ \c -> c { notruetypes = True })@@ -329,9 +332,13 @@ , opt [] ["compile-spec"] (NoArg $ fm $ \c -> c { compileSpec = True }) "Only compile specifications (into .bspec file); skip verification" , opt [] ["typeclass"] (NoArg $ fm $ \c -> c { typeclass = True })- "Enable Typeclass support"+ "Enable typeclass support"+ , opt [] ["check-refinements"] (NoArg $ fm $ \c -> c { checkRefinements = True })+ "Check refinement predicates do not violate the refined specifications" , opt [] ["aux-inline"] (NoArg $ fm $ \c -> c { auxInline = True })- "Enable inlining of class methods"+ ("Beta-reduce applications of methods to dictionaries in Core. Might help\n" +++ "termination checks of functions that use methods."+ ) , opt [] ["rw-termination-check"] (NoArg $ fm $ \c -> c { rwTerminationCheck = True }) ("Enable the rewrite divergence checker. Can speed up verification if rewriting\n" ++ "terminates, but can also cause divergence."@@ -362,6 +369,10 @@ "Allow refining constructors with unsafe refinements" , opt [] ["ddump-timings"] (NoArg $ fm $ \c -> c { ddumpTimings = True }) "Dump time measures of the Liquid Haskell plugin"+ , opt [] ["refcore"] (NoArg $ fm $ \c -> c { refcore = True })+ "Extract RefCore Calculus declarations"+ , opt [] ["refcore-text"] (NoArg $ fm $ \c -> c { refcoreText = True })+ "Also write the human-readable .ilh text dump (debug)" , opt [] ["modern"] (NoArg $ fm $ \c -> c { modern = True }) "Enable modern features (--reflection, --ple, --etabeta, --dependantcase)" , opt [] ["warn-on-term-holes"] (NoArg $ fm $ \c -> c { warnOnTermHoles = True })@@ -533,7 +544,7 @@ so <- lookupEnv "LIQUIDHASKELL_OPTS" case so of Nothing -> return defConfig- Just s -> applyGetOpt defConfig (words s)+ Just s -> applyGetOpt defConfig (shellWords s) where applyGetOpt cfg toks = case getOpt Permute lhOptions toks of@@ -596,15 +607,32 @@ liftIO $ setFxVerbosity (loggingVerbosity cfg) -- restore pure res +-- | Split a string into words like a shell would: unquoted whitespace+-- separates tokens, and single or double quoted substrings are kept as+-- one token (with the quotes stripped). This allows option values that+-- contain spaces, e.g. @--expect-error-containing="Cannot ignore m"@.+shellWords :: String -> [String]+shellWords = filter (not . null) . go [] False False+ where+ -- @go acc dq sq cs@ processes the input string @cs@ character by character,+ -- accumulating the current token in 'acc', and keeping track of whether+ -- we're inside double quotes (dq) or single quotes (sq).+ go acc _ _ [] = [reverse acc | not (null acc)]+ go acc dq sq (c:cs)+ | c == '"' && not sq = go acc (not dq) sq cs+ | c == '\'' && not dq = go acc dq (not sq) cs+ | isSpace c && not dq && not sq =+ if null acc then go [] False False cs+ else reverse acc : go [] False False cs+ | otherwise = go (c : acc) dq sq cs+ -- | Apply a list of pragma strings (each is one option, e.g. @"--ple"@ or -- @"--expect-error-containing=Mismatch"@) on top of an existing 'Config'.--- Each pragma string is tokenised with 'words' so that a two-token form like--- @"--check-var foo"@ also works. processPragmas :: Config -> [Located String] -> IO Config processPragmas cfg pragmas = foldM applyOne cfg pragmas where applyOne c loc =- case getOpt Permute lhOptions (words (val loc)) of+ case getOpt Permute lhOptions [val loc] of (flags, _, []) -> do when (any isHelp flags) $ putStr (formatHelp usageHeader lhOptions) >> error "LiquidHaskell:--help"
src/Language/Haskell/Liquid/UX/Config.hs view
@@ -50,7 +50,6 @@ , totalHaskell :: Bool -- ^ Check for termination and totality, Overrides no-termination flags , nowarnings :: Bool -- ^ disable warnings output (only show errors) , noannotations :: Bool -- ^ disable creation of intermediate annotation files- , checkDerived :: Bool -- ^ check internal (GHC-derived) binders , caseExpandDepth :: Int -- ^ maximum case expand nesting depth. , notruetypes :: Bool -- ^ disable truing top level types , nototality :: Bool -- ^ disable totality check in definitions@@ -89,6 +88,7 @@ , reflection :: Bool -- ^ Allow "reflection"; switches on "--higherorder" and "--adt" , compileSpec :: Bool -- ^ Only "compile" the spec -- into .bspec file -- don't do any checking. , typeclass :: Bool -- ^ enable typeclass support.+ , checkRefinements :: Bool -- ^ check refinement predicates do not violate the refined specifications , auxInline :: Bool -- ^ , rwTerminationCheck :: Bool -- ^ Enable termination checking for rewriting , skipModule :: Bool -- ^ Skip this module entirely (don't even compile any specs in it)@@ -105,6 +105,8 @@ , allowUnsafeConstructors :: Bool -- ^ Allow refining constructors with unsafe refinements , ddumpTimings :: Bool -- ^ Dump time measures of the Liquid Haskell plugin -- Only needed to work around https://github.com/haskell/cabal/issues/11116+ , refcore :: Bool -- Enable extraction of RefCore Calculus declarations+ , refcoreText :: Bool -- Also write the human-readable .ilh text dump (debug) , modern :: Bool -- ^ Enable modern features; enables reflection, ple, etabeta, dependantcase, adt , warnOnTermHoles :: Bool -- ^ Warn about holes in the terms } deriving (Generic, Show, Eq)
src/Language/Haskell/Liquid/UX/Errors.hs view
@@ -54,7 +54,7 @@ = e { ctx = c', tact = F.subst θ tA, texp = F.subst θ tE } where (θ, c') = tidyCtx k xs (ctx e)- xs = F.syms tA ++ F.syms tE+ xs = S.toList (F.syms tA `S.union` F.syms tE) tA = tact e tE = texp e @@ -62,7 +62,7 @@ = e { ctxM = c', tactM = fmap (F.subst θ) tA, texp = fmap (F.subst θ) tE } where (θ, c') = tidyCtxM xs $ ctxM e- xs = F.syms tA ++ F.syms tE+ xs = S.toList (F.syms tA `S.union` F.syms tE) tA = tactM e tE = texp e @@ -71,7 +71,7 @@ where m = ctx e (θ, c') = tidyCtx k xs m- xs = F.syms p+ xs = S.toList (F.syms p) p = cond e tidyErrContext _ e@@ -122,11 +122,7 @@ isInline :: (a, SpecType) -> Either (a, F.Expr) (a, SpecType) isInline (x, t) =- either (Left . (x,)) (Right . (x,)) (isInline' t')- where- -- tidyInternalRefas could drop some conjuncts which affects whether- -- bindings are eliminated in isInline'- t' = tidyInternalRefas t+ either (Left . (x,)) (Right . (x,)) (isInline' t) isInline' :: SpecType -> Either F.Expr SpecType isInline' t = case ro of@@ -166,7 +162,7 @@ tidyREnvM xs m = [(x, t) | x <- xs', t <- maybeToList (M.lookup x m), ok t] where xs' = expandFix deps xs- deps y = maybe [] (F.syms . rTypeReft . dropModel) (M.lookup y m)+ deps y = maybe [] (S.toList . F.syms . rTypeReft . dropModel) (M.lookup y m) ok = not . isFunTy . dropModel expandFix :: (Eq a, Hashable a) => (a -> [a]) -> [a] -> [a]
src/Language/Haskell/Liquid/UX/QuasiQuoter.hs view
@@ -1,7 +1,6 @@ {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE TemplateHaskellQuotes #-}-{-# LANGUAGE TupleSections #-} {-# LANGUAGE OverloadedStrings #-} module Language.Haskell.Liquid.UX.QuasiQuoter
src/Language/Haskell/Liquid/UX/Tidy.hs view
@@ -14,7 +14,6 @@ -- * Tidying functions tidySpecType- , tidyInternalRefas , tidySymbol -- * Panic and Exit@@ -85,7 +84,6 @@ . tidyValueVars . tidyDSymbols . tidySymbols k- . tidyInternalRefas . tidyLocalRefas k . tidyFunBinds . tidyTyVars@@ -98,7 +96,7 @@ | isJunk va = shiftVV r v' | otherwise = r where- v' = if v `elem` xs then symbol ("v'" :: T.Text) else v+ v' = if v `S.member` xs then symbol ("v'" :: T.Text) else v v = symbol ("v" :: T.Text) xs = syms r isJunk = isPrefixOfSym "x"@@ -106,7 +104,7 @@ tidySymbols :: Tidy -> SpecType -> SpecType tidySymbols k t = substa (shortSymbol k . tidySymbol) $ mapBind dropBind t where- xs = S.fromList (syms t)+ xs = syms t dropBind x = if x `S.member` xs then tidySymbol x else nonSymbol shortSymbol :: Tidy -> Symbol -> Symbol@@ -128,20 +126,10 @@ txReft u = u { ur_reft = mapPredReft dropInternals $ ur_reft u } dropInternals = pAnd . L.nub . conjuncts --- | Drop conjuncts that contain data constructor testing or--- selector functions.-tidyInternalRefas :: SpecType -> SpecType-tidyInternalRefas = mapReft txReft- where- txReft u = u { ur_reft = mapPredReft dropInternals $ ur_reft u }- dropInternals = pAnd . filter (not . any isIntern . syms) . conjuncts- isIntern x = "is$" `isPrefixOfSym` x || "$select" `isSuffixOfSym` x-- tidyDSymbols :: SpecType -> SpecType tidyDSymbols t = mapBind tx $ substa tx t where- tx = bindersTx [x | x <- syms t, isTmp x]+ tx = bindersTx (S.toList $ S.filter isTmp $ syms t) isTmp = (tempPrefix `isPrefixOfSym`) tidyFunBinds :: SpecType -> SpecType@@ -179,11 +167,11 @@ subsTyVarsAll :: (Eq k, Hashable k,- IsReft r, TyConable c, SubsTy k (RType c k NoReft) c,+ IsReft r, Meet r, Eq (ReftVar r), TyConable c, SubsTy k (RType c k NoReft) c, SubsTy k (RType c k NoReft) r, SubsTy k (RType c k NoReft) k, SubsTy k (RType c k NoReft) (RType c k NoReft),- SubsTy k (RType c k NoReft) (RTVar k (RType c k NoReft)),+ SubsTy k (RType c k NoReft) (RTVar Symbol Symbol c k), FreeVar c k) => [(k, RType c k NoReft, RType c k r)] -> RType c k r -> RType c k r subsTyVarsAll ats = go
src/Language/Haskell/Liquid/WiredIn.hs view
@@ -1,5 +1,4 @@ {-# LANGUAGE OverloadedStrings #-}-{-# LANGUAGE TemplateHaskellQuotes #-} {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-} @@ -22,9 +21,6 @@ , isWiredInName , dcPrefix - -- * Deriving classes- , isDerivedInstance- , derivingClasses ) where import Prelude hiding (error)@@ -48,7 +44,6 @@ import Data.Bifunctor (first) import qualified Data.HashSet as S import Data.Maybe-import Data.Proxy import Language.Haskell.Liquid.GHC.TypeRep () @@ -85,7 +80,7 @@ wiredSortedSyms :: [(F.Symbol, F.Sort)] wiredSortedSyms = (selfSymbol,selfSort) :- [(pappV (Proxy :: Proxy F.Symbol) n, pappSort n) | n <- [1..pappArity]] +++ [(pappV n, pappSort n) | n <- [1..pappArity]] ++ wiredTheorySortedSyms where selfSort = F.FAbs 1 (F.FVar 0)@@ -129,6 +124,11 @@ , "FF_mul" , "strLen"+ , "subString"+ , "strConcat"+ , "strPrefixOf"+ , "strSuffixOf"+ , "strContains" ] --------------------------------------------------------------------------------@@ -195,8 +195,8 @@ fld = "fldList" xHead = "head" xTail = "tail"- p = PV "p" t (F.vv Nothing) [(t, fld, F.EVar fld)]- px = pdVarReft $ PV "p" t (F.vv Nothing) [(t, fld, F.EVar xHead)]+ p = PV "p" t [(t, fld, F.EVar fld)]+ px = pdVarReft $ PV "p" t [(t, fld, F.EVar xHead)] lt = rApp c [xt] [rPropP [] $ pdVarReft p] mempty xt = rVar tyv xst = rApp c [RVar (RTV tyv) px] [rPropP [] $ pdVarReft p] mempty@@ -245,35 +245,7 @@ mkps_ [] _ _ _ ps = ps mkps_ (n:ns) (t:ts) ((f, x):xs) args ps = mkps_ ns ts xs (a:args) (p:ps) where- p = PV n t (F.vv Nothing) args+ p = PV n t args a = (t, f, x) mkps_ _ _ _ _ _ = panic Nothing "Bare : mkps_" -----------------------------------------------------------------------------------isDerivedInstance :: Ghc.ClsInst -> Bool----------------------------------------------------------------------------------isDerivedInstance i = F.notracepp ("IS-DERIVED: " ++ F.showpp classSym)- $ S.member classSym derivingClassesSet- where- classSym = F.symbol . Ghc.is_cls $ i--derivingClassesSet :: S.HashSet F.Symbol-derivingClassesSet = S.fromList $ map F.symbol derivingClasses--derivingClasses :: [String]-derivingClasses =- [ show ''Eq- , show ''Ord- , show ''Enum- , show ''Show- , show ''Read- , show ''Monad- , show ''Applicative- , show ''Functor- , show ''Foldable- , show ''Traversable- , show ''Fractional- -- , "GHC.Enum.Bounded"- -- , "GHC.Base.Monoid"- ]
tests/Parser.hs view
@@ -20,8 +20,9 @@ import Data.Generics.Schemes import Language.Fixpoint.Types.Spans-import qualified Language.Haskell.Liquid.Parse as LH-import qualified Language.Fixpoint.Types as F+import qualified Language.Haskell.Liquid.Parse as LH+import qualified Language.Fixpoint.Types as F+import Language.Haskell.Liquid.UX.CmdLine (shellWords) import Text.Megaparsec.Error import Text.Megaparsec.Pos@@ -45,8 +46,29 @@ , testReservedAliases , testFails , testErrorReporting+ , testShellWords ] +-- | Tests for 'shellWords', which is used to parse LIQUIDHASKELL_OPTS.+-- Regression test for https://github.com/ucsd-progsys/liquidhaskell/issues/1990+testShellWords :: TestTree+testShellWords = testGroup "shellWords"+ [ testCase "empty string yields no tokens" $+ shellWords "" @?= []+ , testCase "single flag" $+ shellWords "--ple" @?= ["--ple"]+ , testCase "multiple space-separated flags" $+ shellWords "--ple --reflection" @?= ["--ple", "--reflection"]+ , testCase "flag with value" $+ shellWords "--smtsolver z3" @?= ["--smtsolver", "z3"]+ , testCase "multiple flags with leading/trailing spaces" $+ shellWords " --ple --reflection " @?= ["--ple", "--reflection"]+ , testCase "double-quoted value preserves spaces" $+ shellWords "--smtsolver \"my z3\"" @?= ["--smtsolver", "my z3"]+ , testCase "single-quoted value preserves spaces" $+ shellWords "--smtsolver 'my z3'" @?= ["--smtsolver", "my z3"]+ ]+ -- Test that the top level production works, each of the sub-elements will be tested separately testSpecP :: TestTree testSpecP =@@ -264,6 +286,26 @@ parseSingleSpec "x :: k:Int -> B (k + 1)" @?== "x :: k:Int -> (B {k + 1})" + , testCase "unicode :: " $+ parseSingleSpec "assume foo ∷ a -> a " @?==+ parseSingleSpec "assume foo :: a -> a "++ , testCase "unicode -> " $+ parseSingleSpec "assume foo :: a → b " @?==+ parseSingleSpec "assume foo :: a -> b "++ , testCase "unicode => " $+ parseSingleSpec "assume foo :: a ⇒ b " @?==+ parseSingleSpec "assume foo :: a => b "++ , testCase "mixed unicode operators 1 " $+ parseSingleSpec "assume foo ∷ a → a " @?==+ parseSingleSpec "assume foo :: a -> a "++ , testCase "mixed unicode operators 2 " $+ parseSingleSpec "assume foo ∷ a → b ⇒ c " @?==+ parseSingleSpec "assume foo :: a -> b => c "+ , testCase "type spec 1 " $ parseSingleSpec "type IncrListD a D = [a]<{\\x y -> (x+D) <= y}>" @?== "type IncrListD a D = [a]<\\x##2 _ -> {y##3 : LIQUID$dummy | x##2 + D <= y##3}>"@@ -487,7 +529,7 @@ , "1 | x :: Maybe k:Int -> Int" , " | ^" , "unexpected ':'"- , "expecting \"->\", \"=>\", '/', bareTyArgP, end of input, mmonoPredicateP, or monoPredicateP"+ , "expecting \"->\", \"=>\", '/', '→', '⇒', bareTyArgP, end of input, mmonoPredicateP, or monoPredicateP" ] , testCase "type t = Nat (type aliases should start with upper case)" $@@ -517,7 +559,7 @@ , "1 | assume mallocForeignPtrBytes :: n:Nat -> IO (ForeignPtrN a n " , " | ^" , "unexpected '('"- , "expecting \"->\", \"=>\", end of input, mmonoPredicateP, or predicatesP"+ , "expecting \"->\", \"=>\", '→', '⇒', bareTyArgP, end of input, mmonoPredicateP, or predicatesP" ] , testCase "Missing |" $ parseSingleSpec "ff :: {v:Nat v >= 0 }" @?==@@ -527,7 +569,7 @@ , "1 | ff :: {v:Nat v >= 0 }" , " | ^^" , "unexpected \">=\""- , "expecting \"->\", \"<:\", \"=>\", '|', bareTyArgP, mmonoPredicateP, or monoPredicateP"+ , "expecting \"->\", \"<:\", \"=>\", '|', '→', '⇒', bareTyArgP, mmonoPredicateP, or monoPredicateP" ] ]
− tests/WiredInTests.hs
@@ -1,53 +0,0 @@-{-# LANGUAGE PatternGuards #-}-{-# LANGUAGE TemplateHaskell #-}--import Control.Monad (forM, when)-import qualified Language.Haskell.TH as TH-import qualified Language.Haskell.TH.Syntax as TH-import Test.Tasty-import Test.Tasty.HUnit-import Test.Tasty.Runners.AntXML--import Language.Haskell.Liquid.WiredIn (derivingClasses)--import qualified GHC.Internal.Classes-import qualified GHC.Internal.Base-import qualified GHC.Internal.Data.Foldable-import qualified GHC.Internal.Data.Traversable-import qualified GHC.Internal.Enum-import qualified GHC.Internal.Read-import qualified GHC.Internal.Real-import qualified GHC.Internal.Show--main :: IO ()-main =- defaultMainWithIngredients (antXMLRunner:defaultIngredients) testTree--testTree :: TestTree-testTree =- testGroup "WiredIn names"- [ testCase "derivingClasses" testDerivingClasses- ]--testDerivingClasses :: IO ()-testDerivingClasses = do- let xs = $((TH.lift . concat =<<) $ forM derivingClasses $ \s -> do- mName <- TH.lookupTypeName s- case mName of- Nothing ->- pure [s ++ " is not in scope"]- Just n ->- case TH.nameModule n of- Nothing ->- pure [s ++ " doesn't have a module qualifier"]- Just m- | actual == s ->- pure []- | otherwise ->- pure [s ++ " is defined at another place: " ++ actual]- where- actual = m ++ "." ++ TH.nameBase n- ) :: [String]- when (not $ null xs) $- assertFailure $ unlines xs-