code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
module Model.AssetSlot.SQL
( slotAssetRow
, makeSlotAsset
, selectContainerSlotAsset
-- , selectOrigContainerSlotAsset
, selectAssetSlotAsset
, selectVolumeSlotAsset
, selectVolumeSlotIdAsset
-- , selectSlotAsset
, selectAssetSlot
-- , insertSlotAsset
-- , updateSlotAsset
-- , deleteSlotAsset
) where
import Data.Maybe (fromMaybe)
import qualified Language.Haskell.TH as TH
import Has (view)
import Model.Segment
import Model.Volume.Types
import Model.Asset.Types
import Model.Asset.SQL
import Model.Container.Types
import Model.Container.SQL
import Model.Slot.Types
import Model.SQL.Select
import Model.Volume.SQL
import Model.AssetSlot.Types
slotAssetRow :: Selector -- ^ @'Segment'@
slotAssetRow = selectColumn "slot_asset" "segment"
makeSlotAsset :: Asset -> Container -> Segment -> AssetSlot
makeSlotAsset a c s = AssetSlot a (Just (Slot c s))
_selectAssetContainerSlotAsset :: Selector -- ^ @'Asset' -> 'Container' -> 'AssetSlot'@
_selectAssetContainerSlotAsset = selectMap (TH.VarE 'makeSlotAsset `TH.AppE`) slotAssetRow
makeContainerSlotAsset :: Segment -> AssetRow -> Container -> AssetSlot
makeContainerSlotAsset s ar c = makeSlotAsset (Asset ar $ view c) c s
selectContainerSlotAsset :: Selector -- ^ @'Container' -> 'AssetSlot'@
selectContainerSlotAsset = selectJoin 'makeContainerSlotAsset
[ slotAssetRow
, joinOn "slot_asset.asset = asset.id" selectAssetRow -- XXX volumes match?
]
{-
selectOrigContainerSlotAsset :: Selector -- ^ @'Container' -> 'AssetSlot'@
selectOrigContainerSlotAsset = selectJoin 'makeContainerSlotAsset
[ slotAssetRow
, joinOn "slot_asset.asset = asset.id" selectAssetRow -- XXX volumes match?
]
-}
makeVolumeSlotIdAsset :: SlotId -> AssetRow -> Volume -> (Asset, SlotId)
makeVolumeSlotIdAsset s ar v = (Asset ar v, s)
selectVolumeSlotIdAsset :: Selector -- ^ @'Volume' -> ('Asset', 'SlotId')@
selectVolumeSlotIdAsset = selectJoin 'makeVolumeSlotIdAsset
[ selectColumns 'SlotId "slot_asset" ["container", "segment"]
, joinOn "slot_asset.asset = asset.id"
selectAssetRow -- XXX volumes match?
]
makeAssetSlotAsset :: Segment -> (Volume -> Container) -> Asset -> AssetSlot
makeAssetSlotAsset s cf a = makeSlotAsset a (cf (view a)) s
selectAssetSlotAsset :: Selector -- ^ @'Asset' -> 'AssetSlot'@
selectAssetSlotAsset = selectJoin 'makeAssetSlotAsset
[ slotAssetRow
, joinOn "slot_asset.container = container.id"
selectVolumeContainer -- XXX volumes match?
]
makeVolumeSlotAsset :: Segment -> AssetRow -> (Volume -> Container) -> Volume -> AssetSlot
makeVolumeSlotAsset s ar cf v = makeSlotAsset (Asset ar v) (cf v) s
selectVolumeSlotAsset :: Selector -- ^ @'Volume' -> 'AssetSlot'@
selectVolumeSlotAsset = selectJoin 'makeVolumeSlotAsset
[ slotAssetRow
, joinOn "slot_asset.asset = asset.id"
selectAssetRow
, joinOn "slot_asset.container = container.id AND asset.volume = container.volume"
selectVolumeContainer
]
{-
selectSlotAsset :: TH.Name -- ^ @'Identity'@
-> Selector -- ^ @'AssetSlot'@
selectSlotAsset ident = selectJoin '($)
[ selectVolumeSlotAsset
, joinOn "asset.volume = volume.id"
$ selectVolume ident
]
-}
makeVolumeAssetSlot :: AssetRow -> Maybe (Asset -> AssetSlot) -> Volume -> AssetSlot
makeVolumeAssetSlot ar sf = fromMaybe assetNoSlot sf . Asset ar
selectVolumeAssetSlot :: Selector -- ^ @'Volume' -> 'AssetSlot'@
selectVolumeAssetSlot = selectJoin 'makeVolumeAssetSlot
[ selectAssetRow
, maybeJoinOn "asset.id = slot_asset.asset AND asset.volume = container.volume"
selectAssetSlotAsset
]
selectAssetSlot :: TH.Name -- ^ @'Identity'@
-> Selector -- ^ @'AssetSlot'@
selectAssetSlot ident = selectJoin '($)
[ selectVolumeAssetSlot
, joinOn "asset.volume = volume.id"
$ selectVolume ident
]
{-
slotAssetKeys :: String -- ^ @'AssetSlot'@
-> [(String, String)]
slotAssetKeys as =
[ ("asset", "${assetId $ assetRow $ slotAsset " ++ as ++ "}") ]
slotAssetSets :: String -- ^ @'AssetSlot'@
-> [(String, String)]
slotAssetSets as =
[ ("container", "${containerId . containerRow . slotContainer <$> assetSlot " ++ as ++ "}")
, ("segment", "${slotSegment <$> assetSlot " ++ as ++ "}")
]
insertSlotAsset :: TH.Name -- ^ @'AuditIdentity'@
-> TH.Name -- ^ @'AssetSlot'@
-> TH.ExpQ
insertSlotAsset ident o = auditInsert ident "slot_asset"
(slotAssetKeys os ++ slotAssetSets os)
Nothing
where os = nameRef o
updateSlotAsset :: TH.Name -- ^ @'AuditIdentity'@
-> TH.Name -- ^ @'AssetSlot'@
-> TH.ExpQ
updateSlotAsset ident o = auditUpdate ident "slot_asset"
(slotAssetSets os)
(whereEq $ slotAssetKeys os)
Nothing
where os = nameRef o
deleteSlotAsset :: TH.Name -- ^ @'AuditIdentity'@
-> TH.Name -- ^ @'AssetSlot'@
-> TH.ExpQ
deleteSlotAsset ident o = auditDelete ident "slot_asset"
(whereEq $ slotAssetKeys os)
Nothing
where os = nameRef o
-}
| databrary/databrary | src/Model/AssetSlot/SQL.hs | agpl-3.0 | 4,909 | 0 | 9 | 779 | 691 | 390 | 301 | 70 | 1 |
module Data.Tree.Diff
( Difference(..)
, treeDifference
) where
import Data.List
import Data.Tree
import Data.Function
import Data.Maybe
import Control.Applicative
equalRoots :: (Eq a) => Tree a -> Tree a -> Bool
equalRoots = (==) `on` rootLabel
data Difference a =
First a
| Second a
| Both a
deriving (Show, Eq, Ord)
mergeTrees :: (Eq a) => Tree a -> Tree a -> Forest (Difference a)
mergeTrees (Node x xs) (Node y ys)
| x == y =
[ Node (Both x) ( (concat $ zipWith mergeTrees
(intersectBy equalRoots xs ys)
(intersectBy equalRoots ys xs))
++ map (fmap First) (deleteFirstsBy equalRoots xs ys)
++ map (fmap Second) (deleteFirstsBy equalRoots ys xs))
]
| otherwise =
[ Node (First x) (map (fmap First) xs)
, Node (Second y) (map (fmap Second) ys)]
filterCommon :: (Eq a) => Tree (Difference a) -> Maybe (Tree (Difference a))
filterCommon (Node (Both x) xs) =
case catMaybes $ map filterCommon xs of
[] -> Nothing
xs' -> Just (Node (Both x) xs')
filterCommon t = Just t
treeDifference :: (Eq a) => Tree a -> Tree a -> Forest (Difference a)
treeDifference t1 t2 =
catMaybes . map filterCommon $ mergeTrees t1 t2
| JanBessai/dirdiff | src/Data/Tree/Diff.hs | lgpl-3.0 | 1,265 | 0 | 15 | 352 | 541 | 276 | 265 | 35 | 2 |
-- |
-- Module : Water.SWMM
-- Copyright : (C) 2014 Siddhanathan Shanmugam
-- License : LGPL (see LICENSE)
-- Maintainer : siddhanathan@gmail.com
-- Portability : very
--
-- Parser for SWMM 5 Binary .OUT files
--
{-# LANGUAGE Trustworthy #-}
module Water.SWMM ( SWMMObject(..)
, Header(..)
, ObjectIds(..)
, Properties(..)
, ObjectProperties(..)
, Variables(..)
, ReportingVariables(..)
, ReportingInterval(..)
, ValuesForOneDateTime(..)
, ComputedResult(..)
, ClosingRecord(..)
, parseSWMMBinary
) where
import safe Data.Binary.Get (getWord32le, runGet, Get, getLazyByteString)
import safe Control.Applicative ((<$>), (<*>))
import safe qualified Data.ByteString.Lazy as BL (ByteString, pack, unpack)
import safe qualified Data.ByteString.Lazy.Char8 as BLC (ByteString, pack, unpack)
import safe Data.List.Split (chunksOf)
import safe Control.Monad (replicateM)
-- There is an implicit assumption that IEEE-754 is the in-memory representation.
-- If we assume this is the case, then this is safe.
import Data.Binary.IEEE754 (getFloat32le, getFloat64le)
data SWMMObject = SWMMObject { header :: Header
, ids :: ObjectIds
, properties :: ObjectProperties
, variables :: ReportingVariables
, intervals :: ReportingInterval
, result :: ComputedResult
, closingRecord :: ClosingRecord
} deriving (Show, Eq)
data Header = Header { headerIdNumber :: Integer
, versionNumber :: Integer
, codeNumber :: Integer
, numberOfSubcatchments :: Integer
, numberOfNodes :: Integer
, numberOfLinks :: Integer
, numberOfPollutants :: Integer
} deriving (Show, Eq)
data ObjectIds = ObjectIds { subcatchmentIds :: [BLC.ByteString]
, nodeIds :: [BLC.ByteString]
, linkIds :: [BLC.ByteString]
, pollutantIds :: [BLC.ByteString]
, concentrationIds :: [Integer]
} deriving (Show, Eq)
data ObjectProperties = ObjectProperties { subcatchmentProperties :: Properties
, nodeProperties :: Properties
, linkProperties :: Properties
} deriving (Show, Eq)
data ReportingVariables = ReportingVariables { subcatchmentVariables :: Variables
, nodeVariables :: Variables
, linkVariables :: Variables
, systemVariables :: Variables
} deriving (Show, Eq)
data ReportingInterval = ReportingInterval { startDateTime :: Double
, timeIntervals :: Integer
} deriving (Show, Eq)
--type ComputedResult = [ValuesForOneDateTime]
data ComputedResult = ComputedResult { allDateTimes :: [ValuesForOneDateTime] }
deriving (Show, Eq)
data ClosingRecord = ClosingRecord { idBytePosition :: Integer
, propertiesBytePosition :: Integer
, resultBytePosition :: Integer
, numberOfPeriods :: Integer
, errorCode :: Integer
, closingIdNumber :: Integer
} deriving (Show, Eq)
type Ids = [BL.ByteString]
data Properties = Properties { numberOfProperties :: Integer
, codeNumberProperties :: [Integer]
, valueProperties :: [Float]
} deriving (Show, Eq)
data Variables = Variables { numberOfVariables :: Integer
, codeNumberVariables :: [Integer]
} deriving (Show, Eq)
data ValuesForOneDateTime = ValuesForOneDateTime { dateTimeValue :: Double
, subcatchmentValue :: [[Float]]
, nodeValue :: [[Float]]
, linkValue :: [[Float]]
, systemValue :: [Float]
} deriving (Show)
instance Ord ValuesForOneDateTime where
a <= b = dateTimeValue a <= dateTimeValue b
instance Eq ValuesForOneDateTime where
a == b = dateTimeValue a == dateTimeValue b
closingRecordSize :: Int
closingRecordSize = 6 * 4
getHeader :: Get Header
getHeader = Header <$> a
<*> a
<*> a
<*> a
<*> a
<*> a
<*> a
where a = getIntegerWord32le
getSWMMObject :: ClosingRecord -> Get SWMMObject
getSWMMObject closing = do
header <- getHeader
objectIds <- getObjectIds header
objectProperties <- getObjectProperties header
reportingVariables <- getReportingVariables
reportingIntervals <- getReportingIntervals
computedResult <- getComputedResults (numberOfPeriods closing) header reportingVariables
closingRecord <- getClosingRecords
return $ SWMMObject header
objectIds
objectProperties
reportingVariables
reportingIntervals
computedResult
closingRecord
parseSWMMBinary :: BL.ByteString -> SWMMObject
parseSWMMBinary input = do
let closingRecord = runGet getClosingRecords (getClosingByteString input)
swmmObject = runGet (getSWMMObject closingRecord) input
swmmObject
getIntegerWord32le :: Get Integer
getIntegerWord32le = fromIntegral <$> getWord32le
getClosingByteString :: BL.ByteString -> BL.ByteString
getClosingByteString = BL.pack . reverse . take closingRecordSize . reverse . BL.unpack
getObjectIds :: Header -> Get ObjectIds
getObjectIds header =
ObjectIds <$> getIds (numberOfSubcatchments header)
<*> getIds (numberOfNodes header)
<*> getIds (numberOfLinks header)
<*> getIds (numberOfPollutants header)
<*> replicateM (fromInteger . numberOfPollutants $ header) getIntegerWord32le
getIds :: Integer -> Get [BL.ByteString]
getIds n = replicateM (fromInteger n)
(getIntegerWord32le >>= getLazyByteString . fromInteger)
getVariables :: Get Variables
getVariables = do
number <- getIntegerWord32le
codeNumbers <- replicateM (fromInteger number) getIntegerWord32le
return $ Variables number codeNumbers
getProperties :: Integer -> Get Properties
getProperties n = do
number <- getIntegerWord32le
codeNumbers <- replicateM (fromInteger number) getIntegerWord32le
values <- replicateM (fromInteger (number * n)) getFloat32le
return $ Properties number codeNumbers values
getObjectProperties :: Header -> Get ObjectProperties
getObjectProperties header = ObjectProperties <$> getProperties (numberOfSubcatchments header)
<*> getProperties (numberOfNodes header)
<*> getProperties (numberOfLinks header)
getReportingVariables :: Get ReportingVariables
getReportingVariables = ReportingVariables <$> a
<*> a
<*> a
<*> a
where a = getVariables
getReportingIntervals :: Get ReportingInterval
getReportingIntervals = ReportingInterval <$> getFloat64le
<*> getIntegerWord32le
getResults :: Header -> ReportingVariables -> Get ValuesForOneDateTime
getResults header report = do
ValuesForOneDateTime <$> getFloat64le
<*> getSplitValues (numberOfSubcatchments header * ns) ns
<*> getSplitValues (numberOfNodes header * nn) nn
<*> getSplitValues (numberOfLinks header * nl) nl
<*> getValues (numberOfVariables . systemVariables $ report)
where ns = (numberOfVariables . subcatchmentVariables) report
nn = (numberOfVariables . nodeVariables) report
nl = (numberOfVariables . linkVariables) report
getComputedResults :: Integer -> Header -> ReportingVariables -> Get ComputedResult
getComputedResults n header report = ComputedResult <$> replicateM (fromInteger n) (getResults header report)
getValues :: Integer -> Get [Float]
getValues n = replicateM (fromInteger n) getFloat32le
getSplitValues :: Integer -> Integer -> Get [[Float]]
getSplitValues n nv = chunksOf (fromInteger nv) <$> replicateM (fromInteger n) getFloat32le
getClosingRecords :: Get ClosingRecord
getClosingRecords = ClosingRecord <$> a
<*> a
<*> a
<*> a
<*> a
<*> a
where a = getIntegerWord32le
| Acidburn0zzz/SWMMoutGetMB | src/Water/SWMM.hs | lgpl-3.0 | 9,928 | 8 | 14 | 3,938 | 1,854 | 1,026 | 828 | 175 | 1 |
{-# LANGUAGE QuasiQuotes
, RecordWildCards #-}
module QR.BathroomStallsSpec where
import Test.Hspec
import Data.Maybe
import Data.Set
import QR.TripletSort
spec :: Spec
spec = do
describe "test getSleepNumber" $ do
it "test getBathroomStalls" $
fmap getResult [["5","5 6 8 4 3"],["3", "8 9 7"]] `shouldBe` [["OK"],["1"]]
| lihlcnkr/codejam | test/QR/BathroomStallsSpec.hs | apache-2.0 | 347 | 0 | 14 | 70 | 98 | 57 | 41 | 12 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Handler.Global where
import Import
menu :: Route Hermes -> Widget
menu current = [whamlet|
<ul>
<li>
^{createLink PostsR current "Posts"}
<li>
^{createLink (SPageR "idea") current "Idea"}
<li>
^{createLink (SPageR "roadmap") current "Roadmap"}
|]
createLink :: Route Hermes -> Route Hermes -> String -> Widget
createLink specific current label = [whamlet|
$if current == specific
<a .active href=@{specific}>#{label}
$else
<a href=@{specific}>#{label}
|]
emptyWidget :: Widget
emptyWidget = toWidget [hamlet|nu|]
frontIncludes :: Widget
frontIncludes = do
-- addStylesheet (StaticR style_css)
addScriptRemote "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
addScriptRemote "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"
addScript (StaticR js_sh_main_min_js)
addStylesheet (StaticR css_sh_bright_min_css)
frontWidget :: (Widget, Widget, Widget) -> Widget
frontWidget (menuWidget, sidebarWidget, contentWidget) = [whamlet|
^{frontIncludes}
^{recaptchaOptions (RecaptchaOptions (Just "clean") Nothing)}
<div id="header">
<div id="logo">
<a href="/">
<span class="orange">Hermes
<div id="menu">
^{menuWidget}
<div id="main">
<div id="content">
<div id="text">
^{contentWidget}
<div id="sidebar">
^{sidebarWidget}
<div id="footer">
<div id="left_footer">
<div id="right_footer">
--respect for the design creators! o/
<a href="http://www.realitysoftware.ca/services/website-development/design/">Web design</a> released by <a href="http://www.flash-gallery.org/">Flash Gallery</a
|]
specificLayout :: (Widget, Widget, Widget) -> GHandler Hermes Hermes RepHtml
specificLayout (a, b, c) = defaultLayout $ frontWidget (a, b, c)
getAdminR :: Handler RepHtml
getAdminR = do
posts <- runDB $ selectList [] [Desc PostCreated]
pages <- runDB $ selectList [] [Desc SPageTitle]
comments <- runDB $ selectList [] [Desc CommentCreated]
tags <- runDB $ selectList ([] :: [Filter Tag]) []
specificLayout (menu AdminR, emptyWidget, [whamlet|
<div>
<h2>Add content
<ul>
<li>
<a href=@{CreatePostR}>Create Post
<li>
<a href=@{CreateSPageR}>Create page
<h2>Change content
<div .admin-content-view>
<div>
<h2>Posts
$forall post <- posts
<div>
<a href=@{EditPostR $ entityKey post}>Edit
<a href=@{DeletePostR $ entityKey post}>Delete
#{postTitle (entityVal post)}
<div>
<h2>Pages
$forall page <- pages
<div>
<a href=@{EditSPageR $ entityKey page}>Edit
<a href=@{DeleteSPageR $ entityKey page}>Delete
#{sPageTitle (entityVal page)}
<div>
<h2>Comments
$forall comment <- comments
<div>
<a href=@{DeleteCommentR $ entityKey comment}>Delete
#{commentAuthor (entityVal comment)}
#{commentBody (entityVal comment)}
<div>
<h2>Tags
$forall tag <- tags
<div>
<a href=@{DeleteTagR $ entityKey tag}>Delete
#{tagName (entityVal tag)}
|])
test :: forall a. (Integral a) => a -> Int
test _ = 1
getDeleteCommentR :: CommentId -> Handler RepHtml
getDeleteCommentR commentId = do
_ <- runDB $ delete commentId
redirect $ AdminR
getDeleteTagR :: TagId -> Handler RepHtml
getDeleteTagR tagId = do
let aasd = approot :: Approot Hermes
y <- getYesod
case aasd of
ApprootStatic t -> setMessage $ toHtml t
ApprootMaster f -> setMessage $ toHtml $ f y
_ -> setMessage "a"
runDB $ deleteWhere [PostTagTag ==. tagId]
_ <- runDB $ delete tagId
redirect $ AdminR
getRssR :: Handler RepRss
getRssR = do
t <- liftIO getCurrentTime
posts <- runDB $ selectList [] [Desc PostCreated]
let entries = map (\p -> (FeedEntry (PostR $ postSlug $ entityVal p) (postCreated $ entityVal p) (postTitle $ entityVal p) (postBody $ entityVal p))) posts
rssFeed $ Feed "Hermes" RssR PostsR (toHtml ("An attempt to create a simple blog in Yesod" ::String)) "en" t entries
| kostas1/Hermes | Handler/Global.hs | bsd-2-clause | 4,692 | 0 | 17 | 1,475 | 736 | 375 | 361 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module Main where
import Util
import System.Exit ( exitFailure, exitSuccess )
import Test.HUnit
testTakeUntil = "takeUntil" ~: [
takeUntil (> 1) [] ~=? [],
takeUntil (> 1) [2] ~=? [2]]
main = do
cnt <- runTestTT (test testTakeUntil)
if errors cnt + failures cnt == 0
then exitSuccess
else exitFailure
| guillaume-nargeot/hpc-coveralls-testing-sandbox | test/Test.hs | bsd-3-clause | 430 | 0 | 10 | 94 | 124 | 69 | 55 | 14 | 2 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# OPTIONS_GHC -Wno-orphans #-}
module Verifier.SAW.Heapster.Permissions where
import Prelude hiding (pred)
import Numeric (showHex)
import Data.Char
import qualified Data.Text as Text
import Data.Word
import Data.Maybe
import Data.Either
import Data.List hiding (sort)
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NonEmpty
import Data.String
import Data.Proxy
import Data.Reflection
import Data.Functor.Constant
import qualified Data.BitVector.Sized as BV
import Data.BitVector.Sized (BV)
import Numeric.Natural
import GHC.TypeLits
import Data.Kind
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Control.Applicative hiding (empty)
import Control.Monad.Identity hiding (ap)
import Control.Monad.State hiding (ap)
import Control.Monad.Reader hiding (ap)
import Control.Lens hiding ((:>), Index, Empty, ix, op)
import Data.Binding.Hobbits hiding (sym)
import Data.Type.RList (append, memberElem, mapRAssign, mapToList, Eq1(..))
import qualified Data.Type.RList as RL
import Data.Binding.Hobbits.MonadBind as MB
import Data.Binding.Hobbits.NameMap (NameMap, NameAndElem(..))
import qualified Data.Binding.Hobbits.NameMap as NameMap
import Data.Binding.Hobbits.NameSet (NameSet, SomeName(..), toList,
SomeRAssign(..), namesListToNames,
nameSetIsSubsetOf)
import qualified Data.Binding.Hobbits.NameSet as NameSet
import Data.Parameterized.Context (Assignment, AssignView(..),
pattern Empty, viewAssign)
import qualified Data.Parameterized.Context as Ctx
import Data.Parameterized.BoolRepr
import Data.Parameterized.NatRepr
import Data.Parameterized.Pair
import Prettyprinter as PP
import Prettyprinter.Render.String (renderString)
import Lang.Crucible.Types
import Lang.Crucible.FunctionHandle
import Lang.Crucible.LLVM.DataLayout
import Lang.Crucible.LLVM.MemModel
import Lang.Crucible.LLVM.Bytes
import Lang.Crucible.CFG.Core
import Verifier.SAW.Term.Functor (ModuleName)
import Verifier.SAW.Module
import Verifier.SAW.SharedTerm hiding (Constant)
import Verifier.SAW.OpenTerm
import Verifier.SAW.Heapster.CruUtil
import GHC.Stack
import Debug.Trace
----------------------------------------------------------------------
-- * Data types and related types
----------------------------------------------------------------------
-- | The Haskell type of expression variables
type ExprVar = (Name :: CrucibleType -> Type)
-- | Crucible type for lifetimes; we give them a Crucible type so they can be
-- existentially bound in the same way as other Crucible objects
type LifetimeType = IntrinsicType "Lifetime" EmptyCtx
-- | Crucible type for read/write modalities; we give them a Crucible type so
-- they can be used as variables in recursive permission definitions
type RWModalityType = IntrinsicType "RWModality" EmptyCtx
-- | Crucible type for lists of expressions and permissions on them
type PermListType = IntrinsicType "PermList" EmptyCtx
-- | Crucible type for LLVM stack frame objects
type LLVMFrameType w = IntrinsicType "LLVMFrame" (EmptyCtx ::> BVType w)
-- | Crucible type for value permissions themselves
type ValuePermType a = IntrinsicType "Perm" (EmptyCtx ::> a)
-- | Crucible type for LLVM shapes
type LLVMShapeType w = IntrinsicType "LLVMShape" (EmptyCtx ::> BVType w)
-- | Crucible type for LLVM memory blocks
type LLVMBlockType w = IntrinsicType "LLVMBlock" (EmptyCtx ::> BVType w)
-- | Expressions that are considered "pure" for use in permissions. Note that
-- these are in a normal form, that makes them easier to analyze.
data PermExpr (a :: CrucibleType) where
-- | A variable of any type
PExpr_Var :: ExprVar a -> PermExpr a
-- | A unit literal
PExpr_Unit :: PermExpr UnitType
-- | A literal Boolean number
PExpr_Bool :: Bool -> PermExpr BoolType
-- | A literal natural number
PExpr_Nat :: Natural -> PermExpr NatType
-- | A literal string
PExpr_String :: String -> PermExpr (StringType Unicode)
-- | A bitvector expression is a linear expression in @N@ variables, i.e., sum
-- of constant times variable factors plus a constant
--
-- FIXME: make the offset a 'Natural'
PExpr_BV :: (1 <= w, KnownNat w) =>
[BVFactor w] -> BV w -> PermExpr (BVType w)
-- | A struct expression is an expression for each argument of the struct type
PExpr_Struct :: PermExprs (CtxToRList args) -> PermExpr (StructType args)
-- | The @always@ lifetime that is always current
PExpr_Always :: PermExpr LifetimeType
-- | An LLVM value that represents a word, i.e., whose region identifier is 0
PExpr_LLVMWord :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
PermExpr (LLVMPointerType w)
-- | An LLVM value built by adding an offset to an LLVM variable
PExpr_LLVMOffset :: (1 <= w, KnownNat w) =>
ExprVar (LLVMPointerType w) ->
PermExpr (BVType w) ->
PermExpr (LLVMPointerType w)
-- | A literal function pointer
PExpr_Fun :: FnHandle args ret -> PermExpr (FunctionHandleType args ret)
-- | An empty permission list
PExpr_PermListNil :: PermExpr PermListType
-- | A cons of an expression and a permission on it to a permission list
PExpr_PermListCons :: TypeRepr a -> PermExpr a -> ValuePerm a ->
PermExpr PermListType -> PermExpr PermListType
-- | A read/write modality
PExpr_RWModality :: RWModality -> PermExpr RWModalityType
-- | The empty / vacuously true shape
PExpr_EmptyShape :: PermExpr (LLVMShapeType w)
-- | A named shape along with arguments for it, with optional read/write and
-- lifetime modalities that are applied to the body of the shape
PExpr_NamedShape :: KnownNat w => Maybe (PermExpr RWModalityType) ->
Maybe (PermExpr LifetimeType) ->
NamedShape b args w -> PermExprs args ->
PermExpr (LLVMShapeType w)
-- | The equality shape, which describes some @N@ bytes of memory that are
-- equal to a given LLVM block
PExpr_EqShape :: PermExpr (BVType w) -> PermExpr (LLVMBlockType w) ->
PermExpr (LLVMShapeType w)
-- | A shape for a pointer to another memory block, i.e., a @memblock@
-- permission, with a given shape. This @memblock@ permission will have the
-- same read/write and lifetime modalities as the @memblock@ permission
-- containing this pointer shape, unless they are specifically overridden by
-- the pointer shape; i.e., we have that
--
-- > [l]memblock(rw,off,len,ptrsh(rw',l',sh)) =
-- > [l]memblock(rw,off,len,fieldsh([l']memblock(rw',0,len(sh),sh)))
--
-- where @rw'@ and/or @l'@ can be 'Nothing', in which case they default to
-- @rw@ and @l@, respectively.
PExpr_PtrShape :: Maybe (PermExpr RWModalityType) ->
Maybe (PermExpr LifetimeType) ->
PermExpr (LLVMShapeType w) -> PermExpr (LLVMShapeType w)
-- | A shape for a single field with a given permission
PExpr_FieldShape :: (1 <= w, KnownNat w) => LLVMFieldShape w ->
PermExpr (LLVMShapeType w)
-- | A shape for an array of @len@ individual regions of memory, called "array
-- cells"; the size of each cell in bytes is given by the array stride, which
-- must be known statically, and each cell has shape given by the supplied
-- LLVM shape, also called the cell shape
PExpr_ArrayShape :: (1 <= w, KnownNat w) =>
PermExpr (BVType w) -> Bytes ->
PermExpr (LLVMShapeType w) ->
PermExpr (LLVMShapeType w)
-- | A sequence of two shapes
PExpr_SeqShape :: PermExpr (LLVMShapeType w) -> PermExpr (LLVMShapeType w) ->
PermExpr (LLVMShapeType w)
-- | A disjunctive shape
PExpr_OrShape :: PermExpr (LLVMShapeType w) -> PermExpr (LLVMShapeType w) ->
PermExpr (LLVMShapeType w)
-- | An existential shape
PExpr_ExShape :: KnownRepr TypeRepr a =>
Binding a (PermExpr (LLVMShapeType w)) ->
PermExpr (LLVMShapeType w)
-- | A false shape
PExpr_FalseShape :: PermExpr (LLVMShapeType w)
-- | A permission as an expression
PExpr_ValPerm :: ValuePerm a -> PermExpr (ValuePermType a)
-- | A sequence of permission expressions
type PermExprs = RAssign PermExpr
{-
data PermExprs (as :: RList CrucibleType) where
PExprs_Nil :: PermExprs RNil
PExprs_Cons :: PermExprs as -> PermExpr a -> PermExprs (as :> a)
-}
-- | A bitvector variable, possibly multiplied by a constant
data BVFactor w where
-- | A variable of type @'BVType' w@ multiplied by a constant @i@, which
-- should be in the range @0 <= i < 2^w@
BVFactor :: (1 <= w, KnownNat w) => BV w -> ExprVar (BVType w) ->
BVFactor w
-- | Whether a permission allows reads or writes
data RWModality
= Write
| Read
deriving Eq
-- | The Haskell type of permission variables, that is, variables that range
-- over 'ValuePerm's
type PermVar (a :: CrucibleType) = Name (ValuePermType a)
-- | Ranges @[off,off+len)@ of bitvector values @x@ equal to @off+y@ for some
-- unsigned @y < len@. Note that ranges are allowed to wrap around 0, meaning
-- @off+y@ can overflow when testing whether @x@ is in the range. Thus, @x@ is
-- in range @[off,off+len)@ iff @x-off@ is unsigned less than @len@.
data BVRange w = BVRange { bvRangeOffset :: PermExpr (BVType w),
bvRangeLength :: PermExpr (BVType w) }
-- | Propositions about bitvectors
data BVProp w
-- | True iff the two expressions are equal
= BVProp_Eq (PermExpr (BVType w)) (PermExpr (BVType w))
-- | True iff the two expressions are not equal
| BVProp_Neq (PermExpr (BVType w)) (PermExpr (BVType w))
-- | True iff the first expression is unsigned less-than the second
| BVProp_ULt (PermExpr (BVType w)) (PermExpr (BVType w))
-- | True iff the first expression is unsigned @<=@ the second
| BVProp_ULeq (PermExpr (BVType w)) (PermExpr (BVType w))
-- | True iff the first expression is unsigned @<=@ the difference of the
-- second minus the third
| (1 <= w, KnownNat w) =>
BVProp_ULeq_Diff (PermExpr (BVType w)) (PermExpr (BVType w))
(PermExpr (BVType w))
-- | An atomic permission is a value permission that is not one of the compound
-- constructs in the 'ValuePerm' type; i.e., not a disjunction, existential,
-- recursive, or equals permission. These are the permissions that we can put
-- together with separating conjuctions.
data AtomicPerm (a :: CrucibleType) where
-- | Gives permissions to a single field pointed to by an LLVM pointer
Perm_LLVMField :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
LLVMFieldPerm w sz ->
AtomicPerm (LLVMPointerType w)
-- | Gives permissions to an array pointer to by an LLVM pointer
Perm_LLVMArray :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
AtomicPerm (LLVMPointerType w)
-- | Gives read or write access to a memory block, whose contents also give
-- some permissions
Perm_LLVMBlock :: (1 <= w, KnownNat w) => LLVMBlockPerm w ->
AtomicPerm (LLVMPointerType w)
-- | Says that we have permission to free the memory pointed at by this
-- pointer if we have write permission to @e@ words of size @w@
Perm_LLVMFree :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
AtomicPerm (LLVMPointerType w)
-- | Says that we known an LLVM value is a function pointer whose function has
-- the given permissions
Perm_LLVMFunPtr :: (1 <= w, KnownNat w) =>
TypeRepr (FunctionHandleType cargs ret) ->
ValuePerm (FunctionHandleType cargs ret) ->
AtomicPerm (LLVMPointerType w)
-- | Says that a memory block has a given shape
Perm_LLVMBlockShape :: (1 <= w, KnownNat w) => PermExpr (LLVMShapeType w) ->
AtomicPerm (LLVMBlockType w)
-- | Says we know an LLVM value is a pointer value, meaning that its block
-- value is non-zero. Note that this does not say the pointer is allocated.
Perm_IsLLVMPtr :: (1 <= w, KnownNat w) =>
AtomicPerm (LLVMPointerType w)
-- | A named conjunctive permission
Perm_NamedConj :: NameSortIsConj ns ~ 'True =>
NamedPermName ns args a -> PermExprs args ->
PermOffset a -> AtomicPerm a
-- | Permission to allocate (via @alloca@) on an LLVM stack frame, and
-- permission to delete that stack frame if we have exclusive permissions to
-- all the given LLVM pointer objects
Perm_LLVMFrame :: (1 <= w, KnownNat w) => LLVMFramePerm w ->
AtomicPerm (LLVMFrameType w)
-- | Ownership permission for a lifetime, including an assertion that it is
-- still current and permission to end that lifetime. A lifetime also
-- represents a permission "borrow" of some sub-permissions out of some larger
-- permissions. For example, we might borrow a portion of an array, or a
-- portion of a larger data structure. When the lifetime is ended, you have to
-- give back to sub-permissions to get back the larger permissions. Together,
-- these are a form of permission implication, so we write lifetime ownership
-- permissions as @lowned(Pin -o Pout)@. Intuitively, @Pin@ must be given back
-- before the lifetime is ended, and @Pout@ is returned afterwards.
-- Additionally, a lifetime may contain some other lifetimes, meaning the all
-- must end before the current one can be ended.
Perm_LOwned :: [PermExpr LifetimeType] ->
LOwnedPerms ps_in -> LOwnedPerms ps_out ->
AtomicPerm LifetimeType
-- | A simplified version of @lowned@, written just @lowned(ps)@, which
-- represents a lifetime where the permissions @ps@ have been borrowed and no
-- simplifications have been done. Semantically, this is logically equivalent
-- to @lowned ([l](R)ps -o ps)@, i.e., an @lowned@ permissions where the input
-- and output permissions are the same except that the input permissions are
-- the minimal possible versions of @ps@ in lifetime @l@ that could be given
-- back when @l@ is ended.
Perm_LOwnedSimple :: LOwnedPerms ps -> AtomicPerm LifetimeType
-- | Assertion that a lifetime is current during another lifetime
Perm_LCurrent :: PermExpr LifetimeType -> AtomicPerm LifetimeType
-- | Assertion that a lifetime has finished
Perm_LFinished :: AtomicPerm LifetimeType
-- | A struct permission = a sequence of permissions for each field
Perm_Struct :: RAssign ValuePerm (CtxToRList ctx) ->
AtomicPerm (StructType ctx)
-- | A function permission
Perm_Fun :: FunPerm ghosts (CtxToRList cargs) gouts ret ->
AtomicPerm (FunctionHandleType cargs ret)
-- | An LLVM permission that asserts a proposition about bitvectors
Perm_BVProp :: (1 <= w, KnownNat w) => BVProp w ->
AtomicPerm (LLVMPointerType w)
-- | A value permission is a permission to do something with a value, such as
-- use it as a pointer. This also includes a limited set of predicates on values
-- (you can think about this as "permission to assume the value satisfies this
-- predicate" if you like).
data ValuePerm (a :: CrucibleType) where
-- | Says that a value is equal to a known static expression
ValPerm_Eq :: PermExpr a -> ValuePerm a
-- | The disjunction of two value permissions
ValPerm_Or :: ValuePerm a -> ValuePerm a -> ValuePerm a
-- | An existential binding of a value in a value permission
--
-- FIXME: turn the 'KnownRepr' constraint into a normal 'TypeRepr' argument
ValPerm_Exists :: KnownRepr TypeRepr a =>
Binding a (ValuePerm b) ->
ValuePerm b
-- | A named permission
ValPerm_Named :: NamedPermName ns args a -> PermExprs args ->
PermOffset a -> ValuePerm a
-- | A permission variable plus an offset
ValPerm_Var :: PermVar a -> PermOffset a -> ValuePerm a
-- | A separating conjuction of 0 or more atomic permissions, where 0
-- permissions is the trivially true permission
ValPerm_Conj :: [AtomicPerm a] -> ValuePerm a
-- | The false value permission
ValPerm_False :: ValuePerm a
-- | A sequence of value permissions
{-
data ValuePerms as where
ValPerms_Nil :: ValuePerms RNil
ValPerms_Cons :: ValuePerms as -> ValuePerm a -> ValuePerms (as :> a)
-}
type ValuePerms = RAssign ValuePerm
-- | A binding of 0 or more variables, each with permissions
type MbValuePerms ctx = Mb ctx (ValuePerms ctx)
-- | A frame permission is a list of the pointers that have been allocated in
-- the frame and their corresponding allocation sizes in words of size
-- @w@. Write permissions of the given sizes are required to these pointers in
-- order to delete the frame.
type LLVMFramePerm w = [(PermExpr (LLVMPointerType w), Integer)]
-- | A permission for a pointer to a specific field of a given size
data LLVMFieldPerm w sz =
LLVMFieldPerm { llvmFieldRW :: PermExpr RWModalityType,
-- ^ Whether this is a read or write permission
llvmFieldLifetime :: PermExpr LifetimeType,
-- ^ The lifetime during which this field permission is active
llvmFieldOffset :: PermExpr (BVType w),
-- ^ The offset from the pointer in bytes of this field
llvmFieldContents :: ValuePerm (LLVMPointerType sz)
-- ^ The permissions we get for the value read from this field
}
-- | Helper type to represent byte offsets
--
-- > stride * ix + off
--
-- from the beginning of an array permission. Such an expression refers to
-- offset @off@, which must be a statically-known constant, in array cell @ix@.
data LLVMArrayIndex w =
LLVMArrayIndex { llvmArrayIndexCell :: PermExpr (BVType w),
llvmArrayIndexOffset :: BV w }
-- | A permission to an array of @len@ individual regions of memory, called
-- "array cells". The size of each cell in bytes is given by the array /stride/,
-- which must be known statically, and each cell has shape given by the supplied
-- LLVM shape, also called the cell shape.
data LLVMArrayPerm w =
LLVMArrayPerm { llvmArrayRW :: PermExpr RWModalityType,
-- ^ Whether this array gives read or write access
llvmArrayLifetime :: PermExpr LifetimeType,
-- ^ The lifetime during which this array permission is valid
llvmArrayOffset :: PermExpr (BVType w),
-- ^ The offset from the pointer in bytes of this array
llvmArrayLen :: PermExpr (BVType w),
-- ^ The number of array blocks
llvmArrayStride :: Bytes,
-- ^ The array stride in bytes
llvmArrayCellShape :: PermExpr (LLVMShapeType w),
-- ^ The shape of each cell in the array
llvmArrayBorrows :: [LLVMArrayBorrow w]
-- ^ Indices or index ranges that are missing from this array
}
-- | An index or range of indices that are missing from an array perm
--
-- FIXME: think about calling the just @LLVMArrayIndexSet@
data LLVMArrayBorrow w
= FieldBorrow (PermExpr (BVType w))
-- ^ Borrow a specific cell of an array permission
| RangeBorrow (BVRange w)
-- ^ Borrow a range of array cells, where each cell is 'llvmArrayStride'
-- bytes long
-- | An LLVM block permission is read or write access to the memory at a given
-- offset with a given length with a given shape
data LLVMBlockPerm w =
LLVMBlockPerm { llvmBlockRW :: PermExpr RWModalityType,
-- ^ Whether this is a read or write block permission
llvmBlockLifetime :: PermExpr LifetimeType,
-- ^ The lifetime during with this block permission is active
llvmBlockOffset :: PermExpr (BVType w),
-- ^ The offset of the block from the pointer in bytes
llvmBlockLen :: PermExpr (BVType w),
-- ^ The length of the block in bytes
llvmBlockShape :: PermExpr (LLVMShapeType w)
-- ^ The shape of the permissions in the block
}
-- | An LLVM shape for a single pointer field of unknown size
data LLVMFieldShape w =
forall sz. (1 <= sz, KnownNat sz) =>
LLVMFieldShape (ValuePerm (LLVMPointerType sz))
-- | A form of permission used in lifetime ownership permissions
data LOwnedPerm a where
LOwnedPermField :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
PermExpr (LLVMPointerType w) -> LLVMFieldPerm w sz ->
LOwnedPerm (LLVMPointerType w)
LOwnedPermArray :: (1 <= w, KnownNat w) => PermExpr (LLVMPointerType w) ->
LLVMArrayPerm w -> LOwnedPerm (LLVMPointerType w)
LOwnedPermBlock :: (1 <= w, KnownNat w) => PermExpr (LLVMPointerType w) ->
LLVMBlockPerm w -> LOwnedPerm (LLVMPointerType w)
-- | A sequence of 'LOwnedPerm's
type LOwnedPerms = RAssign LOwnedPerm
-- | A function permission is a set of input and output permissions inside a
-- context of ghost variables @ghosts@ with an additional context of output
-- ghost variables @gouts@
data FunPerm ghosts args gouts ret where
FunPerm :: CruCtx ghosts -> CruCtx args -> CruCtx gouts -> TypeRepr ret ->
MbValuePerms (ghosts :++: args) ->
MbValuePerms ((ghosts :++: args) :++: gouts :> ret) ->
FunPerm ghosts args gouts ret
-- | A function permission that existentially quantifies the ghost types
data SomeFunPerm args ret where
SomeFunPerm :: FunPerm ghosts args gouts ret -> SomeFunPerm args ret
-- | The different sorts of name, each of which comes with a 'Bool' flag
-- indicating whether the name can be used as an atomic permission. A recursive
-- sort also comes with a second flag indicating whether it is a reachability
-- permission.
data NameSort = DefinedSort Bool | OpaqueSort Bool | RecursiveSort Bool Bool
type DefinedSort = 'DefinedSort
type OpaqueSort = 'OpaqueSort
type RecursiveSort = 'RecursiveSort
-- | Test whether a name of a given 'NameSort' is conjoinable
type family NameSortIsConj (ns::NameSort) :: Bool where
NameSortIsConj (DefinedSort b) = b
NameSortIsConj (OpaqueSort b) = b
NameSortIsConj (RecursiveSort b _) = b
-- | Test whether a name of a given 'NameSort' is a reachability permission
type family IsReachabilityName (ns::NameSort) :: Bool where
IsReachabilityName (DefinedSort _) = 'False
IsReachabilityName (OpaqueSort _) = 'False
IsReachabilityName (RecursiveSort _ reach) = reach
-- | A singleton representation of 'NameSort'
data NameSortRepr (ns::NameSort) where
DefinedSortRepr :: BoolRepr b -> NameSortRepr (DefinedSort b)
OpaqueSortRepr :: BoolRepr b -> NameSortRepr (OpaqueSort b)
RecursiveSortRepr :: BoolRepr b -> BoolRepr reach ->
NameSortRepr (RecursiveSort b reach)
-- | A constraint that the last argument of a reachability permission is a
-- permission argument
data NameReachConstr ns args a where
NameReachConstr :: (IsReachabilityName ns ~ 'True) =>
NameReachConstr ns (args :> a) a
NameNonReachConstr :: (IsReachabilityName ns ~ 'False) =>
NameReachConstr ns args a
-- | A name for a named permission
data NamedPermName ns args a = NamedPermName {
namedPermNameName :: String,
namedPermNameType :: TypeRepr a,
namedPermNameArgs :: CruCtx args,
namedPermNameSort :: NameSortRepr ns,
namedPermNameReachConstr :: NameReachConstr ns args a
}
-- | An existentially quantified 'NamedPermName'
data SomeNamedPermName where
SomeNamedPermName :: NamedPermName ns args a -> SomeNamedPermName
-- | A named LLVM shape is a name, a list of arguments, and a body, where the
-- Boolean flag @b@ determines whether the shape can be unfolded or not
data NamedShape b args w = NamedShape {
namedShapeName :: String,
namedShapeArgs :: CruCtx args,
namedShapeBody :: NamedShapeBody b args w
}
data NamedShapeBody b args w where
-- | A defined shape is just a definition in terms of the arguments
DefinedShapeBody :: Mb args (PermExpr (LLVMShapeType w)) ->
NamedShapeBody 'True args w
-- | An opaque shape has no body, just a length and a translation to a type
OpaqueShapeBody :: Mb args (PermExpr (BVType w)) -> Ident ->
NamedShapeBody 'False args w
-- | A recursive shape body has a one-step unfolding to a shape, which can
-- refer to the shape itself via the last bound variable; it also has
-- identifiers for the type it is translated to, along with fold and unfold
-- functions for mapping to and from this type. The fold and unfold functions
-- can be undefined if we are in the process of defining this recusive shape.
RecShapeBody :: Mb (args :> LLVMShapeType w) (PermExpr (LLVMShapeType w)) ->
Ident -> Maybe (Ident, Ident) ->
NamedShapeBody 'True args w
-- | An offset that is added to a permission. Only makes sense for llvm
-- permissions (at least for now...?)
data PermOffset a where
NoPermOffset :: PermOffset a
-- | NOTE: the invariant is that the bitvector offset is non-zero
LLVMPermOffset :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
PermOffset (LLVMPointerType w)
-- | The semantics of a named permission, which can can either be an opaque
-- named permission, a recursive named permission, a defined permission, or an
-- LLVM shape
data NamedPerm ns args a where
NamedPerm_Opaque :: OpaquePerm b args a -> NamedPerm (OpaqueSort b) args a
NamedPerm_Rec :: RecPerm b reach args a ->
NamedPerm (RecursiveSort b reach) args a
NamedPerm_Defined :: DefinedPerm b args a -> NamedPerm (DefinedSort b) args a
-- | An opaque named permission is just a name and a SAW core type given by
-- identifier that it is translated to
data OpaquePerm b args a = OpaquePerm {
opaquePermName :: NamedPermName (OpaqueSort b) args a,
opaquePermTrans :: Ident
}
-- | The interpretation of a recursive permission as a reachability permission.
-- Reachability permissions are recursive permissions of the form
--
-- > reach<args,x> = eq(x) | p
--
-- where @reach@ occurs exactly once in @p@ in the form @reach<args,x>@ and @x@
-- does not occur at all in @p@. This means their interpretations look like a
-- list type, where the @eq(x)@ is the nil constructor and the @p@ is the
-- cons. To support the transitivity rule, we need an append function for these
-- lists, which is given by the transitivity method listed here, which has type
--
-- > trans : forall args (x y:A), t args x -> t args y -> t args y
--
-- where @args@ are the arguments and @A@ is the translation of type @a@ (which
-- may correspond to 0 or more arguments)
data ReachMethods reach args a where
ReachMethods :: {
reachMethodTrans :: Ident
} -> ReachMethods (args :> a) a 'True
NoReachMethods :: ReachMethods args a 'False
-- | A recursive permission is a disjunction of 1 or more permissions, each of
-- which can contain the recursive permission itself. NOTE: it is an error to
-- have an empty list of cases. A recursive permission is also associated with a
-- SAW datatype, given by a SAW 'Ident', and each disjunctive permission case is
-- associated with a constructor of that datatype. The @b@ flag indicates
-- whether this recursive permission can be used as an atomic permission, which
-- should be 'True' iff all of the cases are conjunctive permissions as in
-- 'isConjPerm'. If the recursive permission is a reachability permission, then
-- it also has a 'ReachMethods' structure.
data RecPerm b reach args a = RecPerm {
recPermName :: NamedPermName (RecursiveSort b reach) args a,
recPermTransType :: Ident,
recPermFoldFun :: Ident,
recPermUnfoldFun :: Ident,
recPermReachMethods :: ReachMethods args a reach,
recPermCases :: [Mb args (ValuePerm a)]
}
-- | A defined permission is a name and a permission to which it is
-- equivalent. The @b@ flag indicates whether this permission can be used as an
-- atomic permission, which should be 'True' iff the associated permission is a
-- conjunctive permission as in 'isConjPerm'.
data DefinedPerm b args a = DefinedPerm {
definedPermName :: NamedPermName (DefinedSort b) args a,
definedPermDef :: Mb args (ValuePerm a)
}
-- | A pair of a variable and its permission; we give it its own datatype to
-- make certain typeclass instances (like pretty-printing) specific to it
data VarAndPerm a = VarAndPerm (ExprVar a) (ValuePerm a)
-- | A list of "distinguished" permissions to named variables
-- FIXME: just call these VarsAndPerms or something like that...
type DistPerms = RAssign VarAndPerm
-- | A special-purpose 'DistPerms' that specifies a list of permissions needed
-- to prove that a lifetime is current
data LifetimeCurrentPerms ps_l where
-- | The @always@ lifetime needs no proof that it is current
AlwaysCurrentPerms :: LifetimeCurrentPerms RNil
-- | A variable @l@ that is @lowned@ is current, requiring perms
--
-- > l:lowned[ls](ps_in -o ps_out)
LOwnedCurrentPerms :: ExprVar LifetimeType -> [PermExpr LifetimeType] ->
LOwnedPerms ps_in -> LOwnedPerms ps_out ->
LifetimeCurrentPerms (RNil :> LifetimeType)
-- | A variable @l@ with a simple @lowned@ perm is also current
LOwnedSimpleCurrentPerms :: ExprVar LifetimeType -> LOwnedPerms ps ->
LifetimeCurrentPerms (RNil :> LifetimeType)
-- | A variable @l@ that is @lcurrent@ during another lifetime @l'@ is
-- current, i.e., if @ps@ ensure @l'@ is current then we need perms
--
-- > ps, l:lcurrent(l')
CurrentTransPerms :: LifetimeCurrentPerms ps_l -> ExprVar LifetimeType ->
LifetimeCurrentPerms (ps_l :> LifetimeType)
-- | A lifetime functor is a function from a lifetime plus a set of 0 or more
-- rwmodalities to a permission that satisfies a number of properties discussed
-- in Issue #62 (FIXME: copy those here). Rather than try to enforce these
-- properties, we syntactically restrict lifetime functors to one of a few forms
-- that are guaranteed to satisfy the properties. The @args@ type lists all
-- arguments (which should all be rwmodalities) other than the lifetime
-- argument.
data LifetimeFunctor args a where
-- | The functor @\(l,rw) -> [l]ptr((rw,off) |-> p)@
LTFunctorField :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
PermExpr (BVType w) -> ValuePerm (LLVMPointerType sz) ->
LifetimeFunctor (RNil :> RWModalityType) (LLVMPointerType w)
-- | The functor @\(l,rw) -> [l]array(rw,off,<len,*stride,sh,bs)@
LTFunctorArray :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
PermExpr (BVType w) -> Bytes ->
PermExpr (LLVMShapeType w) -> [LLVMArrayBorrow w] ->
LifetimeFunctor (RNil :> RWModalityType) (LLVMPointerType w)
-- | The functor @\(l,rw) -> [l]memblock(rw,off,len,sh)
LTFunctorBlock :: (1 <= w, KnownNat w) =>
PermExpr (BVType w) -> PermExpr (BVType w) ->
PermExpr (LLVMShapeType w) ->
LifetimeFunctor (RNil :> RWModalityType) (LLVMPointerType w)
-- FIXME: add functors for arrays and named permissions
-- | An 'LLVMBlockPerm' with a proof that its type is valid
data SomeLLVMBlockPerm a where
SomeLLVMBlockPerm :: (1 <= w, KnownNat w) => LLVMBlockPerm w ->
SomeLLVMBlockPerm (LLVMPointerType w)
-- | A block permission in a binding at some unknown type
data SomeBindingLLVMBlockPerm w =
forall a. SomeBindingLLVMBlockPerm (Binding a (LLVMBlockPerm w))
-- | A tagged union shape is a shape of the form
--
-- > sh1 orsh sh2 orsh ... orsh shn
--
-- where each @shi@ is equivalent up to associativity of the @;@ operator to a
-- shape of the form
--
-- > fieldsh(eq(llvmword(bvi)));shi'
--
-- That is, each disjunct of the shape starts with an equality permission that
-- determines which disjunct should be used. These shapes are represented as a
-- list of the disjuncts, which are tagged with the bitvector values @bvi@ used
-- in the equality permission.
data TaggedUnionShape w sz
= TaggedUnionShape (NonEmpty (BV sz, PermExpr (LLVMShapeType w)))
-- | A 'TaggedUnionShape' with existentially quantified tag size
data SomeTaggedUnionShape w
= forall sz. (1 <= sz, KnownNat sz) =>
SomeTaggedUnionShape (TaggedUnionShape w sz)
-- | Like a substitution but assigns variables instead of arbitrary expressions
-- to bound variables
data PermVarSubst (ctx :: RList CrucibleType) where
PermVarSubst_Nil :: PermVarSubst RNil
PermVarSubst_Cons :: PermVarSubst ctx -> Name tp -> PermVarSubst (ctx :> tp)
-- | An entry in a permission environment that associates a permission and
-- corresponding SAW identifier with a Crucible function handle
data PermEnvFunEntry where
PermEnvFunEntry :: args ~ CtxToRList cargs => FnHandle cargs ret ->
FunPerm ghosts args gouts ret -> Ident ->
PermEnvFunEntry
-- | An existentially quantified 'NamedPerm'
data SomeNamedPerm where
SomeNamedPerm :: NamedPerm ns args a -> SomeNamedPerm
-- | An existentially quantified LLVM shape with arguments
data SomeNamedShape where
SomeNamedShape :: (1 <= w, KnownNat w) => NamedShape b args w ->
SomeNamedShape
-- | An entry in a permission environment that associates a 'GlobalSymbol' with
-- a permission and a translation of that permission
data PermEnvGlobalEntry where
PermEnvGlobalEntry :: (1 <= w, KnownNat w) => GlobalSymbol ->
ValuePerm (LLVMPointerType w) -> [OpenTerm] ->
PermEnvGlobalEntry
-- | The different sorts hints for blocks
data BlockHintSort args where
-- | This hint specifies the ghost args and input permissions for a block
BlockEntryHintSort ::
CruCtx top_args -> CruCtx ghosts ->
MbValuePerms ((top_args :++: CtxToRList args) :++: ghosts) ->
BlockHintSort args
-- | This hint says that the input perms for a block should be generalized
GenPermsHintSort :: BlockHintSort args
-- | This hint says that a block should be a join point
JoinPointHintSort :: BlockHintSort args
-- | A hint for a block
data BlockHint blocks init ret args where
BlockHint :: FnHandle init ret -> Assignment CtxRepr blocks ->
BlockID blocks args -> BlockHintSort args ->
BlockHint blocks init ret args
-- | A "hint" from the user for type-checking
data Hint where
Hint_Block :: BlockHint blocks init ret args -> Hint
-- | A permission environment that maps function names, permission names, and
-- 'GlobalSymbols' to their respective permission structures
data PermEnv = PermEnv {
permEnvFunPerms :: [PermEnvFunEntry],
permEnvNamedPerms :: [SomeNamedPerm],
permEnvNamedShapes :: [SomeNamedShape],
permEnvGlobalSyms :: [PermEnvGlobalEntry],
permEnvHints :: [Hint]
}
----------------------------------------------------------------------
-- * Template Haskell–generated instances
----------------------------------------------------------------------
instance NuMatchingAny1 PermExpr where
nuMatchingAny1Proof = nuMatchingProof
instance NuMatchingAny1 ValuePerm where
nuMatchingAny1Proof = nuMatchingProof
instance NuMatchingAny1 VarAndPerm where
nuMatchingAny1Proof = nuMatchingProof
instance NuMatchingAny1 LOwnedPerm where
nuMatchingAny1Proof = nuMatchingProof
instance NuMatchingAny1 DistPerms where
nuMatchingAny1Proof = nuMatchingProof
$(mkNuMatching [t| forall a . BVFactor a |])
$(mkNuMatching [t| RWModality |])
$(mkNuMatching [t| forall b args w. NamedShapeBody b args w |])
$(mkNuMatching [t| forall b args w. NamedShape b args w |])
$(mkNuMatching [t| forall w . LLVMFieldShape w |])
$(mkNuMatching [t| forall a . PermExpr a |])
$(mkNuMatching [t| forall w. BVRange w |])
$(mkNuMatching [t| forall w. BVProp w |])
$(mkNuMatching [t| forall w sz . LLVMFieldPerm w sz |])
$(mkNuMatching [t| forall w . LLVMArrayBorrow w |])
$(mkNuMatching [t| forall w . LLVMArrayPerm w |])
$(mkNuMatching [t| forall w . LLVMBlockPerm w |])
$(mkNuMatching [t| forall ns. NameSortRepr ns |])
$(mkNuMatching [t| forall ns args a. NameReachConstr ns args a |])
$(mkNuMatching [t| forall ns args a. NamedPermName ns args a |])
$(mkNuMatching [t| forall a. PermOffset a |])
$(mkNuMatching [t| forall w . LOwnedPerm w |])
$(mkNuMatching [t| forall ghosts args gouts ret. FunPerm ghosts args gouts ret |])
$(mkNuMatching [t| forall a . AtomicPerm a |])
$(mkNuMatching [t| forall a . ValuePerm a |])
-- $(mkNuMatching [t| forall as. ValuePerms as |])
$(mkNuMatching [t| forall a . VarAndPerm a |])
$(mkNuMatching [t| forall w . LLVMArrayIndex w |])
$(mkNuMatching [t| forall args ret. SomeFunPerm args ret |])
$(mkNuMatching [t| SomeNamedPermName |])
$(mkNuMatching [t| forall b args a. OpaquePerm b args a |])
$(mkNuMatching [t| forall args a reach. ReachMethods args a reach |])
$(mkNuMatching [t| forall b reach args a. RecPerm b reach args a |])
$(mkNuMatching [t| forall b args a. DefinedPerm b args a |])
$(mkNuMatching [t| forall ns args a. NamedPerm ns args a |])
$(mkNuMatching [t| forall args a. LifetimeFunctor args a |])
$(mkNuMatching [t| forall ps. LifetimeCurrentPerms ps |])
$(mkNuMatching [t| forall a. SomeLLVMBlockPerm a |])
$(mkNuMatching [t| forall w. SomeBindingLLVMBlockPerm w |])
$(mkNuMatching [t| forall w sz. TaggedUnionShape w sz |])
$(mkNuMatching [t| forall w. SomeTaggedUnionShape w |])
$(mkNuMatching [t| forall ctx. PermVarSubst ctx |])
$(mkNuMatching [t| PermEnvFunEntry |])
$(mkNuMatching [t| SomeNamedPerm |])
$(mkNuMatching [t| SomeNamedShape |])
$(mkNuMatching [t| PermEnvGlobalEntry |])
$(mkNuMatching [t| forall args. BlockHintSort args |])
$(mkNuMatching [t| forall blocks init ret args.
BlockHint blocks init ret args |])
$(mkNuMatching [t| Hint |])
$(mkNuMatching [t| PermEnv |])
-- NOTE: this instance would require a NuMatching instance for NameMap...
-- $(mkNuMatching [t| forall ps. PermSet ps |])
----------------------------------------------------------------------
-- * Utility Functions and Definitions
----------------------------------------------------------------------
-- | Call 'RL.split' twice to split a nested appended 'RAssign' into three
rlSplit3 :: prx1 ctx1 -> RAssign prx2 ctx2 -> RAssign prx3 ctx3 ->
RAssign f ((ctx1 :++: ctx2) :++: ctx3) ->
(RAssign f ctx1, RAssign f ctx2, RAssign f ctx3)
rlSplit3 (ctx1 :: prx1 ctx1) (ctx2 :: RAssign prx2 ctx2) ctx3 fs123 =
let (fs12, fs3) = RL.split (Proxy :: Proxy (ctx1 :++: ctx2)) ctx3 fs123 in
let (fs1, fs2) = RL.split ctx1 ctx2 fs12 in
(fs1, fs2, fs3)
-- | Take the ceiling of a division
ceil_div :: Integral a => a -> a -> a
ceil_div a b = (a + b - fromInteger 1) `div` b
-- | Replace the body of a binding with a constant
mbConst :: a -> Mb ctx b -> Mb ctx a
mbConst a = fmap $ const a
-- | Get the first element of a pair in a binding
mbFst :: NuMatching a => NuMatching b => Mb ctx (a,b) -> Mb ctx a
mbFst = mbMapCl $(mkClosed [| fst |])
-- | Get the second element of a pair in a binding
mbSnd :: NuMatching a => NuMatching b => Mb ctx (a,b) -> Mb ctx b
mbSnd = mbMapCl $(mkClosed [| snd |])
-- | Get the first element of a triple in a binding
mbFst3 :: NuMatching a => NuMatching b => NuMatching c =>
Mb ctx (a,b,c) -> Mb ctx a
mbFst3 = mbMapCl $(mkClosed [| \(a,_,_) -> a |])
-- | Get the first element of a triple in a binding
mbSnd3 :: NuMatching a => NuMatching b => NuMatching c =>
Mb ctx (a,b,c) -> Mb ctx b
mbSnd3 = mbMapCl $(mkClosed [| \(_,b,_) -> b |])
-- | Get the first element of a triple in a binding
mbThd3 :: NuMatching a => NuMatching b => NuMatching c =>
Mb ctx (a,b,c) -> Mb ctx c
mbThd3 = mbMapCl $(mkClosed [| \(_,_,c) -> c |])
-- | FIXME: put this somewhere more appropriate
subNat' :: NatRepr m -> NatRepr n -> Maybe (NatRepr (m-n))
subNat' m n
| Left leq <- decideLeq n m =
Just $ withLeqProof leq $ subNat m n
subNat' _ _ = Nothing
-- | Delete the nth element of a list
deleteNth :: Int -> [a] -> [a]
deleteNth i xs | i >= length xs = error "deleteNth"
deleteNth i xs = take i xs ++ drop (i+1) xs
-- | Apply 'deleteNth' inside a name-binding
mbDeleteNth :: NuMatching a => Int -> Mb ctx [a] -> Mb ctx [a]
mbDeleteNth i = mbMapCl ($(mkClosed [| deleteNth |]) `clApply` toClosed i)
-- | Replace the nth element of a list
replaceNth :: Int -> a -> [a] -> [a]
replaceNth i _ xs | i >= length xs = error "replaceNth"
replaceNth i x xs = take i xs ++ x : drop (i+1) xs
-- | Insert an element at the nth location in a list
insertNth :: Int -> a -> [a] -> [a]
insertNth i x xs = take i xs ++ x : drop i xs
-- | Find the @n@th element of a list in a binding
mbNth :: NuMatching a => Int -> Mb ctx [a] -> Mb ctx a
mbNth i = mbMapCl ($(mkClosed [| flip (!!) |]) `clApply` toClosed i)
-- | Find all elements of list @l@ where @f@ returns a value and return that
-- value plus its index into @l@
findMaybeIndices :: (a -> Maybe b) -> [a] -> [(Int, b)]
findMaybeIndices f l = catMaybes $ zipWith (\i a -> (i,) <$> f a) [0 ..] l
-- | Find the index of the first element of a list that returns the maximal
-- positive value from the supplied ranking function, or return 'Nothing' if all
-- elements have non-positive rank
findBestIndex :: (a -> Int) -> [a] -> Maybe Int
findBestIndex rank_f l =
fst $ foldl (\(best_ix,best_rank) (ix,rank) ->
if rank > best_rank then (Just ix, rank) else
(best_ix,best_rank))
(Nothing, 0) (zipWith (\i a -> (i,rank_f a)) [0 ..] l)
-- | Combine all elements of a list like 'foldr1' unless the list is empty, in
-- which case return the default case
foldr1WithDefault :: (a -> a -> a) -> a -> [a] -> a
foldr1WithDefault _ def [] = def
foldr1WithDefault _ _ [a] = a
foldr1WithDefault f def (a:as) = f a $ foldr1WithDefault f def as
-- | Map a function across a list and then call 'foldr1WithDefault'. This is a
-- form of map-reduce where the default is returned as a special case for the
-- empty list.
foldMapWithDefault :: (b -> b -> b) -> b -> (a -> b) -> [a] -> b
foldMapWithDefault comb def f l = foldr1WithDefault comb def $ map f l
-- | Build a 'NameSet' from a sequence of names and a list of 'Bool' flags
nameSetFromFlags :: RAssign Name (ctx :: RList k) -> [Bool] -> NameSet k
nameSetFromFlags ns flags =
NameSet.fromList $
mapMaybe (\(n,flag) -> if flag then Just n else Nothing) $
zip (RL.mapToList SomeName ns) flags
-- | A flag indicating whether an equality test has unfolded a
-- recursively-defined name on one side of the equation already
data RecurseFlag = RecLeft | RecRight | RecNone
deriving (Eq, Show, Read)
-- | Make a "coq-safe" identifier from a string that might contain
-- non-identifier characters, where we use the SAW core notion of identifier
-- characters as letters, digits, underscore and primes. Any disallowed
-- character is mapped to the string @__xNN@, where @NN@ is the hexadecimal code
-- for that character. Additionally, a SAW core identifier is not allowed to
-- start with a prime, so a leading underscore is added in such a case.
mkSafeIdent :: ModuleName -> String -> Ident
mkSafeIdent _ [] = fromString "_"
mkSafeIdent mnm nm =
let is_safe_char c = isAlphaNum c || c == '_' || c == '\'' in
mkIdent mnm $ Text.pack $
(if nm!!0 == '\'' then ('_' :) else id) $
concatMap
(\c -> if is_safe_char c then [c] else
"__x" ++ showHex (ord c) "")
nm
-- | Insert a definition into a SAW core module
scInsertDef :: SharedContext -> ModuleName -> Ident -> Term -> Term -> IO ()
scInsertDef sc mnm ident def_tp def_tm =
do t <- scConstant' sc (ModuleIdentifier ident) def_tm def_tp
scRegisterGlobal sc ident t
scModifyModule sc mnm $ \m ->
insDef m $ Def { defIdent = ident,
defQualifier = NoQualifier,
defType = def_tp,
defBody = Just def_tm }
----------------------------------------------------------------------
-- * Pretty-printing
----------------------------------------------------------------------
-- | A special-purpose type used to indicate debugging level
data DebugLevel = DebugLevel Int deriving (Eq,Ord)
-- | The debug level for no debugging
noDebugLevel :: DebugLevel
noDebugLevel = DebugLevel 0
-- | The debug level to enable tracing
traceDebugLevel :: DebugLevel
traceDebugLevel = DebugLevel 1
-- | The debug level to enable more verbose tracing
verboseDebugLevel :: DebugLevel
verboseDebugLevel = DebugLevel 2
-- | Output a debug statement to @stderr@ using 'trace' if the second
-- 'DebugLevel' is at least the first, i.e., the first is the required level for
-- emitting this trace and the second is the current level
debugTrace :: DebugLevel -> DebugLevel -> String -> a -> a
debugTrace req dlevel | dlevel >= req = trace
debugTrace _ _ = const id
-- | Call 'debugTrace' at 'traceDebugLevel'
debugTraceTraceLvl :: DebugLevel -> String -> a -> a
debugTraceTraceLvl = debugTrace traceDebugLevel
-- | Like 'debugTrace' but take in a 'Doc' instead of a 'String'
debugTracePretty :: DebugLevel -> DebugLevel -> Doc ann -> a -> a
debugTracePretty req dlevel d a = debugTrace req dlevel (renderDoc d) a
-- | The constant string functor
newtype StringF a = StringF { unStringF :: String }
-- | Convert a type to a base name for printing variables of that type
typeBaseName :: TypeRepr a -> String
typeBaseName UnitRepr = "u"
typeBaseName BoolRepr = "b"
typeBaseName NatRepr = "n"
typeBaseName (BVRepr _) = "bv"
typeBaseName (LLVMPointerRepr _) = "ptr"
typeBaseName (LLVMBlockRepr _) = "blk"
typeBaseName (LLVMFrameRepr _) = "frm"
typeBaseName LifetimeRepr = "l"
typeBaseName RWModalityRepr = "rw"
typeBaseName (ValuePermRepr _) = "perm"
typeBaseName (LLVMShapeRepr _) = "shape"
typeBaseName (StringRepr _) = "str"
typeBaseName (FunctionHandleRepr _ _) = "fn"
typeBaseName (StructRepr _) = "strct"
typeBaseName _ = "x"
-- | A 'PPInfo' maps bound 'Name's to strings used for printing, with the
-- invariant that each 'Name' is mapped to a different string. This invariant is
-- maintained by always assigning each 'Name' to a "base string", which is often
-- determined by the Crucible type of the 'Name', followed by a unique
-- integer. Note that this means no base name should end with an integer. To
-- ensure the uniqueness of these integers, the 'PPInfo' structure tracks the
-- next integer to be used for each base string.
data PPInfo =
PPInfo { ppExprNames :: NameMap (StringF :: CrucibleType -> Type),
ppBaseNextInt :: Map String Int }
-- | Build an empty 'PPInfo' structure
emptyPPInfo :: PPInfo
emptyPPInfo = PPInfo NameMap.empty Map.empty
-- | Add an expression variable to a 'PPInfo' with the given base name
ppInfoAddExprName :: String -> ExprVar a -> PPInfo -> PPInfo
ppInfoAddExprName base _ _
| length base == 0 || isDigit (last base) =
error ("ppInfoAddExprName: invalid base name: " ++ base)
ppInfoAddExprName base x (PPInfo { .. }) =
let (i',str) =
case Map.lookup base ppBaseNextInt of
Just i -> (i+1, base ++ show i)
Nothing -> (1, base) in
PPInfo { ppExprNames = NameMap.insert x (StringF str) ppExprNames,
ppBaseNextInt = Map.insert base i' ppBaseNextInt }
-- | Add a sequence of variables to a 'PPInfo' with the given base name
ppInfoAddExprNames :: String -> RAssign Name (tps :: RList CrucibleType) ->
PPInfo -> PPInfo
ppInfoAddExprNames _ MNil info = info
ppInfoAddExprNames base (ns :>: n) info =
ppInfoAddExprNames base ns $ ppInfoAddExprName base n info
-- | Add a sequence of variables to a 'PPInfo' using their 'typeBaseName's
ppInfoAddTypedExprNames :: CruCtx tps -> RAssign Name tps -> PPInfo -> PPInfo
ppInfoAddTypedExprNames _ MNil info = info
ppInfoAddTypedExprNames (CruCtxCons tps tp) (ns :>: n) info =
ppInfoAddTypedExprNames tps ns $ ppInfoAddExprName (typeBaseName tp) n info
type PermPPM = Reader PPInfo
instance NuMatching (Doc ann) where
nuMatchingProof = unsafeMbTypeRepr
instance Closable (Doc ann) where
toClosed = unsafeClose
instance Liftable (Doc ann) where
mbLift = unClosed . mbLift . fmap toClosed
class PermPretty a where
permPrettyM :: a -> PermPPM (Doc ann)
class PermPrettyF f where
permPrettyMF :: f a -> PermPPM (Doc ann)
permPretty :: PermPretty a => PPInfo -> a -> Doc ann
permPretty info a = runReader (permPrettyM a) info
renderDoc :: Doc ann -> String
renderDoc doc = renderString (layoutPretty opts doc)
where opts = LayoutOptions (AvailablePerLine 80 0.8)
permPrettyString :: PermPretty a => PPInfo -> a -> String
permPrettyString info a = renderDoc $ permPretty info a
tracePretty :: Doc ann -> a -> a
tracePretty doc = trace (renderDoc doc)
-- | Pretty-print a comma-separated list
ppCommaSep :: [Doc ann] -> Doc ann
ppCommaSep ds =
PP.group $ align $ fillSep $ map PP.group $ PP.punctuate comma ds
-- | Pretty-print a comma-separated list using 'fillSep' enclosed inside either
-- parentheses (if the supplied flag is 'True') or brackets (if it is 'False')
ppEncList :: Bool -> [Doc ann] -> Doc ann
ppEncList flag ds =
(if flag then parens else brackets) $ ppCommaSep ds
instance (PermPretty a, PermPretty b) => PermPretty (a,b) where
permPrettyM (a,b) = ppEncList True <$> sequence [permPrettyM a, permPrettyM b]
instance (PermPretty a, PermPretty b, PermPretty c) => PermPretty (a,b,c) where
permPrettyM (a,b,c) =
ppEncList True <$> sequence [permPrettyM a, permPrettyM b, permPrettyM c]
instance PermPretty a => PermPretty [a] where
permPrettyM as = ppEncList False <$> mapM permPrettyM as
instance PermPretty a => PermPretty (Maybe a) where
permPrettyM Nothing = return $ pretty "Nothing"
permPrettyM (Just a) = do
a_pp <- permPrettyM a
return (pretty "Just" <+> a_pp)
instance PermPrettyF f => PermPretty (Some f) where
permPrettyM (Some x) = permPrettyMF x
instance PermPretty (ExprVar a) where
permPrettyM x =
do maybe_str <- NameMap.lookup x <$> ppExprNames <$> ask
case maybe_str of
Just (StringF str) -> return $ pretty str
Nothing -> return $ pretty (show x)
instance PermPrettyF (Name :: CrucibleType -> Type) where
permPrettyMF = permPrettyM
instance PermPretty (SomeName CrucibleType) where
permPrettyM (SomeName x) = permPrettyM x
instance PermPrettyF f => PermPretty (RAssign f ctx) where
permPrettyM xs =
ppCommaSep <$> sequence (RL.mapToList permPrettyMF xs)
instance PermPrettyF f => PermPrettyF (RAssign f) where
permPrettyMF xs = permPrettyM xs
instance PermPretty (TypeRepr a) where
permPrettyM UnitRepr = return $ pretty "unit"
permPrettyM BoolRepr = return $ pretty "bool"
permPrettyM NatRepr = return $ pretty "nat"
permPrettyM (BVRepr w) = return (pretty "bv" <+> pretty (intValue w))
permPrettyM (LLVMPointerRepr w) =
return (pretty "llvmptr" <+> pretty (intValue w))
permPrettyM (LLVMFrameRepr w) =
return (pretty "llvmframe" <+> pretty (intValue w))
permPrettyM LifetimeRepr = return $ pretty "lifetime"
permPrettyM RWModalityRepr = return $ pretty "rwmodality"
permPrettyM (LLVMShapeRepr w) =
return (pretty "llvmshape" <+> pretty (intValue w))
permPrettyM (LLVMBlockRepr w) =
return (pretty "llvmblock" <+> pretty (intValue w))
permPrettyM PermListRepr = return $ pretty "permlist"
permPrettyM (StructRepr flds) =
(pretty "struct" <+>) <$> parens <$> permPrettyM (assignToRList flds)
permPrettyM (ValuePermRepr tp) = (pretty "perm" <+>) <$> permPrettyM tp
permPrettyM tp =
return (pretty "not-yet-printable type" <+> parens (pretty tp))
instance PermPrettyF TypeRepr where
permPrettyMF = permPrettyM
instance PermPretty (CruCtx ctx) where
permPrettyM = permPrettyM . cruCtxToTypes
-- | A pair of a variable and its 'CrucibleType', for pretty-printing
data VarAndType a = VarAndType (ExprVar a) (TypeRepr a)
instance PermPretty (VarAndType a) where
permPrettyM (VarAndType x tp) =
do x_pp <- permPrettyM x
tp_pp <- permPrettyM tp
return (x_pp <> colon <> tp_pp)
instance PermPrettyF VarAndType where
permPrettyMF = permPrettyM
permPrettyExprMb :: PermPretty a =>
(RAssign (Constant (Doc ann)) ctx -> PermPPM (Doc ann) -> PermPPM (Doc ann)) ->
Mb (ctx :: RList CrucibleType) a -> PermPPM (Doc ann)
permPrettyExprMb f mb =
fmap mbLift $ strongMbM $ flip nuMultiWithElim1 mb $ \ns a ->
local (ppInfoAddExprNames "z" ns) $
do docs <- traverseRAssign (\n -> Constant <$> permPrettyM n) ns
PP.group <$> hang 2 <$> f docs (permPrettyM a)
instance PermPretty a => PermPretty (Mb (ctx :: RList CrucibleType) a) where
permPrettyM =
permPrettyExprMb $ \docs ppm ->
(\pp -> ppEncList True (RL.toList docs) <> dot <> line <> pp) <$> ppm
instance PermPretty Integer where
permPrettyM = return . pretty
----------------------------------------------------------------------
-- * Expressions for Permissions
----------------------------------------------------------------------
-- | The object-level representation of 'LifetimeType'
lifetimeTypeRepr :: TypeRepr LifetimeType
lifetimeTypeRepr = knownRepr
-- | Pattern for building/destructing lifetime types
pattern LifetimeRepr :: () => (ty ~ LifetimeType) => TypeRepr ty
pattern LifetimeRepr <-
IntrinsicRepr (testEquality (knownSymbol :: SymbolRepr "Lifetime") ->
Just Refl)
Empty
where LifetimeRepr = IntrinsicRepr knownSymbol Empty
-- | A lifetime is an expression of type 'LifetimeType'
--type Lifetime = PermExpr LifetimeType
-- | The object-level representation of 'RWModalityType'
rwModalityTypeRepr :: TypeRepr RWModalityType
rwModalityTypeRepr = knownRepr
-- | Pattern for building/destructing RWModality types
pattern RWModalityRepr :: () => (ty ~ RWModalityType) => TypeRepr ty
pattern RWModalityRepr <-
IntrinsicRepr (testEquality (knownSymbol :: SymbolRepr "RWModality") ->
Just Refl)
Empty
where RWModalityRepr = IntrinsicRepr knownSymbol Empty
-- | Pattern for building/desctructing permission list types
pattern PermListRepr :: () => ty ~ PermListType => TypeRepr ty
pattern PermListRepr <-
IntrinsicRepr (testEquality (knownSymbol :: SymbolRepr "PermList") ->
Just Refl) Empty
where
PermListRepr = IntrinsicRepr knownSymbol Empty
-- | Pattern for building/desctructing LLVM frame types
pattern LLVMFrameRepr :: () => (1 <= w, ty ~ LLVMFrameType w) =>
NatRepr w -> TypeRepr ty
pattern LLVMFrameRepr w <-
IntrinsicRepr (testEquality (knownSymbol :: SymbolRepr "LLVMFrame") ->
Just Refl)
(viewAssign -> AssignExtend Empty (BVRepr w))
where
LLVMFrameRepr w = IntrinsicRepr knownSymbol (Ctx.extend Empty (BVRepr w))
-- | Pattern for building/desctructing permissions as expressions
pattern ValuePermRepr :: () => (ty ~ ValuePermType a) => TypeRepr a ->
TypeRepr ty
pattern ValuePermRepr a <-
IntrinsicRepr (testEquality (knownSymbol :: SymbolRepr "Perm") ->
Just Refl)
(viewAssign -> AssignExtend Empty a)
where
ValuePermRepr a = IntrinsicRepr knownSymbol (Ctx.extend Empty a)
-- | Pattern for building/desctructing LLVM frame types
pattern LLVMShapeRepr :: () => (1 <= w, ty ~ LLVMShapeType w) =>
NatRepr w -> TypeRepr ty
pattern LLVMShapeRepr w <-
IntrinsicRepr (testEquality (knownSymbol :: SymbolRepr "LLVMShape") ->
Just Refl)
(viewAssign -> AssignExtend Empty (BVRepr w))
where
LLVMShapeRepr w = IntrinsicRepr knownSymbol (Ctx.extend Empty (BVRepr w))
-- | Pattern for building/desctructing LLVM frame types
pattern LLVMBlockRepr :: () => (1 <= w, ty ~ LLVMBlockType w) =>
NatRepr w -> TypeRepr ty
pattern LLVMBlockRepr w <-
IntrinsicRepr (testEquality (knownSymbol :: SymbolRepr "LLVMBlock") ->
Just Refl)
(viewAssign -> AssignExtend Empty (BVRepr w))
where
LLVMBlockRepr w = IntrinsicRepr knownSymbol (Ctx.extend Empty (BVRepr w))
-- | Pattern for an empty 'PermExprs' list
pattern PExprs_Nil :: () => (tps ~ RNil) => PermExprs tps
pattern PExprs_Nil = MNil
-- | Pattern for a non-empty 'PermExprs' list
pattern PExprs_Cons :: () => (tps ~ (tps' :> a)) =>
PermExprs tps' -> PermExpr a -> PermExprs tps
pattern PExprs_Cons es e <- es :>: e
where
PExprs_Cons es e = es :>: e
{-# COMPLETE PExprs_Nil, PExprs_Cons #-}
-- | Convert a 'PermExprs' to an 'RAssign'
exprsToRAssign :: PermExprs as -> RAssign PermExpr as
exprsToRAssign PExprs_Nil = MNil
exprsToRAssign (PExprs_Cons es e) = exprsToRAssign es :>: e
-- | Convert an 'RAssign' to a 'PermExprs'
rassignToExprs :: RAssign PermExpr as -> PermExprs as
rassignToExprs MNil = PExprs_Nil
rassignToExprs (es :>: e) = PExprs_Cons (rassignToExprs es) e
-- | Convert a list of names to a 'PermExprs' list
namesToExprs :: RAssign Name as -> PermExprs as
namesToExprs MNil = PExprs_Nil
namesToExprs (ns :>: n) = PExprs_Cons (namesToExprs ns) (PExpr_Var n)
-- | Create a list of phantom 'Proxy' arguments from a 'PermExprs' list
proxiesOfExprs :: PermExprs as -> RAssign Proxy as
proxiesOfExprs PExprs_Nil = MNil
proxiesOfExprs (PExprs_Cons es _) = proxiesOfExprs es :>: Proxy
-- | Append two 'PermExprs' lists
appendExprs :: PermExprs as -> PermExprs bs -> PermExprs (as :++: bs)
appendExprs as PExprs_Nil = as
appendExprs as (PExprs_Cons bs b) = PExprs_Cons (appendExprs as bs) b
-- | Convenience function to get the known type of an expression-like construct
exprType :: KnownRepr TypeRepr a => f a -> TypeRepr a
exprType _ = knownRepr
-- | Convenience function to get the known type of bound name
bindingType :: KnownRepr TypeRepr a => Binding a b -> TypeRepr a
bindingType _ = knownRepr
-- | Convenience function to get the bit width of an LLVM pointer type
exprLLVMTypeWidth :: KnownNat w => f (LLVMPointerType w) -> NatRepr w
exprLLVMTypeWidth _ = knownNat
-- | Convenience function to get the bit width of an LLVM pointer type
mbExprLLVMTypeWidth :: KnownNat w => Mb ctx (f (LLVMPointerType w)) ->
NatRepr w
mbExprLLVMTypeWidth _ = knownNat
-- | Convenience function to get the bit width of a bitvector type
exprBVTypeWidth :: KnownNat w => f (BVType w) -> NatRepr w
exprBVTypeWidth _ = knownNat
-- | Convenience function to get the bit width of an LLVM pointer type
mbExprBVTypeWidth :: KnownNat w => Mb ctx (f (BVType w)) -> NatRepr w
mbExprBVTypeWidth _ = knownNat
-- | Convenience function to get the bit width of an LLVM pointer type
shapeLLVMTypeWidth :: KnownNat w => f (LLVMShapeType w) -> NatRepr w
shapeLLVMTypeWidth _ = knownNat
-- | Convenience function to get the number of bytes = the bit width divided by
-- 8 of an LLVM pointer type rounded up
exprLLVMTypeBytes :: KnownNat w => f (LLVMPointerType w) -> Integer
exprLLVMTypeBytes e = intValue (exprLLVMTypeWidth e) `ceil_div` 8
-- | Convenience function to get the number of bytes = the bit width divided by
-- 8 of an LLVM pointer type as an expr. Note that this assumes the bit width is
-- a multiple of 8, so does not worry about rounding.
exprLLVMTypeBytesExpr :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
f (LLVMPointerType sz) -> PermExpr (BVType w)
exprLLVMTypeBytesExpr e = bvInt (intValue (exprLLVMTypeWidth e) `ceil_div` 8)
-- | Convenience function to get the width of an LLVM pointer type of an
-- expression in a binding as an expression
mbExprLLVMTypeBytesExpr :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
Mb ctx (f (LLVMPointerType sz)) ->
PermExpr (BVType w)
mbExprLLVMTypeBytesExpr mb_e =
bvInt $ ceil_div (intValue $ mbLift $ fmap exprLLVMTypeWidth mb_e) 8
-- | Pattern-match a permission list expression as a typed list of permissions
-- consed onto a terminator, which can either be the empty list (represented by
-- 'Nothing') or a variable expression
matchPermList :: PermExpr PermListType -> (Some ExprPerms,
Maybe (ExprVar PermListType))
matchPermList PExpr_PermListNil = (Some MNil, Nothing)
matchPermList (PExpr_Var ps) = (Some MNil, Just ps)
matchPermList (PExpr_PermListCons _ e p l)
| (Some eperms, term) <- matchPermList l
= (Some (RL.append (MNil :>: ExprAndPerm e p) eperms), term)
-- | Pattern-match a permission list expression as a list of permissions on
-- variables with an empty list (not a variable) as a terminator
matchVarPermList :: PermExpr PermListType -> Maybe (Some DistPerms)
matchVarPermList PExpr_PermListNil = Just $ Some MNil
matchVarPermList (PExpr_PermListCons _ (PExpr_Var x) p l)
| Just (Some perms) <- matchVarPermList l =
Just $ Some $ RL.append (MNil :>: VarAndPerm x p) perms
matchVarPermList _ = Nothing
-- | Fold over all permissions associated with a specific variable in a
-- permission list
foldPermList :: ExprVar a -> (ValuePerm a -> r -> r) -> r ->
PermExpr PermListType -> r
foldPermList _ _ r PExpr_PermListNil = r
foldPermList _ _ r (PExpr_Var _) = r
foldPermList x f r (PExpr_PermListCons _ (PExpr_Var y) p plist)
| Just Refl <- testEquality x y =
f p $ foldPermList x f r plist
foldPermList x f r (PExpr_PermListCons _ _ _ plist) =
foldPermList x f r plist
-- | Fold over all atomic permissions associated with a specific variable in a
-- permission list
foldPermListAtomic :: ExprVar a -> (AtomicPerm a -> r -> r) -> r ->
PermExpr PermListType -> r
foldPermListAtomic x f =
foldPermList x (\p rest ->
case p of
ValPerm_Conj ps -> foldr f rest ps
_ -> rest)
-- | Find a permission on a specific variable in a permission list
findPermInList :: ExprVar a -> (ValuePerm a -> Bool) -> PermExpr PermListType ->
Maybe (ValuePerm a)
findPermInList x pred plist =
foldPermList x (\p rest -> if pred p then Just p else rest) Nothing plist
-- | Find an atomic permission on a specific variable in a permission list
findAtomicPermInList :: ExprVar a -> (AtomicPerm a -> Bool) ->
PermExpr PermListType -> Maybe (AtomicPerm a)
findAtomicPermInList x pred plist =
foldPermListAtomic x (\p rest ->
if pred p then Just p else rest) Nothing plist
instance Eq (PermExpr a) where
(PExpr_Var x1) == (PExpr_Var x2) = x1 == x2
(PExpr_Var _) == _ = False
PExpr_Unit == PExpr_Unit = True
PExpr_Unit == _ = False
(PExpr_Nat n1) == (PExpr_Nat n2) = n1 == n2
(PExpr_Nat _) == _ = False
(PExpr_String str1) == (PExpr_String str2) = str1 == str2
(PExpr_String _) == _ = False
(PExpr_Bool b1) == (PExpr_Bool b2) = b1 == b2
(PExpr_Bool _) == _ = False
(PExpr_BV factors1 const1) == (PExpr_BV factors2 const2) =
const1 == const2 && eqFactors factors1 factors2
where
eqFactors :: [BVFactor w] -> [BVFactor w] -> Bool
eqFactors [] [] = True
eqFactors (f : fs1) fs2
| elem f fs2 = eqFactors fs1 (delete f fs2)
eqFactors _ _ = False
(PExpr_BV _ _) == _ = False
(PExpr_Struct args1) == (PExpr_Struct args2) = args1 == args2 where
(PExpr_Struct _) == _ = False
PExpr_Always == PExpr_Always = True
PExpr_Always == _ = False
(PExpr_LLVMWord e1) == (PExpr_LLVMWord e2) = e1 == e2
(PExpr_LLVMWord _) == _ = False
(PExpr_LLVMOffset x1 e1) == (PExpr_LLVMOffset x2 e2) =
x1 == x2 && e1 == e2
(PExpr_LLVMOffset _ _) == _ = False
(PExpr_Fun fh1) == (PExpr_Fun fh2) = fh1 == fh2
(PExpr_Fun _) == _ = False
PExpr_PermListNil == PExpr_PermListNil = True
PExpr_PermListNil == _ = False
(PExpr_PermListCons tp1 e1 p1 l1) == (PExpr_PermListCons tp2 e2 p2 l2)
| Just Refl <- testEquality tp1 tp2
= e1 == e2 && p1 == p2 && l1 == l2
(PExpr_PermListCons _ _ _ _) == _ = False
(PExpr_RWModality rw1) == (PExpr_RWModality rw2) = rw1 == rw2
(PExpr_RWModality _) == _ = False
PExpr_EmptyShape == PExpr_EmptyShape = True
PExpr_EmptyShape == _ = False
(PExpr_NamedShape maybe_rw1 maybe_l1 nmsh1 args1)
== (PExpr_NamedShape maybe_rw2 maybe_l2 nmsh2 args2)
| Just (Refl,Refl) <- namedShapeEq nmsh1 nmsh2 =
maybe_rw1 == maybe_rw2 && maybe_l1 == maybe_l2 && args1 == args2
(PExpr_NamedShape _ _ _ _) == _ = False
(PExpr_EqShape len1 b1) == (PExpr_EqShape len2 b2) = len1 == len2 && b1 == b2
(PExpr_EqShape _ _) == _ = False
(PExpr_PtrShape rw1 l1 sh1) == (PExpr_PtrShape rw2 l2 sh2) =
rw1 == rw2 && l1 == l2 && sh1 == sh2
(PExpr_PtrShape _ _ _) == _ = False
(PExpr_FieldShape p1) == (PExpr_FieldShape p2) = p1 == p2
(PExpr_FieldShape _) == _ = False
(PExpr_ArrayShape len1 s1 sh1) == (PExpr_ArrayShape len2 s2 sh2) =
len1 == len2 && s1 == s2 && sh1 == sh2
(PExpr_ArrayShape _ _ _) == _ = False
(PExpr_SeqShape sh1 sh1') == (PExpr_SeqShape sh2 sh2') =
sh1 == sh2 && sh1' == sh2'
(PExpr_SeqShape _ _) == _ = False
(PExpr_OrShape sh1 sh1') == (PExpr_OrShape sh2 sh2') =
sh1 == sh2 && sh1' == sh2'
(PExpr_OrShape _ _) == _ = False
(PExpr_ExShape mb_sh1) == (PExpr_ExShape mb_sh2)
| Just Refl <- testEquality (bindingType mb_sh1) (bindingType mb_sh2)
= mbLift $ mbMap2 (==) mb_sh1 mb_sh2
(PExpr_ExShape _) == _ = False
PExpr_FalseShape == PExpr_FalseShape = True
PExpr_FalseShape == _ = False
(PExpr_ValPerm p1) == (PExpr_ValPerm p2) = p1 == p2
(PExpr_ValPerm _) == _ = False
instance Eq1 PermExpr where
eq1 = (==)
instance Eq (BVFactor w) where
(BVFactor i1 x1) == (BVFactor i2 x2) = i1 == i2 && x1 == x2
instance PermPretty (PermExpr a) where
permPrettyM (PExpr_Var x) = permPrettyM x
permPrettyM PExpr_Unit = return $ pretty "()"
permPrettyM (PExpr_Nat n) = return $ pretty $ show n
permPrettyM (PExpr_String str) = return (pretty '"' <> pretty str <> pretty '"')
permPrettyM (PExpr_Bool b) = return $ pretty b
permPrettyM (PExpr_BV [] constant) =
return $ pretty $ BV.asSigned knownNat constant
permPrettyM (PExpr_BV factors constant) =
do factors_pp <-
encloseSep mempty mempty (pretty "+") <$> mapM permPrettyM factors
case BV.asSigned knownNat constant of
0 -> return factors_pp
c | c > 0 -> return (factors_pp <> pretty "+" <> pretty c)
c -> return (factors_pp <> pretty c)
permPrettyM (PExpr_Struct args) =
(\pp -> pretty "struct" <+> parens pp) <$> permPrettyM args
permPrettyM PExpr_Always = return $ pretty "always"
permPrettyM (PExpr_LLVMWord e) = (pretty "LLVMword" <+>) <$> permPrettyM e
permPrettyM (PExpr_LLVMOffset x e) =
(\ppx ppe -> ppx <+> pretty "&+" <+> ppe)
<$> permPrettyM x <*> permPrettyM e
permPrettyM (PExpr_Fun fh) = return $ angles $ pretty ("fun" ++ show fh)
permPrettyM e@PExpr_PermListNil = prettyPermListM e
permPrettyM e@(PExpr_PermListCons _ _ _ _) = prettyPermListM e
permPrettyM (PExpr_RWModality rw) = permPrettyM rw
permPrettyM PExpr_EmptyShape = return $ pretty "emptysh"
permPrettyM (PExpr_NamedShape maybe_rw maybe_l nmsh args) =
do l_pp <- maybe (return mempty) permPrettyLifetimePrefix maybe_l
rw_pp <- case maybe_rw of
Just rw -> parens <$> permPrettyM rw
Nothing -> return mempty
args_pp <- permPrettyM args
return (l_pp <> rw_pp <> pretty (namedShapeName nmsh) <>
pretty '<' <> align (args_pp <> pretty '>'))
permPrettyM (PExpr_EqShape len b) =
do len_pp <- permPrettyM len
b_pp <- permPrettyM b
return (pretty "eqsh" <> parens (len_pp <> comma <> b_pp))
permPrettyM (PExpr_PtrShape maybe_rw maybe_l sh) =
do l_pp <- maybe (return mempty) permPrettyLifetimePrefix maybe_l
rw_pp <- case maybe_rw of
Just rw -> (<> pretty ",") <$> permPrettyM rw
Nothing -> return mempty
sh_pp <- permPrettyM sh
return (l_pp <> pretty "ptrsh" <> parens (rw_pp <> sh_pp))
permPrettyM (PExpr_FieldShape fld) =
(pretty "fieldsh" <>) <$> permPrettyM fld
permPrettyM (PExpr_ArrayShape len stride sh) =
do len_pp <- permPrettyM len
sh_pp <- permPrettyM sh
let stride_pp = pretty (toInteger stride)
return (pretty "arraysh" <>
ppEncList True [pretty "<" <> len_pp,
pretty "*" <> stride_pp, sh_pp])
permPrettyM (PExpr_SeqShape sh1 sh2) =
do pp1 <- permPrettyM sh1
pp2 <- permPrettyM sh2
return $ nest 2 $ sep [pp1 <> pretty ';', pp2]
permPrettyM (PExpr_OrShape sh1 sh2) =
do pp1 <- permPrettyM sh1
pp2 <- permPrettyM sh2
return $ nest 2 $ sep [pp1 <+> pretty "orsh", pp2]
permPrettyM (PExpr_ExShape mb_sh) =
flip permPrettyExprMb mb_sh $ \(_ :>: Constant pp_n) ppm ->
do pp <- ppm
return $ sep [pretty "exsh" <+> pp_n <> dot, pp]
permPrettyM PExpr_FalseShape = return $ pretty "falsesh"
permPrettyM (PExpr_ValPerm p) = permPrettyM p
instance (1 <= w, KnownNat w) => PermPretty (LLVMFieldShape w) where
permPrettyM fsh@(LLVMFieldShape p)
| Just Refl <- testEquality (natRepr fsh) (exprLLVMTypeWidth p) =
parens <$> permPrettyM p
permPrettyM (LLVMFieldShape p) =
do p_pp <- permPrettyM p
return $ ppEncList True [pretty (intValue $ exprLLVMTypeWidth p), p_pp]
prettyPermListM :: PermExpr PermListType -> PermPPM (Doc ann)
prettyPermListM PExpr_PermListNil =
-- Special case for an empty list of permissions
return $ pretty "empty"
prettyPermListM e =
case matchPermList e of
(Some perms, Just term_var) ->
do pps <- sequence (RL.mapToList permPrettyMF perms)
pp_term <- permPrettyM term_var
return $ align $ fillSep (map (<> comma) (take (length pps - 1) pps)
++ [last pps <+> pretty "::", pp_term])
(Some perms, Nothing) -> permPrettyM perms
instance PermPrettyF PermExpr where
permPrettyMF = permPrettyM
instance PermPretty (BVFactor w) where
permPrettyM (BVFactor i x) =
((pretty (BV.asSigned knownNat i) <> pretty "*") <>) <$> permPrettyM x
instance PermPretty RWModality where
permPrettyM Read = return $ pretty "R"
permPrettyM Write = return $ pretty "W"
-- | The 'Write' modality as an expression
pattern PExpr_Write :: PermExpr RWModalityType
pattern PExpr_Write = PExpr_RWModality Write
-- | The 'Read' modality as an expression
pattern PExpr_Read :: PermExpr RWModalityType
pattern PExpr_Read = PExpr_RWModality Read
-- | Build a "default" expression for a given type
zeroOfType :: TypeRepr tp -> PermExpr tp
zeroOfType (BVRepr w) = withKnownNat w $ PExpr_BV [] $ BV.mkBV w 0
zeroOfType LifetimeRepr = PExpr_Always
zeroOfType _ = error "zeroOfType"
----------------------------------------------------------------------
-- * Operations on Bitvector and LLVM Pointer Expressions
----------------------------------------------------------------------
-- | Build a 'BVFactor' for a variable
varFactor :: (1 <= w, KnownNat w) => ExprVar (BVType w) -> BVFactor w
varFactor = BVFactor $ BV.one knownNat
-- | Merge two normalized / sorted lists of 'BVFactor's
bvMergeFactors :: [BVFactor w] -> [BVFactor w] -> [BVFactor w]
bvMergeFactors fs1 fs2 =
filter (\(BVFactor i _) -> i /= BV.zero knownNat) $
helper fs1 fs2
where
helper factors1 [] = factors1
helper [] factors2 = factors2
helper ((BVFactor i1 x1):factors1) ((BVFactor i2 x2):factors2)
| x1 == x2
= BVFactor (BV.add knownNat i1 i2) x1 : helper factors1 factors2
helper (f1@(BVFactor _ x1):factors1) (f2@(BVFactor _ x2):factors2)
| x1 < x2 = f1 : helper factors1 (f2 : factors2)
helper (f1@(BVFactor _ _):factors1) (f2@(BVFactor _ _):factors2) =
f2 : helper (f1 : factors1) factors2
-- | Convert a bitvector expression to a sum of factors plus a constant
bvMatch :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
([BVFactor w], BV w)
bvMatch (PExpr_Var x) = ([varFactor x], BV.zero knownNat)
bvMatch (PExpr_BV factors constant) = (factors, constant)
-- | Test if a bitvector expression is a constant value
bvMatchConst :: PermExpr (BVType w) -> Maybe (BV w)
bvMatchConst (PExpr_BV [] constant) = Just constant
bvMatchConst _ = Nothing
-- | Test if a bitvector expression is a constant unsigned 'Integer' value
bvMatchConstInt :: PermExpr (BVType w) -> Maybe Integer
bvMatchConstInt = fmap BV.asUnsigned . bvMatchConst
-- | Normalize a bitvector expression to a canonical form. Currently this just
-- means converting @1*x+0@ to @x@.
normalizeBVExpr :: PermExpr (BVType w) -> PermExpr (BVType w)
normalizeBVExpr (PExpr_BV [BVFactor (BV.BV 1) x] (BV.BV 0)) = PExpr_Var x
normalizeBVExpr e = e
-- | Test whether two bitvector expressions are semantically equal
bvEq :: PermExpr (BVType w) -> PermExpr (BVType w) -> Bool
bvEq e1 e2 = normalizeBVExpr e1 == normalizeBVExpr e2
-- | Test whether a bitvector expression is less than another for all
-- substitutions to the free variables. The comparison is unsigned. This is an
-- underapproximation, meaning that it could return 'False' in cases where it is
-- actually 'True'. The current algorithm returns 'False' when the right-hand
-- side is 0, 'True' for constant expressions @k1 < k2@, and 'False' otherwise.
bvLt :: PermExpr (BVType w) -> PermExpr (BVType w) -> Bool
bvLt _ (PExpr_BV [] (BV.BV 0)) = False
bvLt e1 e2 | bvEq e1 e2 = False
bvLt (PExpr_BV [] k1) (PExpr_BV [] k2) = BV.ult k1 k2
bvLt _ _ = False
-- | Test whether a bitvector expression is less than another for all
-- substitutions to the free variables. The comparison is signed. This is an
-- underapproximation, meaning that it could return 'False' in cases where it is
-- actually 'True'. The current algorithm only returns 'True' for constant
-- expressions @k1 < k2@.
bvSLt :: (1 <= w, KnownNat w) =>
PermExpr (BVType w) -> PermExpr (BVType w) -> Bool
bvSLt (bvMatchConst -> Just i1) (bvMatchConst -> Just i2) =
BV.slt knownNat i1 i2
bvSLt _ _ = False
-- | Test whether a bitvector expression @e@ is in a 'BVRange' for all
-- substitutions to the free variables. This is an underapproximation, meaning
-- that it could return 'False' in cases where it is actually 'True'. It is
-- implemented by testing whether @e - off < len@ using the unsigned comparison
-- 'bvLt', where @off@ and @len@ are the offset and length of the 'BVRange'.
bvInRange :: (1 <= w, KnownNat w) => PermExpr (BVType w) -> BVRange w -> Bool
bvInRange e (BVRange off len) = bvLt (bvSub e off) len
-- | Test whether a bitvector @e@ equals @0@
bvIsZero :: PermExpr (BVType w) -> Bool
bvIsZero (PExpr_Var _) = False
bvIsZero (PExpr_BV [] (BV.BV 0)) = True
bvIsZero (PExpr_BV _ _) = False
-- | Test whether a bitvector @e@ could equal @0@, i.e., whether the equation
-- @e=0@ has any solutions.
--
-- NOTE: this is an overapproximation, meaning that it may return 'True' for
-- complex expressions that technically cannot unify with @0@.
bvZeroable :: PermExpr (BVType w) -> Bool
bvZeroable (PExpr_Var _) = True
bvZeroable (PExpr_BV _ (BV.BV 0)) = True
bvZeroable (PExpr_BV [] _) = False
bvZeroable (PExpr_BV _ _) =
-- NOTE: there are cases that match this pattern but are still not solvable,
-- like 8*x + 3 = 0.
True
-- | Test whether two bitvector expressions are potentially unifiable, i.e.,
-- whether some substitution to the variables could make them equal. This is an
-- overapproximation, meaning that some expressions are marked as "could" equal
-- when they actually cannot.
bvCouldEqual :: PermExpr (BVType w) -> PermExpr (BVType w) -> Bool
bvCouldEqual e1@(PExpr_BV _ _) e2 =
-- NOTE: we can only call bvSub when at least one side matches PExpr_BV
bvZeroable (bvSub e1 e2)
bvCouldEqual e1 e2@(PExpr_BV _ _) = bvZeroable (bvSub e1 e2)
bvCouldEqual _ _ = True
-- | Test whether a bitvector expression could potentially be less than another,
-- for some substitution to the free variables. The comparison is unsigned. This
-- is an overapproximation, meaning that some expressions are marked as "could"
-- be less than when they actually cannot. The current algorithm returns 'False'
-- when the right-hand side is 0 and 'True' in all other cases except constant
-- expressions @k1 >= k2@.
bvCouldBeLt :: PermExpr (BVType w) -> PermExpr (BVType w) -> Bool
bvCouldBeLt _ (PExpr_BV [] (BV.BV 0)) = False
bvCouldBeLt e1 e2 | bvEq e1 e2 = False
bvCouldBeLt (PExpr_BV [] (BV.BV k1)) (PExpr_BV [] (BV.BV k2)) = k1 < k2
bvCouldBeLt _ _ = True
-- | Test whether a bitvector expression could potentially be less than another,
-- for some substitution to the free variables. The comparison is signed. This
-- is an overapproximation, meaning that some expressions are marked as "could"
-- be less than when they actually cannot. The current algorithm returns 'True'
-- in all cases except constant expressions @k1 >= k2@.
bvCouldBeSLt :: (1 <= w, KnownNat w) =>
PermExpr (BVType w) -> PermExpr (BVType w) -> Bool
bvCouldBeSLt (bvMatchConst -> Just i1) (bvMatchConst -> Just i2) =
BV.slt knownNat i1 i2
bvCouldBeSLt _ _ = True
-- | Test whether a bitvector expression is less than or equal to another for
-- all substitutions of the free variables. The comparison is unsigned. This is
-- an underapproximation, meaning that it could return 'False' in cases where it
-- is actually 'True'. The current algorithm simply tests if the second
-- epxression 'bvCouldBeLt' the first, and returns the negation of that result.
bvLeq :: (1 <= w, KnownNat w) =>
PermExpr (BVType w) -> PermExpr (BVType w) -> Bool
bvLeq e1 e2 = not (bvCouldBeLt e2 e1)
-- | Test whether a bitvector expression @e@ is in a 'BVRange' for all
-- substitutions to the free variables. This is an overapproximation, meaning
-- that some expressions are marked as "could" be in the range when they
-- actually cannot. The current algorithm tests if @e - off < len@ using the
-- unsigned comparison 'bvCouldBeLt', where @off@ and @len@ are the offset and
-- length of the 'BVRange'.
bvCouldBeInRange :: (1 <= w, KnownNat w) => PermExpr (BVType w) -> BVRange w -> Bool
bvCouldBeInRange e (BVRange off len) = bvCouldBeLt (bvSub e off) len
-- | Test whether a 'BVProp' holds for all substitutions of the free
-- variables. This is an underapproximation, meaning that some propositions are
-- marked as not holding when they actually do.
bvPropHolds :: (1 <= w, KnownNat w) => BVProp w -> Bool
bvPropHolds (BVProp_Eq e1 e2) = bvEq e1 e2
bvPropHolds (BVProp_Neq e1 e2) = not (bvCouldEqual e1 e2)
bvPropHolds (BVProp_ULt e1 e2) = bvLt e1 e2
bvPropHolds (BVProp_ULeq e1 e2) = bvLeq e1 e2
bvPropHolds (BVProp_ULeq_Diff e1 e2 e3) =
not (bvCouldBeLt (bvSub e2 e3) e1)
-- | Test whether a 'BVProp' "could" hold for all substitutions of the free
-- variables. This is an overapproximation, meaning that some propositions are
-- marked as "could" hold when they actually cannot.
bvPropCouldHold :: (1 <= w, KnownNat w) => BVProp w -> Bool
bvPropCouldHold (BVProp_Eq e1 e2) = bvCouldEqual e1 e2
bvPropCouldHold (BVProp_Neq e1 e2) = not (bvEq e1 e2)
bvPropCouldHold (BVProp_ULt e1 e2) = bvCouldBeLt e1 e2
bvPropCouldHold (BVProp_ULeq e1 e2) = not (bvLt e2 e1)
bvPropCouldHold (BVProp_ULeq_Diff e1 e2 e3) = not (bvLt (bvSub e2 e3) e1)
-- | Negate a 'BVProp'
bvPropNegate :: BVProp w -> BVProp w
bvPropNegate (BVProp_Eq e1 e2) = BVProp_Neq e1 e2
bvPropNegate (BVProp_Neq e1 e2) = BVProp_Eq e1 e2
bvPropNegate (BVProp_ULt e1 e2) = BVProp_ULeq e2 e1
bvPropNegate (BVProp_ULeq e1 e2) = BVProp_ULt e2 e1
bvPropNegate (BVProp_ULeq_Diff e1 e2 e3) =
BVProp_ULt (bvSub e2 e3) e1
-- | Build the proposition that @x@ is in the range @[off,off+len)@ as the
-- proposition
--
-- > x-off <u len
bvPropInRange :: (1 <= w, KnownNat w) =>
PermExpr (BVType w) -> BVRange w -> BVProp w
bvPropInRange e (BVRange off len) = BVProp_ULt (bvSub e off) len
-- | Build the proposition that @x@ is /not/ in the range @[off,off+len)@ as the
-- negation of 'bvPropInRange'
bvPropNotInRange :: (1 <= w, KnownNat w) =>
PermExpr (BVType w) -> BVRange w -> BVProp w
bvPropNotInRange e rng = bvPropNegate $ bvPropInRange e rng
-- | Build the proposition that @[off1,off1+len1)@ is a subset of
-- @[off2,off2+len2)@ as the following pair of propositions:
--
-- > off1 - off2 <=u len2
-- > len1 <=u len2 - (off1 - off2)
--
-- The first one states that the first @off1 - off2@ elements of the range
-- @[off2,off2+len2)@ can be removed to get the range
-- @[off1,off1+(len2-(off1-off2)))@. This also ensures that @len2-(off1- off2)@
-- does not underflow. The second then ensures that removing @off1-off2@
-- elements from the front of the second interval still yields a length that is
-- at least as long as @len1@.
--
-- NOTE: this is technically not complete, because the subset relation should
-- always hold when @len1=0@ while the first proposition above does not always
-- hold in this case, but we are ok with this. Equivalently, this approach views
-- @[off1,off1+len1)@ as always containing @off1@ even when @len1=0@.
--
-- NOTE: we cannot simplify the subtraction @len2 - (off1 - off2)@ because when
-- we translate to SAW core both @len2@ and @(off1 - off2)@ become different
-- arguments to @sliceBVVec@ and @updSliceBVVec@, and SAW core does not simplify
-- the subtraction of these two arguments.
bvPropRangeSubset :: (1 <= w, KnownNat w) =>
BVRange w -> BVRange w -> [BVProp w]
bvPropRangeSubset (BVRange off1 len1) (BVRange off2 len2) =
[BVProp_ULeq (bvSub off1 off2) len2,
BVProp_ULeq_Diff len1 len2 (bvSub off1 off2)]
-- | Test that one range is a subset of another, by testing that the
-- propositions returned by 'bvPropRangeSubset' all hold (in the sense of
-- 'bvPropHolds')
bvRangeSubset :: (1 <= w, KnownNat w) => BVRange w -> BVRange w -> Bool
bvRangeSubset rng1 rng2 = all bvPropHolds $ bvPropRangeSubset rng1 rng2
-- | Build the proposition that @[off1,off1+len1)@ and @[off2,off2+len2)@ are
-- disjoint as following pair of propositions:
--
-- > len2 <=u off1 - off2
-- > len1 <=u off2 - off1
--
-- These say that each @off@ is not in the other range.
bvPropRangesDisjoint :: (1 <= w, KnownNat w) =>
BVRange w -> BVRange w -> [BVProp w]
bvPropRangesDisjoint (BVRange off1 len1) (BVRange off2 len2) =
[BVProp_ULeq len2 (bvSub off1 off2), BVProp_ULeq len1 (bvSub off2 off1)]
-- | Test if @[off1,off1+len1)@ and @[off2,off2+len2)@ overlap, i.e., share at
-- least one element, by testing that they could not satisfy (in the sense of
-- 'bvPropCouldHold') the results of 'bvPropRangesDisjoint'
bvRangesOverlap :: (1 <= w, KnownNat w) => BVRange w -> BVRange w -> Bool
bvRangesOverlap rng1 rng2 =
not $ all bvPropCouldHold $ bvPropRangesDisjoint rng1 rng2
-- | Test if @[off1,off1+len1)@ and @[off2,off2+len2)@ could overlap, i.e.,
-- share at least one element, by testing that they do not definitely satisfy
-- (in the sense of 'bvPropHolds') the results of 'bvPropRangesDisjoint'
bvRangesCouldOverlap :: (1 <= w, KnownNat w) => BVRange w -> BVRange w -> Bool
bvRangesCouldOverlap rng1 rng2 =
not $ all bvPropHolds $ bvPropRangesDisjoint rng1 rng2
-- | Get the ending offset of a range
bvRangeEnd :: (1 <= w, KnownNat w) => BVRange w -> PermExpr (BVType w)
bvRangeEnd (BVRange off len) = bvAdd off len
-- | Take the suffix of a range starting at a given offset, assuming that offset
-- is in the range
bvRangeSuffix :: (1 <= w, KnownNat w) => PermExpr (BVType w) -> BVRange w ->
BVRange w
bvRangeSuffix off' (BVRange off len) =
BVRange off' (bvSub len (bvSub off' off))
-- | Subtract a bitvector word from the offset of a 'BVRange'
bvRangeSub :: (1 <= w, KnownNat w) => BVRange w -> PermExpr (BVType w) ->
BVRange w
bvRangeSub (BVRange off len) x = BVRange (bvSub off x) len
-- | Delete all offsets from the first 'BVRange' that are definitely (in the
-- sense of 'bvPropHolds') in the second, returning a list of 'BVRange's that
-- together describe the remaining offsets
bvRangeDelete :: (1 <= w, KnownNat w) => BVRange w -> BVRange w -> [BVRange w]
bvRangeDelete rng1 rng2
-- If rng1 is a subset of rng2, return the empty set
| bvRangeSubset rng1 rng2 = []
bvRangeDelete rng1 rng2
-- If both endpoints of rng1 are in rng2 but it is not a subset of rng2, then
-- one of the ranges wrapped, and we return the range from the end of rng2 to
-- its beginning again
| bvInRange (bvRangeOffset rng1) rng2 &&
bvInRange (bvRangeEnd rng1) rng2 =
[BVRange (bvRangeEnd rng2) (bvSub (bvInt 0) (bvRangeLength rng2))]
bvRangeDelete rng1 rng2
-- If the beginning of rng1 is in rng2 but the above cases don't hold, then
-- rng2 removes some prefix of rng1, so return the range from the end of rng2
-- to the end of rng1
| bvInRange (bvRangeOffset rng1) rng2 =
[bvRangeSuffix (bvRangeEnd rng2) rng1]
bvRangeDelete rng1 rng2
-- If the end of rng1 is in rng2 but the above cases don't hold, then rng2
-- removes some suffix of rng1, so return the range from the beginnning of
-- rng1 to the beginning of rng2
| bvInRange (bvRangeEnd rng1) rng2 =
[BVRange (bvRangeOffset rng1)
(bvSub (bvRangeOffset rng2) (bvRangeOffset rng1))]
bvRangeDelete rng1 rng2
-- If we get here then both endpoints of rng1 are not in rng2, but rng2 sits
-- inside of rng1, so return the prefix of rng1 before rng2 and the suffix of
-- rng1 after rng2
| off1 <- bvRangeOffset rng1
, off2 <- bvRangeOffset rng2
, end1 <- bvRangeEnd rng1
, end2 <- bvRangeEnd rng2
, bvInRange off2 rng1 =
[BVRange off1 (bvSub off2 off1), BVRange end2 (bvSub end1 end2)]
bvRangeDelete rng1 _ =
-- If we get here, then rng2 is completely disjoint from rng1, so return rng1
[rng1]
-- | Delete all offsets in any of a list of ranges from a range, yielding a list
-- of ranges of the remaining offsets
bvRangesDelete :: (1 <= w, KnownNat w) => BVRange w -> [BVRange w] ->
[BVRange w]
bvRangesDelete rng_top =
foldr (\rng_del rngs -> concatMap (flip bvRangeDelete rng_del) rngs) [rng_top]
-- | Build a bitvector expression from an integer
bvInt :: (1 <= w, KnownNat w) => Integer -> PermExpr (BVType w)
bvInt i = PExpr_BV [] $ BV.mkBV knownNat i
-- | Build a bitvector expression of a given size from an integer
bvIntOfSize :: (1 <= sz, KnownNat sz) => prx sz -> Integer -> PermExpr (BVType sz)
bvIntOfSize _ = bvInt
-- | Build a bitvector expression from a Haskell bitvector
bvBV :: (1 <= w, KnownNat w) => BV w -> PermExpr (BVType w)
bvBV i = PExpr_BV [] i
-- | Helper datatype for 'bvFromBytes'
data BVExpr w = (1 <= w, KnownNat w) => BVExpr (PermExpr (BVType w))
-- | Build a bitvector expression from a list of bytes, depending on the
-- endianness
bvFromBytes :: EndianForm -> [Word8] -> Some BVExpr
bvFromBytes endianness bytes =
let bv_fun =
case endianness of
BigEndian -> BV.bytesBE
LittleEndian -> BV.bytesLE in
case bv_fun bytes of
Pair sz bv
| Left leq_proof <- decideLeq (knownNat @1) sz ->
withKnownNat sz $ withLeqProof leq_proof $ Some $ BVExpr $ bvBV bv
Pair _ _ -> error "bvFromBytes: zero-sized bitvector"
-- | Concatenate two bitvectors, using the current endianness to determine how
-- they combine
bvConcat :: KnownNat sz1 => KnownNat sz2 => EndianForm ->
BV.BV sz1 -> BV.BV sz2 -> BV.BV (sz1+sz2)
bvConcat BigEndian bv1 bv2 = BV.concat knownRepr knownRepr bv1 bv2
bvConcat LittleEndian bv1 bv2
| Refl <- plusComm bv1 bv2 =
BV.concat knownRepr knownRepr bv2 bv1
-- | Split a bitvector in two, if this is possible, using the current endianness
-- to determine which is the first versus second part of the split
bvSplit :: KnownNat sz1 => KnownNat sz2 => EndianForm ->
NatRepr sz1 -> BV.BV sz2 -> Maybe (BV.BV sz1, BV.BV (sz2 - sz1))
bvSplit LittleEndian sz1 bv2
| n0 <- knownNat @0
, sz2 <- natRepr bv2
, Left LeqProof <- decideLeq (addNat n0 sz1) sz2
, Left LeqProof <- decideLeq (addNat sz1 (subNat sz2 sz1)) sz2 =
Just (BV.select n0 sz1 bv2, BV.select sz1 (subNat sz2 sz1) bv2)
bvSplit BigEndian sz1 bv2
| n0 <- knownNat @0
, sz2 <- natRepr bv2
, Left LeqProof <- decideLeq sz1 sz2
, Left LeqProof <- decideLeq (addNat (subNat sz2 sz1) sz1) sz2
, Left LeqProof <- decideLeq (addNat n0 (subNat sz2 sz1)) sz2 =
Just (BV.select (subNat sz2 sz1) sz1 bv2,
BV.select n0 (subNat sz2 sz1) bv2)
bvSplit _ _ _ = Nothing
-- | Build a bitvector expression consisting of a single single 'BVFactor',
-- i.e. a variable multiplied by some constant
bvFactorExpr :: (1 <= w, KnownNat w) =>
BV w -> ExprVar (BVType w) -> PermExpr (BVType w)
bvFactorExpr (BV.BV 1) x = PExpr_Var x
bvFactorExpr i x = PExpr_BV [BVFactor i x] (BV.zero knownNat)
-- | Add two bitvector expressions
bvAdd :: (1 <= w, KnownNat w) => PermExpr (BVType w) -> PermExpr (BVType w) ->
PermExpr (BVType w)
bvAdd (bvMatch -> (factors1, const1)) (bvMatch -> (factors2, const2)) =
normalizeBVExpr $
PExpr_BV (bvMergeFactors factors1 factors2) (BV.add knownNat const1 const2)
-- | Multiply a bitvector expression by a bitvector
bvMultBV :: (1 <= w, KnownNat w) => BV.BV w -> PermExpr (BVType w) ->
PermExpr (BVType w)
bvMultBV i_bv (bvMatch -> (factors, off)) =
normalizeBVExpr $
PExpr_BV (map (\(BVFactor j x) ->
BVFactor (BV.mul knownNat i_bv j) x) factors)
(BV.mul knownNat i_bv off)
-- | Multiply a bitvector expression by a constant
bvMult :: (1 <= w, KnownNat w, Integral a) => a -> PermExpr (BVType w) ->
PermExpr (BVType w)
bvMult i = bvMultBV (BV.mkBV knownNat $ toInteger i)
-- | Negate a bitvector expression
bvNegate :: (1 <= w, KnownNat w) => PermExpr (BVType w) -> PermExpr (BVType w)
bvNegate = bvMult (-1 :: Integer)
-- | Subtract one bitvector expression from another
--
-- FIXME: this would be more efficient if we did not use 'bvNegate', which could
-- make very large 'Integer's for negative numbers wrapped around to be positive
bvSub :: (1 <= w, KnownNat w) => PermExpr (BVType w) -> PermExpr (BVType w) ->
PermExpr (BVType w)
bvSub e1 e2 = bvAdd e1 (bvNegate e2)
-- | Integer division on bitvector expressions, truncating any factors @i*x@
-- where @i@ is not a multiple of the divisor to zero
bvDiv :: (1 <= w, KnownNat w, Integral a) => PermExpr (BVType w) -> a ->
PermExpr (BVType w)
bvDiv (bvMatch -> (factors, off)) n =
let n_bv = BV.mkBV knownNat (toInteger n) in
normalizeBVExpr $
PExpr_BV (mapMaybe (\(BVFactor i x) ->
if BV.urem i n_bv == BV.zero knownNat then
Just (BVFactor (BV.uquot i n_bv) x)
else Nothing) factors)
(BV.uquot off n_bv)
-- | Integer Modulus on bitvector expressions, where any factors @i*x@ with @i@
-- not a multiple of the divisor are included in the modulus
bvMod :: (1 <= w, KnownNat w, Integral a) => PermExpr (BVType w) -> a ->
PermExpr (BVType w)
bvMod (bvMatch -> (factors, off)) n =
let n_bv = BV.mkBV knownNat $ toInteger n in
normalizeBVExpr $
PExpr_BV (mapMaybe (\f@(BVFactor i _) ->
if BV.urem i n_bv /= BV.zero knownNat
then Just f else Nothing) factors)
(BV.urem off n_bv)
-- | Given a constant factor @a@, test if a bitvector expression can be written
-- as @a*x+y@ for some constant @y@
bvMatchFactorPlusConst :: (1 <= w, KnownNat w) =>
Integer -> PermExpr (BVType w) ->
Maybe (PermExpr (BVType w), BV w)
bvMatchFactorPlusConst a e =
bvMatchConst (bvMod e a) >>= \y -> Just (bvDiv e a, y)
-- | Returns the greatest common divisor of all the coefficients (i.e. offsets
-- and factor coefficients) of the given bitvectors, returning a negative
-- number iff all coefficients are <= 0
bvGCD :: (1 <= w, KnownNat w) =>
PermExpr (BVType w) -> PermExpr (BVType w) -> BV w
bvGCD (bvMatch -> (fs1, off1)) (bvMatch -> (fs2, off2)) =
fromMaybe (error "bvGCD: overflow") . BV.mkBVSigned knownNat $
foldl' (\d (BVFactor i _) -> d `gcdS` BV.asSigned knownNat i)
(foldl' (\d (BVFactor i _) -> d `gcdS` BV.asSigned knownNat i)
(BV.asSigned knownNat off1 `gcdS` BV.asSigned knownNat off2)
fs1)
fs2
where -- A version of 'gcd' whose return value is negative iff both of
-- its arguments are <= 0
gcdS :: Integer -> Integer -> Integer
gcdS x y | x <= 0 && y <= 0 = - gcd x y
| otherwise = gcd x y
-- | Convert an LLVM pointer expression to a variable + optional offset, if this
-- is possible
asLLVMOffset :: (1 <= w, KnownNat w) => PermExpr (LLVMPointerType w) ->
Maybe (ExprVar (LLVMPointerType w), PermExpr (BVType w))
asLLVMOffset (PExpr_Var x) = Just (x, bvInt 0)
asLLVMOffset (PExpr_LLVMOffset x off) = Just (x, off)
asLLVMOffset _ = Nothing
-- | Add a word expression to an LLVM pointer expression
addLLVMOffset :: (1 <= w, KnownNat w) =>
PermExpr (LLVMPointerType w) -> PermExpr (BVType w) ->
PermExpr (LLVMPointerType w)
addLLVMOffset (PExpr_Var x) off = PExpr_LLVMOffset x off
addLLVMOffset (PExpr_LLVMWord e) off = PExpr_LLVMWord $ bvAdd e off
addLLVMOffset (PExpr_LLVMOffset x e) off =
PExpr_LLVMOffset x $ bvAdd e off
-- | Build a range that contains exactly one index
bvRangeOfIndex :: (1 <= w, KnownNat w) => PermExpr (BVType w) -> BVRange w
bvRangeOfIndex e = BVRange e (bvInt 1)
-- | Add an offset to a 'BVRange'
offsetBVRange :: (1 <= w, KnownNat w) => PermExpr (BVType w) -> BVRange w ->
BVRange w
offsetBVRange off (BVRange off' len) = (BVRange (bvAdd off' off) len)
----------------------------------------------------------------------
-- * Permissions
----------------------------------------------------------------------
deriving instance Eq (BVRange w)
deriving instance Eq (BVProp w)
-- | Build an equality permission in a binding
mbValPerm_Eq :: Mb ctx (PermExpr a) -> Mb ctx (ValuePerm a)
mbValPerm_Eq = mbMapCl $(mkClosed [| ValPerm_Eq |])
-- | The conjunction of a list of atomic permissions in a binding
mbValPerm_Conj :: Mb ctx [AtomicPerm a] -> Mb ctx (ValuePerm a)
mbValPerm_Conj = mbMapCl $(mkClosed [| ValPerm_Conj |])
-- | The vacuously true permission is the conjunction of 0 atomic permissions
pattern ValPerm_True :: ValuePerm a
pattern ValPerm_True = ValPerm_Conj []
-- | The conjunction of exactly 1 atomic permission
pattern ValPerm_Conj1 :: AtomicPerm a -> ValuePerm a
pattern ValPerm_Conj1 p = ValPerm_Conj [p]
-- | The conjunction of exactly 1 atomic permission in a binding
mbValPerm_Conj1 :: Mb ctx (AtomicPerm a) -> Mb ctx (ValuePerm a)
mbValPerm_Conj1 = mbMapCl $(mkClosed [| ValPerm_Conj1 |])
-- | The conjunction of exactly 1 field permission
pattern ValPerm_LLVMField :: () => (a ~ LLVMPointerType w, 1 <= w, KnownNat w,
1 <= sz, KnownNat sz) =>
LLVMFieldPerm w sz -> ValuePerm a
pattern ValPerm_LLVMField fp <- ValPerm_Conj [Perm_LLVMField fp]
where
ValPerm_LLVMField fp = ValPerm_Conj [Perm_LLVMField fp]
{- FIXME: why doesn't this work?
-- | The conjunction of exactly 1 field permission in a binding
pattern MbValPerm_LLVMField :: () => (a ~ LLVMPointerType w, 1 <= w, KnownNat w,
1 <= sz, KnownNat sz) =>
Mb ctx (LLVMFieldPerm w sz) ->
Mb ctx (ValuePerm a)
pattern MbValPerm_LLVMField mb_fp <- [nuP| ValPerm_LLVMField mb_fp |]
where
MbValPerm_LLVMField mb_fp =
mbMapCl $(mkClosed [| ValPerm_LLVMField |]) mb_fp
-}
-- | Build a 'ValPerm_LLVMField' in a binding
mbValPerm_LLVMField :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
Mb ctx (LLVMFieldPerm w sz) ->
Mb ctx (ValuePerm (LLVMPointerType w))
mbValPerm_LLVMField = mbMapCl $(mkClosed [| ValPerm_LLVMField |])
-- | The conjunction of exactly 1 array permission
pattern ValPerm_LLVMArray :: () => (a ~ LLVMPointerType w, 1 <= w, KnownNat w) =>
LLVMArrayPerm w -> ValuePerm a
pattern ValPerm_LLVMArray ap <- ValPerm_Conj [Perm_LLVMArray ap]
where
ValPerm_LLVMArray ap = ValPerm_Conj [Perm_LLVMArray ap]
{- FIXME: why doesn't this work?
-- | The conjunction of exactly 1 array permission
pattern MbValPerm_LLVMArray :: () => (a ~ LLVMPointerType w, 1 <= w, KnownNat w) =>
Mb ctx (LLVMArrayPerm w) -> Mb ctx (ValuePerm a)
pattern MbValPerm_LLVMArray mb_ap <- [nuP| ValPerm_LLVMArray mb_ap |]
where
MbValPerm_LLVMArray mb_ap =
mbMapCl $(mkClosed [| ValPerm_LLVMArray |]) mb_ap
-}
-- | Build a 'ValPerm_LLVMArray' in a binding
mbValPerm_LLVMArray :: (1 <= w, KnownNat w) => Mb ctx (LLVMArrayPerm w) ->
Mb ctx (ValuePerm (LLVMPointerType w))
mbValPerm_LLVMArray = mbMapCl $(mkClosed [| ValPerm_LLVMArray |])
-- | The conjunction of exactly 1 block permission
pattern ValPerm_LLVMBlock :: () => (a ~ LLVMPointerType w, 1 <= w, KnownNat w) =>
LLVMBlockPerm w -> ValuePerm a
pattern ValPerm_LLVMBlock bp <- ValPerm_Conj [Perm_LLVMBlock bp]
where
ValPerm_LLVMBlock bp = ValPerm_Conj [Perm_LLVMBlock bp]
-- | Build a 'ValPerm_LLVMBlock' in a binding
mbValPerm_LLVMBlock :: (1 <= w, KnownNat w) => Mb ctx (LLVMBlockPerm w) ->
Mb ctx (ValuePerm (LLVMPointerType w))
mbValPerm_LLVMBlock = mbMapCl $(mkClosed [| ValPerm_LLVMBlock |])
-- | The conjunction of exactly 1 block shape permission
pattern ValPerm_LLVMBlockShape :: () => (a ~ LLVMBlockType w, b ~ LLVMShapeType w,
1 <= w, KnownNat w) =>
PermExpr b -> ValuePerm a
pattern ValPerm_LLVMBlockShape sh <- ValPerm_Conj [Perm_LLVMBlockShape sh]
where
ValPerm_LLVMBlockShape sh = ValPerm_Conj [Perm_LLVMBlockShape sh]
-- | A single @lowned@ permission
pattern ValPerm_LOwned :: () => (a ~ LifetimeType) => [PermExpr LifetimeType] ->
LOwnedPerms ps_in -> LOwnedPerms ps_out -> ValuePerm a
pattern ValPerm_LOwned ls ps_in ps_out <- ValPerm_Conj [Perm_LOwned
ls ps_in ps_out]
where
ValPerm_LOwned ls ps_in ps_out = ValPerm_Conj [Perm_LOwned ls ps_in ps_out]
-- | A single simple @lowned@ permission
pattern ValPerm_LOwnedSimple :: () => (a ~ LifetimeType) =>
LOwnedPerms ps -> ValuePerm a
pattern ValPerm_LOwnedSimple ps <- ValPerm_Conj [Perm_LOwnedSimple ps]
where
ValPerm_LOwnedSimple ps = ValPerm_Conj [Perm_LOwnedSimple ps]
-- | A single @lcurrent@ permission
pattern ValPerm_LCurrent :: () => (a ~ LifetimeType) =>
PermExpr LifetimeType -> ValuePerm a
pattern ValPerm_LCurrent l <- ValPerm_Conj [Perm_LCurrent l]
where
ValPerm_LCurrent l = ValPerm_Conj [Perm_LCurrent l]
-- | A single @lfinished@ permission
pattern ValPerm_LFinished :: () => (a ~ LifetimeType) => ValuePerm a
pattern ValPerm_LFinished <- ValPerm_Conj [Perm_LFinished]
where
ValPerm_LFinished = ValPerm_Conj [Perm_LFinished]
pattern ValPerms_Nil :: () => (tps ~ RNil) => ValuePerms tps
pattern ValPerms_Nil = MNil
pattern ValPerms_Cons :: () => (tps ~ (tps' :> a)) =>
ValuePerms tps' -> ValuePerm a -> ValuePerms tps
pattern ValPerms_Cons ps p = ps :>: p
{-# COMPLETE ValPerms_Nil, ValPerms_Cons #-}
-- | Fold a function over a 'ValuePerms' list, where
--
-- > foldValuePerms f b ('ValuePermsCons'
-- > ('ValuePermsCons' (... 'ValuePermsNil' ...) p2) p1) =
-- > f (f (... b ...) p2) p1
--
-- FIXME: implement more functions on ValuePerms in terms of this
foldValuePerms :: (forall a. b -> ValuePerm a -> b) -> b -> ValuePerms as -> b
foldValuePerms _ b ValPerms_Nil = b
foldValuePerms f b (ValPerms_Cons ps p) = f (foldValuePerms f b ps) p
-- | Build a one-element 'ValuePerms' list from a single permission
singletonValuePerms :: ValuePerm a -> ValuePerms (RNil :> a)
singletonValuePerms = ValPerms_Cons ValPerms_Nil
-- | Build a 'ValuePerms' from an 'RAssign' of permissions
assignToPerms :: RAssign ValuePerm ps -> ValuePerms ps
assignToPerms MNil = ValPerms_Nil
assignToPerms (ps :>: p) = ValPerms_Cons (assignToPerms ps) p
-- | An LLVM pointer permission is an 'AtomicPerm' of type 'LLVMPointerType'
type LLVMPtrPerm w = AtomicPerm (LLVMPointerType w)
deriving instance Eq (LLVMFieldPerm w sz)
-- | Helper to get a 'NatRepr' for the size of an 'LLVMFieldPerm'
llvmFieldSize :: KnownNat sz => LLVMFieldPerm w sz -> NatRepr sz
llvmFieldSize _ = knownNat
-- | Get the size of an 'LLVMFieldPerm' in bytes
llvmFieldSizeBytes :: KnownNat sz => LLVMFieldPerm w sz -> Integer
llvmFieldSizeBytes fp = intValue (llvmFieldSize fp) `ceil_div` 8
-- | Get the size of an 'LLVMFieldPerm' as an expression
llvmFieldLen :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
LLVMFieldPerm w sz -> PermExpr (BVType w)
llvmFieldLen fp = exprLLVMTypeBytesExpr $ llvmFieldContents fp
-- | Get the ending offset of an 'LLVMFieldPerm'
llvmFieldEndOffset :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
LLVMFieldPerm w sz -> PermExpr (BVType w)
llvmFieldEndOffset fp = bvAdd (llvmFieldOffset fp) (llvmFieldLen fp)
-- | Helper to get a 'NatRepr' for the size of an 'LLVMFieldPerm' in a binding
mbLLVMFieldSize :: KnownNat sz => Mb ctx (LLVMFieldPerm w sz) -> NatRepr sz
mbLLVMFieldSize _ = knownNat
-- | Get the rw-modality-in-binding of a field permission in binding
mbLLVMFieldRW :: Mb ctx (LLVMFieldPerm w sz) -> Mb ctx (PermExpr RWModalityType)
mbLLVMFieldRW = mbMapCl $(mkClosed [| llvmFieldRW |])
-- | Get the lifetime-in-binding of a field permission in binding
mbLLVMFieldLifetime :: Mb ctx (LLVMFieldPerm w sz) ->
Mb ctx (PermExpr LifetimeType)
mbLLVMFieldLifetime = mbMapCl $(mkClosed [| llvmFieldLifetime |])
-- | Get the offset-in-binding of a field permission in binding
mbLLVMFieldOffset :: Mb ctx (LLVMFieldPerm w sz) -> Mb ctx (PermExpr (BVType w))
mbLLVMFieldOffset = mbMapCl $(mkClosed [| llvmFieldOffset |])
-- | Get the contents-in-binding of a field permission in binding
mbLLVMFieldContents :: Mb ctx (LLVMFieldPerm w sz) ->
Mb ctx (ValuePerm (LLVMPointerType sz))
mbLLVMFieldContents = mbMapCl $(mkClosed [| llvmFieldContents |])
-- | Get the range of bytes contained in a field permisison
llvmFieldRange :: (1 <= w, KnownNat w, KnownNat sz) => LLVMFieldPerm w sz ->
BVRange w
llvmFieldRange fp =
BVRange (llvmFieldOffset fp) (bvInt $ llvmFieldSizeBytes fp)
-- NOTE: we need a custom instance of Eq so we can use bvEq on the cell
instance Eq (LLVMArrayIndex w) where
LLVMArrayIndex e1 i1 == LLVMArrayIndex e2 i2 =
bvEq e1 e2 && i1 == i2
deriving instance Eq (LLVMArrayPerm w)
-- | Get the stride of an array in bits
llvmArrayStrideBits :: LLVMArrayPerm w -> Integer
llvmArrayStrideBits = toInteger . bytesToBits . llvmArrayStride
-- | Get the rw-modality-in-binding of an array permission in binding
mbLLVMArrayRW :: Mb ctx (LLVMArrayPerm w) -> Mb ctx (PermExpr RWModalityType)
mbLLVMArrayRW = mbMapCl $(mkClosed [| llvmArrayRW |])
-- | Get the lifetime-in-binding of an array permission in binding
mbLLVMArrayLifetime :: Mb ctx (LLVMArrayPerm w) ->
Mb ctx (PermExpr LifetimeType)
mbLLVMArrayLifetime = mbMapCl $(mkClosed [| llvmArrayLifetime |])
-- | Get the offset-in-binding of an array permission in binding
mbLLVMArrayOffset :: Mb ctx (LLVMArrayPerm w) -> Mb ctx (PermExpr (BVType w))
mbLLVMArrayOffset = mbMapCl $(mkClosed [| llvmArrayOffset |])
-- | Get the length-in-binding of an array permission in binding
mbLLVMArrayLen :: Mb ctx (LLVMArrayPerm w) -> Mb ctx (PermExpr (BVType w))
mbLLVMArrayLen = mbMapCl $(mkClosed [| llvmArrayLen |])
-- | Get the stride of an array permission in binding
mbLLVMArrayStride :: Mb ctx (LLVMArrayPerm w) -> Bytes
mbLLVMArrayStride = mbLift . mbMapCl $(mkClosed [| llvmArrayStride |])
-- | Get the cell-shape-in-binding of an array permission in binding
mbLLVMArrayCellShape :: Mb ctx (LLVMArrayPerm w) ->
Mb ctx (PermExpr (LLVMShapeType w))
mbLLVMArrayCellShape = mbMapCl $(mkClosed [| llvmArrayCellShape |])
-- | Get the borrows in a binding for an array permission in binding
mbLLVMArrayBorrows :: Mb ctx (LLVMArrayPerm w) -> Mb ctx [LLVMArrayBorrow w]
mbLLVMArrayBorrows = mbMapCl $(mkClosed [| llvmArrayBorrows |])
deriving instance Eq (LLVMArrayBorrow w)
deriving instance Eq (LLVMBlockPerm w)
-- | Get the rw-modality-in-binding of a block permission in binding
mbLLVMBlockRW :: Mb ctx (LLVMBlockPerm w) -> Mb ctx (PermExpr RWModalityType)
mbLLVMBlockRW = mbMapCl $(mkClosed [| llvmBlockRW |])
-- | Get the lifetime-in-binding of a block permission in binding
mbLLVMBlockLifetime :: Mb ctx (LLVMBlockPerm w) ->
Mb ctx (PermExpr LifetimeType)
mbLLVMBlockLifetime = mbMapCl $(mkClosed [| llvmBlockLifetime |])
-- | Get the offset-in-binding of a block permission in binding
mbLLVMBlockOffset :: Mb ctx (LLVMBlockPerm w) -> Mb ctx (PermExpr (BVType w))
mbLLVMBlockOffset = mbMapCl $(mkClosed [| llvmBlockOffset |])
-- | Get the length-in-binding of a block permission in binding
mbLLVMBlockLen :: Mb ctx (LLVMBlockPerm w) -> Mb ctx (PermExpr (BVType w))
mbLLVMBlockLen = mbMapCl $(mkClosed [| llvmBlockLen |])
-- | Get the shape-in-binding of a block permission in binding
mbLLVMBlockShape :: Mb ctx (LLVMBlockPerm w) ->
Mb ctx (PermExpr (LLVMShapeType w))
mbLLVMBlockShape = mbMapCl $(mkClosed [| llvmBlockShape |])
-- | Get the range of offsets represented by an 'LLVMBlockPerm'
llvmBlockRange :: LLVMBlockPerm w -> BVRange w
llvmBlockRange bp = BVRange (llvmBlockOffset bp) (llvmBlockLen bp)
-- | Get the range-in-binding of a block permission in binding
mbLLVMBlockRange :: Mb ctx (LLVMBlockPerm w) -> Mb ctx (BVRange w)
mbLLVMBlockRange = mbMapCl $(mkClosed [| llvmBlockRange |])
instance Eq (LLVMFieldShape w) where
(LLVMFieldShape p1) == (LLVMFieldShape p2)
| Just Refl <- testEquality (exprType p1) (exprType p2) = p1 == p2
_ == _ = False
instance TestEquality LOwnedPerm where
testEquality (LOwnedPermField e1 fp1) (LOwnedPermField e2 fp2)
| Just Refl <- testEquality (exprType e1) (exprType e2)
, Just Refl <- testEquality (llvmFieldSize fp1) (llvmFieldSize fp2)
, e1 == e2 && fp1 == fp2
= Just Refl
testEquality (LOwnedPermField _ _) _ = Nothing
testEquality (LOwnedPermArray e1 ap1) (LOwnedPermArray e2 ap2)
| Just Refl <- testEquality (exprType e1) (exprType e2)
, e1 == e2 && ap1 == ap2
= Just Refl
testEquality (LOwnedPermArray _ _) _ = Nothing
testEquality (LOwnedPermBlock e1 bp1) (LOwnedPermBlock e2 bp2)
| Just Refl <- testEquality (exprType e1) (exprType e2)
, e1 == e2 && bp1 == bp2
= Just Refl
testEquality (LOwnedPermBlock _ _) _ = Nothing
instance Eq (LOwnedPerm a) where
lop1 == lop2 | Just Refl <- testEquality lop1 lop2 = True
_ == _ = False
instance Eq1 LOwnedPerm where
eq1 = (==)
-- | Convert an 'LOwnedPerm' to the expression plus permission it represents
lownedPermExprAndPerm :: LOwnedPerm a -> ExprAndPerm a
lownedPermExprAndPerm (LOwnedPermField e fp) =
ExprAndPerm e $ ValPerm_LLVMField fp
lownedPermExprAndPerm (LOwnedPermArray e ap) =
ExprAndPerm e $ ValPerm_LLVMArray ap
lownedPermExprAndPerm (LOwnedPermBlock e bp) =
ExprAndPerm e $ ValPerm_LLVMBlock bp
-- | Convert an 'LOwnedPerm' to a variable plus permission, if possible
lownedPermVarAndPerm :: LOwnedPerm a -> Maybe (VarAndPerm a)
lownedPermVarAndPerm lop
| Just (x, off) <- asVarOffset (lownedPermExpr lop) =
Just $ VarAndPerm x (offsetPerm off $ lownedPermPerm lop)
lownedPermVarAndPerm _ = Nothing
-- | Convert an expression plus permission to an 'LOwnedPerm', if possible
varAndPermLOwnedPerm :: VarAndPerm a -> Maybe (LOwnedPerm a)
varAndPermLOwnedPerm (VarAndPerm x (ValPerm_LLVMField fp)) =
Just $ LOwnedPermField (PExpr_Var x) fp
varAndPermLOwnedPerm (VarAndPerm x (ValPerm_LLVMArray ap)) =
Just $ LOwnedPermArray (PExpr_Var x) ap
varAndPermLOwnedPerm (VarAndPerm x (ValPerm_LLVMBlock bp)) =
Just $ LOwnedPermBlock (PExpr_Var x) bp
varAndPermLOwnedPerm _ = Nothing
-- | Get the expression part of an 'LOwnedPerm'
lownedPermExpr :: LOwnedPerm a -> PermExpr a
lownedPermExpr = exprAndPermExpr . lownedPermExprAndPerm
-- | Convert the expression part of an 'LOwnedPerm' to a variable, if possible
lownedPermVar :: LOwnedPerm a -> Maybe (ExprVar a)
lownedPermVar lop | PExpr_Var x <- lownedPermExpr lop = Just x
lownedPermVar _ = Nothing
-- | Get the permission part of an 'LOwnedPerm'
lownedPermPerm :: LOwnedPerm a -> ValuePerm a
lownedPermPerm = exprAndPermPerm . lownedPermExprAndPerm
-- | Convert the permission part of an 'LOwnedPerm' to a block permission on a
-- variable, if possible
lownedPermVarBlockPerm :: LOwnedPerm a -> Maybe (ExprVar a, SomeLLVMBlockPerm a)
lownedPermVarBlockPerm lop
| Just (x, perm_off) <- asVarOffset (lownedPermExpr lop)
, ValPerm_Conj1 p <- lownedPermPerm lop
, Just (SomeLLVMBlockPerm bp) <- llvmAtomicPermToSomeBlock p
, off <- llvmPermOffsetExpr perm_off =
Just (x, SomeLLVMBlockPerm (offsetLLVMBlockPerm off bp))
lownedPermVarBlockPerm _ = Nothing
-- | Convert the permission part of an 'LOwnedPerm' in a binding to a block
-- permission on a variable in a binding, if possible
mbLownedPermVarBlockPerm :: Mb ctx (LOwnedPerm a) ->
Maybe (Mb ctx (ExprVar a, SomeLLVMBlockPerm a))
mbLownedPermVarBlockPerm =
mbMaybe . mbMapCl $(mkClosed [| lownedPermVarBlockPerm |])
-- | Get the read/write and lifetime modalities of an 'LOwnedPerm' of LLVM type
llvmLownedPermModalities :: LOwnedPerm (LLVMPointerType w) ->
(PermExpr RWModalityType, PermExpr LifetimeType)
llvmLownedPermModalities (LOwnedPermField _ fp) =
(llvmFieldRW fp, llvmFieldLifetime fp)
llvmLownedPermModalities (LOwnedPermArray _ ap) =
(llvmArrayRW ap, llvmArrayLifetime ap)
llvmLownedPermModalities (LOwnedPermBlock _ bp) =
(llvmBlockRW bp, llvmBlockLifetime bp)
-- | Find an 'LOwnedPerm' for a particular variable in an 'LOwnedPerms' list
findLOwnedPermForVar :: ExprVar a -> LOwnedPerms ps -> Maybe (LOwnedPerm a)
findLOwnedPermForVar _ MNil = Nothing
findLOwnedPermForVar x (_ :>: lop)
| Just (y, _) <- asVarOffset (lownedPermExpr lop)
, Just Refl <- testEquality x y = Just lop
findLOwnedPermForVar x (lops :>: _) = findLOwnedPermForVar x lops
-- | Find all 'LOwnedPerm's for a specific variable of LLVM pointer type in an
-- 'LOwnedPerms' list, and return the ranges of offsets that each of those cover
lownedPermsOffsetsForLLVMVar :: (1 <= w, KnownNat w) =>
ExprVar (LLVMPointerType w) -> LOwnedPerms ps ->
[BVRange w]
lownedPermsOffsetsForLLVMVar _ MNil = []
lownedPermsOffsetsForLLVMVar x (lops :>: lop)
| Just (y, SomeLLVMBlockPerm bp) <- lownedPermVarBlockPerm lop
, Just Refl <- testEquality x y =
llvmBlockRange bp : lownedPermsOffsetsForLLVMVar x lops
lownedPermsOffsetsForLLVMVar x (lops :>: _) =
lownedPermsOffsetsForLLVMVar x lops
-- | Extract the @args@ context from a function permission
funPermArgs :: FunPerm ghosts args gouts ret -> CruCtx args
funPermArgs (FunPerm _ args _ _ _ _) = args
-- | Extract the @ghosts@ context from a function permission
funPermGhosts :: FunPerm ghosts args gouts ret -> CruCtx ghosts
funPermGhosts (FunPerm ghosts _ _ _ _ _) = ghosts
-- | Extract the @ghosts@ and @args@ contexts from a function permission
funPermTops :: FunPerm ghosts args gouts ret -> CruCtx (ghosts :++: args)
funPermTops fun_perm =
appendCruCtx (funPermGhosts fun_perm) (funPermArgs fun_perm)
-- | Extract the return type from a function permission
funPermRet :: FunPerm ghosts args gouts ret -> TypeRepr ret
funPermRet (FunPerm _ _ _ ret _ _) = ret
-- | Extract the return types including ghosts from a function permission
funPermRets :: FunPerm ghosts args gouts ret -> CruCtx (gouts :> ret)
funPermRets fun_perm = CruCtxCons (funPermGouts fun_perm) (funPermRet fun_perm)
-- | Extract the @gouts@ context from a function permission
funPermGouts :: FunPerm ghosts args gouts ret -> CruCtx gouts
funPermGouts (FunPerm _ _ gouts _ _ _) = gouts
-- | Extract the input permissions of a function permission
funPermIns :: FunPerm ghosts args gouts ret -> MbValuePerms (ghosts :++: args)
funPermIns (FunPerm _ _ _ _ perms_in _) = perms_in
-- | Extract the output permissions of a function permission
funPermOuts :: FunPerm ghosts args gouts ret ->
MbValuePerms ((ghosts :++: args) :++: gouts :> ret)
funPermOuts (FunPerm _ _ _ _ _ perms_out) = perms_out
-- | Test whether a name of a given 'NameSort' can be folded / unfolded
type family NameSortCanFold (ns::NameSort) :: Bool where
NameSortCanFold (DefinedSort _) = 'True
NameSortCanFold (OpaqueSort _) = 'False
NameSortCanFold (RecursiveSort b _) = 'True
-- | Get a 'BoolRepr' for whether a name sort is conjunctive
nameSortIsConjRepr :: NameSortRepr ns -> BoolRepr (NameSortIsConj ns)
nameSortIsConjRepr (DefinedSortRepr b) = b
nameSortIsConjRepr (OpaqueSortRepr b) = b
nameSortIsConjRepr (RecursiveSortRepr b _) = b
-- | Get a 'BoolRepr' for whether a 'NamedPermName' is conjunctive
nameIsConjRepr :: NamedPermName ns args a -> BoolRepr (NameSortIsConj ns)
nameIsConjRepr = nameSortIsConjRepr . namedPermNameSort
-- | Get a 'BoolRepr' for whether a name sort allows folds / unfolds
nameSortCanFoldRepr :: NameSortRepr ns -> BoolRepr (NameSortCanFold ns)
nameSortCanFoldRepr (DefinedSortRepr _) = TrueRepr
nameSortCanFoldRepr (OpaqueSortRepr _) = FalseRepr
nameSortCanFoldRepr (RecursiveSortRepr _ _) = TrueRepr
-- | Get a 'BoolRepr' for whether a 'NamedPermName' allows folds / unfolds
nameCanFoldRepr :: NamedPermName ns args a -> BoolRepr (NameSortCanFold ns)
nameCanFoldRepr = nameSortCanFoldRepr . namedPermNameSort
-- | Extract to Boolean value out of a 'BoolRepr'
--
-- FIXME: this should probably go in @BoolRepr.hs@
boolVal :: BoolRepr b -> Bool
boolVal TrueRepr = True
boolVal FalseRepr = False
-- | Test whether a name of a given sort can be used as an atomic permission
nameSortIsConj :: NameSortRepr ns -> Bool
nameSortIsConj = boolVal . nameSortIsConjRepr
-- | Get a 'Bool' for whether a 'NamedPermName' allows folds / unfolds
nameCanFold :: NamedPermName ns args a -> Bool
nameCanFold = boolVal . nameCanFoldRepr
instance TestEquality NameSortRepr where
testEquality (DefinedSortRepr b1) (DefinedSortRepr b2)
| Just Refl <- testEquality b1 b2 = Just Refl
testEquality (DefinedSortRepr _) _ = Nothing
testEquality (OpaqueSortRepr b1) (OpaqueSortRepr b2)
| Just Refl <- testEquality b1 b2 = Just Refl
testEquality (OpaqueSortRepr _) _ = Nothing
testEquality (RecursiveSortRepr b1 reach1) (RecursiveSortRepr b2 reach2)
| Just Refl <- testEquality b1 b2
, Just Refl <- testEquality reach1 reach2
= Just Refl
testEquality (RecursiveSortRepr _ _) _ = Nothing
-- | Extract a 'BoolRepr' from a 'NameReachConstr' for whether the name it
-- constrains is a reachability name
nameReachConstrBool :: NameReachConstr ns args a ->
BoolRepr (IsReachabilityName ns)
nameReachConstrBool NameReachConstr = TrueRepr
nameReachConstrBool NameNonReachConstr = FalseRepr
-- FIXME: NamedPermNames should maybe say something about which arguments are
-- covariant? Right now we assume lifetime and rwmodalities are covariant
-- w.r.t. their respective orders, and everything else is invariant, but that
-- could potentially change
-- | Test if two 'NamedPermName's of possibly different types are equal
testNamedPermNameEq :: NamedPermName ns1 args1 a1 ->
NamedPermName ns2 args2 a2 ->
Maybe (ns1 :~: ns2, args1 :~: args2, a1 :~: a2)
testNamedPermNameEq (NamedPermName str1 tp1 ctx1 ns1 _r1)
(NamedPermName str2 tp2 ctx2 ns2 _r2)
| Just Refl <- testEquality tp1 tp2
, Just Refl <- testEquality ctx1 ctx2
, Just Refl <- testEquality ns1 ns2
, str1 == str2 = Just (Refl, Refl, Refl)
testNamedPermNameEq _ _ = Nothing
instance Eq (NamedPermName ns args a) where
n1 == n2 | Just (Refl, Refl, Refl) <- testNamedPermNameEq n1 n2 = True
_ == _ = False
instance Eq SomeNamedPermName where
(SomeNamedPermName n1) == (SomeNamedPermName n2)
| Just (Refl, Refl, Refl) <- testNamedPermNameEq n1 n2 = True
_ == _ = False
-- | An existentially quantified conjunctive 'NamedPermName'
data SomeNamedConjPermName where
SomeNamedConjPermName ::
NameSortIsConj ns ~ 'True => NamedPermName ns args a ->
SomeNamedConjPermName
-- | Test if two 'NamedShapes' of possibly different @b@ and @args@ arguments
-- are equal
namedShapeEq :: NamedShape b1 args1 w -> NamedShape b2 args2 w ->
Maybe (b1 :~: b2, args1 :~: args2)
namedShapeEq nmsh1 nmsh2
| Just Refl <- testEquality (namedShapeArgs nmsh1) (namedShapeArgs nmsh2)
, b1 <- namedShapeCanUnfoldRepr nmsh1
, b2 <- namedShapeCanUnfoldRepr nmsh2
, Just Refl <- testEquality b1 b2
, namedShapeName nmsh1 == namedShapeName nmsh2
, namedShapeBody nmsh1 == namedShapeBody nmsh2 =
Just (Refl,Refl)
namedShapeEq _ _ = Nothing
deriving instance Eq (NamedShapeBody b args w)
-- | Test if a 'NamedShape' is recursive
namedShapeIsRecursive :: NamedShape b args w -> Bool
namedShapeIsRecursive (NamedShape _ _ (RecShapeBody _ _ _)) = True
namedShapeIsRecursive _ = False
-- | Test if a 'NamedShape' in a binding is recursive
mbNamedShapeIsRecursive :: Mb ctx (NamedShape b args w) -> Bool
mbNamedShapeIsRecursive =
mbLift . mbMapCl $(mkClosed [| namedShapeIsRecursive |])
-- | Get a 'BoolRepr' for the Boolean flag for whether a named shape can be
-- unfolded
namedShapeCanUnfoldRepr :: NamedShape b args w -> BoolRepr b
namedShapeCanUnfoldRepr (NamedShape _ _ (DefinedShapeBody _)) = TrueRepr
namedShapeCanUnfoldRepr (NamedShape _ _ (OpaqueShapeBody _ _)) = FalseRepr
namedShapeCanUnfoldRepr (NamedShape _ _ (RecShapeBody _ _ _)) = TrueRepr
-- | Get a 'BoolRepr' for the Boolean flag for whether a named shape in a
-- binding can be unfolded
mbNamedShapeCanUnfoldRepr :: Mb ctx (NamedShape b args w) -> BoolRepr b
mbNamedShapeCanUnfoldRepr =
mbLift . mbMapCl $(mkClosed [| namedShapeCanUnfoldRepr |])
-- | Whether a 'NamedShape' can be unfolded
namedShapeCanUnfold :: NamedShape b args w -> Bool
namedShapeCanUnfold = boolVal . namedShapeCanUnfoldRepr
instance Eq (PermOffset a) where
NoPermOffset == NoPermOffset = True
(LLVMPermOffset e1) == (LLVMPermOffset e2) = e1 == e2
_ == _ = False
-- | Smart constructor for 'LLVMPermOffset', that maps a 0 to 'NoPermOffset'
mkLLVMPermOffset :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
PermOffset (LLVMPointerType w)
mkLLVMPermOffset off | bvIsZero off = NoPermOffset
mkLLVMPermOffset off = LLVMPermOffset off
-- | Extract a bitvector offset expression from a 'PermOffset' of pointer type
llvmPermOffsetExpr :: (1 <= w, KnownNat w) => PermOffset (LLVMPointerType w) ->
PermExpr (BVType w)
llvmPermOffsetExpr NoPermOffset = bvInt 0
llvmPermOffsetExpr (LLVMPermOffset e) = e
-- | Test two 'PermOffset's for semantic, not just syntactic, equality
offsetsEq :: PermOffset a -> PermOffset a -> Bool
offsetsEq NoPermOffset NoPermOffset = True
offsetsEq (LLVMPermOffset off) NoPermOffset = bvIsZero off
offsetsEq NoPermOffset (LLVMPermOffset off) = bvIsZero off
offsetsEq (LLVMPermOffset off1) (LLVMPermOffset off2) = bvEq off1 off2
-- | Add a 'PermOffset' to an expression
offsetExpr :: PermOffset a -> PermExpr a -> PermExpr a
offsetExpr NoPermOffset e = e
offsetExpr (LLVMPermOffset off) e = addLLVMOffset e off
-- | Convert an expression to a variable + optional offset, if this is possible
asVarOffset :: PermExpr a -> Maybe (ExprVar a, PermOffset a)
asVarOffset (PExpr_Var x) = Just (x, NoPermOffset)
asVarOffset (PExpr_LLVMOffset x off) = Just (x, LLVMPermOffset off)
asVarOffset _ = Nothing
-- | Convert an expression to a variable if possible
asVar :: PermExpr a -> Maybe (ExprVar a)
asVar e
| Just (x,off) <- asVarOffset e
, offsetsEq off NoPermOffset =
Just x
asVar _ = Nothing
-- | Negate a 'PermOffset'
negatePermOffset :: PermOffset a -> PermOffset a
negatePermOffset NoPermOffset = NoPermOffset
negatePermOffset (LLVMPermOffset off) = LLVMPermOffset $ bvNegate off
-- | Add two 'PermOffset's
addPermOffsets :: PermOffset a -> PermOffset a -> PermOffset a
addPermOffsets NoPermOffset off = off
addPermOffsets off NoPermOffset = off
addPermOffsets (LLVMPermOffset off1) (LLVMPermOffset off2) =
mkLLVMPermOffset (bvAdd off1 off2)
-- | Get the @n@th expression in a 'PermExprs' list
nthPermExpr :: PermExprs args -> Member args a -> PermExpr a
nthPermExpr (PExprs_Cons _ arg) Member_Base = arg
nthPermExpr (PExprs_Cons args _) (Member_Step memb) =
nthPermExpr args memb
-- | Set the @n@th expression in a 'PermExprs' list
setNthPermExpr :: PermExprs args -> Member args a -> PermExpr a ->
PermExprs args
setNthPermExpr (PExprs_Cons args _) Member_Base a =
PExprs_Cons args a
setNthPermExpr (PExprs_Cons args arg) (Member_Step memb) a =
PExprs_Cons (setNthPermExpr args memb a) arg
-- | Get a list of 'Member' proofs for each expression in a 'PermExprs' list
getPermExprsMembers :: PermExprs args ->
[Some (Member args :: CrucibleType -> Type)]
getPermExprsMembers PExprs_Nil = []
getPermExprsMembers (PExprs_Cons args _) =
map (\case Some memb -> Some (Member_Step memb)) (getPermExprsMembers args)
++ [Some Member_Base]
-- | Extract the name back out of the interpretation of a 'NamedPerm'
namedPermName :: NamedPerm ns args a -> NamedPermName ns args a
namedPermName (NamedPerm_Opaque op) = opaquePermName op
namedPermName (NamedPerm_Rec rp) = recPermName rp
namedPermName (NamedPerm_Defined dp) = definedPermName dp
-- | Extract out the argument context of the name of a 'NamedPerm'
namedPermArgs :: NamedPerm ns args a -> CruCtx args
namedPermArgs = namedPermNameArgs . namedPermName
-- | Get the @trans@ method from a 'RecPerm' for a reachability permission
recPermTransMethod :: RecPerm b 'True args a -> Ident
recPermTransMethod (RecPerm { recPermReachMethods = ReachMethods { .. }}) =
reachMethodTrans
-- | Extract the permissions from a 'VarAndPerm'
varAndPermPerm :: VarAndPerm a -> ValuePerm a
varAndPermPerm (VarAndPerm _ p) = p
-- | A pair that is specifically pretty-printing with a colon
data ColonPair a b = ColonPair a b
-- | Pattern for an empty 'DistPerms'
pattern DistPermsNil :: () => (ps ~ RNil) => DistPerms ps
pattern DistPermsNil = MNil
-- | Pattern for a non-empty 'DistPerms'
pattern DistPermsCons :: () => (ps ~ (ps' :> a)) =>
DistPerms ps' -> ExprVar a -> ValuePerm a ->
DistPerms ps
pattern DistPermsCons ps x p <- ps :>: (VarAndPerm x p)
where
DistPermsCons ps x p = ps :>: VarAndPerm x p
{-# COMPLETE DistPermsNil, DistPermsCons #-}
{-
data DistPerms ps where
DistPermsNil :: DistPerms RNil
DistPermsCons :: DistPerms ps -> ExprVar a -> ValuePerm a ->
DistPerms (ps :> a)
-}
type MbDistPerms ps = Mb ps (DistPerms ps)
-- | A pair of an epxression and its permission; we give it its own datatype to
-- make certain typeclass instances (like pretty-printing) specific to it
data ExprAndPerm a =
ExprAndPerm { exprAndPermExpr :: PermExpr a,
exprAndPermPerm :: ValuePerm a }
-- | A list of expressions and associated permissions; different from
-- 'DistPerms' because the expressions need not be variables
type ExprPerms = RAssign ExprAndPerm
-- | Convert a 'DistPerms' to an 'ExprPerms'
distPermsToExprPerms :: DistPerms ps -> ExprPerms ps
distPermsToExprPerms =
RL.map (\(VarAndPerm x p) -> ExprAndPerm (PExpr_Var x) p)
-- FIXME: change all of the following functions on DistPerms to use the RAssign
-- combinators
-- | Fold a function over a 'DistPerms' list, where
--
-- > foldDistPerms f b ('DistPermsCons'
-- > ('DistPermsCons' (... 'DistPermsNil' ...) x2 p2) x1 p1) =
-- > f (f (... b ...) x2 p2) x1 p1
--
-- FIXME: implement more functions on DistPerms in terms of this
foldDistPerms :: (forall a. b -> ExprVar a -> ValuePerm a -> b) ->
b -> DistPerms as -> b
foldDistPerms _ b DistPermsNil = b
foldDistPerms f b (DistPermsCons ps x p) = f (foldDistPerms f b ps) x p
-- | Find all permissions in a 'DistPerms' on a specific variable
varPermsInDistPerms :: ExprVar a -> DistPerms ps -> [ValuePerm a]
varPermsInDistPerms x =
RL.foldr (\case (VarAndPerm y p) | Just Refl <- testEquality x y -> (p:)
_ -> id)
[]
-- | Find all atomic permissions in a 'DistPerms' on a specific variable
varAtomicPermsInDistPerms :: ExprVar a -> DistPerms ps -> [AtomicPerm a]
varAtomicPermsInDistPerms x =
RL.foldr (\case (VarAndPerm y (ValPerm_Conj ps))
| Just Refl <- testEquality x y -> (ps ++)
_ -> id)
[]
-- | Combine a list of variable names and a list of permissions into a list of
-- distinguished permissions
valuePermsToDistPerms :: RAssign Name ps -> ValuePerms ps -> DistPerms ps
valuePermsToDistPerms MNil _ = DistPermsNil
valuePermsToDistPerms (ns :>: n) (ps :>: p) =
DistPermsCons (valuePermsToDistPerms ns ps) n p
-- | Convert a list of permissions inside bindings for variables into a list of
-- distinguished permissions for those variables
mbValuePermsToDistPerms :: MbValuePerms ps -> MbDistPerms ps
mbValuePermsToDistPerms = nuMultiWithElim1 valuePermsToDistPerms
-- | Extract the permissions from a 'DistPerms'
distPermsToValuePerms :: DistPerms ps -> ValuePerms ps
distPermsToValuePerms DistPermsNil = ValPerms_Nil
distPermsToValuePerms (DistPermsCons dperms _ p) =
ValPerms_Cons (distPermsToValuePerms dperms) p
-- | Extract the permissions-in-binding from a 'DistPerms' in a binding
mbDistPermsToValuePerms :: Mb ctx (DistPerms ps) -> Mb ctx (ValuePerms ps)
mbDistPermsToValuePerms = fmap distPermsToValuePerms
-- | Create a sequence @x1:eq(e1), ..., xn:eq(en)@ of equality permissions
eqDistPerms :: RAssign Name ps -> PermExprs ps -> DistPerms ps
eqDistPerms ns exprs =
valuePermsToDistPerms ns $ RL.map ValPerm_Eq $ exprsToRAssign exprs
-- | Create a sequence @x1:true, ..., xn:true@ of vacuous permissions
trueDistPerms :: RAssign Name ps -> DistPerms ps
trueDistPerms MNil = DistPermsNil
trueDistPerms (ns :>: n) = DistPermsCons (trueDistPerms ns) n ValPerm_True
-- | A list of "distinguished" permissions with types
type TypedDistPerms = RAssign (Typed VarAndPerm)
-- | Convert a permission list expression to a 'TypedDistPerms', if possible
permListToTypedPerms :: PermExpr PermListType -> Maybe (Some TypedDistPerms)
permListToTypedPerms PExpr_PermListNil = Just $ Some MNil
permListToTypedPerms (PExpr_PermListCons tp (PExpr_Var x) p l)
| Just (Some perms) <- permListToTypedPerms l =
Just $ Some $ RL.append (MNil :>: Typed tp (VarAndPerm x p)) perms
permListToTypedPerms _ = Nothing
-- | Convert a 'TypedDistPerms' to a permission list
typedPermsToPermList :: TypedDistPerms ps -> PermExpr PermListType
typedPermsToPermList = flip helper PExpr_PermListNil where
-- We use an accumulator to reverse as we go, because DistPerms cons to the
-- right while PermLists cons to the left
helper :: TypedDistPerms ps' -> PermExpr PermListType -> PermExpr PermListType
helper MNil accum = accum
helper (ps :>: Typed tp (VarAndPerm x p)) accum =
helper ps $ PExpr_PermListCons tp (PExpr_Var x) p accum
-- | Convert a 'TypedDistPerms' to a normal 'DistPerms'
unTypeDistPerms :: TypedDistPerms ps -> DistPerms ps
unTypeDistPerms = RL.map (\(Typed _ v_and_p) -> v_and_p)
instance TestEquality VarAndPerm where
testEquality (VarAndPerm x1 p1) (VarAndPerm x2 p2)
| Just Refl <- testEquality x1 x2
, p1 == p2
= Just Refl
testEquality _ _ = Nothing
instance Eq (VarAndPerm a) where
vp1 == vp2 | Just _ <- testEquality vp1 vp2 = True
_ == _ = False
instance Eq1 VarAndPerm where
eq1 = (==)
{-
instance TestEquality DistPerms where
testEquality DistPermsNil DistPermsNil = Just Refl
testEquality (DistPermsCons ps1 x1 p1) (DistPermsCons ps2 x2 p2)
| Just Refl <- testEquality ps1 ps2
, Just Refl <- testEquality x1 x2
, p1 == p2
= Just Refl
testEquality _ _ = Nothing
instance Eq (DistPerms ps) where
perms1 == perms2 =
case testEquality perms1 perms2 of
Just _ -> True
Nothing -> False
-}
-- | Build the permission and the variable it applies to that is needed to prove
-- that @l@ is current during @l2@. If @l@ is @always@, this holds vacuously, so
-- return the permission @l2:true@, and otherwise, if @l@ is a variable, return
-- @l:[l2]lcurrent@.
lcurrentPerm :: PermExpr LifetimeType -> ExprVar LifetimeType ->
(ExprVar LifetimeType, ValuePerm LifetimeType)
lcurrentPerm PExpr_Always l2 = (l2, ValPerm_True)
lcurrentPerm (PExpr_Var l) l2 = (l, ValPerm_LCurrent $ PExpr_Var l2)
-- | Get the lifetime that a 'LifetimeCurrentPerms' is about
lifetimeCurrentPermsLifetime :: LifetimeCurrentPerms ps_l ->
PermExpr LifetimeType
lifetimeCurrentPermsLifetime AlwaysCurrentPerms = PExpr_Always
lifetimeCurrentPermsLifetime (LOwnedCurrentPerms l _ _ _) = PExpr_Var l
lifetimeCurrentPermsLifetime (LOwnedSimpleCurrentPerms l _) = PExpr_Var l
lifetimeCurrentPermsLifetime (CurrentTransPerms _ l) = PExpr_Var l
-- | Convert a 'LifetimeCurrentPerms' to the 'DistPerms' it represent
lifetimeCurrentPermsPerms :: LifetimeCurrentPerms ps_l -> DistPerms ps_l
lifetimeCurrentPermsPerms AlwaysCurrentPerms = DistPermsNil
lifetimeCurrentPermsPerms (LOwnedCurrentPerms l ls ps_in ps_out) =
DistPermsCons DistPermsNil l $ ValPerm_LOwned ls ps_in ps_out
lifetimeCurrentPermsPerms (LOwnedSimpleCurrentPerms l lops) =
distPerms1 l $ ValPerm_LOwnedSimple lops
lifetimeCurrentPermsPerms (CurrentTransPerms cur_ps l) =
DistPermsCons (lifetimeCurrentPermsPerms cur_ps) l $
ValPerm_Conj1 $ Perm_LCurrent $ lifetimeCurrentPermsLifetime cur_ps
-- | Build a lift of proxies for a 'LifetimeCurrentPerms'
mbLifetimeCurrentPermsProxies :: Mb ctx (LifetimeCurrentPerms ps_l) ->
RAssign Proxy ps_l
mbLifetimeCurrentPermsProxies mb_l = case mbMatch mb_l of
[nuMP| AlwaysCurrentPerms |] -> MNil
[nuMP| LOwnedCurrentPerms _ _ _ _ |] -> MNil :>: Proxy
[nuMP| LOwnedSimpleCurrentPerms _ _ |] -> MNil :>: Proxy
[nuMP| CurrentTransPerms cur_ps _ |] ->
mbLifetimeCurrentPermsProxies cur_ps :>: Proxy
-- | Apply a functor to its arguments to get out a permission
ltFuncApply :: LifetimeFunctor args a -> PermExprs args ->
PermExpr LifetimeType -> ValuePerm a
ltFuncApply (LTFunctorField off p) (MNil :>: rw) l =
ValPerm_LLVMField $ LLVMFieldPerm rw l off p
ltFuncApply (LTFunctorArray off len stride sh bs) (MNil :>: rw) l =
ValPerm_LLVMArray $ LLVMArrayPerm rw l off len stride sh bs
ltFuncApply (LTFunctorBlock off len sh) (MNil :>: rw) l =
ValPerm_LLVMBlock $ LLVMBlockPerm rw l off len sh
-- | Apply a functor to its arguments to get out an 'LOwnedPerm' on a variable
ltFuncApplyLOP :: ExprVar a -> LifetimeFunctor args a -> PermExprs args ->
PermExpr LifetimeType -> LOwnedPerm a
ltFuncApplyLOP x (LTFunctorField off p) (MNil :>: rw) l =
LOwnedPermField (PExpr_Var x) $ LLVMFieldPerm rw l off p
ltFuncApplyLOP x (LTFunctorArray off len stride sh bs) (MNil :>: rw) l =
LOwnedPermArray (PExpr_Var x) $ LLVMArrayPerm rw l off len stride sh bs
ltFuncApplyLOP x (LTFunctorBlock off len sh) (MNil :>: rw) l =
LOwnedPermBlock (PExpr_Var x) $ LLVMBlockPerm rw l off len sh
-- | Apply a functor to a lifetime and the "minimal" rwmodalities, i.e., with
-- all read permissions
ltFuncMinApply :: LifetimeFunctor args a -> PermExpr LifetimeType -> ValuePerm a
ltFuncMinApply (LTFunctorField off p) l =
ValPerm_LLVMField $ LLVMFieldPerm PExpr_Read l off p
ltFuncMinApply (LTFunctorArray off len stride sh bs) l =
ValPerm_LLVMArray $ LLVMArrayPerm PExpr_Read l off len stride sh bs
ltFuncMinApply (LTFunctorBlock off len sh) l =
ValPerm_LLVMBlock $ LLVMBlockPerm PExpr_Read l off len sh
-- | Apply a functor to a lifetime and the "minimal" rwmodalities, i.e., with
-- all read permissions, getting out an 'LOwnedPerm' on a variable
ltFuncMinApplyLOP :: ExprVar a -> LifetimeFunctor args a ->
PermExpr LifetimeType -> LOwnedPerm a
ltFuncMinApplyLOP x (LTFunctorField off p) l =
LOwnedPermField (PExpr_Var x) $ LLVMFieldPerm PExpr_Read l off p
ltFuncMinApplyLOP x (LTFunctorArray off len stride sh bs) l =
LOwnedPermArray (PExpr_Var x) $ LLVMArrayPerm PExpr_Read l off len stride sh bs
ltFuncMinApplyLOP x (LTFunctorBlock off len sh) l =
LOwnedPermBlock (PExpr_Var x) $ LLVMBlockPerm PExpr_Read l off len sh
-- | Convert a field permission to a lifetime functor and its arguments
fieldToLTFunc :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
LLVMFieldPerm w sz ->
(LifetimeFunctor (RNil :> RWModalityType) (LLVMPointerType w),
PermExprs (RNil :> RWModalityType))
fieldToLTFunc fp = (LTFunctorField (llvmFieldOffset fp) (llvmFieldContents fp),
MNil :>: llvmFieldRW fp)
-- | Convert an array permission to a lifetime functor and its arguments
arrayToLTFunc :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
(LifetimeFunctor (RNil :> RWModalityType) (LLVMPointerType w),
PermExprs (RNil :> RWModalityType))
arrayToLTFunc (LLVMArrayPerm rw _ off len stride sh bs) =
(LTFunctorArray off len stride sh bs, MNil :>: rw)
-- | Convert a block permission to a lifetime functor and its arguments
blockToLTFunc :: (1 <= w, KnownNat w) => LLVMBlockPerm w ->
(LifetimeFunctor (RNil :> RWModalityType) (LLVMPointerType w),
PermExprs (RNil :> RWModalityType))
blockToLTFunc bp =
(LTFunctorBlock (llvmBlockOffset bp) (llvmBlockLen bp) (llvmBlockShape bp),
MNil :>: llvmBlockRW bp)
instance Eq (ValuePerm a) where
(ValPerm_Eq e1) == (ValPerm_Eq e2) = e1 == e2
(ValPerm_Eq _) == _ = False
(ValPerm_Or p1 p1') == (ValPerm_Or p2 p2') = p1 == p2 && p1' == p2'
(ValPerm_Or _ _) == _ = False
(ValPerm_Exists (p1 :: Binding a1 (ValuePerm a))) ==
(ValPerm_Exists (p2 :: Binding a2 (ValuePerm a)))
| Just Refl <-
testEquality (knownRepr :: TypeRepr a1) (knownRepr :: TypeRepr a2)
= p1 == p2
(ValPerm_Exists _) == _ = False
(ValPerm_Named n1 args1 off1) == (ValPerm_Named n2 args2 off2)
| Just (Refl, Refl, Refl) <- testNamedPermNameEq n1 n2 =
args1 == args2 && off1 == off2
(ValPerm_Named _ _ _) == _ = False
(ValPerm_Var x1 off1) == (ValPerm_Var x2 off2) = x1 == x2 && off1 == off2
(ValPerm_Var _ _) == _ = False
(ValPerm_Conj aps1) == (ValPerm_Conj aps2) = aps1 == aps2
(ValPerm_Conj _) == _ = False
ValPerm_False == ValPerm_False = True
ValPerm_False == _ = False
instance Eq (AtomicPerm a) where
(Perm_LLVMField fp1) == (Perm_LLVMField fp2)
| Just Refl <- testEquality (llvmFieldSize fp1) (llvmFieldSize fp2)
= fp1 == fp2
(Perm_LLVMField _) == _ = False
(Perm_LLVMArray ap1) == (Perm_LLVMArray ap2) = ap1 == ap2
(Perm_LLVMArray _) == _ = False
(Perm_LLVMBlock bp1) == (Perm_LLVMBlock bp2) = bp1 == bp2
(Perm_LLVMBlock _) == _ = False
(Perm_LLVMFree e1) == (Perm_LLVMFree e2) = e1 == e2
(Perm_LLVMFree _) == _ = False
(Perm_LLVMFunPtr tp1 p1) == (Perm_LLVMFunPtr tp2 p2)
| Just Refl <- testEquality tp1 tp2 = p1 == p2
(Perm_LLVMFunPtr _ _) == _ = False
Perm_IsLLVMPtr == Perm_IsLLVMPtr = True
Perm_IsLLVMPtr == _ = False
(Perm_LLVMBlockShape sh1) == (Perm_LLVMBlockShape sh2) = sh1 == sh2
(Perm_LLVMBlockShape _) == _ = False
(Perm_LLVMFrame frame1) == (Perm_LLVMFrame frame2) = frame1 == frame2
(Perm_LLVMFrame _) == _ = False
(Perm_LOwned ls1 ps_in1 ps_out1) == (Perm_LOwned ls2 ps_in2 ps_out2)
| Just Refl <- testEquality ps_in1 ps_in2
, Just Refl <- testEquality ps_out1 ps_out2
= ls1 == ls2
(Perm_LOwned _ _ _) == _ = False
(Perm_LOwnedSimple lops1) == (Perm_LOwnedSimple lops2)
| Just Refl <- testEquality lops1 lops2 = True
(Perm_LOwnedSimple _) == _ = False
(Perm_LCurrent e1) == (Perm_LCurrent e2) = e1 == e2
(Perm_LCurrent _) == _ = False
Perm_LFinished == Perm_LFinished = True
Perm_LFinished == _ = False
(Perm_Struct ps1) == (Perm_Struct ps2) = ps1 == ps2
(Perm_Struct _) == _ = False
(Perm_Fun fperm1) == (Perm_Fun fperm2)
| Just (Refl, Refl) <- funPermEq fperm1 fperm2 = True
(Perm_Fun _) == _ = False
(Perm_NamedConj n1 args1 off1) == (Perm_NamedConj n2 args2 off2)
| Just (Refl, Refl, Refl) <- testNamedPermNameEq n1 n2 =
args1 == args2 && off1 == off2
(Perm_NamedConj _ _ _) == _ = False
(Perm_BVProp p1) == (Perm_BVProp p2) = p1 == p2
(Perm_BVProp _) == _ = False
instance Eq1 ValuePerm where
eq1 = (==)
{-
instance Eq (ValuePerms as) where
ValPerms_Nil == ValPerms_Nil = True
(ValPerms_Cons ps1 p1) == (ValPerms_Cons ps2 p2) =
ps1 == ps2 && p1 == p2
-}
-- | Test if function permissions with different ghost argument lists are equal
funPermEq :: FunPerm ghosts1 args gouts1 ret ->
FunPerm ghosts2 args gouts2 ret ->
Maybe (ghosts1 :~: ghosts2, gouts1 :~: gouts2)
funPermEq (FunPerm ghosts1 _ gouts1 _ perms_in1 perms_out1)
(FunPerm ghosts2 _ gouts2 _ perms_in2 perms_out2)
| Just Refl <- testEquality ghosts1 ghosts2
, Just Refl <- testEquality gouts1 gouts2
, perms_in1 == perms_in2 && perms_out1 == perms_out2
= Just (Refl, Refl)
funPermEq _ _ = Nothing
-- | Test if function permissions with all 4 type args different are equal
funPermEq4 :: FunPerm ghosts1 args1 gouts1 ret1 ->
FunPerm ghosts2 args2 gouts2 ret2 ->
Maybe (ghosts1 :~: ghosts2, args1 :~: args2,
gouts1 :~: gouts2, ret1 :~: ret2)
funPermEq4 (FunPerm ghosts1 args1 ret1 gouts1 perms_in1 perms_out1)
(FunPerm ghosts2 args2 ret2 gouts2 perms_in2 perms_out2)
| Just Refl <- testEquality ghosts1 ghosts2
, Just Refl <- testEquality args1 args2
, Just Refl <- testEquality gouts1 gouts2
, Just Refl <- testEquality ret1 ret2
, perms_in1 == perms_in2 && perms_out1 == perms_out2
= Just (Refl, Refl, Refl, Refl)
funPermEq4 _ _ = Nothing
instance Eq (FunPerm ghosts args gouts ret) where
fperm1 == fperm2 = isJust (funPermEq fperm1 fperm2)
instance PermPretty (NamedPermName ns args a) where
permPrettyM (NamedPermName str _ _ _ _) = return $ pretty str
instance PermPretty (ValuePerm a) where
permPrettyM (ValPerm_Eq e) = ((pretty "eq" <>) . parens) <$> permPrettyM e
permPrettyM (ValPerm_Or p1 p2) =
-- FIXME: If we ever fix the SAW lexer to handle "\/"...
-- (\pp1 pp2 -> hang 2 (pp1 </> string "\\/" <> pp2))
(\pp1 pp2 -> hang 2 (pp1 <> softline <> pretty "or" <+> pp2))
<$> permPrettyM p1 <*> permPrettyM p2
permPrettyM (ValPerm_Exists mb_p) =
flip permPrettyExprMb mb_p $ \(_ :>: Constant pp_n) ppm ->
(\pp -> pretty "exists" <+> pp_n <> dot <+> pp) <$> ppm
permPrettyM (ValPerm_Named n args off) =
do n_pp <- permPrettyM n
args_pp <- permPrettyM args
off_pp <- permPrettyM off
return (n_pp <> pretty '<' <>
align (args_pp <> pretty '>') <> off_pp)
permPrettyM (ValPerm_Var n off) =
do n_pp <- permPrettyM n
off_pp <- permPrettyM off
return (n_pp <> off_pp)
permPrettyM ValPerm_True = return $ pretty "true"
permPrettyM (ValPerm_Conj ps) =
(hang 2 . encloseSep mempty mempty (pretty "*")) <$> mapM permPrettyM ps
permPrettyM (ValPerm_False) = return $ pretty "false"
instance PermPrettyF ValuePerm where
permPrettyMF = permPrettyM
-- | Pretty-print a lifetime @l@ as either the string @[l]@, or as the empty
-- string if @l==always@
permPrettyLifetimePrefix :: PermExpr LifetimeType -> PermPPM (Doc ann)
permPrettyLifetimePrefix PExpr_Always = return emptyDoc
permPrettyLifetimePrefix l = brackets <$> permPrettyM l
-- | Pretty-print an 'LLVMFieldPerm', either by itself as the form
-- @[l]ptr((rw,off) |-> p)@ if the 'Bool' flag is 'False' or as part of an array
-- permission as the form @[l](rw,off) |-> p@ if the 'Bool' flag is 'True'
permPrettyLLVMField :: (KnownNat w, KnownNat sz) =>
Bool -> LLVMFieldPerm w sz -> PermPPM (Doc ann)
permPrettyLLVMField in_array (LLVMFieldPerm {..} :: LLVMFieldPerm w sz) =
do let w = knownNat @w
let sz = knownNat @sz
pp_l <- permPrettyLifetimePrefix llvmFieldLifetime
pp_off <- permPrettyM llvmFieldOffset
pp_rw <- permPrettyM llvmFieldRW
let pp_parens =
parens $
if intValue sz == intValue w then
pp_rw <> comma <> pp_off
else
pp_rw <> comma <> pp_off <> comma <> pretty (intValue sz)
pp_contents <- permPrettyM llvmFieldContents
return (pp_l <>
(if in_array then id else (pretty "ptr" <>) . parens)
(hang 2
(pp_parens <+> pretty "|->" <> softline <> pp_contents)))
instance (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
PermPretty (LLVMFieldPerm w sz) where
permPrettyM = permPrettyLLVMField False
instance (1 <= w, KnownNat w) => PermPretty (LLVMArrayPerm w) where
permPrettyM (LLVMArrayPerm {..}) =
do pp_l <- permPrettyLifetimePrefix llvmArrayLifetime
pp_rw <- permPrettyM llvmArrayRW
pp_off <- permPrettyM llvmArrayOffset
pp_len <- permPrettyM llvmArrayLen
let pp_stride = pretty (show llvmArrayStride)
pp_sh <- permPrettyM llvmArrayCellShape
pp_bs <- mapM permPrettyM llvmArrayBorrows
return $ PP.group (pp_l <> pretty "array" <>
ppEncList True [pp_rw, pp_off, pretty "<" <> pp_len,
pretty "*" <> pp_stride,
pp_sh,
ppEncList False pp_bs])
instance (1 <= w, KnownNat w) => PermPretty (LLVMBlockPerm w) where
permPrettyM (LLVMBlockPerm {..}) =
do pp_rw <- permPrettyM llvmBlockRW
pp_l <- permPrettyLifetimePrefix llvmBlockLifetime
pp_off <- permPrettyM llvmBlockOffset
pp_len <- permPrettyM llvmBlockLen
pp_sh <- permPrettyM llvmBlockShape
return $ PP.group (pp_l <> pretty "memblock" <>
ppEncList True [pp_rw, pp_off, pp_len, pp_sh])
instance PermPretty (AtomicPerm a) where
permPrettyM (Perm_LLVMField fp) = permPrettyLLVMField False fp
permPrettyM (Perm_LLVMArray ap) = permPrettyM ap
permPrettyM (Perm_LLVMBlock bp) = permPrettyM bp
permPrettyM (Perm_LLVMBlockShape sh) =
((pretty "shape" <>) . parens) <$> permPrettyM sh
permPrettyM (Perm_LLVMFree e) = (pretty "free" <+>) <$> permPrettyM e
permPrettyM (Perm_LLVMFunPtr _tp fp) =
(\pp -> pretty "llvmfunptr" <+> parens pp) <$> permPrettyM fp
permPrettyM Perm_IsLLVMPtr = return (pretty "is_llvmptr")
permPrettyM (Perm_LLVMFrame fperm) =
do pps <- mapM (\(e,i) -> (<> (colon <> pretty i)) <$> permPrettyM e) fperm
return (pretty "llvmframe" <+> ppEncList False pps)
permPrettyM (Perm_LOwned ls ps_in ps_out) =
do pp_in <- permPrettyM ps_in
pp_out <- permPrettyM ps_out
ls_pp <- case ls of
[] -> return emptyDoc
_ -> ppEncList False <$> mapM permPrettyM ls
return (pretty "lowned" <> ls_pp <+>
parens (align $ sep [pp_in, pretty "-o", pp_out]))
permPrettyM (Perm_LOwnedSimple lops) =
(pretty "lowned" <>) <$> parens <$> permPrettyM lops
permPrettyM (Perm_LCurrent l) = (pretty "lcurrent" <+>) <$> permPrettyM l
permPrettyM Perm_LFinished = return (pretty "lfinished")
permPrettyM (Perm_Struct ps) =
((pretty "struct" <+>) . parens) <$> permPrettyM ps
permPrettyM (Perm_Fun fun_perm) = permPrettyM fun_perm
permPrettyM (Perm_BVProp prop) = permPrettyM prop
permPrettyM (Perm_NamedConj n args off) =
do n_pp <- permPrettyM n
args_pp <- permPrettyM args
off_pp <- permPrettyM off
return (n_pp <> pretty '<' <> args_pp <> pretty '>' <> off_pp)
instance PermPretty (PermOffset a) where
permPrettyM NoPermOffset = return mempty
permPrettyM (LLVMPermOffset e) =
do e_pp <- permPrettyM e
return (pretty '@' <> parens e_pp)
instance PermPretty (LOwnedPerm a) where
permPrettyM = permPrettyM . lownedPermExprAndPerm
instance PermPrettyF LOwnedPerm where
permPrettyMF = permPrettyM
instance PermPretty (FunPerm ghosts args gouts ret) where
permPrettyM (FunPerm ghosts args gouts _ mb_ps_in mb_ps_out) =
fmap mbLift $ strongMbM $
flip nuMultiWithElim1 (mbValuePermsToDistPerms mb_ps_out) $
\(ghosts_args_gouts_ns :>: ret_n) ps_out ->
let (ghosts_ns, args_ns, gouts_ns) =
rlSplit3 (cruCtxProxies ghosts) (cruCtxProxies args)
(cruCtxProxies gouts) ghosts_args_gouts_ns in
let ps_in =
varSubst (permVarSubstOfNames $ RL.append ghosts_ns args_ns)
(mbValuePermsToDistPerms mb_ps_in) in
local (ppInfoAddExprName "ret" ret_n) $
local (ppInfoAddExprNames "arg" args_ns) $
local (ppInfoAddTypedExprNames ghosts ghosts_ns) $
local (ppInfoAddTypedExprNames gouts gouts_ns) $
do pp_ps_in <- permPrettyM ps_in
pp_ps_out <- permPrettyM ps_out
pp_ghosts <- permPrettyM (RL.map2 VarAndType ghosts_ns $
cruCtxToTypes ghosts)
pp_gouts <- case gouts of
CruCtxNil -> return mempty
_ -> parens <$> permPrettyM (RL.map2 VarAndType gouts_ns $
cruCtxToTypes gouts)
return $ align $
sep [parens pp_ghosts <> dot, pp_ps_in, pretty "-o",
pp_gouts <> pp_ps_out]
instance PermPretty (BVRange w) where
permPrettyM (BVRange e1 e2) =
(\pp1 pp2 -> braces (pp1 <> comma <+> pp2))
<$> permPrettyM e1 <*> permPrettyM e2
instance PermPretty (BVProp w) where
permPrettyM (BVProp_Eq e1 e2) =
(\pp1 pp2 -> pp1 <+> equals <+> pp2) <$> permPrettyM e1 <*> permPrettyM e2
permPrettyM (BVProp_Neq e1 e2) =
(\pp1 pp2 -> pp1 <+> pretty "/=" <+> pp2) <$> permPrettyM e1 <*> permPrettyM e2
permPrettyM (BVProp_ULt e1 e2) =
(\pp1 pp2 -> pp1 <+> pretty "<u" <+> pp2) <$> permPrettyM e1 <*> permPrettyM e2
permPrettyM (BVProp_ULeq e1 e2) =
(\pp1 pp2 -> pp1 <+> pretty "<=u" <+> pp2) <$> permPrettyM e1 <*> permPrettyM e2
permPrettyM (BVProp_ULeq_Diff e1 e2 e3) =
(\pp1 pp2 pp3 -> pp1 <+> pretty "<=u" <+> pp2 <+> pretty '-' <+> pp3)
<$> permPrettyM e1 <*> permPrettyM e2 <*> permPrettyM e3
instance PermPretty (LLVMArrayBorrow w) where
permPrettyM (FieldBorrow ix) = permPrettyM ix
permPrettyM (RangeBorrow rng) = permPrettyM rng
instance PermPretty (VarAndPerm a) where
permPrettyM (VarAndPerm x p) =
(\pp1 pp2 -> pp1 <> colon <> pp2) <$> permPrettyM x <*> permPrettyM p
instance PermPrettyF VarAndPerm where
permPrettyMF = permPrettyM
instance (PermPretty a, PermPretty b) => PermPretty (ColonPair a b) where
permPrettyM (ColonPair a b) =
(\pp1 pp2 -> pp1 <> colon <> pp2) <$> permPrettyM a <*> permPrettyM b
{-
instance PermPretty (DistPerms ps) where
permPrettyM ps = ppCommaSep <$> helper ps where
helper :: DistPerms ps' -> PermPPM [Doc ann]
helper DistPermsNil = return []
helper (DistPermsCons ps x p) =
do x_pp <- permPrettyM x
p_pp <- permPrettyM p
(++ [x_pp <> colon <> p_pp]) <$> helper ps
-}
instance PermPretty (ExprAndPerm a) where
permPrettyM (ExprAndPerm x p) =
(\pp1 pp2 -> pp1 <> colon <> pp2) <$> permPrettyM x <*> permPrettyM p
instance PermPrettyF ExprAndPerm where
permPrettyMF = permPrettyM
-- | Embed a 'ValuePerm' in a 'PermExpr' - like 'PExpr_ValPerm' but maps
-- 'ValPerm_Var's to 'PExpr_Var's
permToExpr :: ValuePerm a -> PermExpr (ValuePermType a)
permToExpr (ValPerm_Var n NoPermOffset) = PExpr_Var n
permToExpr a = PExpr_ValPerm a
-- | Extract @p1@ from a permission of the form @p1 \/ p2@
orPermLeft :: ValuePerm a -> ValuePerm a
orPermLeft (ValPerm_Or p _) = p
orPermLeft _ = error "orPermLeft"
-- | Extract @p2@ from a permission of the form @p1 \/ p2@
orPermRight :: ValuePerm a -> ValuePerm a
orPermRight (ValPerm_Or _ p) = p
orPermRight _ = error "orPermRight"
-- | Extract the body @p@ from a permission of the form @exists (x:tp).p@
exPermBody :: TypeRepr tp -> ValuePerm a -> Binding tp (ValuePerm a)
exPermBody tp (ValPerm_Exists (p :: Binding tp' (ValuePerm a)))
| Just Refl <- testEquality tp (knownRepr :: TypeRepr tp') = p
exPermBody _ _ = error "exPermBody"
-- | A representation of a context of types as a sequence of 'KnownRepr'
-- instances
--
-- FIXME: this can go away when existentials take explicit 'TypeRepr's instead
-- of 'KnownRepr TypeRepr' instances, as per issue #79
type KnownCruCtx = RAssign (KnownReprObj TypeRepr)
-- | Convert a 'KnownCruCtx' to a 'CruCtx'
knownCtxToCruCtx :: KnownCruCtx ctx -> CruCtx ctx
knownCtxToCruCtx MNil = CruCtxNil
knownCtxToCruCtx (ctx :>: KnownReprObj) =
CruCtxCons (knownCtxToCruCtx ctx) knownRepr
-- | Construct 0 or more nested existential permissions
valPermExistsMulti :: KnownCruCtx ctx -> Mb ctx (ValuePerm a) -> ValuePerm a
valPermExistsMulti MNil mb_p = elimEmptyMb mb_p
valPermExistsMulti (ctx :>: KnownReprObj) mb_p =
valPermExistsMulti ctx (fmap ValPerm_Exists $
mbSeparate (MNil :>: Proxy) mb_p)
-- | Test if an 'AtomicPerm' is a field permission
isLLVMFieldPerm :: AtomicPerm a -> Bool
isLLVMFieldPerm (Perm_LLVMField _) = True
isLLVMFieldPerm _ = False
-- | Test if an 'AtomicPerm' is a field permission with the given offset
isLLVMFieldPermWithOffset :: PermExpr (BVType w) ->
AtomicPerm (LLVMPointerType w) -> Bool
isLLVMFieldPermWithOffset off (Perm_LLVMField fp) =
bvEq off (llvmFieldOffset fp)
isLLVMFieldPermWithOffset _ _ = False
-- | Test if an 'AtomicPerm' starts with the given offset
isLLVMAtomicPermWithOffset :: PermExpr (BVType w) ->
AtomicPerm (LLVMPointerType w) -> Bool
isLLVMAtomicPermWithOffset off p
| Just off' <- llvmAtomicPermOffset p = bvEq off off'
isLLVMAtomicPermWithOffset _ _ = False
-- | Test if an 'AtomicPerm' is an array permission
isLLVMArrayPerm :: AtomicPerm a -> Bool
isLLVMArrayPerm (Perm_LLVMArray _) = True
isLLVMArrayPerm _ = False
-- | Test if an 'AtomicPerm' is an llvmblock permission
isLLVMBlockPerm :: AtomicPerm a -> Bool
isLLVMBlockPerm (Perm_LLVMBlock _) = True
isLLVMBlockPerm _ = False
-- | Test if an 'AtomicPerm' is a lifetime permission
isLifetimePerm :: AtomicPerm a -> Maybe (a :~: LifetimeType)
isLifetimePerm (Perm_LOwned _ _ _) = Just Refl
isLifetimePerm (Perm_LOwnedSimple _) = Just Refl
isLifetimePerm (Perm_LCurrent _) = Just Refl
isLifetimePerm Perm_LFinished = Just Refl
isLifetimePerm _ = Nothing
-- | Test if an 'AtomicPerm' is a lifetime permission that gives ownership
isLifetimeOwnershipPerm :: AtomicPerm a -> Maybe (a :~: LifetimeType)
isLifetimeOwnershipPerm (Perm_LOwned _ _ _) = Just Refl
isLifetimeOwnershipPerm (Perm_LOwnedSimple _) = Just Refl
isLifetimeOwnershipPerm _ = Nothing
-- | Test if an 'AtomicPerm' is a struct permission
isStructPerm :: AtomicPerm a -> Bool
isStructPerm (Perm_Struct _) = True
isStructPerm _ = False
-- | Test if an 'AtomicPerm' is a function permission
isFunPerm :: AtomicPerm a -> Bool
isFunPerm (Perm_Fun _) = True
isFunPerm _ = False
-- | Test if an 'AtomicPerm' is a named conjunctive permission
isNamedConjPerm :: AtomicPerm a -> Bool
isNamedConjPerm (Perm_NamedConj _ _ _) = True
isNamedConjPerm _ = False
-- | Test if an 'AtomicPerm' is a foldable named conjunctive permission
isFoldableConjPerm :: AtomicPerm a -> Bool
isFoldableConjPerm (Perm_NamedConj npn _ _) = nameCanFold npn
isFoldableConjPerm _ = False
-- | Test if an 'AtomicPerm' is a defined conjunctive permission
isDefinedConjPerm :: AtomicPerm a -> Bool
isDefinedConjPerm (Perm_NamedConj
(namedPermNameSort -> DefinedSortRepr _) _ _) = True
isDefinedConjPerm _ = False
-- | Test if an 'AtomicPerm' is a recursive conjunctive permission
isRecursiveConjPerm :: AtomicPerm a -> Bool
isRecursiveConjPerm (Perm_NamedConj
(namedPermNameSort -> RecursiveSortRepr _ _) _ _) = True
isRecursiveConjPerm _ = False
-- | Test that a permission is a conjunctive permission, meaning that it is
-- built inductively using only existentials, disjunctions, conjunctive named
-- permissions, and conjunctions of atomic permissions. Note that an atomic
-- permissions in such a conjunction can itself contain equality permissions;
-- e.g., in LLVM field permissions.
isConjPerm :: ValuePerm a -> Bool
isConjPerm (ValPerm_Eq _) = False
isConjPerm (ValPerm_Or p1 p2) = isConjPerm p1 && isConjPerm p2
isConjPerm (ValPerm_Exists mb_p) = mbLift $ fmap isConjPerm mb_p
isConjPerm (ValPerm_Named n _ _) = nameSortIsConj (namedPermNameSort n)
isConjPerm (ValPerm_Var _ _) = False
isConjPerm (ValPerm_Conj _) = True
isConjPerm (ValPerm_False) = False
-- | Return a struct permission where all fields have @true@ permissions
trueStructAtomicPerm :: Assignment prx ctx -> AtomicPerm (StructType ctx)
trueStructAtomicPerm =
Perm_Struct . RL.map (const ValPerm_True). assignToRList
-- | Take two list of atomic struct permissions, one for structs with fields
-- given by @ctx1@ and one with those given by @ctx2@, and append them pointwise
-- to get a list of atomic struct permissions whose fields are given by the
-- append @ctx1 <+> ctx2@. If one list is shorter than the other, fill it out
-- with struct permissions @struct (true, ..., true)@ of all @true@ permissions.
-- This only works if both lists have only 'Perm_Struct' permissions, and
-- otherwise return 'Nothing'.
tryAppendStructAPerms :: Assignment prx1 ctx1 -> Assignment prx2 ctx2 ->
[AtomicPerm (StructType ctx1)] ->
[AtomicPerm (StructType ctx2)] ->
Maybe [AtomicPerm (StructType (ctx1 <+> ctx2))]
tryAppendStructAPerms _ _ [] [] = return []
tryAppendStructAPerms ctx1 ctx2 (Perm_Struct fs_ps:ps) (Perm_Struct fs_qs:qs) =
(Perm_Struct (assignToRListAppend ctx1 ctx2 fs_ps fs_qs) :) <$>
tryAppendStructAPerms ctx1 ctx2 ps qs
tryAppendStructAPerms ctx1 ctx2 [] qs =
tryAppendStructAPerms ctx1 ctx2 [trueStructAtomicPerm ctx1] qs
tryAppendStructAPerms ctx1 ctx2 ps [] =
tryAppendStructAPerms ctx1 ctx2 ps [trueStructAtomicPerm ctx2]
tryAppendStructAPerms _ _ _ _ = mzero
-- | Try to append struct permissions for structs with fields given by @ctx1@
-- and @ctx2@ to get a permission for structs with fields given by the append
-- @ctx1 <+> ctx2@ of these two contexts. Return 'Nothing' if this is not
-- possible.
tryAppendStructPerms :: Assignment prx1 ctx1 -> Assignment prx2 ctx2 ->
ValuePerm (StructType ctx1) ->
ValuePerm (StructType ctx2) ->
Maybe (ValuePerm (StructType (ctx1 <+> ctx2)))
tryAppendStructPerms ctx1 ctx2 (ValPerm_Or p1 p2) q =
ValPerm_Or <$> tryAppendStructPerms ctx1 ctx2 p1 q <*>
tryAppendStructPerms ctx1 ctx2 p2 q
tryAppendStructPerms ctx1 ctx2 p (ValPerm_Or q1 q2) =
ValPerm_Or <$> tryAppendStructPerms ctx1 ctx2 p q1 <*>
tryAppendStructPerms ctx1 ctx2 p q2
tryAppendStructPerms ctx1 ctx2 (ValPerm_Exists mb_p) q =
ValPerm_Exists <$> mbMaybe (flip fmap mb_p $ \p ->
tryAppendStructPerms ctx1 ctx2 p q)
tryAppendStructPerms ctx1 ctx2 p (ValPerm_Exists mb_q) =
ValPerm_Exists <$> mbMaybe (flip fmap mb_q $ \q ->
tryAppendStructPerms ctx1 ctx2 p q)
tryAppendStructPerms ctx1 ctx2 (ValPerm_Conj ps) (ValPerm_Conj qs) =
ValPerm_Conj <$> tryAppendStructAPerms ctx1 ctx2 ps qs
tryAppendStructPerms _ _ _ _ = mzero
-- | Helper function to build a 'Perm_LLVMFunPtr' from a 'FunPerm'
mkPermLLVMFunPtr :: (1 <= w, KnownNat w) => f w ->
FunPerm ghosts args gouts ret ->
AtomicPerm (LLVMPointerType w)
mkPermLLVMFunPtr (_w :: f w) fun_perm =
case cruCtxToReprEq (funPermArgs fun_perm) of
Refl ->
Perm_LLVMFunPtr (FunctionHandleRepr
(cruCtxToRepr $ funPermArgs fun_perm)
(funPermRet fun_perm))
(ValPerm_Conj1 $ Perm_Fun fun_perm)
-- | Helper function to build a 'Perm_LLVMFunPtr' from a list of 'FunPerm's. The
-- list must be non-empty.
mkPermLLVMFunPtrs :: (1 <= w, KnownNat w) => f w -> [SomeFunPerm args ret] ->
AtomicPerm (LLVMPointerType w)
mkPermLLVMFunPtrs (_w :: f w) [] = error "mkPermLLVMFunPtrs: empty list"
mkPermLLVMFunPtrs (_w :: f w) fun_perms@(SomeFunPerm fun_perm:_) =
case cruCtxToReprEq (funPermArgs fun_perm) of
Refl ->
Perm_LLVMFunPtr (FunctionHandleRepr
(cruCtxToRepr $ funPermArgs fun_perm)
(funPermRet fun_perm))
(ValPerm_Conj $ map (\(SomeFunPerm fp) -> Perm_Fun fp) fun_perms)
-- | Existential permission @x:eq(word(e))@ for some @e@
llvmExEqWord :: (1 <= w, KnownNat w) => prx w ->
Binding (BVType w) (ValuePerm (LLVMPointerType w))
llvmExEqWord _ = nu $ \e -> ValPerm_Eq (PExpr_LLVMWord $ PExpr_Var e)
{-
-- | Create a field pointer permission with offset 0 and @eq(e)@ permissions
-- with the given read-write modality
llvmFieldContents0Eq :: (1 <= w, KnownNat w) =>
RWModality -> PermExpr (LLVMPointerType w) ->
LLVMPtrPerm w
llvmFieldContents0Eq rw e =
Perm_LLVMField $ LLVMFieldPerm { llvmFieldRW = rw,
llvmFieldOffset = bvInt 0,
llvmFieldContents = ValPerm_Eq e }
-}
-- | Create a field permission to read a known value from offset 0 of an LLVM
-- pointer using an existential modality, lifetime, and value
llvmPtr0EqEx :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) => prx sz ->
Mb (RNil :> RWModalityType :> LifetimeType :> LLVMPointerType sz)
(LLVMFieldPerm w sz)
llvmPtr0EqEx _ =
nuMulti (MNil :>: Proxy :>: Proxy :>: Proxy) $ \(_ :>: rw :>: l :>: x) ->
LLVMFieldPerm { llvmFieldRW = PExpr_Var rw,
llvmFieldLifetime = PExpr_Var l,
llvmFieldOffset = bvInt 0,
llvmFieldContents = ValPerm_Eq (PExpr_Var x) }
-- | Create a permission to read a known value from offset 0 of an LLVM pointer
-- using an existential modality, lifetime, and value, i.e., return the
-- permission @exists rw,l,y.[l]ptr ((0,rw) |-> eq(y))@
llvmPtr0EqExPerm :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) => prx sz ->
Mb (RNil :> RWModalityType :> LifetimeType :> LLVMPointerType sz)
(ValuePerm (LLVMPointerType w))
llvmPtr0EqExPerm = fmap (ValPerm_Conj1 . Perm_LLVMField) . llvmPtr0EqEx
-- | Create a permission to read a known value from offset 0 of an LLVM pointer
-- in the given lifetime, i.e., return @exists y.[l]ptr ((0,R) |-> eq(e))@
llvmRead0EqPerm :: (1 <= w, KnownNat w) => PermExpr LifetimeType ->
PermExpr (LLVMPointerType w) ->
ValuePerm (LLVMPointerType w)
llvmRead0EqPerm l e =
ValPerm_Conj [Perm_LLVMField $
LLVMFieldPerm { llvmFieldRW = PExpr_Read,
llvmFieldLifetime = l,
llvmFieldOffset = bvInt 0,
llvmFieldContents = ValPerm_Eq e }]
-- | Create a field write permission with offset 0 and @true@ permissions of a
-- given size
llvmSizedFieldWrite0True :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
f1 w -> f2 sz -> LLVMFieldPerm w sz
llvmSizedFieldWrite0True _ _ =
LLVMFieldPerm { llvmFieldRW = PExpr_Write,
llvmFieldLifetime = PExpr_Always,
llvmFieldOffset = bvInt 0,
llvmFieldContents = ValPerm_True }
-- | Create a field write permission with offset 0 and @true@ permissions
llvmFieldWrite0True :: (1 <= w, KnownNat w) => LLVMFieldPerm w w
llvmFieldWrite0True = llvmSizedFieldWrite0True Proxy Proxy
-- | Create a field write permission with offset 0 and @true@ permissions
llvmWrite0TruePerm :: (1 <= w, KnownNat w) => ValuePerm (LLVMPointerType w)
llvmWrite0TruePerm = ValPerm_Conj [Perm_LLVMField llvmFieldWrite0True]
-- | Create a field write permission with offset 0 and an @eq(e)@ permission
llvmFieldWrite0Eq :: (1 <= w, KnownNat w) => PermExpr (LLVMPointerType w) ->
LLVMFieldPerm w w
llvmFieldWrite0Eq e =
LLVMFieldPerm { llvmFieldRW = PExpr_Write,
llvmFieldLifetime = PExpr_Always,
llvmFieldOffset = bvInt 0,
llvmFieldContents = ValPerm_Eq e }
-- | Create a field write permission with offset 0 and an @eq(e)@ permission
llvmWrite0EqPerm :: (1 <= w, KnownNat w) => PermExpr (LLVMPointerType w) ->
ValuePerm (LLVMPointerType w)
llvmWrite0EqPerm e = ValPerm_Conj [Perm_LLVMField $ llvmFieldWrite0Eq e]
-- | Create a field write permission with offset @e@ and lifetime @l@
llvmFieldWriteTrueL :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
prx sz -> PermExpr (BVType w) ->
PermExpr LifetimeType -> LLVMFieldPerm w sz
llvmFieldWriteTrueL _ off l =
LLVMFieldPerm { llvmFieldRW = PExpr_Write,
llvmFieldLifetime = l,
llvmFieldOffset = off,
llvmFieldContents = ValPerm_True }
-- | Create a field write permission with offset @e@ and an existential lifetime
llvmWriteTrueExLPerm :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
prx sz -> PermExpr (BVType w) ->
Binding LifetimeType (ValuePerm (LLVMPointerType w))
llvmWriteTrueExLPerm sz off =
nu $ \l ->
ValPerm_Conj1 $ Perm_LLVMField $ llvmFieldWriteTrueL sz off (PExpr_Var l)
-- | Create a field permission with offset @e@ and existential lifetime and rw
llvmReadExRWExLPerm :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
Mb (RNil :> RWModalityType :> LifetimeType)
(ValuePerm (LLVMPointerType w))
llvmReadExRWExLPerm (off :: PermExpr (BVType w)) =
nuMulti (MNil :>: Proxy :>: Proxy) $ \(_ :>: rw :>: l) ->
ValPerm_Conj1 $ Perm_LLVMField @w @w $
LLVMFieldPerm { llvmFieldRW = PExpr_Var rw,
llvmFieldLifetime = PExpr_Var l,
llvmFieldOffset = off,
llvmFieldContents = ValPerm_True }
-- | Add a bitvector expression to the offset of a field permission
llvmFieldAddOffset :: (1 <= w, KnownNat w) => LLVMFieldPerm w sz ->
PermExpr (BVType w) -> LLVMFieldPerm w sz
llvmFieldAddOffset fp off =
fp { llvmFieldOffset = bvAdd (llvmFieldOffset fp) off }
-- | Add an integer to the offset of a field permission
llvmFieldAddOffsetInt :: (1 <= w, KnownNat w) => LLVMFieldPerm w sz ->
Integer -> LLVMFieldPerm w sz
llvmFieldAddOffsetInt fp off = llvmFieldAddOffset fp (bvInt off)
-- | Set the contents of a field permission, possibly changing its size
llvmFieldSetContents :: LLVMFieldPerm w sz1 ->
ValuePerm (LLVMPointerType sz2) -> LLVMFieldPerm w sz2
llvmFieldSetContents (LLVMFieldPerm {..}) p =
LLVMFieldPerm { llvmFieldContents = p, .. }
-- | Set the contents of a field permission to an @eq(llvmword(e))@ permission
llvmFieldSetEqWord :: (1 <= sz2, KnownNat sz2) => LLVMFieldPerm w sz1 ->
PermExpr (BVType sz2) -> LLVMFieldPerm w sz2
llvmFieldSetEqWord fp e =
llvmFieldSetContents fp (ValPerm_Eq $ PExpr_LLVMWord e)
-- | Set the contents of a field permission to an @eq(y)@ permission
llvmFieldSetEqVar :: (1 <= sz2, KnownNat sz2) => LLVMFieldPerm w sz1 ->
ExprVar (LLVMPointerType sz2) -> LLVMFieldPerm w sz2
llvmFieldSetEqVar fp y =
llvmFieldSetContents fp (ValPerm_Eq $ PExpr_Var y)
-- | Set the contents of a field permission to an @eq(llvmword(y))@ permission
llvmFieldSetEqWordVar :: (1 <= sz2, KnownNat sz2) => LLVMFieldPerm w sz1 ->
ExprVar (BVType sz2) -> LLVMFieldPerm w sz2
llvmFieldSetEqWordVar fp y =
llvmFieldSetContents fp (ValPerm_Eq $ PExpr_LLVMWord $ PExpr_Var y)
-- | Set the contents of a field permission to an @true@ permission of a
-- specific size
llvmFieldSetTrue :: (1 <= sz2, KnownNat sz2) => LLVMFieldPerm w sz1 ->
f sz2 -> LLVMFieldPerm w sz2
llvmFieldSetTrue fp _ = llvmFieldSetContents fp ValPerm_True
-- | Convert a field permission to a block permission
llvmFieldPermToBlock :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
LLVMFieldPerm w sz -> LLVMBlockPerm w
llvmFieldPermToBlock fp =
LLVMBlockPerm
{ llvmBlockRW = llvmFieldRW fp,
llvmBlockLifetime = llvmFieldLifetime fp,
llvmBlockOffset = llvmFieldOffset fp,
llvmBlockLen = llvmFieldLen fp,
llvmBlockShape = PExpr_FieldShape (LLVMFieldShape $ llvmFieldContents fp) }
-- | Convert a block permission with field shape to a field permission
--
-- NOTE: do not check that the length of the block equals that of the resulting
-- field permission, in case the length of the block has a free variable that
-- might be provably but not syntacitcally equal to the length
llvmBlockPermToField :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
NatRepr sz -> LLVMBlockPerm w ->
Maybe (LLVMFieldPerm w sz)
llvmBlockPermToField sz bp
| PExpr_FieldShape (LLVMFieldShape p) <- llvmBlockShape bp
, Just Refl <- testEquality sz (exprLLVMTypeWidth p)
= Just $ LLVMFieldPerm { llvmFieldRW = llvmBlockRW bp,
llvmFieldLifetime = llvmBlockLifetime bp,
llvmFieldOffset = llvmBlockOffset bp,
llvmFieldContents = p }
llvmBlockPermToField _ _ = Nothing
-- | Convert an array permission with total size @sz@ bits to a field permission
-- of size @sz@ bits, assuming it has no borrows
llvmArrayToField :: (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
NatRepr sz -> LLVMArrayPerm w ->
Maybe (LLVMFieldPerm w sz)
llvmArrayToField sz ap
| bvEq (bvMult (llvmArrayStrideBits ap) (llvmArrayLen ap)) (bvInt $
intValue sz)
, [] <- llvmArrayBorrows ap =
Just $ LLVMFieldPerm { llvmFieldRW = llvmArrayRW ap,
llvmFieldLifetime = llvmArrayLifetime ap,
llvmFieldOffset = llvmArrayOffset ap,
llvmFieldContents = ValPerm_True }
llvmArrayToField _ _ = Nothing
-- | Convert an array permission with no borrows to a block permission
llvmArrayPermToBlock :: (1 <= w, KnownNat w) =>
LLVMArrayPerm w -> Maybe (LLVMBlockPerm w)
llvmArrayPermToBlock ap
| [] <- llvmArrayBorrows ap =
Just $ LLVMBlockPerm
{ llvmBlockRW = llvmArrayRW ap,
llvmBlockLifetime = llvmArrayLifetime ap,
llvmBlockOffset = llvmArrayOffset ap,
llvmBlockLen = bvMult (llvmArrayStride ap) (llvmArrayLen ap),
llvmBlockShape =
PExpr_ArrayShape (llvmArrayLen ap) (llvmArrayStride ap)
(llvmArrayCellShape ap) }
llvmArrayPermToBlock _ = Nothing
-- | Convert a block permission with array shape to an array permission,
-- assuming the length of the block permission equals the size of the array
--
-- NOTE: do not check that the length of the block equals that of the resulting
-- array permission, in case the length of the block has a free variable that
-- might be provably but not syntacitcally equal to the length
llvmBlockPermToArray :: (1 <= w, KnownNat w) => LLVMBlockPerm w ->
Maybe (LLVMArrayPerm w)
llvmBlockPermToArray bp
| PExpr_ArrayShape len stride sh <- llvmBlockShape bp =
Just $ LLVMArrayPerm
{ llvmArrayRW = llvmBlockRW bp,
llvmArrayLifetime = llvmBlockLifetime bp,
llvmArrayOffset = llvmBlockOffset bp,
llvmArrayLen = len,
llvmArrayStride = stride,
llvmArrayCellShape = sh,
llvmArrayBorrows = [] }
llvmBlockPermToArray _ = Nothing
-- | Convert a block permission with statically-known length @len@ to an
-- equivalent array of length 1 with stride @len@
llvmBlockPermToArray1 :: (1 <= w, KnownNat w) => LLVMBlockPerm w ->
Maybe (LLVMArrayPerm w)
llvmBlockPermToArray1 bp
| Just stride <- bvMatchConstInt $ llvmBlockLen bp =
Just $ LLVMArrayPerm
{ llvmArrayRW = llvmBlockRW bp,
llvmArrayLifetime = llvmBlockLifetime bp,
llvmArrayOffset = llvmBlockOffset bp,
llvmArrayLen = bvInt 1,
llvmArrayStride = fromInteger stride,
llvmArrayCellShape = llvmBlockShape bp,
llvmArrayBorrows = [] }
llvmBlockPermToArray1 _ = Nothing
-- | Get the permission for a single cell of an array permission
llvmArrayCellPerm :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
PermExpr (BVType w) -> LLVMBlockPerm w
llvmArrayCellPerm ap cell =
let off = bvAdd (llvmArrayOffset ap) (bvMult (llvmArrayStride ap) cell) in
LLVMBlockPerm { llvmBlockRW = llvmArrayRW ap,
llvmBlockLifetime = llvmArrayLifetime ap,
llvmBlockOffset = off,
llvmBlockLen = bvInt (toInteger $ llvmArrayStride ap),
llvmBlockShape = llvmArrayCellShape ap }
-- | Get the permission for the first cell of an array permission
llvmArrayPermHead :: (1 <= w, KnownNat w) => LLVMArrayPerm w -> LLVMBlockPerm w
llvmArrayPermHead ap = llvmArrayCellPerm ap (bvInt 0)
-- | Get the permission for all of an array permission after the first cell
llvmArrayPermTail :: (1 <= w, KnownNat w) => LLVMArrayPerm w -> LLVMArrayPerm w
llvmArrayPermTail ap =
let off1 = bvInt $ bytesToInteger $ llvmArrayStride ap in
ap { llvmArrayOffset = bvAdd (llvmArrayOffset ap) off1,
llvmArrayLen = bvSub (llvmArrayLen ap) (bvInt 1) }
-- | Convert an atomic permission to a @memblock@, if possible
llvmAtomicPermToBlock :: AtomicPerm (LLVMPointerType w) ->
Maybe (LLVMBlockPerm w)
llvmAtomicPermToBlock (Perm_LLVMField fp) = Just $ llvmFieldPermToBlock fp
llvmAtomicPermToBlock (Perm_LLVMArray ap) = llvmArrayPermToBlock ap
llvmAtomicPermToBlock (Perm_LLVMBlock bp) = Just bp
llvmAtomicPermToBlock _ = Nothing
-- | Convert an atomic permission whose type is unknown to a @memblock@, if
-- possible, along with a proof that its type is a valid llvm pointer type
llvmAtomicPermToSomeBlock :: AtomicPerm a -> Maybe (SomeLLVMBlockPerm a)
llvmAtomicPermToSomeBlock p@(Perm_LLVMField _) =
SomeLLVMBlockPerm <$> llvmAtomicPermToBlock p
llvmAtomicPermToSomeBlock p@(Perm_LLVMArray _) =
SomeLLVMBlockPerm <$> llvmAtomicPermToBlock p
llvmAtomicPermToSomeBlock (Perm_LLVMBlock bp) =
Just $ SomeLLVMBlockPerm $ bp
llvmAtomicPermToSomeBlock _ = Nothing
-- | Get the lifetime of an atomic perm if it is a field, array, or memblock
atomicPermLifetime :: AtomicPerm a -> Maybe (PermExpr LifetimeType)
atomicPermLifetime (Perm_LLVMField fp) = Just $ llvmFieldLifetime fp
atomicPermLifetime (Perm_LLVMArray ap) = Just $ llvmArrayLifetime ap
atomicPermLifetime (Perm_LLVMBlock bp) = Just $ llvmBlockLifetime bp
atomicPermLifetime _ = Nothing
-- | Get the starting offset of an atomic permission, if it has one. This
-- includes array permissions which may have some cells borrowed.
llvmAtomicPermOffset :: AtomicPerm (LLVMPointerType w) ->
Maybe (PermExpr (BVType w))
llvmAtomicPermOffset (Perm_LLVMField fp) = Just $ llvmFieldOffset fp
llvmAtomicPermOffset (Perm_LLVMArray ap) = Just $ llvmArrayOffset ap
llvmAtomicPermOffset (Perm_LLVMBlock bp) = Just $ llvmBlockOffset bp
llvmAtomicPermOffset _ = Nothing
-- | Get the length of an atomic permission, if it has one. This includes array
-- permissions which may have some cells borrowed.
llvmAtomicPermLen :: AtomicPerm (LLVMPointerType w) ->
Maybe (PermExpr (BVType w))
llvmAtomicPermLen (Perm_LLVMField fp) = Just $ llvmFieldLen fp
llvmAtomicPermLen (Perm_LLVMArray ap) = Just $ llvmArrayLengthBytes ap
llvmAtomicPermLen (Perm_LLVMBlock bp) = Just $ llvmBlockLen bp
llvmAtomicPermLen _ = Nothing
-- | Get the ending offset of an atomic permission, if it has one. This
-- includes array permissions which may have some cells borrowed.
llvmAtomicPermEndOffset :: (1 <= w, KnownNat w) =>
AtomicPerm (LLVMPointerType w) ->
Maybe (PermExpr (BVType w))
llvmAtomicPermEndOffset p =
bvAdd <$> llvmAtomicPermOffset p <*> llvmAtomicPermLen p
-- | Get the range of offsets of an atomic permission, if it has one. Note that
-- arrays with borrows do not have a well-defined range.
llvmAtomicPermRange :: AtomicPerm (LLVMPointerType w) -> Maybe (BVRange w)
llvmAtomicPermRange p = fmap llvmBlockRange $ llvmAtomicPermToBlock p
-- | Test if an LLVM atomic permission contains some range of offsets that have
-- an array shape
llvmPermContainsArray :: AtomicPerm (LLVMPointerType w) -> Bool
llvmPermContainsArray (Perm_LLVMArray _) = True
llvmPermContainsArray (Perm_LLVMBlock bp) =
shapeContainsArray $ llvmBlockShape bp where
shapeContainsArray :: PermExpr (LLVMShapeType w) -> Bool
shapeContainsArray (PExpr_ArrayShape _ _ _) = True
shapeContainsArray (PExpr_SeqShape sh1 sh2) =
shapeContainsArray sh1 || shapeContainsArray sh2
shapeContainsArray _ = False
llvmPermContainsArray _ = False
-- | Set the range of an 'LLVMBlock'
llvmBlockSetRange :: LLVMBlockPerm w -> BVRange w -> LLVMBlockPerm w
llvmBlockSetRange bp (BVRange off len) =
bp { llvmBlockOffset = off, llvmBlockLen = len }
-- | Get the ending offset of a block permission
llvmBlockEndOffset :: (1 <= w, KnownNat w) => LLVMBlockPerm w ->
PermExpr (BVType w)
llvmBlockEndOffset = bvRangeEnd . llvmBlockRange
-- | Return the length in bytes of an 'LLVMFieldShape'
llvmFieldShapeLength :: LLVMFieldShape w -> Integer
llvmFieldShapeLength (LLVMFieldShape p) = exprLLVMTypeBytes p
-- | Return the expression for the length of a shape if there is one
llvmShapeLength :: (1 <= w, KnownNat w) => PermExpr (LLVMShapeType w) ->
Maybe (PermExpr (BVType w))
llvmShapeLength (PExpr_Var _) = Nothing
llvmShapeLength PExpr_EmptyShape = Just $ bvInt 0
llvmShapeLength (PExpr_NamedShape _ _ nmsh@(NamedShape _ _
(DefinedShapeBody _)) args) =
llvmShapeLength (unfoldNamedShape nmsh args)
llvmShapeLength (PExpr_NamedShape _ _ (NamedShape _ _
(OpaqueShapeBody mb_len _)) args) =
Just $ subst (substOfExprs args) mb_len
llvmShapeLength (PExpr_NamedShape _ _ nmsh@(NamedShape _ _
(RecShapeBody _ _ _)) args) =
-- FIXME: if the recursive shape contains itself *not* under a pointer, then
-- this could diverge
llvmShapeLength (unfoldNamedShape nmsh args)
llvmShapeLength (PExpr_EqShape len _) = Just len
llvmShapeLength (PExpr_PtrShape _ _ sh)
| w <- shapeLLVMTypeWidth sh
= Just $ bvInt (intValue w `ceil_div` 8)
llvmShapeLength (PExpr_FieldShape fsh) =
Just $ bvInt $ llvmFieldShapeLength fsh
llvmShapeLength (PExpr_ArrayShape len stride _) = Just $ bvMult stride len
llvmShapeLength (PExpr_SeqShape sh1 sh2) =
liftA2 bvAdd (llvmShapeLength sh1) (llvmShapeLength sh2)
llvmShapeLength (PExpr_OrShape sh1 sh2) =
-- We cannot represent a max expression, so we have to statically know which
-- shape is bigger in order to compute the length of an or shape
do len1 <- llvmShapeLength sh1
len2 <- llvmShapeLength sh2
if (bvLeq len1 len2) then return len2 else
if (bvLeq len2 len1) then return len1
else Nothing
llvmShapeLength (PExpr_ExShape mb_sh) =
-- The length of an existential cannot depend on the existential variable, or
-- we cannot return it
case mbMatch $ fmap llvmShapeLength mb_sh of
[nuMP| Just mb_len |] ->
partialSubst (emptyPSubst $ singletonCruCtx $ knownRepr) mb_len
_ -> Nothing
llvmShapeLength PExpr_FalseShape = Just $ bvInt 0
-- | Adjust the read/write and lifetime modalities of a block permission by
-- setting those modalities that are supplied as arguments
llvmBlockAdjustModalities :: Maybe (PermExpr RWModalityType) ->
Maybe (PermExpr LifetimeType) ->
LLVMBlockPerm w -> LLVMBlockPerm w
llvmBlockAdjustModalities maybe_rw maybe_l bp =
let rw = maybe (llvmBlockRW bp) id maybe_rw
l = maybe (llvmBlockLifetime bp) id maybe_l in
bp { llvmBlockRW = rw, llvmBlockLifetime = l }
-- | Convert a block permission of pointer shape to the block permission of
-- field shape that it represents. That is, convert the block permission
--
-- > [l]memblock(rw,off,w/8,[l2]ptrsh(rw2,sh))
--
-- to
--
-- > [l]memblock(rw,off,w/8,fieldsh([l2]memblock(rw2,0,sh_len,sh)))
--
-- where @sh_len@ is the 'llvmShapeLength' of @sh@. It is an error if the input
-- block permission does not have the required form displayed above.
llvmBlockPtrShapeUnfold :: (1 <= w, KnownNat w) => LLVMBlockPerm w ->
Maybe (LLVMBlockPerm w)
llvmBlockPtrShapeUnfold bp
| PExpr_PtrShape maybe_rw maybe_l sh <- llvmBlockShape bp
, Just sh_len <- llvmShapeLength sh
, bvEq (llvmBlockLen bp) (bvInt $ machineWordBytes bp) =
Just $ bp { llvmBlockShape =
PExpr_FieldShape $ LLVMFieldShape $ ValPerm_LLVMBlock $
LLVMBlockPerm
{ llvmBlockRW = maybe (llvmBlockRW bp) id maybe_rw,
llvmBlockLifetime = maybe (llvmBlockLifetime bp) id maybe_l,
llvmBlockOffset = bvInt 0,
llvmBlockLen = sh_len,
llvmBlockShape = sh } }
llvmBlockPtrShapeUnfold _ = Nothing
-- | Create a read block permission with shape @sh@, i.e., the 'LLVMBlockPerm'
-- corresponding to the permission @memblock(R,0,'llvmShapeLength'(sh),sh)@
llvmReadBlockOfShape :: (1 <= w, KnownNat w) => PermExpr (LLVMShapeType w) ->
LLVMBlockPerm w
llvmReadBlockOfShape sh
| Just len <- llvmShapeLength sh =
LLVMBlockPerm { llvmBlockRW = PExpr_Read,
llvmBlockLifetime = PExpr_Always,
llvmBlockOffset = bvInt 0,
llvmBlockLen = len,
llvmBlockShape = sh }
llvmReadBlockOfShape _ =
error "llvmReadBlockOfShape: shape without known length"
-- | Test if an LLVM shape is a sequence of field shapes, and if so, return that
-- sequence
matchLLVMFieldShapeSeq :: (1 <= w, KnownNat w) => PermExpr (LLVMShapeType w) ->
Maybe [LLVMFieldShape w]
matchLLVMFieldShapeSeq (PExpr_FieldShape fsh) = Just [fsh]
matchLLVMFieldShapeSeq (PExpr_SeqShape sh1 sh2) =
(++) <$> matchLLVMFieldShapeSeq sh1 <*> matchLLVMFieldShapeSeq sh2
matchLLVMFieldShapeSeq _ = Nothing
-- | Add the given read/write and lifetime modalities to all top-level pointer
-- shapes in a shape. Top-level here means we do not recurse inside pointer
-- shapes, as pointer shape modalities also apply recursively to the contained
-- shapes. If there are any top-level variables in the shape, then this fails,
-- since there is no way to modalize a variable shape.
--
-- The high-level idea here is that pointer shapes take on the read/write and
-- lifetime modalities of the @memblock@ permission containing them, and
-- 'modalizeShape' folds these modalities into the shape itself.
modalizeShape :: Maybe (PermExpr RWModalityType) ->
Maybe (PermExpr LifetimeType) ->
PermExpr (LLVMShapeType w) ->
Maybe (PermExpr (LLVMShapeType w))
modalizeShape Nothing Nothing sh =
-- If neither modality is given, it is a no-op
Just sh
modalizeShape _ _ (PExpr_Var _) =
-- Variables cannot be modalized; NOTE: we could fix this if necessary by
-- adding a modalized variable shape constructor
Nothing
modalizeShape _ _ PExpr_EmptyShape = Just PExpr_EmptyShape
modalizeShape _ _ sh@(PExpr_NamedShape _ _ nmsh _)
| not (namedShapeCanUnfold nmsh) =
-- Opaque shapes are not affected by modalization, because we assume they do
-- not have any top-level pointers in them
Just sh
modalizeShape rw l (PExpr_NamedShape rw' l' nmsh args) =
-- If a named shape already has modalities, they take precedence
Just $ PExpr_NamedShape (rw' <|> rw) (l' <|> l) nmsh args
modalizeShape _ _ sh@(PExpr_EqShape _ _) = Just sh
modalizeShape rw l (PExpr_PtrShape rw' l' sh) =
-- If a pointer shape already has modalities, they take precedence
Just $ PExpr_PtrShape (rw' <|> rw) (l' <|> l) sh
modalizeShape _ _ sh@(PExpr_FieldShape _) = Just sh
modalizeShape _ _ sh@(PExpr_ArrayShape _ _ _) = Just sh
modalizeShape rw l (PExpr_SeqShape sh1 sh2) =
PExpr_SeqShape <$> modalizeShape rw l sh1 <*> modalizeShape rw l sh2
modalizeShape rw l (PExpr_OrShape sh1 sh2) =
PExpr_OrShape <$> modalizeShape rw l sh1 <*> modalizeShape rw l sh2
modalizeShape rw l (PExpr_ExShape mb_sh) =
PExpr_ExShape <$> mbM (fmap (modalizeShape rw l) mb_sh)
modalizeShape _ _ PExpr_FalseShape = Just PExpr_FalseShape
-- | Apply 'modalizeShape' to the shape of a block permission, raising an error
-- if 'modalizeShape' cannot be applied
modalizeBlockShape :: LLVMBlockPerm w -> PermExpr (LLVMShapeType w)
modalizeBlockShape (LLVMBlockPerm {..}) =
maybe (error "modalizeBlockShape") id $
modalizeShape (Just llvmBlockRW) (Just llvmBlockLifetime) llvmBlockShape
-- | Unfold a named shape
unfoldNamedShape :: KnownNat w => NamedShape 'True args w -> PermExprs args ->
PermExpr (LLVMShapeType w)
unfoldNamedShape (NamedShape _ _ (DefinedShapeBody mb_sh)) args =
subst (substOfExprs args) mb_sh
unfoldNamedShape sh@(NamedShape _ _ (RecShapeBody mb_sh _ _)) args =
subst (substOfExprs (args :>: PExpr_NamedShape Nothing Nothing sh args)) mb_sh
-- | Unfold a named shape and apply 'modalizeShape' to the result
unfoldModalizeNamedShape :: KnownNat w => Maybe (PermExpr RWModalityType) ->
Maybe (PermExpr LifetimeType) ->
NamedShape 'True args w -> PermExprs args ->
Maybe (PermExpr (LLVMShapeType w))
unfoldModalizeNamedShape rw l nmsh args =
modalizeShape rw l $ unfoldNamedShape nmsh args
-- | Unfold the shape of a block permission using 'unfoldModalizeNamedShape' if
-- it has a named shape
unfoldModalizeNamedShapeBlock :: KnownNat w => LLVMBlockPerm w ->
Maybe (LLVMBlockPerm w)
unfoldModalizeNamedShapeBlock bp
| PExpr_NamedShape rw l nmsh args <- llvmBlockShape bp
, TrueRepr <- namedShapeCanUnfoldRepr nmsh
, Just sh' <- unfoldModalizeNamedShape rw l nmsh args =
Just (bp { llvmBlockShape = sh' })
unfoldModalizeNamedShapeBlock _ = Nothing
-- | Unfold the shape of a block permission in a binding using
-- 'unfoldModalizeNamedShape' if it has a named shape
mbUnfoldModalizeNamedShapeBlock :: KnownNat w => Mb ctx (LLVMBlockPerm w) ->
Maybe (Mb ctx (LLVMBlockPerm w))
mbUnfoldModalizeNamedShapeBlock =
mbMaybe . mbMapCl $(mkClosed [| unfoldModalizeNamedShapeBlock |])
-- | Change the shape of a disjunctive block to either its left or right
-- disjunct, depending on whether the supplied 'Bool' is 'True' or 'False'
disjBlockToSubShape :: Bool -> LLVMBlockPerm w -> LLVMBlockPerm w
disjBlockToSubShape flag bp
| PExpr_OrShape sh1 sh2 <- llvmBlockShape bp =
bp { llvmBlockShape = if flag then sh1 else sh2 }
disjBlockToSubShape _ _ = error "disjBlockToSubShape"
-- | Change the shape of a disjunctive block in a binding to either its left or
-- right disjunct, depending on whether the supplied 'Bool' is 'True' or 'False'
mbDisjBlockToSubShape :: Bool -> Mb ctx (LLVMBlockPerm w) ->
Mb ctx (LLVMBlockPerm w)
mbDisjBlockToSubShape flag =
mbMapCl ($(mkClosed [| disjBlockToSubShape |]) `clApply` toClosed flag)
-- | Match an existential shape with the given bidning type
matchExShape :: TypeRepr a -> PermExpr (LLVMShapeType w) ->
Maybe (Binding a (PermExpr (LLVMShapeType w)))
matchExShape a (PExpr_ExShape (mb_sh :: Binding b (PermExpr (LLVMShapeType w))))
| Just Refl <- testEquality a (knownRepr :: TypeRepr b) =
Just mb_sh
matchExShape _ _ = Nothing
-- | Change the shape of an existential block to the body of its existential
exBlockToSubShape :: TypeRepr a -> LLVMBlockPerm w ->
Binding a (LLVMBlockPerm w)
exBlockToSubShape a bp
| Just mb_sh <- matchExShape a $ llvmBlockShape bp =
-- NOTE: even when exBlockToSubShape is called inside a binding as part of
-- mbExBlockToSubShape, the existential binding will probably be a fresh
-- function instead of a fresh pair, because it itself has not been
-- mbMatched, so this fmap shouldn't be re-subsituting names
fmap (\sh -> bp { llvmBlockShape = sh }) mb_sh
exBlockToSubShape _ _ = error "exBlockToSubShape"
-- | Change the shape of an existential block in a binding to the body of its
-- existential
mbExBlockToSubShape :: TypeRepr a -> Mb ctx (LLVMBlockPerm w) ->
Mb (ctx :> a) (LLVMBlockPerm w)
mbExBlockToSubShape a =
mbCombine RL.typeCtxProxies .
mbMapCl ($(mkClosed [| exBlockToSubShape |]) `clApply` toClosed a)
-- | Split a block permission into portions that are before and after a given
-- offset, if possible, assuming the offset is in the block permission
splitLLVMBlockPerm :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
LLVMBlockPerm w ->
Maybe (LLVMBlockPerm w, LLVMBlockPerm w)
splitLLVMBlockPerm off bp
| bvEq off (llvmBlockOffset bp)
= Just (bp { llvmBlockLen = bvInt 0, llvmBlockShape = PExpr_EmptyShape },
bp)
splitLLVMBlockPerm off bp@(llvmBlockShape -> PExpr_EmptyShape) =
Just (bp { llvmBlockLen = bvSub off (llvmBlockOffset bp) },
bp { llvmBlockOffset = off,
llvmBlockLen = bvSub (llvmBlockEndOffset bp) off })
splitLLVMBlockPerm off bp@(LLVMBlockPerm { llvmBlockShape = sh })
| Just sh_len <- llvmShapeLength sh
, bvLt sh_len (bvSub off (llvmBlockOffset bp)) =
-- If we are splitting after the end of the natural length of a shape, then
-- pad out the block permission to its natural length and fall back to the
-- sequence shape case below
splitLLVMBlockPerm off (bp { llvmBlockShape =
PExpr_SeqShape sh PExpr_EmptyShape })
splitLLVMBlockPerm _ (llvmBlockShape -> PExpr_Var _) = Nothing
splitLLVMBlockPerm off bp@(llvmBlockShape ->
PExpr_NamedShape maybe_rw maybe_l nmsh args)
| TrueRepr <- namedShapeCanUnfoldRepr nmsh
, Just sh' <- unfoldModalizeNamedShape maybe_rw maybe_l nmsh args =
splitLLVMBlockPerm off (bp { llvmBlockShape = sh' })
splitLLVMBlockPerm _ (llvmBlockShape -> PExpr_NamedShape _ _ _ _) = Nothing
splitLLVMBlockPerm _ (llvmBlockShape -> PExpr_EqShape _ _) = Nothing
splitLLVMBlockPerm _ (llvmBlockShape -> PExpr_PtrShape _ _ _) = Nothing
splitLLVMBlockPerm _ (llvmBlockShape -> PExpr_FieldShape _) = Nothing
splitLLVMBlockPerm off bp@(llvmBlockShape -> PExpr_ArrayShape len stride sh)
| Just (ix, BV.BV 0) <-
bvMatchFactorPlusConst (bytesToInteger stride) (bvSub off $
llvmBlockOffset bp)
, off_diff <- bvSub off (llvmBlockOffset bp)
= Just (bp { llvmBlockLen = off_diff,
llvmBlockShape = PExpr_ArrayShape ix stride sh },
bp { llvmBlockOffset = off,
llvmBlockLen = bvSub (llvmBlockLen bp) off_diff,
llvmBlockShape = PExpr_ArrayShape (bvSub len ix) stride sh })
splitLLVMBlockPerm off bp@(llvmBlockShape -> PExpr_SeqShape sh1 sh2)
| Just sh1_len <- llvmShapeLength sh1
, off_diff <- bvSub off (llvmBlockOffset bp)
, bvLt off_diff sh1_len
= splitLLVMBlockPerm off (bp { llvmBlockLen = sh1_len,
llvmBlockShape = sh1 }) >>= \(bp1,bp2) ->
Just (bp1,
bp2 { llvmBlockLen = bvSub (llvmBlockLen bp) off_diff,
llvmBlockShape = PExpr_SeqShape (llvmBlockShape bp2) sh2 })
splitLLVMBlockPerm off bp@(llvmBlockShape -> PExpr_SeqShape sh1 sh2)
| Just sh1_len <- llvmShapeLength sh1
= splitLLVMBlockPerm off
(bp { llvmBlockOffset = bvAdd (llvmBlockOffset bp) sh1_len,
llvmBlockLen = bvSub (llvmBlockLen bp) sh1_len,
llvmBlockShape = sh2 }) >>= \(bp1,bp2) ->
Just (bp1 { llvmBlockOffset = llvmBlockOffset bp,
llvmBlockLen = bvAdd (llvmBlockLen bp1) sh1_len,
llvmBlockShape = PExpr_SeqShape sh1 (llvmBlockShape bp1) },
bp2)
splitLLVMBlockPerm off bp@(llvmBlockShape -> PExpr_OrShape sh1 sh2) =
do (bp1_L,bp1_R) <- splitLLVMBlockPerm off (bp { llvmBlockShape = sh1 })
(bp2_L,bp2_R) <- splitLLVMBlockPerm off (bp { llvmBlockShape = sh2 })
let or_helper bp1 bp2 =
bp1 { llvmBlockShape =
PExpr_OrShape (llvmBlockShape bp1) (llvmBlockShape bp2)}
Just (or_helper bp1_L bp2_L, or_helper bp1_R bp2_R)
splitLLVMBlockPerm off bp@(llvmBlockShape -> PExpr_ExShape mb_sh) =
case mbMatch $ fmap (\sh -> splitLLVMBlockPerm off
(bp { llvmBlockShape = sh })) mb_sh of
[nuMP| Just (mb_bp1,mb_bp2) |] ->
let off_diff = bvSub off (llvmBlockOffset bp) in
Just (bp { llvmBlockLen = off_diff,
llvmBlockShape = PExpr_ExShape (fmap llvmBlockShape mb_bp1) },
bp { llvmBlockOffset = off,
llvmBlockLen = bvSub (llvmBlockLen bp) off_diff,
llvmBlockShape = PExpr_ExShape (fmap llvmBlockShape mb_bp2) })
_ -> Nothing
splitLLVMBlockPerm _ _ = Nothing
-- | Remove a range of offsets from a block permission, if possible, yielding a
-- list of block permissions for the remaining offsets
remLLVMBLockPermRange :: (1 <= w, KnownNat w) => BVRange w -> LLVMBlockPerm w ->
Maybe [LLVMBlockPerm w]
remLLVMBLockPermRange rng bp
| bvRangeSubset (llvmBlockRange bp) rng = Just []
remLLVMBLockPermRange rng bp =
do (bps_l, bp') <-
if bvInRange (bvRangeOffset rng) (llvmBlockRange bp) then
do (bp_l,bp') <- splitLLVMBlockPerm (bvRangeOffset rng) bp
return ([bp_l],bp')
else return ([],bp)
bp_r <-
if bvInRange (bvRangeEnd rng) (llvmBlockRange bp) then
snd <$> splitLLVMBlockPerm (bvRangeEnd rng) bp
else return bp'
return (bps_l ++ [bp_r])
-- | Extract the disjunctive shapes from a 'TaggedUnionShape'
taggedUnionDisjs :: TaggedUnionShape w sz -> [PermExpr (LLVMShapeType w)]
taggedUnionDisjs (TaggedUnionShape disjs) =
map snd $ NonEmpty.toList disjs
-- | Extract the disjunctive shapes from a 'TaggedUnionShape' in a binding
mbTaggedUnionDisjs :: Mb ctx (TaggedUnionShape w sz) ->
Mb ctx [PermExpr (LLVMShapeType w)]
mbTaggedUnionDisjs = mbMapCl $(mkClosed [| taggedUnionDisjs |])
-- | Get the @n@th disjunct of a 'TaggedUnionShape' in a binding
mbTaggedUnionNthDisj :: Int -> Mb ctx (TaggedUnionShape w sz) ->
Mb ctx (PermExpr (LLVMShapeType w))
mbTaggedUnionNthDisj n_top =
mbMapCl ($(mkClosed [| \n -> (!!n) . taggedUnionDisjs |])
`clApply` toClosed n_top)
-- | Change a block permisison with a tagged union shape to have the @n@th
-- disjunct shape of this tagged union
taggedUnionNthDisjBlock :: Int -> LLVMBlockPerm w -> LLVMBlockPerm w
taggedUnionNthDisjBlock 0 bp
| PExpr_OrShape sh1 _ <- llvmBlockShape bp =
bp { llvmBlockShape = sh1 }
taggedUnionNthDisjBlock 0 bp =
-- NOTE: this case happens for the last shape in a tagged union, which is not
-- or-ed with anything, and is guaranteed not to be an or itsef (so it won't
-- match the above case)
bp
taggedUnionNthDisjBlock n bp
| PExpr_OrShape _ sh2 <- llvmBlockShape bp =
taggedUnionNthDisjBlock (n-1) $ bp { llvmBlockShape = sh2 }
taggedUnionNthDisjBlock _ _ = error "taggedUnionNthDisjBlock"
-- | Change the a block permisison in a binding with a tagged union shape to
-- have the @n@th disjunct shape of this tagged union
mbTaggedUnionNthDisjBlock :: Int -> Mb ctx (LLVMBlockPerm w) ->
Mb ctx (LLVMBlockPerm w)
mbTaggedUnionNthDisjBlock n =
mbMapCl ($(mkClosed [| taggedUnionNthDisjBlock |]) `clApply` toClosed n)
-- | Get the tags from a 'TaggedUnionShape'
taggedUnionTags :: TaggedUnionShape w sz -> [BV sz]
taggedUnionTags (TaggedUnionShape disjs) = map fst $ NonEmpty.toList disjs
-- | Build a 'TaggedUnionShape' with a single disjunct
taggedUnionSingle :: BV sz -> PermExpr (LLVMShapeType w) ->
TaggedUnionShape w sz
taggedUnionSingle tag sh = TaggedUnionShape ((tag,sh) :| [])
-- | Add a disjunct to the front of a 'TaggedUnionShape'
taggedUnionCons :: BV sz -> PermExpr (LLVMShapeType w) ->
TaggedUnionShape w sz -> TaggedUnionShape w sz
taggedUnionCons tag sh (TaggedUnionShape disjs) =
TaggedUnionShape $ NonEmpty.cons (tag,sh) disjs
-- | Convert a 'TaggedUnionShape' to the shape it represents
taggedUnionToShape :: TaggedUnionShape w sz -> PermExpr (LLVMShapeType w)
taggedUnionToShape (TaggedUnionShape disjs) =
foldr1 PExpr_OrShape $ NonEmpty.map snd disjs
-- | A bitvector value of some unknown size
data SomeBV = forall sz. (1 <= sz, KnownNat sz) => SomeBV (BV sz)
-- | Test if a shape is of the form @fieldsh(eq(llvmword(bv)))@ for some @bv@.
-- If so, return @bv@.
shapeToTag :: PermExpr (LLVMShapeType w) -> Maybe SomeBV
shapeToTag (PExpr_FieldShape
(LLVMFieldShape
(ValPerm_Eq (PExpr_LLVMWord (PExpr_BV [] bv))))) =
Just (SomeBV bv)
shapeToTag _ = Nothing
-- | Test if a shape begins with an equality permission to a bitvector value and
-- return that bitvector value
getShapeBVTag :: PermExpr (LLVMShapeType w) -> Maybe SomeBV
getShapeBVTag sh | Just some_bv <- shapeToTag sh = Just some_bv
getShapeBVTag (PExpr_SeqShape sh1 _) = getShapeBVTag sh1
getShapeBVTag _ = Nothing
-- | Test if a shape is a tagged union shape and, if so, convert it to the
-- 'TaggedUnionShape' representation
asTaggedUnionShape :: PermExpr (LLVMShapeType w) ->
Maybe (SomeTaggedUnionShape w)
asTaggedUnionShape (PExpr_OrShape sh1 sh2)
| Just (SomeBV tag1) <- getShapeBVTag sh1
, Just (SomeTaggedUnionShape tag_u2) <- asTaggedUnionShape sh2
, Just Refl <- testEquality (natRepr tag1) (natRepr tag_u2) =
Just $ SomeTaggedUnionShape $ taggedUnionCons tag1 sh1 tag_u2
asTaggedUnionShape sh
| Just (SomeBV tag) <- getShapeBVTag sh =
Just $ SomeTaggedUnionShape $ taggedUnionSingle tag sh
asTaggedUnionShape _ = Nothing
-- | Try to convert a @memblock@ permission in a binding to a tagged union shape
-- in a binding
mbLLVMBlockToTaggedUnion :: Mb ctx (LLVMBlockPerm w) ->
Maybe (Mb ctx (SomeTaggedUnionShape w))
mbLLVMBlockToTaggedUnion =
mbMaybe . mbMapCl $(mkClosed [| asTaggedUnionShape . llvmBlockShape |])
-- | Convert a @memblock@ permission with a union shape to a field permission
-- with an equality permission @eq(z)@ with evar @z@ for the tag
taggedUnionExTagPerm :: (1 <= sz, KnownNat sz) => LLVMBlockPerm w ->
Binding (BVType sz) (LLVMFieldPerm w sz)
taggedUnionExTagPerm bp =
nu $ \z -> LLVMFieldPerm { llvmFieldRW = llvmBlockRW bp,
llvmFieldLifetime = llvmBlockLifetime bp,
llvmFieldOffset = llvmBlockOffset bp,
llvmFieldContents =
ValPerm_Eq (PExpr_LLVMWord $ PExpr_Var z) }
-- | Convert a @memblock@ permission in a binding with a tagged union shape to a
-- field permission with permission @eq(z)@ using evar @z@ for the tag
mbTaggedUnionExTagPerm :: (1 <= sz, KnownNat sz) => Mb ctx (LLVMBlockPerm w) ->
Mb (ctx :> BVType sz) (LLVMFieldPerm w sz)
mbTaggedUnionExTagPerm =
mbCombine RL.typeCtxProxies . mbMapCl $(mkClosed [| taggedUnionExTagPerm |])
-- | Find a disjunct in a 'TaggedUnionShape' with the given tag
findTaggedUnionIndex :: BV.BV sz -> TaggedUnionShape w sz -> Maybe Int
findTaggedUnionIndex tag_bv (TaggedUnionShape disjs) =
findIndex (== tag_bv) $ map fst $ NonEmpty.toList disjs
-- | Find a disjunct in a 'TaggedUnionShape' in a binding with the given tag
mbFindTaggedUnionIndex :: BV.BV sz -> Mb ctx (TaggedUnionShape w sz) ->
Maybe Int
mbFindTaggedUnionIndex tag_bv =
mbLift . mbMapCl ($(mkClosed [| findTaggedUnionIndex |])
`clApply` toClosed tag_bv)
-- FIXME: delete these?
{-
-- | Find a disjunct in a 'TaggedUnionShape' that could be proven at the given
-- offset from the given atomic permission, by checking if it is a field or
-- block permission containing an equality permission to one of the tags. If
-- some disjunct can be proved, return its index in the list of disjuncts.
findTaggedUnionIndexForPerm :: PermExpr (BVType w) ->
AtomicPerm (LLVMPointerType w) ->
TaggedUnionShape w -> Maybe Int
findTaggedUnionIndexForPerm off p (TaggedUnionShape disjs@((bv1,_) :| _))
| Just bp <- llvmAtomicPermToBlock p
, bvEq off (llvmBlockOffset bp)
, Just (SomeBV tag_bv) <- getShapeBVTag $ llvmBlockShape bp
, Just Refl <- testEquality (natRepr tag_bv) (natRepr bv1)
, Just i <- findIndex (== tag_bv) $ map fst $ NonEmpty.toList disjs
= Just i
findTaggedUnionIndexForPerm _ _ _ = Nothing
-- | Find a disjunct in a 'TaggedUnionShape' that could be proven at the given
-- offset from the given atomic permissions, by looking for a field or block
-- permission containing an equality permission to one of the tags. If some
-- disjunct can be proved, return its index in the list of disjuncts.
findTaggedUnionIndexForPerms :: PermExpr (BVType w) ->
[AtomicPerm (LLVMPointerType w)] ->
TaggedUnionShape w -> Maybe Int
findTaggedUnionIndexForPerms off ps tag_un =
asum $ map (\p -> findTaggedUnionIndexForPerm off p tag_un) ps
-}
-- | Convert an array cell number @cell@ to the byte offset for that cell, given
-- by @stride * cell@
llvmArrayCellToOffset :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
PermExpr (BVType w) -> PermExpr (BVType w)
llvmArrayCellToOffset ap cell =
bvMult (bytesToInteger $ llvmArrayStride ap) cell
-- | Convert an array cell number @cell@ to the "absolute" byte offset for that
-- cell, given by @off + stride * cell@, where @off@ is the offset of the
-- supplied array permission
llvmArrayCellToAbsOffset :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
PermExpr (BVType w) -> PermExpr (BVType w)
llvmArrayCellToAbsOffset ap cell =
bvAdd (llvmArrayOffset ap) (llvmArrayCellToOffset ap cell)
-- | Convert a range of cell numbers to a range of byte offsets from the
-- beginning of the array permission
llvmArrayCellsToOffsets :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
BVRange w -> BVRange w
llvmArrayCellsToOffsets ap (BVRange cell num_cells) =
BVRange (llvmArrayCellToOffset ap cell) (llvmArrayCellToOffset ap num_cells)
-- | Return the clopen range @[0,len)@ of the cells of an array permission
llvmArrayCells :: (1 <= w, KnownNat w) => LLVMArrayPerm w -> BVRange w
llvmArrayCells ap = BVRange (bvInt 0) (llvmArrayLen ap)
-- | Build the 'BVRange' of "absolute" offsets @[off,off+len_bytes)@
llvmArrayAbsOffsets :: (1 <= w, KnownNat w) => LLVMArrayPerm w -> BVRange w
llvmArrayAbsOffsets ap =
BVRange (llvmArrayOffset ap) (llvmArrayCellToOffset ap $ llvmArrayLen ap)
-- | Return the number of bytes per machine word; @w@ is the number of bits
machineWordBytes :: KnownNat w => f w -> Integer
machineWordBytes w
| natVal w `mod` 8 /= 0 =
error "machineWordBytes: word size is not a multiple of 8!"
machineWordBytes w = natVal w `ceil_div` 8
-- | Convert bytes to machine words, rounded up, i.e., return @ceil(n/W)@,
-- where @W@ is the number of bytes per machine word
bytesToMachineWords :: KnownNat w => f w -> Integer -> Integer
bytesToMachineWords w n = n `ceil_div` machineWordBytes w
-- | Return the largest multiple of 'machineWordBytes' less than the input
prevMachineWord :: KnownNat w => f w -> Integer -> Integer
prevMachineWord w n = (bytesToMachineWords w n - 1) * machineWordBytes w
-- | Build the permission that corresponds to a borrow from an array, i.e., that
-- would need to be returned in order to remove this borrow. For 'RangeBorrow's,
-- that is the sub-array permission with no borrows of its own.
permForLLVMArrayBorrow :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
LLVMArrayBorrow w -> ValuePerm (LLVMPointerType w)
permForLLVMArrayBorrow ap (FieldBorrow cell) =
ValPerm_LLVMBlock $ llvmArrayCellPerm ap cell
permForLLVMArrayBorrow ap (RangeBorrow (BVRange off len)) =
ValPerm_Conj1 $ Perm_LLVMArray $
ap { llvmArrayOffset = llvmArrayCellToOffset ap off,
llvmArrayLen = len,
llvmArrayBorrows = [] }
-- | Add a borrow to an 'LLVMArrayPerm'
llvmArrayAddBorrow :: LLVMArrayBorrow w -> LLVMArrayPerm w -> LLVMArrayPerm w
llvmArrayAddBorrow b ap = ap { llvmArrayBorrows = b : llvmArrayBorrows ap }
-- | Add a list of borrows to an 'LLVMArrayPerm'
llvmArrayAddBorrows :: [LLVMArrayBorrow w] -> LLVMArrayPerm w -> LLVMArrayPerm w
llvmArrayAddBorrows bs ap = foldr llvmArrayAddBorrow ap bs
-- | Add all borrows from the second array to the first, assuming the one is an
-- offset array as in 'llvmArrayIsOffsetArray'
llvmArrayAddArrayBorrows :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
LLVMArrayPerm w -> LLVMArrayPerm w
llvmArrayAddArrayBorrows ap sub_ap
| Just cell_num <- llvmArrayIsOffsetArray ap sub_ap =
llvmArrayAddBorrows
(map (cellOffsetLLVMArrayBorrow cell_num) (llvmArrayBorrows sub_ap))
ap
llvmArrayAddArrayBorrows _ _ = error "llvmArrayAddArrayBorrows"
-- | Find the position in the list of borrows of an 'LLVMArrayPerm' of a
-- specific borrow
llvmArrayFindBorrow :: HasCallStack => LLVMArrayBorrow w -> LLVMArrayPerm w ->
Int
llvmArrayFindBorrow b ap =
case findIndex (== b) (llvmArrayBorrows ap) of
Just i -> i
Nothing -> error "llvmArrayFindBorrow: borrow not found"
-- | Remove a borrow from an 'LLVMArrayPerm'
llvmArrayRemBorrow :: HasCallStack => LLVMArrayBorrow w -> LLVMArrayPerm w ->
LLVMArrayPerm w
llvmArrayRemBorrow b ap =
ap { llvmArrayBorrows =
deleteNth (llvmArrayFindBorrow b ap) (llvmArrayBorrows ap) }
-- | Remove a sequence of borrows from an 'LLVMArrayPerm'
llvmArrayRemBorrows :: HasCallStack => [LLVMArrayBorrow w] -> LLVMArrayPerm w ->
LLVMArrayPerm w
llvmArrayRemBorrows bs ap = foldr llvmArrayRemBorrow ap bs
-- | Remove all borrows from the second array to the first, assuming the one is
-- an offset array as in 'llvmArrayIsOffsetArray'
llvmArrayRemArrayBorrows :: HasCallStack => (1 <= w, KnownNat w) =>
LLVMArrayPerm w -> LLVMArrayPerm w ->
LLVMArrayPerm w
llvmArrayRemArrayBorrows ap sub_ap
| Just cell_num <- llvmArrayIsOffsetArray ap sub_ap =
let sub_bs =
map (cellOffsetLLVMArrayBorrow cell_num) (llvmArrayBorrows sub_ap)
bs' = filter (flip notElem sub_bs) $ llvmArrayBorrows ap in
ap { llvmArrayBorrows = bs' }
llvmArrayRemArrayBorrows _ _ = error "llvmArrayRemArrayBorrows"
-- | Test if the borrows of an array can be permuted to another order
llvmArrayBorrowsPermuteTo :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
[LLVMArrayBorrow w] -> Bool
llvmArrayBorrowsPermuteTo ap bs =
all (flip elem (llvmArrayBorrows ap)) bs &&
all (flip elem bs) (llvmArrayBorrows ap)
-- | Add a cell offset to an 'LLVMArrayBorrow', meaning we change the borrow to
-- be relative to an array with that many more cells added to the front
cellOffsetLLVMArrayBorrow :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
LLVMArrayBorrow w -> LLVMArrayBorrow w
cellOffsetLLVMArrayBorrow off (FieldBorrow ix) =
FieldBorrow (bvAdd ix off)
cellOffsetLLVMArrayBorrow off (RangeBorrow rng) =
RangeBorrow $ offsetBVRange off rng
-- | Test if a byte offset @o@ statically aligns with a statically-known offset
-- into some array cell, i.e., whether
--
-- > o - off = stride*ix + cell_off
--
-- for some @ix@ and @cell_off@, where @off@ is the array offset and @stride@ is
-- the array stride. Return @ix@ and @cell_off@ as an 'LLVMArrayIndex' on
-- success.
matchLLVMArrayIndex :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
PermExpr (BVType w) -> Maybe (LLVMArrayIndex w)
matchLLVMArrayIndex ap o =
do let rel_off = bvSub o (llvmArrayOffset ap)
(ix, cell_off) <-
bvMatchFactorPlusConst (bytesToInteger $ llvmArrayStride ap) rel_off
return $ LLVMArrayIndex ix cell_off
-- | Test if a byte offset @o@ statically aligns with a cell boundary in an
-- array, i.e., whether
--
-- > o - off = stride*cell
--
-- for some @cell@. Return @cell@ on success.
matchLLVMArrayCell :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
PermExpr (BVType w) -> Maybe (PermExpr (BVType w))
matchLLVMArrayCell ap off
| Just (LLVMArrayIndex cell (BV.BV 0)) <- matchLLVMArrayIndex ap off =
Just cell
matchLLVMArrayCell _ _ = Nothing
-- | Return a list 'BVProp' stating that the cell(s) represented by an array
-- borrow are in the "base" set of cells in an array, before the borrows are
-- considered
llvmArrayBorrowInArrayBase :: (1 <= w, KnownNat w) =>
LLVMArrayPerm w -> LLVMArrayBorrow w ->
[BVProp w]
llvmArrayBorrowInArrayBase ap (FieldBorrow ix) =
[bvPropInRange ix (llvmArrayCells ap)]
llvmArrayBorrowInArrayBase ap (RangeBorrow rng) =
bvPropRangeSubset rng (llvmArrayCells ap)
-- | Return a list of 'BVProp's stating that two array borrows are disjoint. The
-- empty list is returned if they are trivially disjoint because they refer to
-- statically distinct field numbers.
llvmArrayBorrowsDisjoint :: (1 <= w, KnownNat w) =>
LLVMArrayBorrow w -> LLVMArrayBorrow w -> [BVProp w]
llvmArrayBorrowsDisjoint (FieldBorrow ix1) (FieldBorrow ix2) =
[BVProp_Neq ix1 ix2]
llvmArrayBorrowsDisjoint (FieldBorrow ix) (RangeBorrow rng) =
[bvPropNotInRange ix rng]
llvmArrayBorrowsDisjoint (RangeBorrow rng) (FieldBorrow ix) =
[bvPropNotInRange ix rng]
llvmArrayBorrowsDisjoint (RangeBorrow rng1) (RangeBorrow rng2) =
bvPropRangesDisjoint rng1 rng2
-- | Return a list of propositions stating that the cell(s) represented by an
-- array borrow are in the set of fields of an array permission. This takes into
-- account the current borrows on the array permission, which are fields that
-- are /not/ currently in that array permission.
llvmArrayBorrowInArray :: (1 <= w, KnownNat w) =>
LLVMArrayPerm w -> LLVMArrayBorrow w -> [BVProp w]
llvmArrayBorrowInArray ap b =
llvmArrayBorrowInArrayBase ap b ++
concatMap (llvmArrayBorrowsDisjoint b) (llvmArrayBorrows ap)
-- | Shorthand for 'llvmArrayBorrowInArray' with a single index
llvmArrayIndexInArray :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
LLVMArrayIndex w -> [BVProp w]
llvmArrayIndexInArray ap ix =
llvmArrayBorrowInArray ap (FieldBorrow $ llvmArrayIndexCell ix)
-- | Test if a cell is in an array permission and is not currently being
-- borrowed
llvmArrayCellInArray :: (1 <= w, KnownNat w) =>
LLVMArrayPerm w -> PermExpr (BVType w) -> [BVProp w]
llvmArrayCellInArray ap cell = llvmArrayBorrowInArray ap (FieldBorrow cell)
-- | Test if all cell numbers in a 'BVRange' are in an array permission and are
-- not currently being borrowed
llvmArrayCellsInArray :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
BVRange w -> [BVProp w]
llvmArrayCellsInArray ap rng = llvmArrayBorrowInArray ap (RangeBorrow rng)
-- | Test if an array permission @ap2@ is offset by an even multiple of cell
-- sizes from the start of @ap1@, and return that number of cells if so. Note
-- that 'llvmArrayIsOffsetArray' @ap1@ @ap2@ returns the negative of
-- 'llvmArrayIsOffsetArray' @ap2@ @ap1@ whenever either returns a value.
llvmArrayIsOffsetArray :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
LLVMArrayPerm w -> Maybe (PermExpr (BVType w))
llvmArrayIsOffsetArray ap1 ap2
| llvmArrayStride ap1 == llvmArrayStride ap2 =
matchLLVMArrayCell ap1 (llvmArrayOffset ap2)
llvmArrayIsOffsetArray _ _ = Nothing
-- | Build a 'BVRange' for the cells of a sub-array @ap2@ in @ap1@
llvmSubArrayRange :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
LLVMArrayPerm w -> BVRange w
llvmSubArrayRange ap1 ap2
| Just cell_num <- llvmArrayIsOffsetArray ap1 ap2 =
BVRange cell_num (llvmArrayLen ap2)
llvmSubArrayRange _ _ = error "llvmSubArrayRange"
-- | Build a 'RangeBorrow' for the cells of a sub-array @ap2@ of @ap1@
llvmSubArrayBorrow :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
LLVMArrayPerm w -> LLVMArrayBorrow w
llvmSubArrayBorrow ap1 ap2 = RangeBorrow $ llvmSubArrayRange ap1 ap2
-- | Return the propositions stating that the first array permission @ap@
-- contains the second @sub_ap@, meaning that array indices that are in @sub_ap@
-- (in the sense of 'llvmArrayIndexInArray') are in @ap@. This requires that the
-- range of @sub_ap@ be a subset of that of @ap@ and that it be disjoint from
-- all borrows in @ap@ that aren't also in @sub_ap@, i.e., that after removing
-- all borrows in @sub_ap@ from @ap@ we have that the 'llvmArrayCellsInArray'
-- propositions hold for the range of @sub_ap@.
--
-- NOTE: @sub_ap@ must satisfy 'llvmArrayIsOffsetArray', i.e., have the same
-- stride as @ap@ and be at a cell boundary in @ap@, or it is an error
llvmArrayContainsArray :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
LLVMArrayPerm w -> [BVProp w]
llvmArrayContainsArray ap sub_ap =
llvmArrayCellsInArray
(llvmArrayRemArrayBorrows ap sub_ap)
(llvmSubArrayRange ap sub_ap)
-- | Build a sub-array of an array permission at a given offset with a given
-- length, keeping only those borrows from the original array that could (in the
-- sense of 'bvPropCouldHold') overlap with the range of the sub-array. This
-- means that the borrows in the returned sub-array are an over-approximation of
-- the borrows that overlap with it, i.e., there could be borrows in the
-- returned sub-array permission that are not in its range.
llvmMakeSubArray :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
PermExpr (BVType w) -> PermExpr (BVType w) ->
LLVMArrayPerm w
llvmMakeSubArray ap off len
| Just cell <- matchLLVMArrayCell ap off
, cell_rng <- BVRange cell len =
ap { llvmArrayOffset = off, llvmArrayLen = len,
llvmArrayBorrows =
filter (not . all bvPropHolds .
llvmArrayBorrowsDisjoint (RangeBorrow cell_rng)) $
llvmArrayBorrows ap }
llvmMakeSubArray _ _ _ = error "llvmMakeSubArray"
-- | Test if an atomic LLVM permission potentially allows a read or write of a
-- given offset. If so, return a list of the propositions required for the read
-- to be allowed, and whether the propositions definitely hold (as in
-- 'bvPropHolds') or only could hold (as in 'bvPropCouldHold'). For fields and
-- blocks, the offset must simply be in their range, while for arrays, the
-- offset must only /not/ match any outstanding borrows, and the propositions
-- returned codify that as well as the requirement that the offset is in the
-- array range.
llvmPermContainsOffset :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
AtomicPerm (LLVMPointerType w) ->
Maybe ([BVProp w], Bool)
llvmPermContainsOffset off (Perm_LLVMField fp)
| prop <- bvPropInRange off (llvmFieldRange fp)
, bvPropCouldHold prop =
Just ([prop], bvPropHolds prop)
llvmPermContainsOffset off (Perm_LLVMArray ap)
| Just ix <- matchLLVMArrayIndex ap off
, props <- llvmArrayIndexInArray ap ix
, all bvPropCouldHold props =
Just (props, all bvPropHolds props)
llvmPermContainsOffset off (Perm_LLVMBlock bp)
| prop <- bvPropInRange off (llvmBlockRange bp)
, bvPropCouldHold prop =
Just ([prop], bvPropHolds prop)
llvmPermContainsOffset _ _ = Nothing
-- | Test if an atomic LLVM permission definitely contains an offset. This is
-- the 'Bool' flag returned by 'llvmPermContainsOffset', or 'False' if that is
-- undefined.
llvmPermContainsOffsetBool :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
AtomicPerm (LLVMPointerType w) -> Bool
llvmPermContainsOffsetBool off p =
maybe False snd $ llvmPermContainsOffset off p
-- | Test if an atomic LLVM permission contains (in the sense of 'bvPropHolds')
-- all offsets in a given range
llvmAtomicPermContainsRange :: (1 <= w, KnownNat w) => BVRange w ->
AtomicPerm (LLVMPointerType w) -> Bool
llvmAtomicPermContainsRange rng (Perm_LLVMArray ap)
| Just ix1 <- matchLLVMArrayIndex ap (bvRangeOffset rng)
, Just ix2 <- matchLLVMArrayIndex ap (bvRangeEnd rng)
, props <- llvmArrayBorrowInArray ap (RangeBorrow $ BVRange
(llvmArrayIndexCell ix1)
(llvmArrayIndexCell ix2)) =
all bvPropHolds props
llvmAtomicPermContainsRange rng (Perm_LLVMField fp) =
bvRangeSubset rng (llvmFieldRange fp)
llvmAtomicPermContainsRange rng (Perm_LLVMBlock bp) =
bvRangeSubset rng (llvmBlockRange bp)
llvmAtomicPermContainsRange _ _ = False
-- | Test if an atomic LLVM permission has a range that overlaps with (in the
-- sense of 'bvPropHolds') the offsets in a given range
llvmAtomicPermOverlapsRange :: (1 <= w, KnownNat w) => BVRange w ->
AtomicPerm (LLVMPointerType w) -> Bool
llvmAtomicPermOverlapsRange rng (Perm_LLVMArray ap) =
bvRangesOverlap rng (llvmArrayAbsOffsets ap) &&
not (null $ bvRangesDelete rng $
map (llvmArrayBorrowOffsets ap) (llvmArrayBorrows ap))
llvmAtomicPermOverlapsRange rng (Perm_LLVMField fp) =
bvRangesOverlap rng (llvmFieldRange fp)
llvmAtomicPermOverlapsRange rng (Perm_LLVMBlock bp) =
bvRangesOverlap rng (llvmBlockRange bp)
llvmAtomicPermOverlapsRange _ _ = False
-- | Return the total length of an LLVM array permission in bytes
llvmArrayLengthBytes :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
PermExpr (BVType w)
llvmArrayLengthBytes ap = llvmArrayCellToOffset ap (llvmArrayLen ap)
-- | Return the byte offset of an array index from the beginning of the array
llvmArrayIndexByteOffset :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
LLVMArrayIndex w -> PermExpr (BVType w)
llvmArrayIndexByteOffset ap (LLVMArrayIndex cell cell_off) =
bvAdd (llvmArrayCellToOffset ap cell) (bvBV cell_off)
-- | Convert an array permission with a statically-known size @N@ to a list of
-- @memblock@ permissions for cells @0@ through @N-1@
llvmArrayToBlocks :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
Maybe [LLVMBlockPerm w]
llvmArrayToBlocks ap
| Just len <- bvMatchConstInt $ llvmArrayLen ap =
Just $ map (llvmArrayCellPerm ap . bvInt) [0..len-1]
llvmArrayToBlocks _ = Nothing
-- | Get the range of byte offsets represented by an array borrow relative to
-- the beginning of the array permission
llvmArrayBorrowOffsets :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
LLVMArrayBorrow w -> BVRange w
llvmArrayBorrowOffsets ap (FieldBorrow ix) =
bvRangeOfIndex $ llvmArrayCellToOffset ap ix
llvmArrayBorrowOffsets ap (RangeBorrow r) = llvmArrayCellsToOffsets ap r
-- | Get the range of byte offsets represented by an array borrow relative to
-- the variable @x@ that has the supplied array permission. This is equivalent
-- to the addition of 'llvmArrayOffset' to the range of relative offsets
-- returned by 'llvmArrayBorrowOffsets'.
llvmArrayBorrowAbsOffsets :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
LLVMArrayBorrow w -> BVRange w
llvmArrayBorrowAbsOffsets ap b =
offsetBVRange (llvmArrayOffset ap) (llvmArrayBorrowOffsets ap b)
-- | Divide an array permission @x:array(off,<len,*1,flds,bs)@ into two arrays,
-- one of length @len'@ starting at @off@ and one of length @len-len'@ starting
-- at offset @off+len'*stride@. All borrows that are definitely (in the sense of
-- 'bvPropHolds') in the first portion of the array are moved to that first
-- portion, and otherwise they are left in the second.
llvmArrayPermDivide :: (1 <= w, KnownNat w) => LLVMArrayPerm w ->
PermExpr (BVType w) -> (LLVMArrayPerm w, LLVMArrayPerm w)
llvmArrayPermDivide ap len =
let len_bytes = llvmArrayCellToOffset ap len
borrow_in_first b =
all bvPropHolds (bvPropRangeSubset
(llvmArrayBorrowOffsets ap b)
(BVRange (bvInt 0) len_bytes)) in
(ap { llvmArrayLen = len,
llvmArrayBorrows = filter borrow_in_first (llvmArrayBorrows ap) }
,
ap { llvmArrayOffset = bvAdd (llvmArrayOffset ap) len_bytes
, llvmArrayLen = bvSub (llvmArrayLen ap) len
, llvmArrayBorrows =
filter (not . borrow_in_first) (llvmArrayBorrows ap) })
-- | Create a list of field permissions that cover @N@ bytes:
--
-- > ptr((W,0) |-> true, (W,M) |-> true, (W,2*M) |-> true,
-- > ..., (W, (i-1)*M, 8*(sz-(i-1)*M)) |-> true)
--
-- where @sz@ is the number of bytes allocated, @M@ is the machine word size in
-- bytes, and @i@ is the greatest natural number such that @(i-1)*M < sz@
llvmFieldsOfSize :: (1 <= w, KnownNat w) => f w -> Integer ->
[AtomicPerm (LLVMPointerType w)]
llvmFieldsOfSize (w :: f w) sz
| sz_last_int <- 8 * (sz - prevMachineWord w sz)
, Just (Some sz_last) <- someNat sz_last_int
, Left LeqProof <- decideLeq (knownNat @1) sz_last =
withKnownNat sz_last $
map (\i -> Perm_LLVMField $
(llvmFieldWrite0True @w) { llvmFieldOffset =
bvInt (i * machineWordBytes w) })
[0 .. bytesToMachineWords w sz - 2]
++
[Perm_LLVMField $
(llvmSizedFieldWrite0True w sz_last)
{ llvmFieldOffset =
bvInt ((bytesToMachineWords w sz - 1) * machineWordBytes w) }]
| otherwise = error "impossible (sz_last_int is always >= 8)"
-- | Return the permission built from the field permissions returned by
-- 'llvmFieldsOfSize'
llvmFieldsPermOfSize :: (1 <= w, KnownNat w) => f w -> Integer ->
ValuePerm (LLVMPointerType w)
llvmFieldsPermOfSize w n = ValPerm_Conj $ llvmFieldsOfSize w n
-- | Return a memblock permission with empty shape of given size
llvmEmptyBlockPermOfSize :: (1 <= w, KnownNat w) => f w -> Integer ->
ValuePerm (LLVMPointerType w)
llvmEmptyBlockPermOfSize _ n = ValPerm_LLVMBlock $
LLVMBlockPerm { llvmBlockRW = PExpr_RWModality Write
, llvmBlockLifetime = PExpr_Always
, llvmBlockOffset = bvInt 0
, llvmBlockLen = bvInt n
, llvmBlockShape = PExpr_EmptyShape
}
-- | Create an LLVM shape for a single byte with @true@ permissions
llvmByteTrueShape :: (1 <= w, KnownNat w) => PermExpr (LLVMShapeType w)
llvmByteTrueShape =
PExpr_FieldShape $ LLVMFieldShape (ValPerm_True
:: ValuePerm (LLVMPointerType 8))
-- | Create an 'LLVMArrayPerm' for an array of uninitialized bytes
llvmByteArrayArrayPerm :: (1 <= w, KnownNat w) =>
PermExpr (BVType w) -> PermExpr (BVType w) ->
PermExpr RWModalityType -> PermExpr LifetimeType ->
LLVMArrayPerm w
llvmByteArrayArrayPerm off len rw l =
LLVMArrayPerm { llvmArrayRW = rw, llvmArrayLifetime = l,
llvmArrayOffset = off, llvmArrayLen = len,
llvmArrayStride = 1, llvmArrayCellShape = llvmByteTrueShape,
llvmArrayBorrows = [] }
-- | Create a permission for an array of bytes
llvmByteArrayPerm :: (1 <= w, KnownNat w) =>
PermExpr (BVType w) -> PermExpr (BVType w) ->
PermExpr RWModalityType -> PermExpr LifetimeType ->
ValuePerm (LLVMPointerType w)
llvmByteArrayPerm off len rw l =
ValPerm_Conj1 $ Perm_LLVMArray $ llvmByteArrayArrayPerm off len rw l
-- | Map an 'LLVMBlockPerm' to a byte array perm with the same components
llvmBlockPermToByteArrayPerm :: (1 <= w, KnownNat w) => LLVMBlockPerm w ->
ValuePerm (LLVMPointerType w)
llvmBlockPermToByteArrayPerm (LLVMBlockPerm {..}) =
llvmByteArrayPerm llvmBlockOffset llvmBlockLen llvmBlockRW llvmBlockLifetime
-- | Create a @memblock(W,0,sz,emptysh)@ permission for a given size @sz@
llvmBlockPermOfSize :: (1 <= w, KnownNat w) => Integer ->
ValuePerm (LLVMPointerType w)
llvmBlockPermOfSize sz =
ValPerm_Conj1 $ Perm_LLVMBlock $
LLVMBlockPerm { llvmBlockRW = PExpr_Write, llvmBlockLifetime = PExpr_Always,
llvmBlockOffset = bvInt 0, llvmBlockLen = bvInt sz,
llvmBlockShape = PExpr_EmptyShape }
-- | Add an offset @off@ to an LLVM permission @p@, meaning change @p@ so that
-- it indicates that @x+off@ has permission @p@.
--
-- FIXME: this should be the general-purpose function 'offsetPerm' that recurses
-- through permissions; that would allow other sorts of offsets at other types
offsetLLVMPerm :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
ValuePerm (LLVMPointerType w) -> ValuePerm (LLVMPointerType w)
offsetLLVMPerm off (ValPerm_Eq e) = ValPerm_Eq $ addLLVMOffset e (bvNegate off)
offsetLLVMPerm off (ValPerm_Or p1 p2) =
ValPerm_Or (offsetLLVMPerm off p1) (offsetLLVMPerm off p2)
offsetLLVMPerm off (ValPerm_Exists mb_p) =
ValPerm_Exists $ fmap (offsetLLVMPerm off) mb_p
offsetLLVMPerm off (ValPerm_Named n args off') =
ValPerm_Named n args (addPermOffsets off' (mkLLVMPermOffset off))
offsetLLVMPerm off (ValPerm_Var x off') =
ValPerm_Var x $ addPermOffsets off' (mkLLVMPermOffset off)
offsetLLVMPerm off (ValPerm_Conj ps) =
ValPerm_Conj $ mapMaybe (offsetLLVMAtomicPerm off) ps
offsetLLVMPerm _ ValPerm_False = ValPerm_False
-- | Test if an LLVM pointer permission can be offset by the given offset; i.e.,
-- whether 'offsetLLVMAtomicPerm' returns a value
canOffsetLLVMAtomicPerm :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
LLVMPtrPerm w -> Bool
canOffsetLLVMAtomicPerm off p = isJust $ offsetLLVMAtomicPerm off p
-- | Add an offset to an LLVM pointer permission, returning 'Nothing' for
-- permissions like @free@ and @llvm_funptr@ that cannot be offset
offsetLLVMAtomicPerm :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
LLVMPtrPerm w -> Maybe (LLVMPtrPerm w)
offsetLLVMAtomicPerm (bvMatchConstInt -> Just 0) p = Just p
offsetLLVMAtomicPerm off (Perm_LLVMField fp) =
Just $ Perm_LLVMField $ offsetLLVMFieldPerm off fp
offsetLLVMAtomicPerm off (Perm_LLVMArray ap) =
Just $ Perm_LLVMArray $ offsetLLVMArrayPerm off ap
offsetLLVMAtomicPerm off (Perm_LLVMBlock bp) =
Just $ Perm_LLVMBlock $ offsetLLVMBlockPerm off bp
offsetLLVMAtomicPerm _ (Perm_LLVMFree _) = Nothing
offsetLLVMAtomicPerm _ (Perm_LLVMFunPtr _ _) = Nothing
offsetLLVMAtomicPerm _ p@Perm_IsLLVMPtr = Just p
offsetLLVMAtomicPerm off (Perm_NamedConj n args off') =
Just $ Perm_NamedConj n args $ addPermOffsets off' (mkLLVMPermOffset off)
offsetLLVMAtomicPerm _ p@(Perm_BVProp _) = Just p
-- | Add an offset to a field permission
offsetLLVMFieldPerm :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
LLVMFieldPerm w sz -> LLVMFieldPerm w sz
offsetLLVMFieldPerm off (LLVMFieldPerm {..}) =
LLVMFieldPerm { llvmFieldOffset = bvAdd llvmFieldOffset off, ..}
-- | Add an offset to an array permission
offsetLLVMArrayPerm :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
LLVMArrayPerm w -> LLVMArrayPerm w
offsetLLVMArrayPerm off (LLVMArrayPerm {..}) =
LLVMArrayPerm { llvmArrayOffset = bvAdd llvmArrayOffset off, ..}
-- | Add an offset to a block permission
offsetLLVMBlockPerm :: (1 <= w, KnownNat w) => PermExpr (BVType w) ->
LLVMBlockPerm w -> LLVMBlockPerm w
offsetLLVMBlockPerm off (LLVMBlockPerm {..}) =
LLVMBlockPerm { llvmBlockOffset = bvAdd llvmBlockOffset off, ..}
-- | Add a 'PermOffset' to a permission, assuming that it is a conjunctive
-- permission, meaning that it is built inductively using only existentials,
-- disjunctions, conjunctive named permissions, and conjunctions of atomic
-- permissions (though these atomic permissions can contain equality permissions
-- in, e.g., LLVM field permissions)
offsetPerm :: PermOffset a -> ValuePerm a -> ValuePerm a
offsetPerm (LLVMPermOffset off) p = offsetLLVMPerm off p
offsetPerm NoPermOffset p = p
-- | Lens for the atomic permissions in a 'ValPerm_Conj'; it is an error to use
-- this lens with a value permission not of this form
conjAtomicPerms :: Lens' (ValuePerm a) [AtomicPerm a]
conjAtomicPerms =
lens
(\p -> case p of
ValPerm_Conj ps -> ps
_ -> error "conjAtomicPerms: not a conjuction of atomic permissions")
(\p ps ->
case p of
ValPerm_Conj _ -> ValPerm_Conj ps
_ -> error "conjAtomicPerms: not a conjuction of atomic permissions")
-- | Lens for the @i@th atomic permission in a 'ValPerm_Conj'; it is an error to
-- use this lens with a value permission not of this form
conjAtomicPerm :: Int -> Lens' (ValuePerm a) (AtomicPerm a)
conjAtomicPerm i =
lens
(\p -> if i >= length (p ^. conjAtomicPerms) then
error "conjAtomicPerm: index out of bounds"
else (p ^. conjAtomicPerms) !! i)
(\p pp ->
-- FIXME: there has got to be a nicer, more lens-like way to do this
let pps = p ^. conjAtomicPerms in
if i >= length pps then
error "conjAtomicPerm: index out of bounds"
else set conjAtomicPerms (take i pps ++ (pp : drop (i+1) pps)) p)
-- | Add a new atomic permission to the end of the list of those contained in
-- the 'conjAtomicPerms' of a permission
addAtomicPerm :: AtomicPerm a -> ValuePerm a -> ValuePerm a
addAtomicPerm pp = over conjAtomicPerms (++ [pp])
-- | Delete the atomic permission at the given index from the list of those
-- contained in the 'conjAtomicPerms' of a permission
deleteAtomicPerm :: Int -> ValuePerm a -> ValuePerm a
deleteAtomicPerm i =
over conjAtomicPerms (\pps ->
if i >= length pps then
error "deleteAtomicPerm: index out of bounds"
else take i pps ++ drop (i+1) pps)
-- | Lens for the LLVM pointer permissions in a 'ValPerm_Conj'; it is an error
-- to use this lens with a value permission not of this form
llvmPtrPerms :: Lens' (ValuePerm (LLVMPointerType w)) [LLVMPtrPerm w]
llvmPtrPerms = conjAtomicPerms
-- | Lens for the @i@th LLVM pointer permission of a 'ValPerm_Conj'
llvmPtrPerm :: Int -> Lens' (ValuePerm (LLVMPointerType w)) (LLVMPtrPerm w)
llvmPtrPerm = conjAtomicPerm
-- | Add a new 'LLVMPtrPerm' to the end of the list of those contained in the
-- 'llvmPtrPerms' of a permission
addLLVMPtrPerm :: LLVMPtrPerm w -> ValuePerm (LLVMPointerType w) ->
ValuePerm (LLVMPointerType w)
addLLVMPtrPerm pp = over llvmPtrPerms (++ [pp])
-- | Delete the 'LLVMPtrPerm' at the given index from the list of those
-- contained in the 'llvmPtrPerms' of a permission
deleteLLVMPtrPerm :: Int -> ValuePerm (LLVMPointerType w) ->
ValuePerm (LLVMPointerType w)
deleteLLVMPtrPerm i =
over llvmPtrPerms (\pps ->
if i >= length pps then
error "deleteLLVMPtrPerm: index out of bounds"
else take i pps ++ drop (i+1) pps)
-- | Return the index of the last 'LLVMPtrPerm' of a permission
lastLLVMPtrPermIndex :: ValuePerm (LLVMPointerType w) -> Int
lastLLVMPtrPermIndex p =
let len = length (p ^. llvmPtrPerms) in
if len > 0 then len - 1 else error "lastLLVMPtrPerms: no pointer perms!"
-- | Create a list of pointer permissions needed in order to deallocate a frame
-- that has the given frame permissions. It is an error if any of the required
-- permissions are for LLVM words instead of pointers.
llvmFrameDeletionPerms :: (1 <= w, KnownNat w) => LLVMFramePerm w ->
Some DistPerms
llvmFrameDeletionPerms [] = Some DistPermsNil
llvmFrameDeletionPerms ((asLLVMOffset -> Just (x,_off), sz):fperm')
| Some del_perms <- llvmFrameDeletionPerms fperm' =
Some $ DistPermsCons del_perms x $ llvmBlockPermOfSize sz
llvmFrameDeletionPerms _ =
error "llvmFrameDeletionPerms: unexpected LLVM word allocated in frame"
-- | Build a 'DistPerms' with just one permission
distPerms1 :: ExprVar a -> ValuePerm a -> DistPerms (RNil :> a)
distPerms1 x p = DistPermsCons DistPermsNil x p
-- | Build a 'DistPerms' with two permissions
distPerms2 :: ExprVar a1 -> ValuePerm a1 ->
ExprVar a2 -> ValuePerm a2 -> DistPerms (RNil :> a1 :> a2)
distPerms2 x1 p1 x2 p2 = DistPermsCons (distPerms1 x1 p1) x2 p2
-- | Build a 'DistPerms' with three permissions
distPerms3 :: ExprVar a1 -> ValuePerm a1 -> ExprVar a2 -> ValuePerm a2 ->
ExprVar a3 -> ValuePerm a3 -> DistPerms (RNil :> a1 :> a2 :> a3)
distPerms3 x1 p1 x2 p2 x3 p3 = DistPermsCons (distPerms2 x1 p1 x2 p2) x3 p3
-- | Get the first permission in a 'DistPerms'
distPermsHeadPerm :: DistPerms (ps :> a) -> ValuePerm a
distPermsHeadPerm (DistPermsCons _ _ p) = p
-- | Drop the last permission in a 'DistPerms'
distPermsSnoc :: DistPerms (ps :> a) -> DistPerms ps
distPermsSnoc (DistPermsCons ps _ _) = ps
-- | Map a function on permissions across a 'DistPerms'
mapDistPerms :: (forall a. ValuePerm a -> ValuePerm a) ->
DistPerms ps -> DistPerms ps
mapDistPerms _ DistPermsNil = DistPermsNil
mapDistPerms f (DistPermsCons perms x p) =
DistPermsCons (mapDistPerms f perms) x (f p)
-- | Create a sequence of @true@ permissions
trueValuePerms :: RAssign any ps -> ValuePerms ps
trueValuePerms MNil = ValPerms_Nil
trueValuePerms (ps :>: _) = ValPerms_Cons (trueValuePerms ps) ValPerm_True
-- | Create a list of @eq(xi)@ permissions from a list of variables @x1,x2,...@
eqValuePerms :: RAssign Name ps -> ValuePerms ps
eqValuePerms MNil = ValPerms_Nil
eqValuePerms (xs :>: x) =
ValPerms_Cons (eqValuePerms xs) (ValPerm_Eq (PExpr_Var x))
-- | Append two lists of permissions
appendValuePerms :: ValuePerms ps1 -> ValuePerms ps2 -> ValuePerms (ps1 :++: ps2)
appendValuePerms ps1 ValPerms_Nil = ps1
appendValuePerms ps1 (ValPerms_Cons ps2 p) =
ValPerms_Cons (appendValuePerms ps1 ps2) p
distPermsToProxies :: DistPerms ps -> RAssign Proxy ps
distPermsToProxies (DistPermsNil) = MNil
distPermsToProxies (DistPermsCons ps _ _) = distPermsToProxies ps :>: Proxy
mbDistPermsToProxies :: Mb ctx (DistPerms ps) -> RAssign Proxy ps
mbDistPermsToProxies mb_ps = case mbMatch mb_ps of
[nuMP| DistPermsNil |] -> MNil
[nuMP| DistPermsCons ps _ _ |] ->
mbDistPermsToProxies ps :>: Proxy
-- | Extract the variables in a 'DistPerms'
distPermsVars :: DistPerms ps -> RAssign Name ps
distPermsVars DistPermsNil = MNil
distPermsVars (DistPermsCons ps x _) = distPermsVars ps :>: x
-- | Append two lists of distinguished permissions
appendDistPerms :: DistPerms ps1 -> DistPerms ps2 -> DistPerms (ps1 :++: ps2)
appendDistPerms ps1 DistPermsNil = ps1
appendDistPerms ps1 (DistPermsCons ps2 x p) =
DistPermsCons (appendDistPerms ps1 ps2) x p
-- | Filter a list of distinguished permissions using a predicate
filterDistPerms :: (forall a. Name a -> ValuePerm a -> Bool) ->
DistPerms ps -> Some DistPerms
filterDistPerms _ DistPermsNil = Some DistPermsNil
filterDistPerms pred (DistPermsCons ps x p)
| pred x p
, Some ps' <- filterDistPerms pred ps = Some (DistPermsCons ps' x p)
filterDistPerms pred (DistPermsCons ps _ _) = filterDistPerms pred ps
-- | Build a list of distinguished permissions from a list of variables
buildDistPerms :: (forall a. Name a -> ValuePerm a) -> RAssign Name ps ->
DistPerms ps
buildDistPerms _ MNil = DistPermsNil
buildDistPerms f (ns :>: n) = DistPermsCons (buildDistPerms f ns) n (f n)
-- | Split a list of distinguished permissions into two
splitDistPerms :: f ps1 -> RAssign g ps2 -> DistPerms (ps1 :++: ps2) ->
(DistPerms ps1, DistPerms ps2)
splitDistPerms _ = helper where
helper :: RAssign g ps2 -> DistPerms (ps1 :++: ps2) ->
(DistPerms ps1, DistPerms ps2)
helper MNil perms = (perms, DistPermsNil)
helper (prxs :>: _) (DistPermsCons ps x p) =
let (perms1, perms2) = helper prxs ps in
(perms1, DistPermsCons perms2 x p)
-- | Split a list of value permissions in bindings into two
splitMbValuePerms :: f ps1 -> RAssign g ps2 ->
Mb vars (ValuePerms (ps1 :++: ps2)) ->
(Mb vars (ValuePerms ps1), Mb vars (ValuePerms ps2))
splitMbValuePerms _ MNil mb_perms =
(mb_perms, fmap (const ValPerms_Nil) mb_perms)
splitMbValuePerms prx (ps2 :>: _) (mbMatch -> [nuMP| ValPerms_Cons mb_perms p |]) =
let (ret1, ret2) = splitMbValuePerms prx ps2 mb_perms in
(ret1, mbMap2 ValPerms_Cons ret2 p)
-- | Lens for the top permission in a 'DistPerms' stack
distPermsHead :: ExprVar a -> Lens' (DistPerms (ps :> a)) (ValuePerm a)
distPermsHead x =
lens (\(DistPermsCons _ y p) ->
if x == y then p else error "distPermsHead: incorrect variable name!")
(\(DistPermsCons pstk y _) p ->
if x == y then DistPermsCons pstk y p else
error "distPermsHead: incorrect variable name!")
-- | The lens for the tail of a 'DistPerms' stack
distPermsTail :: Lens' (DistPerms (ps :> a)) (DistPerms ps)
distPermsTail =
lens (\(DistPermsCons pstk _ _) -> pstk)
(\(DistPermsCons _ x p) pstk -> DistPermsCons pstk x p)
-- | The lens for the nth permission in a 'DistPerms' stack
nthVarPerm :: Member ps a -> ExprVar a -> Lens' (DistPerms ps) (ValuePerm a)
nthVarPerm Member_Base x = distPermsHead x
nthVarPerm (Member_Step memb') x = distPermsTail . nthVarPerm memb' x
-- | Test if a permission can be copied, i.e., whether @p -o p*p@. This is true
-- iff @p@ does not contain any 'Write' modalities, any frame permissions, or
-- any lifetime ownership permissions. Note that this must be true for all
-- substitutions of free (permission or expression) variables, so free variables
-- can make a permission not copyable as well.
permIsCopyable :: ValuePerm a -> Bool
permIsCopyable (ValPerm_Eq _) = True
permIsCopyable (ValPerm_Or p1 p2) = permIsCopyable p1 && permIsCopyable p2
permIsCopyable (ValPerm_Exists mb_p) = mbLift $ fmap permIsCopyable mb_p
permIsCopyable (ValPerm_Named npn args _offset) =
-- FIXME: this is wrong. For transparent perms, should make this just unfold
-- the definition; for opaque perms, look at arguments. For recursive perms,
-- unfold and assume the recursive call is copyable, then see if the unfolded
-- version is still copyable
namedPermArgsAreCopyable (namedPermNameArgs npn) args
permIsCopyable (ValPerm_Var _ _) = False
permIsCopyable (ValPerm_Conj ps) = all atomicPermIsCopyable ps
permIsCopyable ValPerm_False = True
-- | The same as 'permIsCopyable' except for atomic permissions
atomicPermIsCopyable :: AtomicPerm a -> Bool
atomicPermIsCopyable (Perm_LLVMField
(LLVMFieldPerm { llvmFieldRW = PExpr_Read,
llvmFieldContents = p })) =
permIsCopyable p
atomicPermIsCopyable (Perm_LLVMField _) = False
atomicPermIsCopyable (Perm_LLVMArray (LLVMArrayPerm {..})) =
llvmArrayRW == PExpr_Read && shapeIsCopyable llvmArrayRW llvmArrayCellShape
atomicPermIsCopyable (Perm_LLVMBlock (LLVMBlockPerm {..})) =
llvmBlockRW == PExpr_Read && shapeIsCopyable llvmBlockRW llvmBlockShape
atomicPermIsCopyable (Perm_LLVMFree _) = True
atomicPermIsCopyable (Perm_LLVMFunPtr _ _) = True
atomicPermIsCopyable Perm_IsLLVMPtr = True
atomicPermIsCopyable (Perm_LLVMBlockShape sh) = shapeIsCopyable PExpr_Write sh
atomicPermIsCopyable (Perm_LLVMFrame _) = False
atomicPermIsCopyable (Perm_LOwned _ _ _) = False
atomicPermIsCopyable (Perm_LOwnedSimple _) = False
atomicPermIsCopyable (Perm_LCurrent _) = True
atomicPermIsCopyable Perm_LFinished = True
atomicPermIsCopyable (Perm_Struct ps) = and $ RL.mapToList permIsCopyable ps
atomicPermIsCopyable (Perm_Fun _) = True
atomicPermIsCopyable (Perm_BVProp _) = True
atomicPermIsCopyable (Perm_NamedConj n args _) =
namedPermArgsAreCopyable (namedPermNameArgs n) args
-- | 'permIsCopyable' for the arguments of a named permission
namedPermArgIsCopyable :: TypeRepr a -> PermExpr a -> Bool
namedPermArgIsCopyable RWModalityRepr PExpr_Read = True
namedPermArgIsCopyable RWModalityRepr _ = False
namedPermArgIsCopyable (ValuePermRepr _) (PExpr_ValPerm p) = permIsCopyable p
namedPermArgIsCopyable (ValuePermRepr _) (PExpr_Var _) = False
namedPermArgIsCopyable _ _ = True
-- | 'permIsCopyable' for an argument of a named permission
namedPermArgsAreCopyable :: CruCtx args -> PermExprs args -> Bool
namedPermArgsAreCopyable CruCtxNil PExprs_Nil = True
namedPermArgsAreCopyable (CruCtxCons tps tp) (PExprs_Cons args arg) =
namedPermArgsAreCopyable tps args && namedPermArgIsCopyable tp arg
-- | Test if an LLVM shape corresponds to a copyable permission relative to the
-- given read/write modality
shapeIsCopyable :: PermExpr RWModalityType -> PermExpr (LLVMShapeType w) -> Bool
shapeIsCopyable _ (PExpr_Var _) = False
shapeIsCopyable _ PExpr_EmptyShape = True
shapeIsCopyable rw (PExpr_NamedShape maybe_rw' _ nmsh args) =
case namedShapeBody nmsh of
DefinedShapeBody _ ->
let rw' = maybe rw id maybe_rw' in
shapeIsCopyable rw' $ unfoldNamedShape nmsh args
-- NOTE: we are assuming that opaque shapes are copyable iff their args are
OpaqueShapeBody _ _ ->
namedPermArgsAreCopyable (namedShapeArgs nmsh) args
-- HACK: the real computation we want to perform is to assume nmsh is copyable
-- and prove it is under that assumption; to accomplish this, we substitute
-- the empty shape for the recursive shape
RecShapeBody mb_sh _ _ ->
shapeIsCopyable rw $ subst (substOfExprs (args :>: PExpr_EmptyShape)) mb_sh
shapeIsCopyable _ (PExpr_EqShape _ _) = True
shapeIsCopyable rw (PExpr_PtrShape maybe_rw' _ sh) =
let rw' = maybe rw id maybe_rw' in
rw' == PExpr_Read && shapeIsCopyable rw' sh
shapeIsCopyable _ (PExpr_FieldShape (LLVMFieldShape p)) = permIsCopyable p
shapeIsCopyable rw (PExpr_ArrayShape _ _ sh) = shapeIsCopyable rw sh
shapeIsCopyable rw (PExpr_SeqShape sh1 sh2) =
shapeIsCopyable rw sh1 && shapeIsCopyable rw sh2
shapeIsCopyable rw (PExpr_OrShape sh1 sh2) =
shapeIsCopyable rw sh1 && shapeIsCopyable rw sh2
shapeIsCopyable rw (PExpr_ExShape mb_sh) =
mbLift $ fmap (shapeIsCopyable rw) mb_sh
shapeIsCopyable _ PExpr_FalseShape = True
-- FIXME: need a traversal function for RAssign for the following two funs
-- | Convert an 'LOwnedPerms' list to a 'DistPerms'
lownedPermsToDistPerms :: LOwnedPerms ps -> Maybe (DistPerms ps)
lownedPermsToDistPerms MNil = Just MNil
lownedPermsToDistPerms (lops :>: lop) =
(:>:) <$> lownedPermsToDistPerms lops <*> lownedPermVarAndPerm lop
-- | Optionally set the modalities of the permissions in an 'LOwnedPerms' list
modalizeLOwnedPerms ::Maybe (PermExpr RWModalityType) ->
Maybe (PermExpr LifetimeType) -> LOwnedPerms ps ->
LOwnedPerms ps
modalizeLOwnedPerms rw l = RL.map $ \case
LOwnedPermField x fp ->
LOwnedPermField x $
fp { llvmFieldRW = fromMaybe (llvmFieldRW fp) rw,
llvmFieldLifetime = fromMaybe (llvmFieldLifetime fp) l }
LOwnedPermArray x ap ->
LOwnedPermArray x $
ap { llvmArrayRW = fromMaybe (llvmArrayRW ap) rw,
llvmArrayLifetime = fromMaybe (llvmArrayLifetime ap) l }
LOwnedPermBlock x bp ->
LOwnedPermBlock x $
bp { llvmBlockRW = fromMaybe (llvmBlockRW bp) rw,
llvmBlockLifetime = fromMaybe (llvmBlockLifetime bp) l }
-- | Convert an 'LOwnedPerms' list @ps@ to the input permission list @[l](R)ps@
-- used in a simple @lowned@ permission
lownedPermsSimpleIn :: ExprVar LifetimeType -> LOwnedPerms ps ->
LOwnedPerms ps
lownedPermsSimpleIn l =
modalizeLOwnedPerms (Just PExpr_Read) (Just $ PExpr_Var l)
-- | Convert the expressions of an 'LOwnedPerms' to variables, if possible
lownedPermsVars :: LOwnedPerms ps -> Maybe (RAssign Name ps)
lownedPermsVars = fmap distPermsVars . lownedPermsToDistPerms
-- | Test if an 'LOwnedPerm' could help prove any of a list of permissions
lownedPermCouldProve :: LOwnedPerm a -> DistPerms ps -> Bool
lownedPermCouldProve (LOwnedPermField (PExpr_Var x) fp) ps =
any (\case (llvmAtomicPermRange -> Just rng) ->
bvCouldBeInRange (llvmFieldOffset fp) rng
_ -> False) $
varAtomicPermsInDistPerms x ps
lownedPermCouldProve (LOwnedPermArray (PExpr_Var x) ap) ps =
any (\case (llvmAtomicPermRange -> Just rng) ->
bvRangesCouldOverlap (llvmArrayAbsOffsets ap) rng
_ -> False) $
varAtomicPermsInDistPerms x ps
lownedPermCouldProve (LOwnedPermBlock (PExpr_Var x) bp) ps =
any (\case (llvmAtomicPermRange -> Just rng) ->
bvRangesCouldOverlap (llvmBlockRange bp) rng
_ -> False) $
varAtomicPermsInDistPerms x ps
lownedPermCouldProve _ _ = False
-- | Test if an 'LOwnedPerms' list could help prove any of a list of permissions
lownedPermsCouldProve :: LOwnedPerms ps -> DistPerms ps' -> Bool
lownedPermsCouldProve lops ps =
RL.foldr (\lop rest -> lownedPermCouldProve lop ps || rest) False lops
{-
-- | Convert a 'FunPerm' in a name-binding to a 'FunPerm' that takes those bound
-- names as additional ghost arguments with the supplied input permissions and
-- no output permissions
mbFunPerm :: CruCtx ctx -> Mb ctx (ValuePerms ctx) ->
Mb ctx (FunPerm ghosts args gouts ret) ->
FunPerm (ctx :++: ghosts) args gouts ret
mbFunPerm ctx mb_ps (mbMatch ->
[nuMP| FunPerm mb_ghosts mb_args
mb_gouts mb_ret ps_in ps_out |]) =
let ghosts = mbLift mb_ghosts
args = mbLift mb_args
ctx_perms = trueValuePerms $ cruCtxToTypes ctx
args_prxs = cruCtxProxies args
ghosts_prxs = cruCtxProxies ghosts
gouts_prxs = cruCtxProxies gouts
prxs_in = RL.append ghosts_prxs args_prxs
prxs_out =
RL.append ghosts_prxs $ RL.append args_prxs gouts_prxs :>: Proxy in
case RL.appendAssoc ctx ghosts arg_types of
Refl ->
FunPerm (appendCruCtx ctx ghosts) args (mbLift mb_gouts) (mbLift mb_ret)
(mbCombine prxs_in $
mbMap2 (\ps mb_ps_in -> fmap (RL.append ps) mb_ps_in) mb_ps ps_in)
(fmap (RL.append ctx_perms) $
mbCombine prxs_out ps_out)
-}
-- | Substitute ghost and regular arguments into a function permission to get
-- its input permissions for those arguments, where ghost arguments are given
-- both as variables and expressions to which those variables are instantiated.
-- For a 'FunPerm' of the form @(gctx). xs:ps -o xs:ps'@, return
--
-- > [gs/gctx]xs : [gexprs/gctx]ps, g1:eq(gexpr1), ..., gm:eq(gexprm)
funPermDistIns :: FunPerm ghosts args gouts ret -> RAssign Name ghosts ->
PermExprs ghosts -> RAssign Name args ->
DistPerms ((ghosts :++: args) :++: ghosts)
funPermDistIns fun_perm ghosts gexprs args =
appendDistPerms
(valuePermsToDistPerms (RL.append ghosts args) $
subst (appendSubsts (substOfExprs gexprs) (substOfVars args)) $
funPermIns fun_perm)
(eqDistPerms ghosts gexprs)
-- | Substitute ghost and regular arguments into a function permission to get
-- its input permissions for those arguments, where ghost arguments are given
-- both as variables and expressions to which those variables are instantiated.
-- For a 'FunPerm' of the form @(gctx). xs:ps -o xs:ps'@, return
--
-- > [gs/gctx]xs : [gexprs/gctx]ps'
funPermDistOuts :: FunPerm ghosts args gouts ret -> RAssign Name ghosts ->
PermExprs ghosts -> RAssign Name args ->
RAssign Name (gouts :> ret) ->
DistPerms ((ghosts :++: args) :++: gouts :> ret)
funPermDistOuts fun_perm ghosts gexprs args gouts_ret =
valuePermsToDistPerms (RL.append (RL.append ghosts args) gouts_ret) $
subst (appendSubsts
(appendSubsts (substOfExprs gexprs) (substOfVars args))
(substOfVars gouts_ret)) $
funPermOuts fun_perm
-- | Unfold a recursive permission given a 'RecPerm' for it
unfoldRecPerm :: RecPerm b reach args a -> PermExprs args -> PermOffset a ->
ValuePerm a
unfoldRecPerm rp args off =
offsetPerm off $ foldr1 ValPerm_Or $ map (subst (substOfExprs args)) $
recPermCases rp
-- | Unfold a defined permission given arguments
unfoldDefinedPerm :: DefinedPerm b args a -> PermExprs args ->
PermOffset a -> ValuePerm a
unfoldDefinedPerm dp args off =
offsetPerm off $ subst (substOfExprs args) (definedPermDef dp)
-- | Unfold a named permission as long as it is unfoldable
unfoldPerm :: NameSortCanFold ns ~ 'True => NamedPerm ns args a ->
PermExprs args -> PermOffset a -> ValuePerm a
unfoldPerm (NamedPerm_Defined dp) = unfoldDefinedPerm dp
unfoldPerm (NamedPerm_Rec rp) = unfoldRecPerm rp
-- | Generic function to get free variables
class FreeVars a where
freeVars :: a -> NameSet CrucibleType
-- | Get the free variables of an expression as an 'RAssign'
freeVarsRAssign :: FreeVars a => a -> Some (RAssign ExprVar)
freeVarsRAssign =
foldl (\(Some ns) (SomeName n) -> Some (ns :>: n)) (Some MNil) . toList . freeVars
instance FreeVars a => FreeVars (Maybe a) where
freeVars = maybe NameSet.empty freeVars
instance FreeVars a => FreeVars [a] where
freeVars = foldr (NameSet.union . freeVars) NameSet.empty
instance (FreeVars a, FreeVars b) => FreeVars (a,b) where
freeVars (a,b) = NameSet.union (freeVars a) (freeVars b)
instance FreeVars a => FreeVars (Mb ctx a) where
freeVars = NameSet.liftNameSet . fmap freeVars
instance FreeVars (PermExpr a) where
freeVars (PExpr_Var x) = NameSet.singleton x
freeVars PExpr_Unit = NameSet.empty
freeVars (PExpr_Bool _) = NameSet.empty
freeVars (PExpr_Nat _) = NameSet.empty
freeVars (PExpr_String _) = NameSet.empty
freeVars (PExpr_BV factors _) = freeVars factors
freeVars (PExpr_Struct elems) = freeVars elems
freeVars PExpr_Always = NameSet.empty
freeVars (PExpr_LLVMWord e) = freeVars e
freeVars (PExpr_LLVMOffset ptr off) =
NameSet.insert ptr (freeVars off)
freeVars (PExpr_Fun _) = NameSet.empty
freeVars PExpr_PermListNil = NameSet.empty
freeVars (PExpr_PermListCons _ e p l) =
NameSet.unions [freeVars e, freeVars p, freeVars l]
freeVars (PExpr_RWModality _) = NameSet.empty
freeVars PExpr_EmptyShape = NameSet.empty
freeVars (PExpr_NamedShape rw l nmsh args) =
NameSet.unions [freeVars rw, freeVars l, freeVars nmsh, freeVars args]
freeVars (PExpr_EqShape len b) = NameSet.union (freeVars len) (freeVars b)
freeVars (PExpr_PtrShape maybe_rw maybe_l sh) =
NameSet.unions [freeVars maybe_rw, freeVars maybe_l, freeVars sh]
freeVars (PExpr_FieldShape fld) = freeVars fld
freeVars (PExpr_ArrayShape len _ sh) =
NameSet.union (freeVars len) (freeVars sh)
freeVars (PExpr_SeqShape sh1 sh2) =
NameSet.union (freeVars sh1) (freeVars sh2)
freeVars (PExpr_OrShape sh1 sh2) =
NameSet.union (freeVars sh1) (freeVars sh2)
freeVars (PExpr_ExShape mb_sh) = NameSet.liftNameSet $ fmap freeVars mb_sh
freeVars PExpr_FalseShape = NameSet.empty
freeVars (PExpr_ValPerm p) = freeVars p
instance FreeVars (BVFactor w) where
freeVars (BVFactor _ x) = NameSet.singleton x
instance FreeVars (PermExprs as) where
freeVars PExprs_Nil = NameSet.empty
freeVars (PExprs_Cons es e) = NameSet.union (freeVars es) (freeVars e)
instance FreeVars (LLVMFieldShape w) where
freeVars (LLVMFieldShape p) = freeVars p
instance FreeVars (BVRange w) where
freeVars (BVRange off len) = NameSet.union (freeVars off) (freeVars len)
instance FreeVars (BVProp w) where
freeVars (BVProp_Eq e1 e2) = NameSet.union (freeVars e1) (freeVars e2)
freeVars (BVProp_Neq e1 e2) = NameSet.union (freeVars e1) (freeVars e2)
freeVars (BVProp_ULt e1 e2) = NameSet.union (freeVars e1) (freeVars e2)
freeVars (BVProp_ULeq e1 e2) = NameSet.union (freeVars e1) (freeVars e2)
freeVars (BVProp_ULeq_Diff e1 e2 e3) =
NameSet.unions [freeVars e1, freeVars e2, freeVars e3]
instance FreeVars (AtomicPerm tp) where
freeVars (Perm_LLVMField fp) = freeVars fp
freeVars (Perm_LLVMArray ap) = freeVars ap
freeVars (Perm_LLVMBlock bp) = freeVars bp
freeVars (Perm_LLVMFree e) = freeVars e
freeVars (Perm_LLVMFunPtr _ fun_perm) = freeVars fun_perm
freeVars Perm_IsLLVMPtr = NameSet.empty
freeVars (Perm_LLVMBlockShape sh) = freeVars sh
freeVars (Perm_LLVMFrame fperms) = freeVars $ map fst fperms
freeVars (Perm_LOwned ls ps_in ps_out) =
NameSet.unions [freeVars ls, freeVars ps_in, freeVars ps_out]
freeVars (Perm_LOwnedSimple lops) = freeVars lops
freeVars (Perm_LCurrent l) = freeVars l
freeVars Perm_LFinished = NameSet.empty
freeVars (Perm_Struct ps) = NameSet.unions $ RL.mapToList freeVars ps
freeVars (Perm_Fun fun_perm) = freeVars fun_perm
freeVars (Perm_BVProp prop) = freeVars prop
freeVars (Perm_NamedConj _ args off) =
NameSet.union (freeVars args) (freeVars off)
instance FreeVars (ValuePerm tp) where
freeVars (ValPerm_Eq e) = freeVars e
freeVars (ValPerm_Or p1 p2) = NameSet.union (freeVars p1) (freeVars p2)
freeVars (ValPerm_Exists mb_p) =
NameSet.liftNameSet $ fmap freeVars mb_p
freeVars (ValPerm_Named _ args off) =
NameSet.union (freeVars args) (freeVars off)
freeVars (ValPerm_Var x off) = NameSet.insert x $ freeVars off
freeVars (ValPerm_Conj ps) = freeVars ps
freeVars ValPerm_False = NameSet.empty
instance FreeVars (ValuePerms tps) where
freeVars ValPerms_Nil = NameSet.empty
freeVars (ValPerms_Cons ps p) = NameSet.union (freeVars ps) (freeVars p)
instance FreeVars (DistPerms tps) where
freeVars dperms =
NameSet.unions $
RL.mapToList (\(VarAndPerm x p) -> NameSet.insert x (freeVars p)) dperms
instance FreeVars (LLVMFieldPerm w sz) where
freeVars (LLVMFieldPerm {..}) =
NameSet.unions [freeVars llvmFieldRW, freeVars llvmFieldLifetime,
freeVars llvmFieldOffset, freeVars llvmFieldContents]
instance FreeVars (LLVMArrayPerm w) where
freeVars (LLVMArrayPerm {..}) =
NameSet.unions [freeVars llvmArrayRW,
freeVars llvmArrayLifetime,
freeVars llvmArrayOffset,
freeVars llvmArrayLen,
freeVars llvmArrayCellShape,
freeVars llvmArrayBorrows]
instance FreeVars (LLVMArrayIndex w) where
freeVars (LLVMArrayIndex cell _) = freeVars cell
instance FreeVars (LLVMArrayBorrow w) where
freeVars (FieldBorrow ix) = freeVars ix
freeVars (RangeBorrow rng) = freeVars rng
instance FreeVars (LLVMBlockPerm w) where
freeVars (LLVMBlockPerm rw l off len sh) =
NameSet.unions [freeVars rw, freeVars l, freeVars off,
freeVars len, freeVars sh]
instance FreeVars (PermOffset tp) where
freeVars NoPermOffset = NameSet.empty
freeVars (LLVMPermOffset e) = freeVars e
instance FreeVars (LOwnedPerm a) where
freeVars (LOwnedPermField e fp) =
NameSet.unions [freeVars e, freeVars fp]
freeVars (LOwnedPermArray e ap) =
NameSet.unions [freeVars e, freeVars ap]
freeVars (LOwnedPermBlock e bp) =
NameSet.unions [freeVars e, freeVars bp]
instance FreeVars (LOwnedPerms ps) where
freeVars = NameSet.unions . RL.mapToList freeVars
instance FreeVars (FunPerm ghosts args gouts ret) where
freeVars (FunPerm _ _ _ _ perms_in perms_out) =
NameSet.union
(NameSet.liftNameSet $ fmap freeVars perms_in)
(NameSet.liftNameSet $ fmap freeVars perms_out)
instance FreeVars (NamedShape b args w) where
freeVars (NamedShape _ _ body) = freeVars body
instance FreeVars (NamedShapeBody b args w) where
freeVars (DefinedShapeBody mb_sh) = freeVars mb_sh
freeVars (OpaqueShapeBody mb_len _) = freeVars mb_len
freeVars (RecShapeBody mb_sh _ _) = freeVars mb_sh
-- | Test if an expression @e@ is a /determining/ expression, meaning that
-- proving @x:eq(e)@ will necessarily determine the values of the free variables
-- of @e@ in the sense of 'determinedVars'.
isDeterminingExpr :: PermExpr a -> Bool
isDeterminingExpr (PExpr_Var _) = True
isDeterminingExpr (PExpr_LLVMWord e) = isDeterminingExpr e
isDeterminingExpr (PExpr_BV [BVFactor _ _] _) =
-- A linear expression N*x + M lets you solve for x when it is possible
True
isDeterminingExpr (PExpr_ValPerm (ValPerm_Eq e)) = isDeterminingExpr e
isDeterminingExpr (PExpr_LLVMOffset _ off) = isDeterminingExpr off
isDeterminingExpr e =
-- If an expression has no free variables then it vacuously determines all of
-- its free variables
NameSet.null $ freeVars e
-- FIXME: consider adding a case for y &+ e
-- | Generic function to compute the /needed/ variables of a permission, meaning
-- those whose values must be determined before that permission can be
-- proved. This includes, e.g., all the offsets and lengths of field and array
-- permissions.
class NeededVars a where
neededVars :: a -> NameSet CrucibleType
instance NeededVars a => NeededVars [a] where
neededVars as = NameSet.unions $ map neededVars as
instance NeededVars (PermExpr a) where
-- FIXME: need a better explanation of why this is the right answer...
neededVars e = if isDeterminingExpr e then NameSet.empty else freeVars e
instance NeededVars (PermExprs args) where
neededVars PExprs_Nil = NameSet.empty
neededVars (PExprs_Cons es e) = NameSet.union (neededVars es) (neededVars e)
instance NeededVars (ValuePerm a) where
neededVars (ValPerm_Eq e) = neededVars e
neededVars (ValPerm_Or p1 p2) = NameSet.union (neededVars p1) (neededVars p2)
neededVars (ValPerm_Exists mb_p) = NameSet.liftNameSet $ fmap neededVars mb_p
neededVars (ValPerm_Named name args offset)
| OpaqueSortRepr _ <- namedPermNameSort name =
NameSet.union (neededVars args) (freeVars offset)
-- FIXME: for non-opaque named permissions, we currently define the
-- @neededVars@ as all free variables of @p@, but this is incorrect for
-- defined or recursive permissions that do determine their variable arguments
-- when unfolded.
neededVars p@(ValPerm_Named _ _ _) = freeVars p
neededVars p@(ValPerm_Var _ _) = freeVars p
neededVars (ValPerm_Conj ps) = neededVars ps
neededVars ValPerm_False = NameSet.empty
instance NeededVars (AtomicPerm a) where
neededVars (Perm_LLVMField fp) = neededVars fp
neededVars (Perm_LLVMArray ap) = neededVars ap
neededVars (Perm_LLVMBlock bp) = neededVars bp
neededVars (Perm_LLVMBlockShape _) = NameSet.empty
neededVars p@(Perm_LOwned _ _ _) = freeVars p
neededVars (Perm_LOwnedSimple lops) = neededVars $ RL.map lownedPermPerm lops
neededVars p = freeVars p
instance NeededVars (LLVMFieldPerm w sz) where
neededVars (LLVMFieldPerm {..}) =
NameSet.unions [freeVars llvmFieldOffset, neededVars llvmFieldRW,
neededVars llvmFieldLifetime, neededVars llvmFieldContents]
instance NeededVars (LLVMArrayPerm w) where
neededVars (LLVMArrayPerm {..}) =
NameSet.unions [neededVars llvmArrayRW, neededVars llvmArrayLifetime,
freeVars llvmArrayOffset, freeVars llvmArrayLen,
freeVars llvmArrayBorrows, neededVars llvmArrayCellShape]
instance NeededVars (LLVMBlockPerm w) where
neededVars (LLVMBlockPerm {..}) =
NameSet.unions [neededVars llvmBlockRW, neededVars llvmBlockLifetime,
freeVars llvmBlockOffset, freeVars llvmBlockLen]
instance NeededVars (ValuePerms as) where
neededVars =
foldValuePerms (\vars p ->
NameSet.union vars (neededVars p)) NameSet.empty
instance NeededVars (DistPerms as) where
neededVars =
foldDistPerms (\vars _ p ->
NameSet.union vars (neededVars p)) NameSet.empty
-- | Change all pointer shapes that are associated with the current lifetime of
-- that shape (i.e., that are not inside a pointer shape with an explicit
-- lifetime) to 'PExpr_Read'.
readOnlyShape :: PermExpr (LLVMShapeType w) -> PermExpr (LLVMShapeType w)
readOnlyShape e@(PExpr_Var _) = e
readOnlyShape PExpr_EmptyShape = PExpr_EmptyShape
readOnlyShape (PExpr_NamedShape _ l nmsh args) =
PExpr_NamedShape (Just PExpr_Read) l nmsh args
readOnlyShape e@(PExpr_EqShape _ _) = e
readOnlyShape e@(PExpr_PtrShape _ (Just _) _) = e
readOnlyShape (PExpr_PtrShape _ Nothing sh) =
PExpr_PtrShape (Just PExpr_Read) Nothing $ readOnlyShape sh
readOnlyShape e@(PExpr_FieldShape _) = e
readOnlyShape (PExpr_ArrayShape len stride sh) =
PExpr_ArrayShape len stride $ readOnlyShape sh
readOnlyShape (PExpr_SeqShape sh1 sh2) =
PExpr_SeqShape (readOnlyShape sh1) (readOnlyShape sh2)
readOnlyShape (PExpr_OrShape sh1 sh2) =
PExpr_OrShape (readOnlyShape sh1) (readOnlyShape sh2)
readOnlyShape (PExpr_ExShape mb_sh) =
PExpr_ExShape $ fmap readOnlyShape mb_sh
readOnlyShape PExpr_FalseShape = PExpr_FalseShape
----------------------------------------------------------------------
-- * Generalized Substitution
----------------------------------------------------------------------
-- FIXME: these two EFQ proofs may no longer be needed...?
noTypesInExprCtx :: forall (ctx :: RList CrucibleType) (a :: Type) b.
Member ctx a -> b
noTypesInExprCtx (Member_Step ctx) = noTypesInExprCtx ctx
noExprsInTypeCtx :: forall (ctx :: RList Type) (a :: CrucibleType) b.
Member ctx a -> b
noExprsInTypeCtx (Member_Step ctx) = noExprsInTypeCtx ctx
-- No case for Member_Base
-- | Defines a substitution type @s@ that supports substituting into expression
-- and permission variables in a given monad @m@
class MonadBind m => SubstVar s m | s -> m where
extSubst :: s ctx -> ExprVar a -> s (ctx :> a)
substExprVar :: s ctx -> Mb ctx (ExprVar a) -> m (PermExpr a)
substPermVar :: SubstVar s m => s ctx -> Mb ctx (PermVar a) -> m (ValuePerm a)
substPermVar s mb_x =
substExprVar s mb_x >>= \e ->
case e of
PExpr_Var x -> return $ ValPerm_Var x NoPermOffset
PExpr_ValPerm p -> return p
-- | Extend a substitution with 0 or more variables
extSubstMulti :: SubstVar s m => s ctx -> RAssign ExprVar ctx' ->
s (ctx :++: ctx')
extSubstMulti s MNil = s
extSubstMulti s (xs :>: x) = extSubst (extSubstMulti s xs) x
-- | Generalized notion of substitution, which says that substitution type @s@
-- supports substituting into type @a@ in monad @m@
--
-- FIXME: the 'Mb' argument should really be a 'MatchedMb', to emphasize that we
-- expect it to be in fresh pair form
class SubstVar s m => Substable s a m where
genSubst :: s ctx -> Mb ctx a -> m a
-- | A version of 'Substable' for type functors
class SubstVar s m => Substable1 s f m where
genSubst1 :: s ctx -> Mb ctx (f a) -> m (f a)
instance SubstVar s m => Substable s Integer m where
genSubst _ mb_i = return $ mbLift mb_i
instance (NuMatching a, Substable s a m) => Substable s [a] m where
genSubst s as = mapM (genSubst s) (mbList as)
instance (NuMatching a, Substable s a m) => Substable s (NonEmpty a) m where
genSubst s (mbMatch -> [nuMP| x :| xs |]) =
(:|) <$> genSubst s x <*> genSubst s xs
instance (NuMatching a, NuMatching b,
Substable s a m, Substable s b m) => Substable s (a,b) m where
genSubst s [nuP| (a,b) |] = (,) <$> genSubst s a <*> genSubst s b
instance (NuMatching a, NuMatching b, NuMatching c, Substable s a m,
Substable s b m, Substable s c m) => Substable s (a,b,c) m where
genSubst s [nuP| (a,b,c) |] =
(,,) <$> genSubst s a <*> genSubst s b <*> genSubst s c
instance (NuMatching a, NuMatching b, NuMatching c, NuMatching d,
Substable s a m, Substable s b m,
Substable s c m, Substable s d m) => Substable s (a,b,c,d) m where
genSubst s [nuP| (a,b,c,d) |] =
(,,,) <$> genSubst s a <*> genSubst s b <*> genSubst s c <*> genSubst s d
instance (NuMatching a, Substable s a m) => Substable s (Maybe a) m where
genSubst s mb_x = case mbMatch mb_x of
[nuMP| Just a |] -> Just <$> genSubst s a
[nuMP| Nothing |] -> return Nothing
instance {-# INCOHERENT #-} (Given (RAssign Proxy (ctx :: RList CrucibleType)),
Substable s a m, NuMatching a) =>
Substable s (Mb ctx a) m where
genSubst = genSubstMb given
instance {-# INCOHERENT #-}
(Substable s a m, NuMatching a) =>
Substable s (Mb (RNil :: RList CrucibleType) a) m where
genSubst = genSubstMb RL.typeCtxProxies
instance {-# INCOHERENT #-} (Substable s a m, NuMatching a) =>
Substable s (Binding (c :: CrucibleType) a) m where
genSubst = genSubstMb RL.typeCtxProxies
genSubstMb ::
Substable s a m =>
NuMatching a =>
RAssign Proxy (ctx :: RList CrucibleType) ->
s ctx' -> Mb ctx' (Mb ctx a) -> m (Mb ctx a)
genSubstMb p s mbmb =
mbM $ nuMulti p $ \ns -> genSubst (extSubstMulti s ns) (mbCombine p mbmb)
instance SubstVar s m => Substable s (Member ctx a) m where
genSubst _ mb_memb = return $ mbLift mb_memb
instance (NuMatchingAny1 f, Substable1 s f m) =>
Substable s (RAssign f ctx) m where
genSubst s mb_xs = case mbMatch mb_xs of
[nuMP| MNil |] -> return MNil
[nuMP| xs :>: x |] -> (:>:) <$> genSubst s xs <*> genSubst1 s x
instance (NuMatchingAny1 f, Substable1 s f m) =>
Substable s (Assignment f ctx) m where
genSubst s mb_assign =
case mbMatch $ fmap viewAssign mb_assign of
[nuMP| AssignEmpty |] -> return $ Ctx.empty
[nuMP| AssignExtend asgn' x |] ->
Ctx.extend <$> genSubst s asgn' <*> genSubst1 s x
instance SubstVar s m => Substable s (a :~: b) m where
genSubst _ = return . mbLift
instance SubstVar s m => Substable1 s ((:~:) a) m where
genSubst1 _ = return . mbLift
-- | Helper function to substitute into 'BVFactor's
substBVFactor :: SubstVar s m => s ctx -> Mb ctx (BVFactor w) ->
m (PermExpr (BVType w))
substBVFactor s (mbMatch -> [nuMP| BVFactor (BV.BV i) x |]) =
bvMult (mbLift i) <$> substExprVar s x
instance SubstVar s m =>
Substable s (NatRepr n) m where
genSubst _ = return . mbLift
instance SubstVar PermVarSubst m =>
Substable PermVarSubst (ExprVar a) m where
genSubst s mb_x = return $ varSubstVar s mb_x
instance SubstVar PermVarSubst m => Substable1 PermVarSubst ExprVar m where
genSubst1 = genSubst
instance SubstVar s m => Substable s (PermExpr a) m where
genSubst s mb_expr = case mbMatch mb_expr of
[nuMP| PExpr_Var x |] -> substExprVar s x
[nuMP| PExpr_Unit |] -> return $ PExpr_Unit
[nuMP| PExpr_Bool b |] -> return $ PExpr_Bool $ mbLift b
[nuMP| PExpr_Nat n |] -> return $ PExpr_Nat $ mbLift n
[nuMP| PExpr_String str |] -> return $ PExpr_String $ mbLift str
[nuMP| PExpr_BV factors off |] ->
foldr bvAdd (PExpr_BV [] (mbLift off)) <$>
mapM (substBVFactor s) (mbList factors)
[nuMP| PExpr_Struct args |] ->
PExpr_Struct <$> genSubst s args
[nuMP| PExpr_Always |] -> return PExpr_Always
[nuMP| PExpr_LLVMWord e |] ->
PExpr_LLVMWord <$> genSubst s e
[nuMP| PExpr_LLVMOffset x off |] ->
addLLVMOffset <$> substExprVar s x <*> genSubst s off
[nuMP| PExpr_Fun fh |] ->
return $ PExpr_Fun $ mbLift fh
[nuMP| PExpr_PermListNil |] ->
return $ PExpr_PermListNil
[nuMP| PExpr_PermListCons tp e p l |] ->
PExpr_PermListCons (mbLift tp) <$> genSubst s e <*> genSubst s p
<*> genSubst s l
[nuMP| PExpr_RWModality rw |] ->
return $ PExpr_RWModality $ mbLift rw
[nuMP| PExpr_EmptyShape |] -> return PExpr_EmptyShape
[nuMP| PExpr_NamedShape rw l nmsh args |] ->
PExpr_NamedShape <$> genSubst s rw <*> genSubst s l <*> genSubst s nmsh
<*> genSubst s args
[nuMP| PExpr_EqShape len b |] ->
PExpr_EqShape <$> genSubst s len <*> genSubst s b
[nuMP| PExpr_PtrShape maybe_rw maybe_l sh |] ->
PExpr_PtrShape <$> genSubst s maybe_rw <*> genSubst s maybe_l
<*> genSubst s sh
[nuMP| PExpr_FieldShape sh |] ->
PExpr_FieldShape <$> genSubst s sh
[nuMP| PExpr_ArrayShape len stride sh |] ->
PExpr_ArrayShape <$> genSubst s len <*> return (mbLift stride)
<*> genSubst s sh
[nuMP| PExpr_SeqShape sh1 sh2 |] ->
PExpr_SeqShape <$> genSubst s sh1 <*> genSubst s sh2
[nuMP| PExpr_OrShape sh1 sh2 |] ->
PExpr_OrShape <$> genSubst s sh1 <*> genSubst s sh2
[nuMP| PExpr_ExShape mb_sh |] ->
PExpr_ExShape <$> genSubstMb RL.typeCtxProxies s mb_sh
[nuMP| PExpr_FalseShape |] -> return PExpr_FalseShape
[nuMP| PExpr_ValPerm p |] ->
PExpr_ValPerm <$> genSubst s p
instance SubstVar s m => Substable1 s PermExpr m where
genSubst1 = genSubst
instance SubstVar s m => Substable s (BVRange w) m where
genSubst s (mbMatch -> [nuMP| BVRange e1 e2 |]) =
BVRange <$> genSubst s e1 <*> genSubst s e2
instance SubstVar s m => Substable s (BVProp w) m where
genSubst s mb_prop = case mbMatch mb_prop of
[nuMP| BVProp_Eq e1 e2 |] ->
BVProp_Eq <$> genSubst s e1 <*> genSubst s e2
[nuMP| BVProp_Neq e1 e2 |] ->
BVProp_Neq <$> genSubst s e1 <*> genSubst s e2
[nuMP| BVProp_ULt e1 e2 |] ->
BVProp_ULt <$> genSubst s e1 <*> genSubst s e2
[nuMP| BVProp_ULeq e1 e2 |] ->
BVProp_ULeq <$> genSubst s e1 <*> genSubst s e2
[nuMP| BVProp_ULeq_Diff e1 e2 e3 |] ->
BVProp_ULeq_Diff <$> genSubst s e1 <*> genSubst s e2 <*> genSubst s e3
instance SubstVar s m => Substable s (AtomicPerm a) m where
genSubst s mb_p = case mbMatch mb_p of
[nuMP| Perm_LLVMField fp |] -> Perm_LLVMField <$> genSubst s fp
[nuMP| Perm_LLVMArray ap |] -> Perm_LLVMArray <$> genSubst s ap
[nuMP| Perm_LLVMBlock bp |] -> Perm_LLVMBlock <$> genSubst s bp
[nuMP| Perm_LLVMFree e |] -> Perm_LLVMFree <$> genSubst s e
[nuMP| Perm_LLVMFunPtr tp p |] ->
Perm_LLVMFunPtr (mbLift tp) <$> genSubst s p
[nuMP| Perm_IsLLVMPtr |] -> return Perm_IsLLVMPtr
[nuMP| Perm_LLVMBlockShape sh |] ->
Perm_LLVMBlockShape <$> genSubst s sh
[nuMP| Perm_LLVMFrame fp |] -> Perm_LLVMFrame <$> genSubst s fp
[nuMP| Perm_LOwned ls ps_in ps_out |] ->
Perm_LOwned <$> genSubst s ls <*> genSubst s ps_in <*> genSubst s ps_out
[nuMP| Perm_LOwnedSimple lops |] -> Perm_LOwnedSimple <$> genSubst s lops
[nuMP| Perm_LCurrent e |] -> Perm_LCurrent <$> genSubst s e
[nuMP| Perm_LFinished |] -> return Perm_LFinished
[nuMP| Perm_Struct tps |] -> Perm_Struct <$> genSubst s tps
[nuMP| Perm_Fun fperm |] -> Perm_Fun <$> genSubst s fperm
[nuMP| Perm_BVProp prop |] -> Perm_BVProp <$> genSubst s prop
[nuMP| Perm_NamedConj n args off |] ->
Perm_NamedConj (mbLift n) <$> genSubst s args <*> genSubst s off
instance SubstVar s m => Substable s (NamedShape b args w) m where
genSubst s (mbMatch -> [nuMP| NamedShape str args body |]) =
NamedShape (mbLift str) (mbLift args) <$> genSubstNSB (cruCtxProxies (mbLift args)) s body
genSubstNSB ::
SubstVar s m =>
RAssign Proxy args ->
s ctx -> Mb ctx (NamedShapeBody b args w) -> m (NamedShapeBody b args w)
genSubstNSB px s mb_body = case mbMatch mb_body of
[nuMP| DefinedShapeBody mb_sh |] ->
DefinedShapeBody <$> genSubstMb px s mb_sh
[nuMP| OpaqueShapeBody mb_len trans_id |] ->
OpaqueShapeBody <$> genSubstMb px s mb_len <*> return (mbLift trans_id)
[nuMP| RecShapeBody mb_sh trans_id fold_ids |] ->
RecShapeBody <$> genSubstMb (px :>: Proxy) s mb_sh
<*> return (mbLift trans_id)
<*> return (mbLift fold_ids)
instance SubstVar s m => Substable s (NamedPermName ns args a) m where
genSubst _ mb_rpn = return $ mbLift mb_rpn
instance SubstVar s m => Substable s (PermOffset a) m where
genSubst s mb_off = case mbMatch mb_off of
[nuMP| NoPermOffset |] -> return NoPermOffset
[nuMP| LLVMPermOffset e |] -> mkLLVMPermOffset <$> genSubst s e
instance SubstVar s m => Substable s (NamedPerm ns args a) m where
genSubst s mb_np = case mbMatch mb_np of
[nuMP| NamedPerm_Opaque p |] -> NamedPerm_Opaque <$> genSubst s p
[nuMP| NamedPerm_Rec p |] -> NamedPerm_Rec <$> genSubst s p
[nuMP| NamedPerm_Defined p |] -> NamedPerm_Defined <$> genSubst s p
instance SubstVar s m => Substable s (OpaquePerm ns args a) m where
genSubst _ (mbMatch -> [nuMP| OpaquePerm n i |]) =
return $ OpaquePerm (mbLift n) (mbLift i)
instance SubstVar s m => Substable s (RecPerm ns reach args a) m where
genSubst s (mbMatch -> [nuMP| RecPerm rpn dt_i f_i u_i reachMeths cases |]) =
RecPerm (mbLift rpn) (mbLift dt_i) (mbLift f_i) (mbLift u_i)
(mbLift reachMeths) <$> mapM (genSubstMb (cruCtxProxies (mbLift (fmap namedPermNameArgs rpn))) s) (mbList cases)
instance SubstVar s m => Substable s (DefinedPerm ns args a) m where
genSubst s (mbMatch -> [nuMP| DefinedPerm n p |]) =
DefinedPerm (mbLift n) <$> genSubstMb (cruCtxProxies (mbLift (fmap namedPermNameArgs n))) s p
instance SubstVar s m => Substable s (ValuePerm a) m where
genSubst s mb_p = case mbMatch mb_p of
[nuMP| ValPerm_Eq e |] -> ValPerm_Eq <$> genSubst s e
[nuMP| ValPerm_Or p1 p2 |] ->
ValPerm_Or <$> genSubst s p1 <*> genSubst s p2
[nuMP| ValPerm_Exists p |] ->
-- FIXME: maybe we don't need extSubst at all, but can just use the
-- Substable instance for Mb ctx a from above
ValPerm_Exists <$> genSubstMb RL.typeCtxProxies s p
-- nuM (\x -> genSubst (extSubst s x) $ mbCombine p)
[nuMP| ValPerm_Named n args off |] ->
ValPerm_Named (mbLift n) <$> genSubst s args <*> genSubst s off
[nuMP| ValPerm_Var mb_x mb_off |] ->
offsetPerm <$> genSubst s mb_off <*> substPermVar s mb_x
[nuMP| ValPerm_Conj aps |] ->
ValPerm_Conj <$> mapM (genSubst s) (mbList aps)
[nuMP| ValPerm_False |] ->
pure ValPerm_False
instance SubstVar s m => Substable1 s ValuePerm m where
genSubst1 = genSubst
{-
instance SubstVar s m => Substable s (ValuePerms as) m where
genSubst s mb_ps = case mbMatch mb_ps of
[nuMP| ValPerms_Nil |] -> return ValPerms_Nil
[nuMP| ValPerms_Cons ps p |] ->
ValPerms_Cons <$> genSubst s ps <*> genSubst s p
-}
instance SubstVar s m => Substable s RWModality m where
genSubst _ mb_rw = case mbMatch mb_rw of
[nuMP| Write |] -> return Write
[nuMP| Read |] -> return Read
instance SubstVar s m => Substable s (LLVMFieldPerm w sz) m where
genSubst s (mbMatch -> [nuMP| LLVMFieldPerm rw ls off p |]) =
LLVMFieldPerm <$> genSubst s rw <*> genSubst s ls <*>
genSubst s off <*> genSubst s p
instance SubstVar s m => Substable s (LLVMArrayPerm w) m where
genSubst s (mbMatch -> [nuMP| LLVMArrayPerm rw l off len stride sh bs |]) =
LLVMArrayPerm <$> genSubst s rw <*> genSubst s l <*> genSubst s off
<*> genSubst s len <*> return (mbLift stride) <*> genSubst s sh
<*> genSubst s bs
instance SubstVar s m => Substable s (LLVMArrayIndex w) m where
genSubst s (mbMatch -> [nuMP| LLVMArrayIndex ix off |]) =
LLVMArrayIndex <$> genSubst s ix <*> return (mbLift off)
instance SubstVar s m => Substable s (LLVMArrayBorrow w) m where
genSubst s mb_borrow = case mbMatch mb_borrow of
[nuMP| FieldBorrow ix |] -> FieldBorrow <$> genSubst s ix
[nuMP| RangeBorrow r |] -> RangeBorrow <$> genSubst s r
instance SubstVar s m => Substable s (LLVMBlockPerm w) m where
genSubst s (mbMatch -> [nuMP| LLVMBlockPerm rw l off len sh |]) =
LLVMBlockPerm <$> genSubst s rw <*> genSubst s l <*> genSubst s off
<*> genSubst s len <*> genSubst s sh
instance SubstVar s m => Substable s (LLVMFieldShape w) m where
genSubst s (mbMatch -> [nuMP| LLVMFieldShape p |]) =
LLVMFieldShape <$> genSubst s p
instance SubstVar s m => Substable s (LOwnedPerm a) m where
genSubst s mb_x = case mbMatch mb_x of
[nuMP| LOwnedPermField e fp |] ->
LOwnedPermField <$> genSubst s e <*> genSubst s fp
[nuMP| LOwnedPermArray e ap |] ->
LOwnedPermArray <$> genSubst s e <*> genSubst s ap
[nuMP| LOwnedPermBlock e bp |] ->
LOwnedPermBlock <$> genSubst s e <*> genSubst s bp
instance SubstVar s m => Substable1 s LOwnedPerm m where
genSubst1 = genSubst
instance SubstVar s m => Substable s (FunPerm ghosts args gouts ret) m where
genSubst s (mbMatch ->
[nuMP| FunPerm mb_ghosts mb_args mb_gouts
mb_ret perms_in perms_out |]) =
let ghosts = mbLift mb_ghosts
args = mbLift mb_args
gouts = mbLift mb_gouts
ret = mbLift mb_ret
ghosts_args_prxs =
RL.append (cruCtxProxies ghosts) (cruCtxProxies args)
ghosts_args_gouts_ret_prxs =
RL.append ghosts_args_prxs (cruCtxProxies gouts) :>: Proxy in
FunPerm ghosts args gouts ret
<$> genSubstMb ghosts_args_prxs s perms_in
<*> genSubstMb ghosts_args_gouts_ret_prxs s perms_out
instance SubstVar PermVarSubst m =>
Substable PermVarSubst (LifetimeCurrentPerms ps) m where
genSubst s mb_x = case mbMatch mb_x of
[nuMP| AlwaysCurrentPerms |] -> return AlwaysCurrentPerms
[nuMP| LOwnedCurrentPerms l ls ps_in ps_out |] ->
LOwnedCurrentPerms <$> genSubst s l <*> genSubst s ls
<*> genSubst s ps_in <*> genSubst s ps_out
[nuMP| LOwnedSimpleCurrentPerms l ps |] ->
LOwnedSimpleCurrentPerms <$> genSubst s l <*> genSubst s ps
[nuMP| CurrentTransPerms ps l |] ->
CurrentTransPerms <$> genSubst s ps <*> genSubst s l
instance SubstVar PermVarSubst m =>
Substable PermVarSubst (VarAndPerm a) m where
genSubst s (mbMatch -> [nuMP| VarAndPerm x p |]) =
VarAndPerm <$> genSubst s x <*> genSubst s p
instance SubstVar PermVarSubst m => Substable1 PermVarSubst VarAndPerm m where
genSubst1 = genSubst
instance Substable1 s f m => Substable1 s (Typed f) m where
genSubst1 s mb_typed =
Typed (mbLift $ fmap typedType mb_typed) <$>
genSubst1 s (fmap typedObj mb_typed)
{-
instance SubstVar PermVarSubst m =>
Substable PermVarSubst (DistPerms ps) m where
genSubst s mb_dperms = case mbMatch mb_dperms of
[nuMP| DistPermsNil |] -> return DistPermsNil
[nuMP| DistPermsCons dperms' x p |] ->
DistPermsCons <$> genSubst s dperms' <*>
return (varSubstVar s x) <*> genSubst s p
-}
instance SubstVar s m => Substable s (LifetimeFunctor args a) m where
genSubst s mb_x = case mbMatch mb_x of
[nuMP| LTFunctorField off p |] ->
LTFunctorField <$> genSubst s off <*> genSubst s p
[nuMP| LTFunctorArray off len stride sh bs |] ->
LTFunctorArray <$> genSubst s off <*> genSubst s len <*>
return (mbLift stride) <*> genSubst s sh <*> genSubst s bs
[nuMP| LTFunctorBlock off len sh |] ->
LTFunctorBlock <$> genSubst s off <*> genSubst s len <*> genSubst s sh
----------------------------------------------------------------------
-- * Expression Substitutions
----------------------------------------------------------------------
-- | A substitution assigns a permission expression to each bound name in a
-- name-binding context
newtype PermSubst ctx =
PermSubst { unPermSubst :: RAssign PermExpr ctx }
emptySubst :: PermSubst RNil
emptySubst = PermSubst RL.empty
consSubst :: PermSubst ctx -> PermExpr a -> PermSubst (ctx :> a)
consSubst (PermSubst elems) e = PermSubst (elems :>: e)
singletonSubst :: PermExpr a -> PermSubst (RNil :> a)
singletonSubst e = PermSubst (RL.empty :>: e)
appendSubsts :: PermSubst ctx1 -> PermSubst ctx2 -> PermSubst (ctx1 :++: ctx2)
appendSubsts (PermSubst es1) (PermSubst es2) = PermSubst $ RL.append es1 es2
substOfVars :: RAssign ExprVar ctx -> PermSubst ctx
substOfVars = PermSubst . RL.map PExpr_Var
substOfExprs :: PermExprs ctx -> PermSubst ctx
substOfExprs = PermSubst
-- FIXME: Maybe PermSubst should just be PermExprs?
exprsOfSubst :: PermSubst ctx -> PermExprs ctx
exprsOfSubst = unPermSubst
substLookup :: PermSubst ctx -> Member ctx a -> PermExpr a
substLookup (PermSubst m) memb = RL.get memb m
noPermsInCruCtx :: forall (ctx :: RList CrucibleType) (a :: CrucibleType) b.
Member ctx (ValuePerm a) -> b
noPermsInCruCtx (Member_Step ctx) = noPermsInCruCtx ctx
-- No case for Member_Base
instance SubstVar PermSubst Identity where
extSubst (PermSubst elems) x = PermSubst $ elems :>: PExpr_Var x
substExprVar s x =
case mbNameBoundP x of
Left memb -> return $ substLookup s memb
Right y -> return $ PExpr_Var y
{-
substPermVar s mb_x =
case mbNameBoundP mb_x of
Left memb -> noTypesInExprCtx memb
Right x -> return $ ValPerm_Var x -}
-- | Apply a substitution to an object
subst :: Substable PermSubst a Identity => PermSubst ctx -> Mb ctx a -> a
subst s mb = runIdentity $ genSubst s mb
-- | Substitute a single expression into an object
subst1 :: Substable PermSubst a Identity => PermExpr b -> Binding b a -> a
subst1 e = subst (singletonSubst e)
----------------------------------------------------------------------
-- * Variable Substitutions
----------------------------------------------------------------------
-- FIXME HERE: PermVarSubst and other types should just be instances of a
-- RAssign, except it is annoying to build NuMatching instances for RAssign
-- because there are different ways one might do it, so we need to use
-- OVERLAPPING and/or INCOHERENT pragmas for them
emptyVarSubst :: PermVarSubst RNil
emptyVarSubst = PermVarSubst_Nil
singletonVarSubst :: ExprVar a -> PermVarSubst (RNil :> a)
singletonVarSubst x = PermVarSubst_Cons emptyVarSubst x
consVarSubst :: PermVarSubst ctx -> ExprVar a -> PermVarSubst (ctx :> a)
consVarSubst = PermVarSubst_Cons
permVarSubstOfNames :: RAssign Name ctx -> PermVarSubst ctx
permVarSubstOfNames MNil = PermVarSubst_Nil
permVarSubstOfNames (ns :>: n) = PermVarSubst_Cons (permVarSubstOfNames ns) n
permVarSubstToNames :: PermVarSubst ctx -> RAssign Name ctx
permVarSubstToNames PermVarSubst_Nil = MNil
permVarSubstToNames (PermVarSubst_Cons s n) = permVarSubstToNames s :>: n
varSubstLookup :: PermVarSubst ctx -> Member ctx a -> ExprVar a
varSubstLookup (PermVarSubst_Cons _ x) Member_Base = x
varSubstLookup (PermVarSubst_Cons s _) (Member_Step memb) =
varSubstLookup s memb
appendVarSubsts :: PermVarSubst ctx1 -> PermVarSubst ctx2 ->
PermVarSubst (ctx1 :++: ctx2)
appendVarSubsts es1 PermVarSubst_Nil = es1
appendVarSubsts es1 (PermVarSubst_Cons es2 x) =
PermVarSubst_Cons (appendVarSubsts es1 es2) x
-- | Convert a 'PermVarSubst' to a 'PermSubst'
permVarSubstToSubst :: PermVarSubst ctx -> PermSubst ctx
permVarSubstToSubst s = PermSubst $ RL.map PExpr_Var $ permVarSubstToNames s
varSubstVar :: PermVarSubst ctx -> Mb ctx (ExprVar a) -> ExprVar a
varSubstVar s mb_x =
case mbNameBoundP mb_x of
Left memb -> varSubstLookup s memb
Right x -> x
instance SubstVar PermVarSubst Identity where
extSubst s x = PermVarSubst_Cons s x
substExprVar s x =
case mbNameBoundP x of
Left memb -> return $ PExpr_Var $ varSubstLookup s memb
Right y -> return $ PExpr_Var y
{-
substPermVar s mb_x =
case mbNameBoundP mb_x of
Left memb -> noTypesInExprCtx memb
Right x -> return $ ValPerm_Var x -}
-- | Wrapper function to apply a renamionmg to an expression type
varSubst :: Substable PermVarSubst a Identity => PermVarSubst ctx ->
Mb ctx a -> a
varSubst s mb = runIdentity $ genSubst s mb
-- | Build a list of all possible 'PermVarSubst's of variables in a 'NameMap'
-- for variables listed in a 'CruCtx'
allPermVarSubsts :: NameMap TypeRepr -> CruCtx ctx -> [PermVarSubst ctx]
allPermVarSubsts nmap = helper (NameMap.assocs nmap) where
helper :: [NameAndElem TypeRepr] -> CruCtx ctx -> [PermVarSubst ctx]
helper _ CruCtxNil = return emptyVarSubst
helper ns_ts (CruCtxCons ctx tp) =
helper ns_ts ctx >>= \sbst ->
map (consVarSubst sbst) (getVarsOfType ns_ts tp)
getVarsOfType :: [NameAndElem TypeRepr] -> TypeRepr tp -> [Name tp]
getVarsOfType [] _ = []
getVarsOfType (NameAndElem n tp':ns_ts) tp
| Just Refl <- testEquality tp tp' = n : (getVarsOfType ns_ts tp)
getVarsOfType (_:ns_ts) tp = getVarsOfType ns_ts tp
----------------------------------------------------------------------
-- * Partial Substitutions
----------------------------------------------------------------------
-- | An element of a partial substitution = maybe an expression
newtype PSubstElem a = PSubstElem { unPSubstElem :: Maybe (PermExpr a) }
-- | Partial substitutions assign expressions to some of the bound names in a
-- context
newtype PartialSubst ctx =
PartialSubst { unPartialSubst :: RAssign PSubstElem ctx }
-- | Build an empty partial substitution for a given set of variables, i.e., the
-- partial substitution that assigns no expressions to those variables
emptyPSubst :: CruCtx ctx -> PartialSubst ctx
emptyPSubst = PartialSubst . helper where
helper :: CruCtx ctx -> RAssign PSubstElem ctx
helper CruCtxNil = MNil
helper (CruCtxCons ctx' _) = helper ctx' :>: PSubstElem Nothing
-- | Return the set of variables that have been assigned values by a partial
-- substitution inside a binding for all of its variables
psubstMbDom :: PartialSubst ctx -> Mb ctx (NameSet CrucibleType)
psubstMbDom (PartialSubst elems) =
nuMulti (RL.map (\_-> Proxy) elems) $ \ns ->
NameSet.fromList $ catMaybes $ RL.toList $
RL.map2 (\n (PSubstElem maybe_e) ->
if isJust maybe_e
then Constant (Just $ SomeName n)
else Constant Nothing) ns elems
-- | Return the set of variables that have not been assigned values by a partial
-- substitution inside a binding for all of its variables
psubstMbUnsetVars :: PartialSubst ctx -> Mb ctx (NameSet CrucibleType)
psubstMbUnsetVars (PartialSubst elems) =
nuMulti (RL.map (\_ -> Proxy) elems) $ \ns ->
NameSet.fromList $ catMaybes $ RL.toList $
RL.map2 (\n (PSubstElem maybe_e) ->
if maybe_e == Nothing
then Constant (Just $ SomeName n)
else Constant Nothing) ns elems
-- | Return a list of 'Bool's indicating which of the bound names in context
-- @ctx@ are unset in the given partial substitution
psubstUnsetVarsBool :: PartialSubst ctx -> [Bool]
psubstUnsetVarsBool (PartialSubst elems) =
RL.mapToList (\(PSubstElem maybe_e) -> isNothing maybe_e) elems
-- | Set the expression associated with a variable in a partial substitution. It
-- is an error if it is already set.
psubstSet :: Member ctx a -> PermExpr a -> PartialSubst ctx ->
PartialSubst ctx
psubstSet memb e (PartialSubst elems) =
PartialSubst $
RL.modify memb
(\pse -> case pse of
PSubstElem Nothing -> PSubstElem $ Just e
PSubstElem (Just _) -> error "psubstSet: value already set for variable")
elems
-- | Extend a partial substitution with an unassigned variable
extPSubst :: PartialSubst ctx -> PartialSubst (ctx :> a)
extPSubst (PartialSubst elems) = PartialSubst $ elems :>: PSubstElem Nothing
-- | Shorten a partial substitution
unextPSubst :: PartialSubst (ctx :> a) -> PartialSubst ctx
unextPSubst (PartialSubst (elems :>: _)) = PartialSubst elems
-- | Complete a partial substitution into a total substitution, filling in zero
-- values using 'zeroOfType' if necessary
completePSubst :: CruCtx vars -> PartialSubst vars -> PermSubst vars
completePSubst ctx (PartialSubst pselems) = PermSubst $ helper ctx pselems where
helper :: CruCtx vars -> RAssign PSubstElem vars -> RAssign PermExpr vars
helper _ MNil = MNil
helper (CruCtxCons ctx' tp) (pselems' :>: pse) =
helper ctx' pselems' :>:
(fromMaybe (zeroOfType tp) (unPSubstElem pse))
-- | Look up an optional expression in a partial substitution
psubstLookup :: PartialSubst ctx -> Member ctx a -> Maybe (PermExpr a)
psubstLookup (PartialSubst m) memb = unPSubstElem $ RL.get memb m
-- | Append two partial substitutions
psubstAppend :: PartialSubst ctx1 -> PartialSubst ctx2 ->
PartialSubst (ctx1 :++: ctx2)
psubstAppend (PartialSubst elems1) (PartialSubst elems2) =
PartialSubst $ RL.append elems1 elems2
instance SubstVar PartialSubst Maybe where
extSubst (PartialSubst elems) x =
PartialSubst $ elems :>: PSubstElem (Just $ PExpr_Var x)
substExprVar s x =
case mbNameBoundP x of
Left memb -> psubstLookup s memb
Right y -> return $ PExpr_Var y
{-
substPermVar s mb_x =
case mbNameBoundP mb_x of
Left memb -> noTypesInExprCtx memb
Right x -> return $ ValPerm_Var x -}
-- | Wrapper function to apply a partial substitution to an expression type
partialSubst :: Substable PartialSubst a Maybe => PartialSubst ctx ->
Mb ctx a -> Maybe a
partialSubst = genSubst
-- | Apply a partial substitution, raising an error (with the given string) if
-- this fails
partialSubstForce :: Substable PartialSubst a Maybe => PartialSubst ctx ->
Mb ctx a -> String -> a
partialSubstForce s mb msg = fromMaybe (error msg) $ partialSubst s mb
----------------------------------------------------------------------
-- * Additional functions involving partial substitutions
----------------------------------------------------------------------
-- | If there is exactly one 'BVFactor' in a list of 'BVFactor's which is
-- an unset variable, return the value of its 'BV', the witness that it
-- is bound, and the result of adding together the remaining factors
getUnsetBVFactor :: (1 <= w, KnownNat w) => PartialSubst vars ->
Mb vars [BVFactor w] ->
Maybe (Integer, Member vars (BVType w), PermExpr (BVType w))
getUnsetBVFactor psubst (mbList -> mb_factors) =
case partitionEithers $ mbFactorNameBoundP psubst <$> mb_factors of
([(n, memb)], xs) -> Just (n, memb, foldl' bvAdd (bvInt 0) xs)
_ -> Nothing
-- | If a 'BVFactor' in a binding is an unset variable, return the value
-- of its 'BV' and the witness that it is bound. Otherwise, return the
-- constant of the factor multiplied by the variable's value if it is
-- a set variable, or the constant of the factor multiplied by the
-- variable, if it is an unbound variable
mbFactorNameBoundP :: PartialSubst vars ->
Mb vars (BVFactor w) ->
Either (Integer, Member vars (BVType w))
(PermExpr (BVType w))
mbFactorNameBoundP psubst (mbMatch -> [nuMP| BVFactor (BV.BV mb_n) mb_z |]) =
let n = mbLift mb_n in
case mbNameBoundP mb_z of
Left memb -> case psubstLookup psubst memb of
Nothing -> Left (n, memb)
Just e' -> Right (bvMultBV (BV.mkBV knownNat n) e')
Right z -> Right (bvFactorExpr (BV.mkBV knownNat n) z)
----------------------------------------------------------------------
-- * Abstracting Out Variables
----------------------------------------------------------------------
mbMbApply :: Mb (ctx1 :: RList k1) (Mb (ctx2 :: RList k2) (a -> b)) ->
Mb ctx1 (Mb ctx2 a) -> Mb ctx1 (Mb ctx2 b)
mbMbApply = mbApply . (fmap mbApply)
clMbMbApplyM :: Monad m =>
m (Closed (Mb (ctx1 :: RList k1)
(Mb (ctx2 :: RList k2) (a -> b)))) ->
m (Closed (Mb ctx1 (Mb ctx2 a))) ->
m (Closed (Mb ctx1 (Mb ctx2 b)))
clMbMbApplyM fm am =
(\f a -> $(mkClosed [| mbMbApply |]) `clApply` f `clApply` a) <$> fm <*> am
absVarsReturnH :: Monad m => RAssign f1 (ctx1 :: RList k1) ->
RAssign f2 (ctx2 :: RList k2) ->
Closed a -> m (Closed (Mb ctx1 (Mb ctx2 a)))
absVarsReturnH fs1 fs2 cl_a =
return ( $(mkClosed [| \prxs1 prxs2 a ->
nuMulti prxs1 (const $ nuMulti prxs2 $ const a) |])
`clApply` closedProxies fs1 `clApply` closedProxies fs2
`clApply` cl_a)
-- | Map an 'RAssign' to a 'Closed' 'RAssign' of 'Proxy' objects
closedProxies :: RAssign f args -> Closed (RAssign Proxy args)
closedProxies = toClosed . mapRAssign (const Proxy)
-- | Class for types that support abstracting out all permission and expression
-- variables. If the abstraction succeeds, we get a closed element of the type
-- inside a binding for those permission and expression variables that are free
-- in the original input.
--
-- NOTE: if a variable occurs more than once, we associate it with the left-most
-- occurrence, i.e., the earliest binding
class AbstractVars a where
abstractPEVars :: RAssign Name (pctx :: RList Type) ->
RAssign Name (ectx :: RList CrucibleType) -> a ->
Maybe (Closed (Mb pctx (Mb ectx a)))
-- | Call 'abstractPEVars' with only variables that have 'CrucibleType's
abstractVars :: AbstractVars a =>
RAssign Name (ctx :: RList CrucibleType) -> a ->
Maybe (Closed (Mb ctx a))
abstractVars ns a =
fmap (clApply $(mkClosed [| elimEmptyMb |])) $ abstractPEVars MNil ns a
-- | An expression or other object which the variables have been abstracted out
-- of, along with those variables that were abstracted out of it
data AbsObj a = forall ctx. AbsObj (RAssign ExprVar ctx) (Closed (Mb ctx a))
-- | Find all free variables of an expresssion and abstract them out. Note that
-- this should always succeed, if 'freeVars' is implemented correctly.
abstractFreeVars :: (AbstractVars a, FreeVars a) => a -> AbsObj a
abstractFreeVars a
| Some ns <- freeVarsRAssign a
, Just cl_mb_a <- abstractVars ns a = AbsObj ns cl_mb_a
abstractFreeVars _ = error "abstractFreeVars"
-- | Try to close an expression by calling 'abstractPEVars' with an empty list
-- of expression variables
tryClose :: AbstractVars a => a -> Maybe (Closed a)
tryClose a =
fmap (clApply $(mkClosed [| elimEmptyMb . elimEmptyMb |])) $
abstractPEVars MNil MNil a
instance AbstractVars (Name (a :: CrucibleType)) where
abstractPEVars ns1 ns2 (n :: Name a)
| Just memb <- memberElem n ns2
= return ( $(mkClosed
[| \prxs1 prxs2 memb' ->
nuMulti prxs1 (const $ nuMulti prxs2 (RL.get memb')) |])
`clApply` closedProxies ns1 `clApply` closedProxies ns2
`clApply` toClosed memb)
abstractPEVars _ _ _ = Nothing
instance AbstractVars (Name (a :: Type)) where
abstractPEVars ns1 ns2 (n :: Name a)
| Just memb <- memberElem n ns1
= return ( $(mkClosed
[| \prxs1 prxs2 memb' ->
nuMulti prxs1 $ \ns ->
nuMulti prxs2 (const $ RL.get memb' ns) |])
`clApply` closedProxies ns1 `clApply` closedProxies ns2
`clApply` toClosed memb)
abstractPEVars _ _ _ = Nothing
instance AbstractVars a => AbstractVars (Mb (ctx :: RList CrucibleType) a) where
abstractPEVars ns1 ns2 mb =
mbLift $
nuMultiWithElim1
(\ns a ->
clApply ( $(mkClosed [| \prxs -> fmap (mbSeparate prxs) |])
`clApply` closedProxies ns) <$>
abstractPEVars ns1 (append ns2 ns) a)
mb
instance AbstractVars a => AbstractVars (Mb (ctx :: RList Type) a) where
abstractPEVars ns1 ns2 mb =
mbLift $
nuMultiWithElim1
(\ns a ->
clApply ( $(mkClosed [| \prxs2 prxs -> fmap (mbSwap prxs2) . mbSeparate prxs |])
`clApply` closedProxies ns2
`clApply` closedProxies ns) <$>
abstractPEVars (append ns1 ns) ns2 a)
mb
instance AbstractVars (RAssign Name (ctx :: RList CrucibleType)) where
abstractPEVars ns1 ns2 MNil = absVarsReturnH ns1 ns2 $(mkClosed [| MNil |])
abstractPEVars ns1 ns2 (ns :>: n) =
absVarsReturnH ns1 ns2 $(mkClosed [| (:>:) |])
`clMbMbApplyM` abstractPEVars ns1 ns2 ns
`clMbMbApplyM` abstractPEVars ns1 ns2 n
instance AbstractVars Integer where
abstractPEVars ns1 ns2 i = absVarsReturnH ns1 ns2 (toClosed i)
instance AbstractVars (BV w) where
abstractPEVars ns1 ns2 bv = absVarsReturnH ns1 ns2 (toClosed bv)
instance AbstractVars Bytes where
abstractPEVars ns1 ns2 bytes = absVarsReturnH ns1 ns2 (toClosed bytes)
instance AbstractVars Natural where
abstractPEVars ns1 ns2 n = absVarsReturnH ns1 ns2 (toClosed n)
instance AbstractVars Char where
abstractPEVars ns1 ns2 c = absVarsReturnH ns1 ns2 (toClosed c)
instance AbstractVars Bool where
abstractPEVars ns1 ns2 b = absVarsReturnH ns1 ns2 (toClosed b)
instance AbstractVars (Member ctx a) where
abstractPEVars ns1 ns2 memb = absVarsReturnH ns1 ns2 (toClosed memb)
instance AbstractVars a => AbstractVars (Maybe a) where
abstractPEVars ns1 ns2 Nothing =
absVarsReturnH ns1 ns2 $(mkClosed [| Nothing |])
abstractPEVars ns1 ns2 (Just a) =
absVarsReturnH ns1 ns2 $(mkClosed [| Just |])
`clMbMbApplyM` abstractPEVars ns1 ns2 a
instance AbstractVars a => AbstractVars [a] where
abstractPEVars ns1 ns2 [] =
absVarsReturnH ns1 ns2 $(mkClosed [| [] |])
abstractPEVars ns1 ns2 (a:as) =
absVarsReturnH ns1 ns2 $(mkClosed [| (:) |])
`clMbMbApplyM` abstractPEVars ns1 ns2 a
`clMbMbApplyM` abstractPEVars ns1 ns2 as
instance (AbstractVars a, AbstractVars b) => AbstractVars (a,b) where
abstractPEVars ns1 ns2 (a,b) =
absVarsReturnH ns1 ns2 $(mkClosed [| (,) |])
`clMbMbApplyM` abstractPEVars ns1 ns2 a
`clMbMbApplyM` abstractPEVars ns1 ns2 b
instance AbstractVars (PermExpr a) where
abstractPEVars ns1 ns2 (PExpr_Var x) =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_Var |])
`clMbMbApplyM` abstractPEVars ns1 ns2 x
abstractPEVars ns1 ns2 PExpr_Unit =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_Unit |])
abstractPEVars ns1 ns2 (PExpr_Bool b) =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_Bool |])
`clMbMbApplyM` abstractPEVars ns1 ns2 b
abstractPEVars ns1 ns2 (PExpr_Nat i) =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_Nat |])
`clMbMbApplyM` abstractPEVars ns1 ns2 i
abstractPEVars ns1 ns2 (PExpr_String str) =
absVarsReturnH ns1 ns2 ($(mkClosed [| PExpr_String |])
`clApply` toClosed str)
abstractPEVars ns1 ns2 (PExpr_BV factors k) =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_BV |])
`clMbMbApplyM` abstractPEVars ns1 ns2 factors
`clMbMbApplyM` abstractPEVars ns1 ns2 k
abstractPEVars ns1 ns2 (PExpr_Struct es) =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_Struct |])
`clMbMbApplyM` abstractPEVars ns1 ns2 es
abstractPEVars ns1 ns2 PExpr_Always =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_Always |])
abstractPEVars ns1 ns2 (PExpr_LLVMWord e) =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_LLVMWord |])
`clMbMbApplyM` abstractPEVars ns1 ns2 e
abstractPEVars ns1 ns2 (PExpr_LLVMOffset x e) =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_LLVMOffset |])
`clMbMbApplyM` abstractPEVars ns1 ns2 x
`clMbMbApplyM` abstractPEVars ns1 ns2 e
abstractPEVars ns1 ns2 (PExpr_Fun fh) =
absVarsReturnH ns1 ns2 ($(mkClosed [| PExpr_Fun |]) `clApply` toClosed fh)
abstractPEVars ns1 ns2 PExpr_PermListNil =
absVarsReturnH ns1 ns2 ($(mkClosed [| PExpr_PermListNil |]))
abstractPEVars ns1 ns2 (PExpr_PermListCons tp e p l) =
absVarsReturnH ns1 ns2 ($(mkClosed [| PExpr_PermListCons |])
`clApply` toClosed tp)
`clMbMbApplyM` abstractPEVars ns1 ns2 e
`clMbMbApplyM` abstractPEVars ns1 ns2 p
`clMbMbApplyM` abstractPEVars ns1 ns2 l
abstractPEVars ns1 ns2 (PExpr_RWModality rw) =
absVarsReturnH ns1 ns2 ($(mkClosed [| PExpr_RWModality |])
`clApply` toClosed rw)
abstractPEVars ns1 ns2 PExpr_EmptyShape =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_EmptyShape |])
abstractPEVars ns1 ns2 (PExpr_NamedShape rw l nmsh args) =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_NamedShape |])
`clMbMbApplyM` abstractPEVars ns1 ns2 rw
`clMbMbApplyM` abstractPEVars ns1 ns2 l
`clMbMbApplyM` abstractPEVars ns1 ns2 nmsh
`clMbMbApplyM` abstractPEVars ns1 ns2 args
abstractPEVars ns1 ns2 (PExpr_EqShape len b) =
absVarsReturnH ns1 ns2 ($(mkClosed [| PExpr_EqShape |]))
`clMbMbApplyM` abstractPEVars ns1 ns2 len
`clMbMbApplyM` abstractPEVars ns1 ns2 b
abstractPEVars ns1 ns2 (PExpr_PtrShape maybe_rw maybe_l sh) =
absVarsReturnH ns1 ns2 ($(mkClosed [| PExpr_PtrShape |]))
`clMbMbApplyM` abstractPEVars ns1 ns2 maybe_rw
`clMbMbApplyM` abstractPEVars ns1 ns2 maybe_l
`clMbMbApplyM` abstractPEVars ns1 ns2 sh
abstractPEVars ns1 ns2 (PExpr_FieldShape fsh) =
absVarsReturnH ns1 ns2 ($(mkClosed [| PExpr_FieldShape |]))
`clMbMbApplyM` abstractPEVars ns1 ns2 fsh
abstractPEVars ns1 ns2 (PExpr_ArrayShape len stride sh) =
absVarsReturnH ns1 ns2 ($(mkClosed [| flip PExpr_ArrayShape |])
`clApply` toClosed stride)
`clMbMbApplyM` abstractPEVars ns1 ns2 len
`clMbMbApplyM` abstractPEVars ns1 ns2 sh
abstractPEVars ns1 ns2 (PExpr_SeqShape sh1 sh2) =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_SeqShape |])
`clMbMbApplyM` abstractPEVars ns1 ns2 sh1
`clMbMbApplyM` abstractPEVars ns1 ns2 sh2
abstractPEVars ns1 ns2 (PExpr_OrShape sh1 sh2) =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_OrShape |])
`clMbMbApplyM` abstractPEVars ns1 ns2 sh1
`clMbMbApplyM` abstractPEVars ns1 ns2 sh2
abstractPEVars ns1 ns2 (PExpr_ExShape mb_sh) =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_ExShape |])
`clMbMbApplyM` abstractPEVars ns1 ns2 mb_sh
abstractPEVars ns1 ns2 PExpr_FalseShape =
absVarsReturnH ns1 ns2 $(mkClosed [| PExpr_FalseShape |])
abstractPEVars ns1 ns2 (PExpr_ValPerm p) =
absVarsReturnH ns1 ns2 ($(mkClosed [| PExpr_ValPerm |]))
`clMbMbApplyM` abstractPEVars ns1 ns2 p
instance AbstractVars (PermExprs as) where
abstractPEVars ns1 ns2 PExprs_Nil =
absVarsReturnH ns1 ns2 $(mkClosed [| PExprs_Nil |])
abstractPEVars ns1 ns2 (PExprs_Cons es e) =
absVarsReturnH ns1 ns2 $(mkClosed [| PExprs_Cons |])
`clMbMbApplyM` abstractPEVars ns1 ns2 es
`clMbMbApplyM` abstractPEVars ns1 ns2 e
instance AbstractVars (BVFactor w) where
abstractPEVars ns1 ns2 (BVFactor i x) =
absVarsReturnH ns1 ns2 $(mkClosed [| BVFactor |])
`clMbMbApplyM` abstractPEVars ns1 ns2 i
`clMbMbApplyM` abstractPEVars ns1 ns2 x
instance AbstractVars (BVRange w) where
abstractPEVars ns1 ns2 (BVRange e1 e2) =
absVarsReturnH ns1 ns2 $(mkClosed [| BVRange |])
`clMbMbApplyM` abstractPEVars ns1 ns2 e1
`clMbMbApplyM` abstractPEVars ns1 ns2 e2
instance AbstractVars (BVProp w) where
abstractPEVars ns1 ns2 (BVProp_Eq e1 e2) =
absVarsReturnH ns1 ns2 $(mkClosed [| BVProp_Eq |])
`clMbMbApplyM` abstractPEVars ns1 ns2 e1
`clMbMbApplyM` abstractPEVars ns1 ns2 e2
abstractPEVars ns1 ns2 (BVProp_Neq e1 e2) =
absVarsReturnH ns1 ns2 $(mkClosed [| BVProp_Neq |])
`clMbMbApplyM` abstractPEVars ns1 ns2 e1
`clMbMbApplyM` abstractPEVars ns1 ns2 e2
abstractPEVars ns1 ns2 (BVProp_ULt e1 e2) =
absVarsReturnH ns1 ns2 $(mkClosed [| BVProp_ULt |])
`clMbMbApplyM` abstractPEVars ns1 ns2 e1
`clMbMbApplyM` abstractPEVars ns1 ns2 e2
abstractPEVars ns1 ns2 (BVProp_ULeq e1 e2) =
absVarsReturnH ns1 ns2 $(mkClosed [| BVProp_ULeq |])
`clMbMbApplyM` abstractPEVars ns1 ns2 e1
`clMbMbApplyM` abstractPEVars ns1 ns2 e2
abstractPEVars ns1 ns2 (BVProp_ULeq_Diff e1 e2 e3) =
absVarsReturnH ns1 ns2 $(mkClosed [| BVProp_ULeq_Diff |])
`clMbMbApplyM` abstractPEVars ns1 ns2 e1
`clMbMbApplyM` abstractPEVars ns1 ns2 e2
`clMbMbApplyM` abstractPEVars ns1 ns2 e3
instance AbstractVars (AtomicPerm a) where
abstractPEVars ns1 ns2 (Perm_LLVMField fp) =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_LLVMField |])
`clMbMbApplyM` abstractPEVars ns1 ns2 fp
abstractPEVars ns1 ns2 (Perm_LLVMArray ap) =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_LLVMArray |])
`clMbMbApplyM` abstractPEVars ns1 ns2 ap
abstractPEVars ns1 ns2 (Perm_LLVMBlock bp) =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_LLVMBlock |])
`clMbMbApplyM` abstractPEVars ns1 ns2 bp
abstractPEVars ns1 ns2 (Perm_LLVMFree e) =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_LLVMFree |])
`clMbMbApplyM` abstractPEVars ns1 ns2 e
abstractPEVars ns1 ns2 (Perm_LLVMFunPtr tp p) =
absVarsReturnH ns1 ns2
($(mkClosed [| Perm_LLVMFunPtr |]) `clApply` toClosed tp)
`clMbMbApplyM` abstractPEVars ns1 ns2 p
abstractPEVars ns1 ns2 Perm_IsLLVMPtr =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_IsLLVMPtr |])
abstractPEVars ns1 ns2 (Perm_LLVMBlockShape sh) =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_LLVMBlockShape |])
`clMbMbApplyM` abstractPEVars ns1 ns2 sh
abstractPEVars ns1 ns2 (Perm_LLVMFrame fp) =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_LLVMFrame |])
`clMbMbApplyM` abstractPEVars ns1 ns2 fp
abstractPEVars ns1 ns2 (Perm_LOwned ls ps_in ps_out) =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_LOwned |])
`clMbMbApplyM` abstractPEVars ns1 ns2 ls
`clMbMbApplyM` abstractPEVars ns1 ns2 ps_in
`clMbMbApplyM` abstractPEVars ns1 ns2 ps_out
abstractPEVars ns1 ns2 (Perm_LOwnedSimple lops) =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_LOwnedSimple |])
`clMbMbApplyM` abstractPEVars ns1 ns2 lops
abstractPEVars ns1 ns2 (Perm_LCurrent e) =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_LCurrent |])
`clMbMbApplyM` abstractPEVars ns1 ns2 e
abstractPEVars ns1 ns2 Perm_LFinished =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_LFinished |])
abstractPEVars ns1 ns2 (Perm_Struct ps) =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_Struct |])
`clMbMbApplyM` abstractPEVars ns1 ns2 ps
abstractPEVars ns1 ns2 (Perm_Fun fperm) =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_Fun |])
`clMbMbApplyM` abstractPEVars ns1 ns2 fperm
abstractPEVars ns1 ns2 (Perm_BVProp prop) =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_BVProp |])
`clMbMbApplyM` abstractPEVars ns1 ns2 prop
abstractPEVars ns1 ns2 (Perm_NamedConj n args off) =
absVarsReturnH ns1 ns2 $(mkClosed [| Perm_NamedConj |])
`clMbMbApplyM` abstractPEVars ns1 ns2 n
`clMbMbApplyM` abstractPEVars ns1 ns2 args
`clMbMbApplyM` abstractPEVars ns1 ns2 off
instance AbstractVars (ValuePerm a) where
abstractPEVars ns1 ns2 (ValPerm_Var x off) =
absVarsReturnH ns1 ns2 $(mkClosed [| ValPerm_Var |])
`clMbMbApplyM` abstractPEVars ns1 ns2 x
`clMbMbApplyM` abstractPEVars ns1 ns2 off
abstractPEVars ns1 ns2 (ValPerm_Eq e) =
absVarsReturnH ns1 ns2 $(mkClosed [| ValPerm_Eq |])
`clMbMbApplyM` abstractPEVars ns1 ns2 e
abstractPEVars ns1 ns2 (ValPerm_Or p1 p2) =
absVarsReturnH ns1 ns2 $(mkClosed [| ValPerm_Or |])
`clMbMbApplyM` abstractPEVars ns1 ns2 p1
`clMbMbApplyM` abstractPEVars ns1 ns2 p2
abstractPEVars ns1 ns2 (ValPerm_Exists p) =
absVarsReturnH ns1 ns2 $(mkClosed [| ValPerm_Exists |])
`clMbMbApplyM` abstractPEVars ns1 ns2 p
abstractPEVars ns1 ns2 (ValPerm_Named n args off) =
absVarsReturnH ns1 ns2 $(mkClosed [| ValPerm_Named |])
`clMbMbApplyM` abstractPEVars ns1 ns2 n
`clMbMbApplyM` abstractPEVars ns1 ns2 args
`clMbMbApplyM` abstractPEVars ns1 ns2 off
abstractPEVars ns1 ns2 (ValPerm_Conj ps) =
absVarsReturnH ns1 ns2 $(mkClosed [| ValPerm_Conj |])
`clMbMbApplyM` abstractPEVars ns1 ns2 ps
abstractPEVars ns1 ns2 ValPerm_False =
absVarsReturnH ns1 ns2 $(mkClosed [| ValPerm_False |])
instance AbstractVars (ValuePerms as) where
abstractPEVars ns1 ns2 ValPerms_Nil =
absVarsReturnH ns1 ns2 $(mkClosed [| ValPerms_Nil |])
abstractPEVars ns1 ns2 (ValPerms_Cons ps p) =
absVarsReturnH ns1 ns2 $(mkClosed [| ValPerms_Cons |])
`clMbMbApplyM` abstractPEVars ns1 ns2 ps
`clMbMbApplyM` abstractPEVars ns1 ns2 p
instance AbstractVars RWModality where
abstractPEVars ns1 ns2 Write =
absVarsReturnH ns1 ns2 $(mkClosed [| Write |])
abstractPEVars ns1 ns2 Read =
absVarsReturnH ns1 ns2 $(mkClosed [| Read |])
instance AbstractVars (LLVMFieldPerm w sz) where
abstractPEVars ns1 ns2 (LLVMFieldPerm rw ls off p) =
absVarsReturnH ns1 ns2 $(mkClosed [| LLVMFieldPerm |])
`clMbMbApplyM` abstractPEVars ns1 ns2 rw
`clMbMbApplyM` abstractPEVars ns1 ns2 ls
`clMbMbApplyM` abstractPEVars ns1 ns2 off
`clMbMbApplyM` abstractPEVars ns1 ns2 p
instance AbstractVars (LLVMArrayPerm w) where
abstractPEVars ns1 ns2 (LLVMArrayPerm rw l off len str flds bs) =
absVarsReturnH ns1 ns2 $(mkClosed [| LLVMArrayPerm |])
`clMbMbApplyM` abstractPEVars ns1 ns2 rw
`clMbMbApplyM` abstractPEVars ns1 ns2 l
`clMbMbApplyM` abstractPEVars ns1 ns2 off
`clMbMbApplyM` abstractPEVars ns1 ns2 len
`clMbMbApplyM` abstractPEVars ns1 ns2 str
`clMbMbApplyM` abstractPEVars ns1 ns2 flds
`clMbMbApplyM` abstractPEVars ns1 ns2 bs
instance AbstractVars (LLVMArrayIndex w) where
abstractPEVars ns1 ns2 (LLVMArrayIndex ix off) =
absVarsReturnH ns1 ns2 $(mkClosed [| LLVMArrayIndex |])
`clMbMbApplyM` abstractPEVars ns1 ns2 ix
`clMbMbApplyM` abstractPEVars ns1 ns2 off
instance AbstractVars (PermOffset a) where
abstractPEVars ns1 ns2 NoPermOffset =
absVarsReturnH ns1 ns2 $(mkClosed [| NoPermOffset |])
abstractPEVars ns1 ns2 (LLVMPermOffset off) =
absVarsReturnH ns1 ns2 $(mkClosed [| LLVMPermOffset |])
`clMbMbApplyM` abstractPEVars ns1 ns2 off
instance AbstractVars (LLVMArrayBorrow w) where
abstractPEVars ns1 ns2 (FieldBorrow ix) =
absVarsReturnH ns1 ns2 $(mkClosed [| FieldBorrow |])
`clMbMbApplyM` abstractPEVars ns1 ns2 ix
abstractPEVars ns1 ns2 (RangeBorrow r) =
absVarsReturnH ns1 ns2 $(mkClosed [| RangeBorrow |])
`clMbMbApplyM` abstractPEVars ns1 ns2 r
instance AbstractVars (LLVMFieldShape w) where
abstractPEVars ns1 ns2 (LLVMFieldShape p) =
absVarsReturnH ns1 ns2 $(mkClosed [| LLVMFieldShape |])
`clMbMbApplyM` abstractPEVars ns1 ns2 p
instance AbstractVars (LLVMBlockPerm w) where
abstractPEVars ns1 ns2 (LLVMBlockPerm rw l off len sh) =
absVarsReturnH ns1 ns2 $(mkClosed [| LLVMBlockPerm |])
`clMbMbApplyM` abstractPEVars ns1 ns2 rw
`clMbMbApplyM` abstractPEVars ns1 ns2 l
`clMbMbApplyM` abstractPEVars ns1 ns2 off
`clMbMbApplyM` abstractPEVars ns1 ns2 len
`clMbMbApplyM` abstractPEVars ns1 ns2 sh
instance AbstractVars (DistPerms ps) where
abstractPEVars ns1 ns2 DistPermsNil =
absVarsReturnH ns1 ns2 $(mkClosed [| DistPermsNil |])
abstractPEVars ns1 ns2 (DistPermsCons perms x p) =
absVarsReturnH ns1 ns2 $(mkClosed [| DistPermsCons |])
`clMbMbApplyM` abstractPEVars ns1 ns2 perms
`clMbMbApplyM` abstractPEVars ns1 ns2 x `clMbMbApplyM` abstractPEVars ns1 ns2 p
instance AbstractVars (LOwnedPerm a) where
abstractPEVars ns1 ns2 (LOwnedPermField e fp) =
absVarsReturnH ns1 ns2 $(mkClosed [| LOwnedPermField |])
`clMbMbApplyM` abstractPEVars ns1 ns2 e
`clMbMbApplyM` abstractPEVars ns1 ns2 fp
abstractPEVars ns1 ns2 (LOwnedPermArray e ap) =
absVarsReturnH ns1 ns2 $(mkClosed [| LOwnedPermArray |])
`clMbMbApplyM` abstractPEVars ns1 ns2 e
`clMbMbApplyM` abstractPEVars ns1 ns2 ap
abstractPEVars ns1 ns2 (LOwnedPermBlock e bp) =
absVarsReturnH ns1 ns2 $(mkClosed [| LOwnedPermBlock |])
`clMbMbApplyM` abstractPEVars ns1 ns2 e
`clMbMbApplyM` abstractPEVars ns1 ns2 bp
instance AbstractVars (LOwnedPerms ps) where
abstractPEVars ns1 ns2 MNil =
absVarsReturnH ns1 ns2 $(mkClosed [| MNil |])
abstractPEVars ns1 ns2 (ps :>: p) =
absVarsReturnH ns1 ns2 $(mkClosed [| (:>:) |])
`clMbMbApplyM` abstractPEVars ns1 ns2 ps
`clMbMbApplyM` abstractPEVars ns1 ns2 p
instance AbstractVars (FunPerm ghosts args gouts ret) where
abstractPEVars ns1 ns2 (FunPerm ghosts args gouts ret perms_in perms_out) =
absVarsReturnH ns1 ns2
($(mkClosed [| FunPerm |])
`clApply` toClosed ghosts `clApply` toClosed args
`clApply` toClosed gouts `clApply` toClosed ret)
`clMbMbApplyM` abstractPEVars ns1 ns2 perms_in
`clMbMbApplyM` abstractPEVars ns1 ns2 perms_out
instance AbstractVars (NamedShape b args w) where
abstractPEVars ns1 ns2 (NamedShape nm args body) =
absVarsReturnH ns1 ns2 ($(mkClosed [| NamedShape |])
`clApply` toClosed nm `clApply` toClosed args)
`clMbMbApplyM` abstractPEVars ns1 ns2 body
instance AbstractVars (NamedShapeBody b args w) where
abstractPEVars ns1 ns2 (DefinedShapeBody mb_sh) =
absVarsReturnH ns1 ns2 $(mkClosed [| DefinedShapeBody |])
`clMbMbApplyM` abstractPEVars ns1 ns2 mb_sh
abstractPEVars ns1 ns2 (OpaqueShapeBody mb_len trans_id) =
absVarsReturnH ns1 ns2 ($(mkClosed [| \i l -> OpaqueShapeBody l i |])
`clApply` toClosed trans_id)
`clMbMbApplyM` abstractPEVars ns1 ns2 mb_len
abstractPEVars ns1 ns2 (RecShapeBody mb_sh trans_id fold_ids) =
absVarsReturnH ns1 ns2 ($(mkClosed
[| \i1 i2 l -> RecShapeBody l i1 i2 |])
`clApply` toClosed trans_id
`clApply` toClosed fold_ids)
`clMbMbApplyM` abstractPEVars ns1 ns2 mb_sh
instance AbstractVars (NamedPermName ns args a) where
abstractPEVars ns1 ns2 (NamedPermName n tp args ns reachConstr) =
absVarsReturnH ns1 ns2
($(mkClosed [| NamedPermName |])
`clApply` toClosed n `clApply` toClosed tp `clApply` toClosed args
`clApply` toClosed ns`clApply` toClosed reachConstr)
----------------------------------------------------------------------
-- * Abstracting out named shapes
----------------------------------------------------------------------
-- | An existentially quantified, partially defined LLVM shape applied to
-- some arguments
data SomePartialNamedShape w where
NonRecShape :: String -> CruCtx args -> Mb args (PermExpr (LLVMShapeType w))
-> SomePartialNamedShape w
RecShape :: String -> CruCtx args
-> Mb (args :> LLVMShapeType w) (PermExpr (LLVMShapeType w))
-> SomePartialNamedShape w
-- | An existentially quantified LLVM shape applied to some arguments
data SomeNamedShapeApp w where
SomeNamedShapeApp :: String -> CruCtx args -> PermExprs args ->
NatRepr w -> SomeNamedShapeApp w
class AbstractNamedShape w a where
abstractNSM :: a -> ReaderT (SomeNamedShapeApp w) Maybe
(Binding (LLVMShapeType w) a)
abstractNS :: (KnownNat w, AbstractNamedShape w a) =>
String -> CruCtx args -> PermExprs args ->
a -> Maybe (Binding (LLVMShapeType w) a)
abstractNS nsh args_ctx args x = runReaderT (abstractNSM x) nshApp
where nshApp = SomeNamedShapeApp nsh args_ctx args knownNat
pureBindingM :: Monad m => b -> m (Binding a b)
pureBindingM = pure . nu . const
instance (NuMatching a, AbstractNamedShape w a) =>
AbstractNamedShape w (Mb ctx a) where
abstractNSM = fmap (mbSwap RL.typeCtxProxies) . mbM . fmap abstractNSM
instance AbstractNamedShape w Integer where
abstractNSM = pureBindingM
instance AbstractNamedShape w a => AbstractNamedShape w (Maybe a) where
abstractNSM (Just x) = fmap Just <$> abstractNSM x
abstractNSM Nothing = pureBindingM Nothing
instance AbstractNamedShape w a => AbstractNamedShape w [a] where
abstractNSM [] = pureBindingM []
abstractNSM (x:xs) = mbMap2 (:) <$> abstractNSM x <*> abstractNSM xs
instance (AbstractNamedShape w a, AbstractNamedShape w b) =>
AbstractNamedShape w (a, b) where
abstractNSM (x,y) = mbMap2 (,) <$> abstractNSM x <*> abstractNSM y
instance AbstractNamedShape w (PermExpr a) where
abstractNSM (PExpr_Var x) = pureBindingM (PExpr_Var x)
abstractNSM PExpr_Unit = pureBindingM PExpr_Unit
abstractNSM (PExpr_Bool b) = pureBindingM (PExpr_Bool b)
abstractNSM (PExpr_Nat n) = pureBindingM (PExpr_Nat n)
abstractNSM (PExpr_String s) = pureBindingM (PExpr_String s)
abstractNSM (PExpr_BV fs c) = pureBindingM (PExpr_BV fs c)
abstractNSM (PExpr_Struct es) = fmap PExpr_Struct <$> abstractNSM es
abstractNSM PExpr_Always = pureBindingM PExpr_Always
abstractNSM (PExpr_LLVMWord e) = fmap PExpr_LLVMWord <$> abstractNSM e
abstractNSM (PExpr_LLVMOffset x e) = fmap (PExpr_LLVMOffset x) <$> abstractNSM e
abstractNSM (PExpr_Fun fh) = pureBindingM (PExpr_Fun fh)
abstractNSM PExpr_PermListNil = pureBindingM PExpr_PermListNil
abstractNSM (PExpr_PermListCons tp e p l) =
mbMap3 (PExpr_PermListCons tp) <$> abstractNSM e <*> abstractNSM p <*> abstractNSM l
abstractNSM (PExpr_RWModality rw) = pureBindingM (PExpr_RWModality rw)
abstractNSM PExpr_EmptyShape = pureBindingM PExpr_EmptyShape
abstractNSM e@(PExpr_NamedShape maybe_rw maybe_l nmsh args) =
do SomeNamedShapeApp nm_abs args_ctx_abs args_abs w_abs <- ask
case namedShapeName nmsh == nm_abs of
True | Just Refl <- testEquality (namedShapeArgs nmsh) args_ctx_abs
, True <- args == args_abs
, Nothing <- maybe_rw, Nothing <- maybe_l
, Just Refl <- testEquality w_abs (shapeLLVMTypeWidth e)
-> pure $ nu PExpr_Var
True -> fail "named shape not applied to its arguments"
False -> pureBindingM (PExpr_NamedShape maybe_rw maybe_l nmsh args)
abstractNSM (PExpr_EqShape len b) =
mbMap2 PExpr_EqShape <$> abstractNSM len <*> abstractNSM b
abstractNSM (PExpr_PtrShape rw l sh) =
mbMap3 PExpr_PtrShape <$> abstractNSM rw <*> abstractNSM l <*> abstractNSM sh
abstractNSM (PExpr_FieldShape fsh) = fmap PExpr_FieldShape <$> abstractNSM fsh
abstractNSM (PExpr_ArrayShape len s sh) =
mbMap3 PExpr_ArrayShape <$> abstractNSM len <*> pureBindingM s <*> abstractNSM sh
abstractNSM (PExpr_SeqShape sh1 sh2) =
mbMap2 PExpr_SeqShape <$> abstractNSM sh1 <*> abstractNSM sh2
abstractNSM (PExpr_OrShape sh1 sh2) =
mbMap2 PExpr_OrShape <$> abstractNSM sh1 <*> abstractNSM sh2
abstractNSM (PExpr_ExShape mb_sh) = fmap PExpr_ExShape <$> abstractNSM mb_sh
abstractNSM PExpr_FalseShape = pureBindingM PExpr_FalseShape
abstractNSM (PExpr_ValPerm p) = fmap PExpr_ValPerm <$> abstractNSM p
instance AbstractNamedShape w (PermExprs as) where
abstractNSM PExprs_Nil = pureBindingM PExprs_Nil
abstractNSM (PExprs_Cons es e) =
mbMap2 PExprs_Cons <$> abstractNSM es <*> abstractNSM e
instance AbstractNamedShape w' (LLVMFieldShape w) where
abstractNSM (LLVMFieldShape p) = fmap LLVMFieldShape <$> abstractNSM p
instance AbstractNamedShape w (ValuePerm a) where
abstractNSM (ValPerm_Eq e) = fmap ValPerm_Eq <$> abstractNSM e
abstractNSM (ValPerm_Or p1 p2) =
mbMap2 ValPerm_Or <$> abstractNSM p1 <*> abstractNSM p2
abstractNSM (ValPerm_Exists p) = fmap ValPerm_Exists <$> abstractNSM p
abstractNSM (ValPerm_Named n args off) =
mbMap2 (ValPerm_Named n) <$> abstractNSM args <*> abstractNSM off
abstractNSM (ValPerm_Var x off) =
fmap (ValPerm_Var x) <$> abstractNSM off
abstractNSM (ValPerm_Conj aps) = fmap ValPerm_Conj <$> abstractNSM aps
abstractNSM ValPerm_False = (pure . pure) ValPerm_False
instance AbstractNamedShape w (PermOffset a) where
abstractNSM NoPermOffset = pureBindingM NoPermOffset
abstractNSM (LLVMPermOffset e) = fmap LLVMPermOffset <$> abstractNSM e
instance AbstractNamedShape w (AtomicPerm a) where
abstractNSM (Perm_LLVMField fp) = fmap Perm_LLVMField <$> abstractNSM fp
abstractNSM (Perm_LLVMArray ap) = fmap Perm_LLVMArray <$> abstractNSM ap
abstractNSM (Perm_LLVMBlock bp) = fmap Perm_LLVMBlock <$> abstractNSM bp
abstractNSM (Perm_LLVMFree e) = fmap Perm_LLVMFree <$> abstractNSM e
abstractNSM (Perm_LLVMFunPtr tp p) = fmap (Perm_LLVMFunPtr tp) <$> abstractNSM p
abstractNSM (Perm_LLVMBlockShape sh) = fmap Perm_LLVMBlockShape <$> abstractNSM sh
abstractNSM Perm_IsLLVMPtr = pureBindingM Perm_IsLLVMPtr
abstractNSM (Perm_NamedConj n args off) =
mbMap2 (Perm_NamedConj n) <$> abstractNSM args <*> abstractNSM off
abstractNSM (Perm_LLVMFrame fp) = fmap Perm_LLVMFrame <$> abstractNSM fp
abstractNSM (Perm_LOwned ls ps_in ps_out) =
mbMap3 Perm_LOwned <$> abstractNSM ls <*> abstractNSM ps_in <*>
abstractNSM ps_out
abstractNSM (Perm_LOwnedSimple lops) =
fmap Perm_LOwnedSimple <$> abstractNSM lops
abstractNSM (Perm_LCurrent e) = fmap Perm_LCurrent <$> abstractNSM e
abstractNSM Perm_LFinished = pureBindingM Perm_LFinished
abstractNSM (Perm_Struct ps) = fmap Perm_Struct <$> abstractNSM ps
abstractNSM (Perm_Fun fp) = fmap Perm_Fun <$> abstractNSM fp
abstractNSM (Perm_BVProp prop) = pureBindingM (Perm_BVProp prop)
instance AbstractNamedShape w' (LLVMFieldPerm w sz) where
abstractNSM (LLVMFieldPerm rw l off p) =
mbMap4 LLVMFieldPerm <$> abstractNSM rw <*> abstractNSM l
<*> abstractNSM off <*> abstractNSM p
-- | FIXME: move this to Hobbits?
mbApplyM :: Applicative m => m (Mb ctx (a -> b)) -> m (Mb ctx a) -> m (Mb ctx b)
mbApplyM f x = mbApply <$> f <*> x
instance AbstractNamedShape w' (LLVMArrayPerm w) where
abstractNSM (LLVMArrayPerm rw l off len stride sh bs) =
pureBindingM LLVMArrayPerm `mbApplyM` abstractNSM rw
`mbApplyM` abstractNSM l `mbApplyM` abstractNSM off
`mbApplyM` abstractNSM len `mbApplyM` pureBindingM stride
`mbApplyM` abstractNSM sh `mbApplyM` abstractNSM bs
instance AbstractNamedShape w' (LLVMArrayBorrow w) where
abstractNSM (FieldBorrow ix) = fmap FieldBorrow <$> abstractNSM ix
abstractNSM (RangeBorrow rng) = pureBindingM (RangeBorrow rng)
instance AbstractNamedShape w' (LLVMBlockPerm w) where
abstractNSM (LLVMBlockPerm rw l off len sh) =
mbMap5 LLVMBlockPerm <$> abstractNSM rw <*> abstractNSM l
<*> abstractNSM off <*> abstractNSM len
<*> abstractNSM sh
instance AbstractNamedShape w (LOwnedPerms ps) where
abstractNSM MNil = pureBindingM MNil
abstractNSM (fp :>: fps) = mbMap2 (:>:) <$> abstractNSM fp <*> abstractNSM fps
instance AbstractNamedShape w (LOwnedPerm a) where
abstractNSM (LOwnedPermField e fp) =
mbMap2 LOwnedPermField <$> abstractNSM e <*> abstractNSM fp
abstractNSM (LOwnedPermArray e ap) =
mbMap2 LOwnedPermArray <$> abstractNSM e <*> abstractNSM ap
abstractNSM (LOwnedPermBlock e bp) =
mbMap2 LOwnedPermBlock <$> abstractNSM e <*> abstractNSM bp
instance AbstractNamedShape w (ValuePerms as) where
abstractNSM ValPerms_Nil = pureBindingM ValPerms_Nil
abstractNSM (ValPerms_Cons ps p) =
mbMap2 ValPerms_Cons <$> abstractNSM ps <*> abstractNSM p
instance AbstractNamedShape w (FunPerm ghosts args gouts ret) where
abstractNSM (FunPerm ghosts args gouts ret perms_in perms_out) =
mbMap2 (FunPerm ghosts args gouts ret) <$> abstractNSM perms_in
<*> abstractNSM perms_out
instance Liftable RWModality where
mbLift mb_rw = case mbMatch mb_rw of
[nuMP| Write |] -> Write
[nuMP| Read |] -> Read
instance Closable RWModality where
toClosed Write = $(mkClosed [| Write |])
toClosed Read = $(mkClosed [| Read |])
instance Closable (NameSortRepr ns) where
toClosed (DefinedSortRepr b) =
$(mkClosed [| DefinedSortRepr |]) `clApply` toClosed b
toClosed (OpaqueSortRepr b) =
$(mkClosed [| OpaqueSortRepr |]) `clApply` toClosed b
toClosed (RecursiveSortRepr b reach) =
$(mkClosed [| RecursiveSortRepr |])
`clApply` toClosed b `clApply` toClosed reach
instance Liftable (NameSortRepr ns) where
mbLift = unClosed . mbLift . fmap toClosed
instance Closable (NameReachConstr ns args a) where
toClosed NameReachConstr = $(mkClosed [| NameReachConstr |])
toClosed NameNonReachConstr = $(mkClosed [| NameNonReachConstr |])
instance Liftable (NameReachConstr ns args a) where
mbLift = unClosed . mbLift . fmap toClosed
instance Liftable (NamedPermName ns args a) where
mbLift (mbMatch -> [nuMP| NamedPermName n tp args ns r |]) =
NamedPermName (mbLift n) (mbLift tp) (mbLift args) (mbLift ns) (mbLift r)
instance Liftable SomeNamedPermName where
mbLift (mbMatch -> [nuMP| SomeNamedPermName rpn |]) =
SomeNamedPermName $ mbLift rpn
instance Liftable (ReachMethods args a reach) where
mbLift mb_x = case mbMatch mb_x of
[nuMP| ReachMethods transIdent |] ->
ReachMethods (mbLift transIdent)
[nuMP| NoReachMethods |] -> NoReachMethods
----------------------------------------------------------------------
-- * Permission Environments
----------------------------------------------------------------------
-- | Get the 'BlockHintSort' for a 'BlockHint'
blockHintSort :: BlockHint blocks init ret args -> BlockHintSort args
blockHintSort (BlockHint _ _ _ sort) = sort
-- | Test if a 'BlockHintSort' is a block entry hint
isBlockEntryHint :: BlockHintSort args -> Bool
isBlockEntryHint (BlockEntryHintSort _ _ _) = True
isBlockEntryHint _ = False
-- | Test if a 'BlockHintSort' is a generalization hint
isGenPermsHint :: BlockHintSort args -> Bool
isGenPermsHint GenPermsHintSort = True
isGenPermsHint _ = False
-- | Test if a 'BlockHintSort' is a generalization hint
isJoinPointHint :: BlockHintSort args -> Bool
isJoinPointHint JoinPointHintSort = True
isJoinPointHint _ = False
-- FIXME: all the per-block hints
-- | The empty 'PermEnv'
emptyPermEnv :: PermEnv
emptyPermEnv = PermEnv [] [] [] [] []
-- | Add a 'NamedPerm' to a permission environment
permEnvAddNamedPerm :: PermEnv -> NamedPerm ns args a -> PermEnv
permEnvAddNamedPerm env np =
env { permEnvNamedPerms = SomeNamedPerm np : permEnvNamedPerms env }
-- | Add a 'NamedShape' to a permission environment
permEnvAddNamedShape :: (1 <= w, KnownNat w) =>
PermEnv -> NamedShape b args w -> PermEnv
permEnvAddNamedShape env ns =
env { permEnvNamedShapes = SomeNamedShape ns : permEnvNamedShapes env }
-- | Add an opaque named permission to a 'PermEnv'
permEnvAddOpaquePerm :: PermEnv -> String -> CruCtx args -> TypeRepr a ->
Ident -> PermEnv
permEnvAddOpaquePerm env str args tp i =
let n = NamedPermName str tp args (OpaqueSortRepr
TrueRepr) NameNonReachConstr in
permEnvAddNamedPerm env $ NamedPerm_Opaque $ OpaquePerm n i
-- | Add a recursive named permission to a 'PermEnv', assuming that the
-- 'recPermCases' and the fold and unfold functions depend recursively on the
-- recursive named permission being defined. This is handled by adding a
-- "temporary" version of the named permission to the environment to be used to
-- compute the 'recPermCases' and the fold and unfold functions and then passing
-- the expanded environment with this temporary named permission to the supplied
-- functions for computing these values. This temporary named permission has its
-- 'recPermCases' and its fold and unfold functions undefined, so the supplied
-- functions cannot depend on these values being defined, which makes sense
-- because they are defining them! Note that the function for computing the
-- 'recPermCases' can be called multiple times, so should not perform any
-- non-idempotent mutation in the monad @m@.
permEnvAddRecPermM :: Monad m => PermEnv -> String -> CruCtx args ->
TypeRepr a -> Ident ->
(forall b. NameReachConstr (RecursiveSort b reach) args a) ->
(forall b. NamedPermName (RecursiveSort b reach) args a ->
PermEnv -> m [Mb args (ValuePerm a)]) ->
(forall b. NamedPermName (RecursiveSort b reach) args a ->
[Mb args (ValuePerm a)] -> PermEnv -> m (Ident, Ident)) ->
(forall b. NamedPermName (RecursiveSort b reach) args a ->
PermEnv -> m (ReachMethods args a reach)) ->
m PermEnv
permEnvAddRecPermM env nm args tp trans_ident reachC casesF foldIdentsF reachMethsF =
-- NOTE: we start by assuming nm is conjoinable, and then, if it's not, we
-- call casesF again, and thereby compute a fixed-point
do let reach = nameReachConstrBool reachC
let mkTmpEnv :: NamedPermName (RecursiveSort b reach) args a -> PermEnv
mkTmpEnv npn =
permEnvAddNamedPerm env $ NamedPerm_Rec $
RecPerm npn trans_ident
(error "Analyzing recursive perm cases before it is defined!")
(error "Folding recursive perm before it is defined!")
(error "Using reachability methods for recursive perm before it is defined!")
(error "Unfolding recursive perm before it is defined!")
mkRealEnv :: Monad m => NamedPermName (RecursiveSort b reach) args a ->
[Mb args (ValuePerm a)] ->
(PermEnv -> m (Ident, Ident)) ->
(PermEnv -> m (ReachMethods args a reach)) ->
m PermEnv
mkRealEnv npn cases identsF rmethsF =
do let tmp_env = mkTmpEnv npn
(fold_ident, unfold_ident) <- identsF tmp_env
reachMeths <- rmethsF tmp_env
return $ permEnvAddNamedPerm env $ NamedPerm_Rec $
RecPerm npn trans_ident fold_ident unfold_ident reachMeths cases
let npn1 = NamedPermName nm tp args (RecursiveSortRepr TrueRepr reach) reachC
cases1 <- casesF npn1 (mkTmpEnv npn1)
case someBool $ all (mbLift . fmap isConjPerm) cases1 of
Some TrueRepr -> mkRealEnv npn1 cases1 (foldIdentsF npn1 cases1) (reachMethsF npn1)
Some FalseRepr ->
do let npn2 = NamedPermName nm tp args (RecursiveSortRepr
FalseRepr reach) reachC
cases2 <- casesF npn2 (mkTmpEnv npn2)
mkRealEnv npn2 cases2 (foldIdentsF npn2 cases2) (reachMethsF npn2)
-- | Add a defined named permission to a 'PermEnv'
permEnvAddDefinedPerm :: PermEnv -> String -> CruCtx args -> TypeRepr a ->
Mb args (ValuePerm a) -> PermEnv
permEnvAddDefinedPerm env str args tp p =
case someBool $ mbLift $ fmap isConjPerm p of
Some b ->
let n = NamedPermName str tp args (DefinedSortRepr b) NameNonReachConstr
np = NamedPerm_Defined (DefinedPerm n p) in
env { permEnvNamedPerms = SomeNamedPerm np : permEnvNamedPerms env }
-- | Add a defined LLVM shape to a permission environment
permEnvAddDefinedShape :: (1 <= w, KnownNat w) => PermEnv -> String ->
CruCtx args -> Mb args (PermExpr (LLVMShapeType w)) ->
PermEnv
permEnvAddDefinedShape env nm args mb_sh =
env { permEnvNamedShapes =
SomeNamedShape (NamedShape nm args $
DefinedShapeBody mb_sh) : permEnvNamedShapes env }
-- | Add an opaque LLVM shape to a permission environment
permEnvAddOpaqueShape :: (1 <= w, KnownNat w) => PermEnv -> String ->
CruCtx args -> Mb args (PermExpr (BVType w)) ->
Ident -> PermEnv
permEnvAddOpaqueShape env nm args mb_len tp_id =
env { permEnvNamedShapes =
SomeNamedShape (NamedShape nm args $
OpaqueShapeBody mb_len tp_id) : permEnvNamedShapes env }
-- | Add a global symbol with a function permission to a 'PermEnv'
permEnvAddGlobalSymFun :: (1 <= w, KnownNat w) => PermEnv -> GlobalSymbol ->
f w -> FunPerm ghosts args gouts ret ->
OpenTerm -> PermEnv
permEnvAddGlobalSymFun env sym (w :: f w) fun_perm t =
let p = ValPerm_Conj1 $ mkPermLLVMFunPtr w fun_perm in
env { permEnvGlobalSyms =
PermEnvGlobalEntry sym p [t] : permEnvGlobalSyms env }
-- | Add a global symbol with 0 or more function permissions to a 'PermEnv'
permEnvAddGlobalSymFunMulti :: (1 <= w, KnownNat w) => PermEnv ->
GlobalSymbol -> f w ->
[(SomeFunPerm args ret, OpenTerm)] -> PermEnv
permEnvAddGlobalSymFunMulti env sym (w :: f w) ps_ts =
let p = ValPerm_Conj1 $ mkPermLLVMFunPtrs w $ map fst ps_ts in
env { permEnvGlobalSyms =
PermEnvGlobalEntry sym p (map snd ps_ts) : permEnvGlobalSyms env }
-- | Add some 'PermEnvGlobalEntry's to a 'PermEnv'
permEnvAddGlobalSyms :: PermEnv -> [PermEnvGlobalEntry] -> PermEnv
permEnvAddGlobalSyms env entries = env { permEnvGlobalSyms =
entries ++ permEnvGlobalSyms env }
-- | Add a 'Hint' to a 'PermEnv'
permEnvAddHint :: PermEnv -> Hint -> PermEnv
permEnvAddHint env hint = env { permEnvHints = hint : permEnvHints env }
-- | Look up a 'FnHandle' by name in a 'PermEnv'
lookupFunHandle :: PermEnv -> String -> Maybe SomeHandle
lookupFunHandle env str =
case find (\(PermEnvFunEntry h _ _) ->
handleName h == fromString str) (permEnvFunPerms env) of
Just (PermEnvFunEntry h _ _) -> Just (SomeHandle h)
Nothing -> Nothing
-- | Look up the function permission and SAW translation for a 'FnHandle'
lookupFunPerm :: PermEnv -> FnHandle cargs ret ->
Maybe (SomeFunPerm (CtxToRList cargs) ret, Ident)
lookupFunPerm env = helper (permEnvFunPerms env) where
helper :: [PermEnvFunEntry] -> FnHandle cargs ret ->
Maybe (SomeFunPerm (CtxToRList cargs) ret, Ident)
helper [] _ = Nothing
helper ((PermEnvFunEntry h' fun_perm ident):_) h
| Just Refl <- testEquality (handleType h') (handleType h)
, h' == h
= Just (SomeFunPerm fun_perm, ident)
helper (_:entries) h = helper entries h
-- | Look up a 'NamedPermName' by name in a 'PermEnv'
lookupNamedPermName :: PermEnv -> String -> Maybe SomeNamedPermName
lookupNamedPermName env str =
case find (\(SomeNamedPerm np) ->
namedPermNameName (namedPermName np) == str) (permEnvNamedPerms env) of
Just (SomeNamedPerm np) -> Just (SomeNamedPermName (namedPermName np))
Nothing -> Nothing
-- | Look up a conjunctive 'NamedPermName' by name in a 'PermEnv'
lookupNamedConjPermName :: PermEnv -> String -> Maybe SomeNamedConjPermName
lookupNamedConjPermName env str =
case find (\(SomeNamedPerm np) ->
namedPermNameName (namedPermName np) == str)
(permEnvNamedPerms env) of
Just (SomeNamedPerm np)
| TrueRepr <- nameIsConjRepr $ namedPermName np ->
Just (SomeNamedConjPermName (namedPermName np))
_ -> Nothing
-- | Look up the 'NamedPerm' for a 'NamedPermName' in a 'PermEnv'
lookupNamedPerm :: PermEnv -> NamedPermName ns args a ->
Maybe (NamedPerm ns args a)
lookupNamedPerm env = helper (permEnvNamedPerms env) where
helper :: [SomeNamedPerm] -> NamedPermName ns args a ->
Maybe (NamedPerm ns args a)
helper [] _ = Nothing
helper (SomeNamedPerm rp:_) rpn
| Just (Refl, Refl, Refl) <- testNamedPermNameEq (namedPermName rp) rpn
= Just rp
helper (_:rps) rpn = helper rps rpn
-- | Look up the 'NamedPerm' for a 'NamedPermName' in a 'PermEnv' or raise an
-- error if it does not exist
requireNamedPerm :: PermEnv -> NamedPermName ns args a -> NamedPerm ns args a
requireNamedPerm env npn
| Just np <- lookupNamedPerm env npn = np
requireNamedPerm _ npn =
error ("requireNamedPerm: named perm does not exist: "
++ namedPermNameName npn)
-- | Look up an LLVM shape by name in a 'PermEnv' and cast it to a given width
lookupNamedShape :: PermEnv -> String -> Maybe SomeNamedShape
lookupNamedShape env nm =
find (\case SomeNamedShape nmsh ->
nm == namedShapeName nmsh) (permEnvNamedShapes env)
-- | Look up the permissions and translation for a 'GlobalSymbol' at a
-- particular machine word width
lookupGlobalSymbol :: PermEnv -> GlobalSymbol -> NatRepr w ->
Maybe (ValuePerm (LLVMPointerType w), [OpenTerm])
lookupGlobalSymbol env = helper (permEnvGlobalSyms env) where
helper :: [PermEnvGlobalEntry] -> GlobalSymbol -> NatRepr w ->
Maybe (ValuePerm (LLVMPointerType w), [OpenTerm])
helper (PermEnvGlobalEntry sym'
(p :: ValuePerm (LLVMPointerType w')) t:_) sym w
| sym' == sym
, Just Refl <- testEquality w (knownNat :: NatRepr w') =
Just (p, t)
helper (_:entries) sym w = helper entries sym w
helper [] _ _ = Nothing
-- | Look up all hints associated with a 'BlockID' in a function
lookupBlockHints :: PermEnv -> FnHandle init ret -> Assignment CtxRepr blocks ->
BlockID blocks args -> [BlockHintSort args]
lookupBlockHints env h blocks blkID =
mapMaybe (\hint -> case hint of
Hint_Block (BlockHint h' blocks' blkID' sort)
| Just Refl <- testEquality (handleID h') (handleID h)
, Just Refl <- testEquality blocks' blocks
, Just Refl <- testEquality blkID blkID' ->
return sort
_ -> Nothing) $
permEnvHints env
-- | Look up all hints with sort 'BlockEntryHintSort' for a given function
lookupBlockEntryHints :: PermEnv -> FnHandle init ret ->
Assignment CtxRepr blocks ->
[Some (BlockHint blocks init ret)]
lookupBlockEntryHints env h blocks =
mapMaybe (\hint -> case hint of
Hint_Block blk_hint@(BlockHint h' blocks' _blkID'
(BlockEntryHintSort _ _ _))
| Just Refl <- testEquality (handleID h') (handleID h)
, Just Refl <- testEquality blocks' blocks ->
return $ Some blk_hint
_ -> Nothing) $
permEnvHints env
-- | Test if a 'BlockID' in a 'CFG' has a hint with sort 'GenPermsHintSort'
lookupBlockGenPermsHint :: PermEnv -> FnHandle init ret ->
Assignment CtxRepr blocks -> BlockID blocks args ->
Bool
lookupBlockGenPermsHint env h blocks blkID =
any (\case GenPermsHintSort -> True
_ -> False) $
lookupBlockHints env h blocks blkID
-- | Test if a 'BlockID' in a 'CFG' has a hint with sort 'JoinPointHintSort'
lookupBlockJoinPointHint :: PermEnv -> FnHandle init ret ->
Assignment CtxRepr blocks -> BlockID blocks args ->
Bool
lookupBlockJoinPointHint env h blocks blkID =
any (\case JoinPointHintSort -> True
_ -> False) $
lookupBlockHints env h blocks blkID
----------------------------------------------------------------------
-- * Permission Sets
----------------------------------------------------------------------
-- FIXME: revisit all the operations in this section and remove those that we no
-- longer need
-- | A permission set associates permissions with expression variables, and also
-- has a stack of "distinguished permissions" that are used for intro rules
data PermSet ps = PermSet { _varPermMap :: NameMap ValuePerm,
_distPerms :: DistPerms ps }
makeLenses ''PermSet
-- | Get all variables that have permissions set in a 'PermSet'
permSetVars :: PermSet ps -> [SomeName CrucibleType]
permSetVars =
map (\case (NameAndElem n _) ->
SomeName n) . NameMap.assocs . view varPermMap
-- | Build a 'PermSet' with only distinguished permissions
distPermSet :: DistPerms ps -> PermSet ps
distPermSet perms = PermSet NameMap.empty perms
-- | The lens for the permissions associated with a given variable
varPerm :: ExprVar a -> Lens' (PermSet ps) (ValuePerm a)
varPerm x =
lens
(\(PermSet nmap _) ->
case NameMap.lookup x nmap of
Just p -> p
Nothing -> ValPerm_True)
(\(PermSet nmap ps) p -> PermSet (NameMap.insert x p nmap) ps)
-- | Set the primary permission for a variable, assuming it is currently the
-- trivial permission @true@
setVarPerm :: ExprVar a -> ValuePerm a -> PermSet ps -> PermSet ps
setVarPerm x p =
over (varPerm x) $ \p' ->
case p' of
ValPerm_True -> p
_ -> error "setVarPerm: permission for variable already set!"
-- | Get a permission list for multiple variables
varPermsMulti :: RAssign Name ns -> PermSet ps -> DistPerms ns
varPermsMulti MNil _ = DistPermsNil
varPermsMulti (ns :>: n) ps =
DistPermsCons (varPermsMulti ns ps) n (ps ^. varPerm n)
-- | Get a permission list for all variable permissions
permSetAllVarPerms :: PermSet ps -> Some DistPerms
permSetAllVarPerms perm_set =
foldr (\(NameAndElem x p) (Some perms) -> Some (DistPermsCons perms x p))
(Some DistPermsNil) (NameMap.assocs $ _varPermMap perm_set)
-- | A determined vars clause says that the variable on the right-hand side is
-- determined (as in the description of 'determinedVars') if all those on the
-- left-hand side are. Note that this is an if and not an iff, as there may be
-- other ways to mark that RHS variable determined.
data DetVarsClause =
DetVarsClause (NameSet CrucibleType) (SomeName CrucibleType)
-- | Union a 'NameSet' to the left-hand side of a 'DetVarsClause'
detVarsClauseAddLHS :: NameSet CrucibleType -> DetVarsClause -> DetVarsClause
detVarsClauseAddLHS names (DetVarsClause lhs rhs) =
DetVarsClause (NameSet.union lhs names) rhs
-- | Add a single variable to the left-hand side of a 'DetVarsClause'
detVarsClauseAddLHSVar :: ExprVar a -> DetVarsClause -> DetVarsClause
detVarsClauseAddLHSVar n (DetVarsClause lhs rhs) =
DetVarsClause (NameSet.insert n lhs) rhs
-- | Generic function to compute the 'DetVarsClause's for a permission
class GetDetVarsClauses a where
getDetVarsClauses ::
a -> ReaderT (PermSet ps) (State (NameSet CrucibleType)) [DetVarsClause]
instance GetDetVarsClauses a => GetDetVarsClauses [a] where
getDetVarsClauses l = concat <$> mapM getDetVarsClauses l
instance GetDetVarsClauses (ExprVar a) where
-- If x has not been visited yet, then return a clause stating that x is
-- determined and add all variables that are potentially determined by the
-- current permissions on x
getDetVarsClauses x =
do seen_vars <- get
perms <- ask
if NameSet.member x seen_vars then return [] else
do modify (NameSet.insert x)
perm_clauses <- getDetVarsClauses (perms ^. varPerm x)
return (DetVarsClause NameSet.empty (SomeName x) :
map (detVarsClauseAddLHSVar x) perm_clauses)
instance GetDetVarsClauses (PermExpr a) where
getDetVarsClauses e
| isDeterminingExpr e =
concat <$> mapM (\(SomeName n) ->
getDetVarsClauses n) (NameSet.toList $ freeVars e)
getDetVarsClauses _ = return []
instance GetDetVarsClauses (PermExprs as) where
getDetVarsClauses PExprs_Nil = return []
getDetVarsClauses (PExprs_Cons es e) =
(++) <$> getDetVarsClauses es <*> getDetVarsClauses e
instance GetDetVarsClauses (ValuePerm a) where
getDetVarsClauses (ValPerm_Eq e) = getDetVarsClauses e
getDetVarsClauses (ValPerm_Conj ps) = concat <$> mapM getDetVarsClauses ps
-- FIXME: For named perms, we currently require the offset to have no free
-- vars, as a simplification, but this could maybe be loosened...?
getDetVarsClauses (ValPerm_Named _ args off)
| NameSet.null (freeVars off) = getDetVarsClauses args
getDetVarsClauses _ = return []
instance GetDetVarsClauses (ValuePerms as) where
getDetVarsClauses ValPerms_Nil = return []
getDetVarsClauses (ValPerms_Cons ps p) =
(++) <$> getDetVarsClauses ps <*> getDetVarsClauses p
instance GetDetVarsClauses (AtomicPerm a) where
getDetVarsClauses (Perm_LLVMField fp) = getDetVarsClauses fp
getDetVarsClauses (Perm_LLVMArray ap) = getDetVarsClauses ap
getDetVarsClauses (Perm_LLVMBlock bp) = getDetVarsClauses bp
getDetVarsClauses (Perm_LLVMBlockShape sh) = getDetVarsClauses sh
getDetVarsClauses (Perm_LLVMFrame frame_perm) =
concat <$> mapM (getDetVarsClauses . fst) frame_perm
getDetVarsClauses (Perm_LOwned _ _ _) = return []
getDetVarsClauses (Perm_LOwnedSimple lops) =
getDetVarsClauses $ RL.map lownedPermPerm lops
getDetVarsClauses _ = return []
instance (1 <= w, KnownNat w, 1 <= sz, KnownNat sz) =>
GetDetVarsClauses (LLVMFieldPerm w sz) where
getDetVarsClauses (LLVMFieldPerm {..}) =
map (detVarsClauseAddLHS (freeVars llvmFieldOffset)) <$> concat <$>
sequence [getDetVarsClauses llvmFieldRW,
getDetVarsClauses llvmFieldLifetime,
getDetVarsClauses llvmFieldContents]
instance (1 <= w, KnownNat w) => GetDetVarsClauses (LLVMArrayPerm w) where
getDetVarsClauses (LLVMArrayPerm {..}) =
map (detVarsClauseAddLHS $
NameSet.unions [freeVars llvmArrayOffset, freeVars llvmArrayLen,
freeVars llvmArrayBorrows]) <$> concat <$>
sequence [getDetVarsClauses llvmArrayRW,
getDetVarsClauses llvmArrayLifetime,
getDetVarsClauses llvmArrayCellShape]
instance (1 <= w, KnownNat w) => GetDetVarsClauses (LLVMBlockPerm w) where
getDetVarsClauses (LLVMBlockPerm {..}) =
map (detVarsClauseAddLHS $
NameSet.unions [freeVars llvmBlockOffset, freeVars llvmBlockLen]) <$>
concat <$> sequence [getDetVarsClauses llvmBlockRW,
getDetVarsClauses llvmBlockLifetime,
getShapeDetVarsClauses llvmBlockShape]
instance GetDetVarsClauses (LLVMFieldShape w) where
getDetVarsClauses (LLVMFieldShape p) = getDetVarsClauses p
-- | Compute the 'DetVarsClause's for a block permission with the given shape
getShapeDetVarsClauses ::
(1 <= w, KnownNat w) => PermExpr (LLVMShapeType w) ->
ReaderT (PermSet ps) (State (NameSet CrucibleType)) [DetVarsClause]
getShapeDetVarsClauses (PExpr_Var x) =
getDetVarsClauses x
getShapeDetVarsClauses (PExpr_NamedShape _ _ _ args) =
-- FIXME: maybe also include the variables determined by the modalities?
getDetVarsClauses args
getShapeDetVarsClauses (PExpr_EqShape len e) =
map (detVarsClauseAddLHS (freeVars len)) <$> getDetVarsClauses e
getShapeDetVarsClauses (PExpr_PtrShape _ _ sh) =
-- FIXME: maybe also include the variables determined by the modalities?
getShapeDetVarsClauses sh
getShapeDetVarsClauses (PExpr_FieldShape fldsh) = getDetVarsClauses fldsh
getShapeDetVarsClauses (PExpr_ArrayShape len _ sh) =
map (detVarsClauseAddLHS (freeVars len)) <$> getDetVarsClauses sh
getShapeDetVarsClauses (PExpr_SeqShape sh1 sh2)
| isJust $ llvmShapeLength sh1 =
(++) <$> getDetVarsClauses sh1 <*> getDetVarsClauses sh2
getShapeDetVarsClauses _ = return []
-- | Compute all the variables whose values are /determined/ by the permissions
-- on the given input variables, other than those variables themselves. The
-- intuitive idea is that permission @x:p@ determines the value of @y@ iff there
-- is always a uniquely determined value of @y@ for any proof of @exists y.x:p@.
determinedVars :: PermSet ps -> RAssign ExprVar ns -> [SomeName CrucibleType]
determinedVars top_perms vars =
let vars_set = NameSet.fromList $ mapToList SomeName vars
multigraph =
evalState (runReaderT (getDetVarsClauses (distPermsToValuePerms $
varPermsMulti vars top_perms))
top_perms)
vars_set in
evalState (determinedVarsForGraph multigraph) vars_set
where
-- Find all variables that are not already marked as determined in our
-- NameSet state but that are determined given the current determined
-- variables, mark these variables as determiend, and then repeat, returning
-- all variables that are found in order
determinedVarsForGraph :: [DetVarsClause] ->
State (NameSet CrucibleType) [SomeName CrucibleType]
determinedVarsForGraph graph =
do det_vars <- concat <$> mapM determinedVarsForClause graph
if det_vars == [] then return [] else
(det_vars ++) <$> determinedVarsForGraph graph
-- If the LHS of a clause has become determined but its RHS is not, return
-- its RHS, otherwise return nothing
determinedVarsForClause :: DetVarsClause ->
State (NameSet CrucibleType) [SomeName CrucibleType]
determinedVarsForClause (DetVarsClause lhs_vars (SomeName rhs_var)) =
do det_vars <- get
if not (NameSet.member rhs_var det_vars) &&
nameSetIsSubsetOf lhs_vars det_vars
then modify (NameSet.insert rhs_var) >> return [SomeName rhs_var]
else return []
-- | Compute the transitive free variables of the permissions on some input list
-- @ns@ of variables, which includes all variables @ns1@ that are free in the
-- permissions associated with @ns@, all the variables @ns2@ free in the
-- permissions of @ns1@, etc. Every variable in the returned list is guaranteed
-- to be listed /after/ (i.e., to the right of where) it is used.
varPermsTransFreeVars :: RAssign ExprVar ns -> PermSet ps ->
Some (RAssign ExprVar)
varPermsTransFreeVars =
helper NameSet.empty . mapToList SomeName
where
helper :: NameSet CrucibleType -> [SomeName CrucibleType] -> PermSet ps ->
Some (RAssign ExprVar)
helper seen_vars ns perms =
let seen_vars' =
foldr (\(SomeName n) -> NameSet.insert n) seen_vars ns
free_vars =
NameSet.unions $
map (\(SomeName n) -> freeVars (perms ^. varPerm n)) ns
new_vars = NameSet.difference free_vars seen_vars' in
case toList new_vars of
[] -> Some MNil
new_ns ->
case (namesListToNames new_ns, helper seen_vars' new_ns perms) of
(SomeRAssign ns', Some rest) ->
Some $ append ns' rest
-- | Initialize the primary permission of a variable to the given permission if
-- the variable is not yet set
initVarPermWith :: ExprVar a -> ValuePerm a -> PermSet ps -> PermSet ps
initVarPermWith x p =
over varPermMap $ \nmap ->
if NameMap.member x nmap then nmap else NameMap.insert x p nmap
-- | Initialize the primary permission of a variable to @true@ if it is not set
initVarPerm :: ExprVar a -> PermSet ps -> PermSet ps
initVarPerm x =
initVarPermWith x ValPerm_True
-- | Set the primary permissions for a sequence of variables to @true@
initVarPerms :: RAssign Name (as :: RList CrucibleType) -> PermSet ps ->
PermSet ps
initVarPerms MNil perms = perms
initVarPerms (ns :>: n) perms = initVarPerms ns $ initVarPerm n perms
-- | The lens for a particular distinguished perm, checking that it is indeed
-- associated with the given variable
distPerm :: Member ps a -> ExprVar a -> Lens' (PermSet ps) (ValuePerm a)
distPerm memb x = distPerms . nthVarPerm memb x
-- | The lens for the distinguished perm at the top of the stack, checking that
-- it has the given variable
topDistPerm :: ExprVar a -> Lens' (PermSet (ps :> a)) (ValuePerm a)
topDistPerm x = distPerms . distPermsHead x
-- | Modify the distinguished permission stack of a 'PermSet'
modifyDistPerms :: (DistPerms ps1 -> DistPerms ps2) ->
PermSet ps1 -> PermSet ps2
modifyDistPerms f (PermSet perms dperms) = PermSet perms $ f dperms
-- | Get all the permissions in the permission set as a sequence of
-- distinguished permissions
getAllPerms :: PermSet ps -> Some DistPerms
getAllPerms perms = helper (NameMap.assocs $ perms ^. varPermMap) where
helper :: [NameAndElem ValuePerm] -> Some DistPerms
helper [] = Some DistPermsNil
helper (NameAndElem x p : xps) =
case helper xps of
Some ps -> Some $ DistPermsCons ps x p
-- | Delete permission @x:p@ from the permission set, assuming @x@ has precisely
-- permissions @p@, replacing it with @x:true@
deletePerm :: ExprVar a -> ValuePerm a -> PermSet ps -> PermSet ps
deletePerm x p =
over (varPerm x) $ \p' ->
if p' == p then ValPerm_True else error "deletePerm"
-- | Push a new distinguished permission onto the top of the stack
pushPerm :: ExprVar a -> ValuePerm a -> PermSet ps -> PermSet (ps :> a)
pushPerm x p (PermSet nmap ps) = PermSet nmap (DistPermsCons ps x p)
-- | Pop the top distinguished permission off of the stack
popPerm :: ExprVar a -> PermSet (ps :> a) -> (PermSet ps, ValuePerm a)
popPerm x (PermSet nmap pstk) =
(PermSet nmap (pstk ^. distPermsTail), pstk ^. distPermsHead x)
-- | Drop the top distinguished permission on the stack
dropPerm :: ExprVar a -> PermSet (ps :> a) -> PermSet ps
dropPerm x = fst . popPerm x
| GaloisInc/saw-script | heapster-saw/src/Verifier/SAW/Heapster/Permissions.hs | bsd-3-clause | 349,676 | 6,114 | 128 | 75,992 | 83,972 | 44,405 | 39,567 | -1 | -1 |
{-# LANGUAGE DeriveGeneric, FlexibleInstances, StandaloneDeriving #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Kraken.Web.TargetGraph where
import Control.Applicative
import Data.Aeson
import Data.Graph.Wrapper
import GHC.Generics
import Kraken.ActionM
import Kraken.Graph
data WebNode = WebNode {
monitor :: Maybe TargetName
}
deriving (Generic)
toWebNode :: Node -> WebNode
toWebNode node =
WebNode (fmap nodeMonitorName (Kraken.Graph.nodeMonitor node))
instance FromJSON WebNode
instance ToJSON WebNode
instance FromJSON TargetName
instance ToJSON TargetName
newtype TargetGraph = TargetGraph (Graph TargetName WebNode)
deriving (Generic)
instance FromJSON TargetGraph where
parseJSON value = TargetGraph <$> fromListLenient <$> parseJSON value
instance ToJSON TargetGraph where
toJSON (TargetGraph g) = toJSON $ toList g
toTargetGraph :: Graph TargetName Node -> TargetGraph
toTargetGraph = TargetGraph . fmap toWebNode
| zalora/kraken | src/Kraken/Web/TargetGraph.hs | bsd-3-clause | 1,015 | 0 | 10 | 196 | 235 | 124 | 111 | 27 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ParallelListComp #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.SubLayouts
-- Description : A layout combinator that allows layouts to be nested.
-- Copyright : (c) 2009 Adam Vogt
-- License : BSD-style (see xmonad/LICENSE)
--
-- Maintainer : vogt.adam@gmail.com
-- Stability : unstable
-- Portability : unportable
--
-- A layout combinator that allows layouts to be nested.
--
-----------------------------------------------------------------------------
module XMonad.Layout.SubLayouts (
-- * Usage
-- $usage
subLayout,
subTabbed,
pushGroup, pullGroup,
pushWindow, pullWindow,
onGroup, toSubl, mergeDir,
GroupMsg(..),
Broadcast(..),
defaultSublMap,
Sublayout,
-- * Screenshots
-- $screenshots
-- * Todo
-- $todo
)
where
import XMonad.Layout.Circle () -- so haddock can find the link
import XMonad.Layout.Decoration(Decoration, DefaultShrinker)
import XMonad.Layout.LayoutModifier(LayoutModifier(handleMess, modifyLayout,
redoLayout),
ModifiedLayout(..))
import XMonad.Layout.Simplest(Simplest(..))
import XMonad.Layout.Tabbed(shrinkText,
TabbedDecoration, addTabs)
import XMonad.Layout.WindowNavigation(Navigate(Apply))
import XMonad.Util.Invisible(Invisible(..))
import XMonad.Util.Types(Direction2D(..))
import XMonad hiding (def)
import XMonad.Prelude
import Control.Arrow(Arrow(second, (&&&)))
import qualified XMonad as X
import qualified XMonad.Layout.BoringWindows as B
import qualified XMonad.StackSet as W
import qualified Data.Map as M
import Data.Map(Map)
import qualified Data.Set as S
-- $screenshots
--
-- <<http://haskell.org/sitewiki/images/thumb/8/8b/Xmonad-SubLayouts-xinerama.png/480px-Xmonad-SubLayouts-xinerama.png>>
--
-- Larger version: <http://haskell.org/sitewiki/images/8/8b/Xmonad-SubLayouts-xinerama.png>
-- $todo
-- /Issue 288/
--
-- "XMonad.Layout.ResizableTile" assumes that its environment
-- contains only the windows it is running: sublayouts are currently run with
-- the stack containing only the windows passed to it in its environment, but
-- any changes that the layout makes are not merged back.
--
-- Should the behavior be made optional?
--
-- /Features/
--
-- * suggested managehooks for merging specific windows, or the apropriate
-- layout based hack to find out the number of groups currently showed, but
-- the size of current window groups is not available (outside of this
-- growing module)
--
-- /SimpleTabbed as a SubLayout/
--
-- 'subTabbed' works well, but it would be more uniform to avoid the use of
-- addTabs, with the sublayout being Simplest (but
-- 'XMonad.Layout.Tabbed.simpleTabbed' is this...). The only thing to be
-- gained by fixing this issue is the ability to mix and match decoration
-- styles. Better compatibility with some other layouts of which I am not
-- aware could be another benefit.
--
-- 'simpleTabbed' (and other decorated layouts) fail horribly when used as
-- subLayouts:
--
-- * decorations stick around: layout is run after being told to Hide
--
-- * mouse events do not change focus: the group-ungroup does not respect
-- the focus changes it wants?
--
-- * sending ReleaseResources before running it makes xmonad very slow, and
-- still leaves borders sticking around
--
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Layout.SubLayouts
-- > import XMonad.Layout.WindowNavigation
--
-- Using "XMonad.Layout.BoringWindows" is optional and it allows you to add a
-- keybinding to skip over the non-visible windows.
--
-- > import XMonad.Layout.BoringWindows
--
-- Then edit your @layoutHook@ by adding the 'subTabbed' layout modifier:
--
-- > myLayout = windowNavigation $ subTabbed $ boringWindows $
-- > Tall 1 (3/100) (1/2) ||| etc..
-- > main = xmonad def { layoutHook = myLayout }
--
-- "XMonad.Layout.WindowNavigation" is used to specify which windows to merge,
-- and it is not integrated into the modifier because it can be configured, and
-- works best as the outer modifier.
--
-- Then to your keybindings add:
--
-- > , ((modm .|. controlMask, xK_h), sendMessage $ pullGroup L)
-- > , ((modm .|. controlMask, xK_l), sendMessage $ pullGroup R)
-- > , ((modm .|. controlMask, xK_k), sendMessage $ pullGroup U)
-- > , ((modm .|. controlMask, xK_j), sendMessage $ pullGroup D)
-- >
-- > , ((modm .|. controlMask, xK_m), withFocused (sendMessage . MergeAll))
-- > , ((modm .|. controlMask, xK_u), withFocused (sendMessage . UnMerge))
-- >
-- > , ((modm .|. controlMask, xK_period), onGroup W.focusUp')
-- > , ((modm .|. controlMask, xK_comma), onGroup W.focusDown')
--
-- These additional keybindings require the optional
-- "XMonad.Layout.BoringWindows" layoutModifier. The focus will skip over the
-- windows that are not focused in each sublayout.
--
-- > , ((modm, xK_j), focusDown)
-- > , ((modm, xK_k), focusUp)
--
-- A 'submap' can be used to make modifying the sublayouts using 'onGroup' and
-- 'toSubl' simpler:
--
-- > ,((modm, xK_s), submap $ defaultSublMap conf)
--
-- /NOTE:/ is there some reason that @asks config >>= submap . defaultSublMap@
-- could not be used in the keybinding instead? It avoids having to explicitly
-- pass the conf.
--
-- For more detailed instructions, see:
--
-- "XMonad.Doc.Extending#Editing_the_layout_hook"
-- "XMonad.Doc.Extending#Adding_key_bindings"
-- | The main layout modifier arguments:
--
-- @subLayout advanceInnerLayouts innerLayout outerLayout@
--
-- [@advanceInnerLayouts@] When a new group at index @n@ in the outer layout
-- is created (even with one element), the @innerLayout@ is used as the
-- layout within that group after being advanced with @advanceInnerLayouts !!
-- n@ 'NextLayout' messages. If there is no corresponding element in the
-- @advanceInnerLayouts@ list, then @innerLayout@ is not given any 'NextLayout'
-- messages.
--
-- [@innerLayout@] The single layout given to be run as a sublayout.
--
-- [@outerLayout@] The layout that determines the rectangles given to each
-- group.
--
-- Ex. The second group is 'Tall', the third is 'Circle', all others are tabbed
-- with:
--
-- > myLayout = addTabs shrinkText def
-- > $ subLayout [0,1,2] (Simplest ||| Tall 1 0.2 0.5 ||| Circle)
-- > $ Tall 1 0.2 0.5 ||| Full
subLayout :: [Int] -> subl a -> l a -> ModifiedLayout (Sublayout subl) l a
subLayout nextLayout sl = ModifiedLayout (Sublayout (I []) (nextLayout,sl) [])
-- | @subTabbed@ is a use of 'subLayout' with 'addTabs' to show decorations.
subTabbed :: (Eq a, LayoutModifier (Sublayout Simplest) a, LayoutClass l a) =>
l a -> ModifiedLayout (Decoration TabbedDecoration DefaultShrinker)
(ModifiedLayout (Sublayout Simplest) l) a
subTabbed x = addTabs shrinkText X.def $ subLayout [] Simplest x
-- | @defaultSublMap@ is an attempt to create a set of keybindings like the
-- defaults ones but to be used as a 'submap' for sending messages to the
-- sublayout.
defaultSublMap :: XConfig l -> Map (KeyMask, KeySym) (X ())
defaultSublMap XConfig{ modMask = modm } = M.fromList
[((modm, xK_space), toSubl NextLayout),
((modm, xK_j), onGroup W.focusDown'),
((modm, xK_k), onGroup W.focusUp'),
((modm, xK_h), toSubl Shrink),
((modm, xK_l), toSubl Expand),
((modm, xK_Tab), onGroup W.focusDown'),
((modm .|. shiftMask, xK_Tab), onGroup W.focusUp'),
((modm, xK_m), onGroup focusMaster'),
((modm, xK_comma), toSubl $ IncMasterN 1),
((modm, xK_period), toSubl $ IncMasterN (-1)),
((modm, xK_Return), onGroup swapMaster')
]
where
-- should these go into XMonad.StackSet?
focusMaster' st = let (notEmpty -> f :| fs) = W.integrate st
in W.Stack f [] fs
swapMaster' (W.Stack f u d) = W.Stack f [] $ reverse u ++ d
data Sublayout l a = Sublayout
{ delayMess :: Invisible [] (SomeMessage,a)
-- ^ messages are handled when running the layout,
-- not in the handleMessage, I'm not sure that this
-- is necessary
, def :: ([Int], l a) -- ^ how many NextLayout messages to send to newly
-- populated layouts. If there is no corresponding
-- index, then don't send any.
, subls :: [(l a,W.Stack a)]
-- ^ The sublayouts and the stacks they manage
}
deriving (Read,Show)
-- | Groups assumes this invariant:
-- M.keys gs == map W.focus (M.elems gs) (ignoring order)
-- All windows in the workspace are in the Map
--
-- The keys are visible windows, the rest are hidden.
--
-- This representation probably simplifies the internals of the modifier.
type Groups a = Map a (W.Stack a)
-- | Stack of stacks, a simple representation of groups for purposes of focus.
type GroupStack a = W.Stack (W.Stack a)
-- | GroupMsg take window parameters to determine which group the action should
-- be applied to
data GroupMsg a
= UnMerge a -- ^ free the focused window from its tab stack
| UnMergeAll a
-- ^ separate the focused group into singleton groups
| Merge a a -- ^ merge the first group into the second group
| MergeAll a
-- ^ make one large group, keeping the parameter focused
| Migrate a a
-- ^ used to the window named in the first argument to the
-- second argument's group, this may be replaced by a
-- combination of 'UnMerge' and 'Merge'
| WithGroup (W.Stack a -> X (W.Stack a)) a
| SubMessage SomeMessage a
-- ^ the sublayout with the given window will get the message
-- | merge the window that would be focused by the function when applied to the
-- W.Stack of all windows, with the current group removed. The given window
-- should be focused by a sublayout. Example usage: @withFocused (sendMessage .
-- mergeDir W.focusDown')@
mergeDir :: (W.Stack Window -> W.Stack Window) -> Window -> GroupMsg Window
mergeDir f = WithGroup g
where g cs = do
let onlyOthers = W.filter (`notElem` W.integrate cs)
(`whenJust` sendMessage . Merge (W.focus cs) . W.focus . f)
. (onlyOthers =<<)
=<< currentStack
return cs
newtype Broadcast = Broadcast SomeMessage -- ^ send a message to all sublayouts
instance Message Broadcast
instance Typeable a => Message (GroupMsg a)
-- | @pullGroup@, @pushGroup@ allow you to merge windows or groups inheriting
-- the position of the current window (pull) or the other window (push).
--
-- @pushWindow@ and @pullWindow@ move individual windows between groups. They
-- are less effective at preserving window positions.
pullGroup,pushGroup,pullWindow,pushWindow :: Direction2D -> Navigate
pullGroup = mergeNav (\o c -> sendMessage $ Merge o c)
pushGroup = mergeNav (\o c -> sendMessage $ Merge c o)
pullWindow = mergeNav (\o c -> sendMessage $ Migrate o c)
pushWindow = mergeNav (\o c -> sendMessage $ Migrate c o)
mergeNav :: (Window -> Window -> X ()) -> Direction2D -> Navigate
mergeNav f = Apply (withFocused . f)
-- | Apply a function on the stack belonging to the currently focused group. It
-- works for rearranging windows and for changing focus.
onGroup :: (W.Stack Window -> W.Stack Window) -> X ()
onGroup f = withFocused (sendMessage . WithGroup (return . f))
-- | Send a message to the currently focused sublayout.
toSubl :: (Message a) => a -> X ()
toSubl m = withFocused (sendMessage . SubMessage (SomeMessage m))
instance forall l. (Read (l Window), Show (l Window), LayoutClass l Window) => LayoutModifier (Sublayout l) Window where
modifyLayout Sublayout{ subls = osls } (W.Workspace i la st) r = do
let gs' = updateGroup st $ toGroups osls
st' = W.filter (`elem` M.keys gs') =<< st
updateWs gs'
oldStack <- currentStack
setStack st'
runLayout (W.Workspace i la st') r <* setStack oldStack
-- FIXME: merge back reordering, deletions?
redoLayout Sublayout{ delayMess = I ms, def = defl, subls = osls } _r st arrs = do
let gs' = updateGroup st $ toGroups osls
sls <- fromGroups defl st gs' osls
let newL :: LayoutClass l Window => Rectangle -> WorkspaceId -> l Window -> Bool
-> Maybe (W.Stack Window) -> X ([(Window, Rectangle)], l Window)
newL rect n ol isNew sst = do
orgStack <- currentStack
let handle l (y,_)
| not isNew = fromMaybe l <$> handleMessage l y
| otherwise = return l
kms = filter ((`elem` M.keys gs') . snd) ms
setStack sst
nl <- foldM handle ol $ filter ((`elem` W.integrate' sst) . snd) kms
result <- runLayout (W.Workspace n nl sst) rect
setStack orgStack -- FIXME: merge back reordering, deletions?
return $ fromMaybe nl `second` result
(urls,ssts) = unzip [ (newL gr i l isNew sst, sst)
| (isNew,(l,_st)) <- sls
| i <- map show [ 0 :: Int .. ]
| (k,gr) <- arrs, let sst = M.lookup k gs' ]
arrs' <- sequence urls
sls' <- return . Sublayout (I []) defl . map snd <$> fromGroups defl st gs'
[ (l,s) | (_,l) <- arrs' | (Just s) <- ssts ]
return (concatMap fst arrs', sls')
handleMess (Sublayout (I ms) defl sls) m
| Just (SubMessage sm w) <- fromMessage m =
return $ Just $ Sublayout (I ((sm,w):ms)) defl sls
| Just (Broadcast sm) <- fromMessage m = do
ms' <- fmap (zip (repeat sm) . W.integrate') currentStack
return $ if null ms' then Nothing
else Just $ Sublayout (I $ ms' ++ ms) defl sls
| Just B.UpdateBoring <- fromMessage m = do
let bs = concatMap unfocused $ M.elems gs
ws <- gets (W.workspace . W.current . windowset)
flip sendMessageWithNoRefresh ws $ B.Replace "Sublayouts" bs
return Nothing
| Just (WithGroup f w) <- fromMessage m
, Just g <- M.lookup w gs = do
g' <- f g
let gs' = M.insert (W.focus g') g' $ M.delete (W.focus g) gs
when (gs' /= gs) $ updateWs gs'
when (w /= W.focus g') $ windows (W.focusWindow $ W.focus g')
return Nothing
| Just (MergeAll w) <- fromMessage m =
let gs' = fmap (M.singleton w)
$ (focusWindow' w =<<) $ W.differentiate
$ concatMap W.integrate $ M.elems gs
in maybe (return Nothing) fgs gs'
| Just (UnMergeAll w) <- fromMessage m =
let ws = concatMap W.integrate $ M.elems gs
_ = w :: Window
mkSingleton f = M.singleton f (W.Stack f [] [])
in fgs $ M.unions $ map mkSingleton ws
| Just (Merge x y) <- fromMessage m
, Just (W.Stack _ xb xn) <- findGroup x
, Just yst <- findGroup y =
let zs = W.Stack x xb (xn ++ W.integrate yst)
in fgs $ M.insert x zs $ M.delete (W.focus yst) gs
| Just (UnMerge x) <- fromMessage m =
fgs . M.fromList . map (W.focus &&& id) . M.elems
$ M.mapMaybe (W.filter (x/=)) gs
-- XXX sometimes this migrates an incorrect window, why?
| Just (Migrate x y) <- fromMessage m
, Just xst <- findGroup x
, Just (W.Stack yf yu yd) <- findGroup y =
let zs = W.Stack x (yf:yu) yd
nxsAdd = maybe id (\e -> M.insert (W.focus e) e) $ W.filter (x/=) xst
in fgs $ nxsAdd $ M.insert x zs $ M.delete yf gs
| otherwise = join <$> sequenceA (catchLayoutMess <$> fromMessage m)
where gs = toGroups sls
fgs gs' = do
st <- currentStack
Just . Sublayout (I ms) defl . map snd <$> fromGroups defl st gs' sls
findGroup z = mplus (M.lookup z gs) $ listToMaybe
$ M.elems $ M.filter ((z `elem`) . W.integrate) gs
catchLayoutMess :: LayoutMessages -> X (Maybe (Sublayout l Window))
catchLayoutMess x = do
let m' = x `asTypeOf` (undefined :: LayoutMessages)
ms' <- zip (repeat $ SomeMessage m') . W.integrate'
<$> currentStack
return $ do guard $ not $ null ms'
Just $ Sublayout (I $ ms' ++ ms) defl sls
currentStack :: X (Maybe (W.Stack Window))
currentStack = gets (W.stack . W.workspace . W.current . windowset)
-- | update Group to follow changes in the workspace
updateGroup :: Ord a => Maybe (W.Stack a) -> Groups a -> Groups a
updateGroup Nothing _ = mempty
updateGroup (Just st) gs = fromGroupStack (toGroupStack gs st)
-- | rearrange the windowset to put the groups of tabs next to each other, so
-- that the stack of tabs stays put.
updateWs :: Groups Window -> X ()
updateWs = windowsMaybe . updateWs'
updateWs' :: Groups Window -> WindowSet -> Maybe WindowSet
updateWs' gs ws = do
w <- W.stack . W.workspace . W.current $ ws
let w' = flattenGroupStack . toGroupStack gs $ w
guard $ w /= w'
pure $ W.modify' (const w') ws
-- | Flatten a stack of stacks.
flattenGroupStack :: GroupStack a -> W.Stack a
flattenGroupStack (W.Stack (W.Stack f lf rf) ls rs) =
let l = lf ++ concatMap (reverse . W.integrate) ls
r = rf ++ concatMap W.integrate rs
in W.Stack f l r
-- | Extract Groups from a stack of stacks.
fromGroupStack :: (Ord a) => GroupStack a -> Groups a
fromGroupStack = M.fromList . map (W.focus &&& id) . W.integrate
-- | Arrange a stack of windows into a stack of stacks, according to (possibly
-- outdated) Groups.
--
-- Assumes that the groups are disjoint and there are no duplicates in the
-- stack; will result in additional duplicates otherwise. This is a reasonable
-- assumption—the rest of xmonad will mishave too—but it isn't checked
-- anywhere and there had been bugs breaking this assumption in the past.
toGroupStack :: (Ord a) => Groups a -> W.Stack a -> GroupStack a
toGroupStack gs st@(W.Stack f ls rs) =
W.Stack (fromJust (lu f)) (mapMaybe lu ls) (mapMaybe lu rs)
where
wset = S.fromList (W.integrate st)
dead = W.filter (`S.member` wset) -- drop dead windows or entire groups
refocus s | f `elem` W.integrate s -- sync focus/order of current group
= W.filter (`elem` W.integrate s) st
| otherwise = pure s
gs' = mapGroups (refocus <=< dead) gs
gset = S.fromList . concatMap W.integrate . M.elems $ gs'
-- after refocus, f is either the focused window of some group, or not in
-- gs' at all, so `lu f` is never Nothing
lu w | w `S.member` gset = w `M.lookup` gs'
| otherwise = Just (W.Stack w [] []) -- singleton groups for new wins
mapGroups :: (Ord a) => (W.Stack a -> Maybe (W.Stack a)) -> Groups a -> Groups a
mapGroups f = M.fromList . map (W.focus &&& id) . mapMaybe f . M.elems
-- | focusWindow'. focus an element of a stack, is Nothing if that element is
-- absent. See also 'W.focusWindow'
focusWindow' :: (Eq a) => a -> W.Stack a -> Maybe (W.Stack a)
focusWindow' w st = do
guard $ w `elem` W.integrate st
return $ until ((w ==) . W.focus) W.focusDown' st
-- update only when Just
windowsMaybe :: (WindowSet -> Maybe WindowSet) -> X ()
windowsMaybe f = do
xst <- get
ws <- gets windowset
let up fws = put xst { windowset = fws }
maybe (return ()) up $ f ws
unfocused :: W.Stack a -> [a]
unfocused x = W.up x ++ W.down x
toGroups :: (Ord a) => [(a1, W.Stack a)] -> Map a (W.Stack a)
toGroups ws = M.fromList . map (W.focus &&& id) . nubBy (on (==) W.focus)
$ map snd ws
-- | restore the default layout for each group. It needs the X monad to switch
-- the default layout to a specific one (handleMessage NextLayout)
fromGroups :: (LayoutClass layout a, Ord k) =>
([Int], layout a)
-> Maybe (W.Stack k)
-> Groups k
-> [(layout a, b)]
-> X [(Bool,(layout a, W.Stack k))]
fromGroups (skips,defl) st gs sls = do
defls <- mapM (iterateM nextL defl !!) skips
return $ fromGroups' defl defls st gs (map fst sls)
where nextL l = fromMaybe l <$> handleMessage l (SomeMessage NextLayout)
iterateM f = iterate (>>= f) . return
fromGroups' :: (Ord k) => a -> [a] -> Maybe (W.Stack k) -> Groups k -> [a]
-> [(Bool,(a, W.Stack k))]
fromGroups' defl defls st gs sls =
[ (isNew,fromMaybe2 (dl, single w) (l, M.lookup w gs))
| l <- map Just sls ++ repeat Nothing, let isNew = isNothing l
| dl <- defls ++ repeat defl
| w <- W.integrate' $ W.filter (`notElem` unfocs) =<< st ]
where unfocs = unfocused =<< M.elems gs
single w = W.Stack w [] []
fromMaybe2 (a,b) (x,y) = (fromMaybe a x, fromMaybe b y)
-- this would be much cleaner with some kind of data-accessor
setStack :: Maybe (W.Stack Window) -> X ()
setStack x = modify (\s -> s { windowset = (windowset s)
{ W.current = (W.current $ windowset s)
{ W.workspace = (W.workspace $ W.current $ windowset s) { W.stack = x }}}})
| xmonad/xmonad-contrib | XMonad/Layout/SubLayouts.hs | bsd-3-clause | 21,855 | 35 | 23 | 5,729 | 5,317 | 2,841 | 2,476 | 259 | 1 |
-- Copyright (c) 2017 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS''
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -Wall -Werror #-}
{-# LANGUAGE MultiParamTypeClasses, FlexibleContexts, FlexibleInstances #-}
module IR.Common.Alloc(
Allocator(..),
Allocation(..)
) where
import Data.Hashable
import IR.Common.Names
import IR.Common.Ptr
import IR.Common.Rename.Class
import IR.Common.RenameType.Class
import Text.Format
import Text.XML.Expat.Pickle hiding (Node)
import Text.XML.Expat.Tree(NodeG)
-- | A description of a source for allocated bytes, to be used in
-- 'Allocation's.
data Allocator =
-- | Use alloca (stack allocator).
Alloca
-- | Call a function, passing in a size parameter.
| Direct {
directName :: !Globalname
}
-- | Make a call to an intrinsic.
| Intrinsic {
intrinsicName :: !Globalname
}
deriving (Eq, Ord)
-- | A description of object allocations. For tagged data, this
-- includes the initialization of the tag data.
data Allocation tagty nativety expty =
Allocation {
-- | Allocator to use.
allocSrc :: !Allocator,
-- | Kind of object to allocate.
allocType :: !(Ptr tagty nativety),
-- | Possibly-empty list of allocation sizes. Used to supply
-- sizes to unsized arrays
allocSizes :: ![expty]
}
deriving (Eq, Ord)
instance Hashable Allocator where
hashWithSalt s Alloca = s `hashWithSalt` (0 :: Int)
hashWithSalt s Direct { directName = name } =
s `hashWithSalt` (1 :: Int) `hashWithSalt` name
hashWithSalt s Intrinsic { intrinsicName = name } =
s `hashWithSalt` (2 :: Int) `hashWithSalt` name
instance (Hashable expty, Hashable tagty, Hashable nativety) =>
Hashable (Allocation tagty nativety expty) where
hashWithSalt s Allocation { allocSrc = src, allocType = ty,
allocSizes = sizes } =
s `hashWithSalt` src `hashWithSalt` ty `hashWithSalt` sizes
instance (Rename Id expty) =>
Rename Id (Allocation tagty nativety expty) where
rename f a @ Allocation { allocSizes = sizes } =
a { allocSizes = map (rename f) sizes }
instance (RenameType Typename expty, RenameType Typename nativety) =>
RenameType Typename (Allocation tagty nativety expty) where
renameType f a @ Allocation { allocType = ty, allocSizes = sizes } =
a { allocType = fmap (renameType f) ty,
allocSizes = map (renameType f) sizes }
instance Format Allocator where
format Alloca = string "alloca"
format Direct { directName = name } = string "direct" <+> format name
format Intrinsic { intrinsicName = name } =
string "intrinsic" <+> format name
allocaPickler :: (GenericXMLString tag, Show tag,
GenericXMLString text, Show text) =>
PU [NodeG [] tag text] Allocator
allocaPickler = xpWrap (const Alloca, const ())
(xpElemNodes (gxFromString "Alloca") xpUnit)
directPickler :: (GenericXMLString tag, Show tag,
GenericXMLString text, Show text) =>
PU [NodeG [] tag text] Allocator
directPickler =
let
revfunc Direct { directName = name } = name
revfunc _ = error "cannot convert"
in
xpWrap (Direct, revfunc)
(xpElemNodes (gxFromString "Direct") xpickle)
intrinsicPickler :: (GenericXMLString tag, Show tag,
GenericXMLString text, Show text) =>
PU [NodeG [] tag text] Allocator
intrinsicPickler =
let
revfunc Intrinsic { intrinsicName = name } = name
revfunc _ = error "cannot convert"
in
xpWrap (Intrinsic, revfunc)
(xpElemNodes (gxFromString "Intrinsic") xpickle)
instance (GenericXMLString tag, Show tag, GenericXMLString text, Show text) =>
XmlPickler [NodeG [] tag text] Allocator where
xpickle =
let
picker Alloca = 0
picker Direct {} = 1
picker Intrinsic {} = 1
in
xpAlt picker [allocaPickler, directPickler, intrinsicPickler]
instance (GenericXMLString tag, Show tag, GenericXMLString text, Show text,
XmlPickler [NodeG [] tag text] tagty,
XmlPickler [NodeG [] tag text] nativety,
XmlPickler [NodeG [] tag text] expty) =>
XmlPickler [NodeG [] tag text] (Allocation tagty nativety expty) where
xpickle =
xpWrap (\(src, ty, sizes) -> Allocation { allocSrc = src, allocType = ty,
allocSizes = sizes },
\Allocation { allocSrc = src, allocType = ty,
allocSizes = sizes } ->(src, ty, sizes))
(xpElemNodes (gxFromString "Allocation")
(xpTriple (xpElemNodes (gxFromString "src") xpickle)
(xpElemNodes (gxFromString "type") xpickle)
(xpElemNodes (gxFromString "sizes")
(xpList xpickle))))
| emc2/chill | src/IR/Common/Alloc.hs | bsd-3-clause | 6,374 | 2 | 14 | 1,609 | 1,360 | 755 | 605 | 107 | 2 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedStrings #-}
module Serv.Server.Core.Config.ServerData
( ServerConfig(..)
, defaultConfig
) where
import Control.Exception
import Data.Aeson (FromJSON (..), ToJSON (..),
Value (..), object, (.:), (.:?),
(.=))
import qualified Data.Aeson as JS
import qualified Data.Aeson.Types as JS
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Monoid hiding ((<>))
import Data.Semigroup (Semigroup (..))
import Data.Text (Text)
import qualified Data.Yaml as Y
import qualified Data.Yaml as Yaml
import GHC.Generics
import Serv.Server.Core.Config.Types
import Serv.Server.Core.Config.Types
import Serv.Util.GenericMonoid
import Serv.Util.Validate
validateConfig :: RawConfig -> Either [String] ServerConfig
validateConfig (RawConfig apiPort sysPort serverName logConfig) =
runValidate $
ServerConfig <$> validatePort apiPort
<*> validatePort sysPort
<*> validateServerName serverName
<*> validateLog (LogConfig [None] None) logConfig
validatePort :: Last Int -> Validate Int
validatePort = requiredField "a port number is required"
validateServerName :: Last ServerName -> Validate ServerName
validateServerName = requiredField "server name is required"
data RawConfig = RawConfig
(Last Port) -- API port
(Last Port) -- Management port
(Last ServerName) -- server name
(Last RawLogConfig)
deriving (Eq, Show, Generic)
instance Semigroup RawConfig where
(<>) = gmappend
instance Monoid RawConfig where
mempty = gmempty
mappend = (<>)
instance ToJSON RawConfig where
toJSON (RawConfig apiPort sysPort serverName serverLog) =
object [ "apiPort" .= apiPort
, "sysPort" .= sysPort
, "serverName" .= serverName
, "log" .= serverLog
]
instance FromJSON RawConfig where
parseJSON =
JS.withObject "RawConfig" $ \o ->
RawConfig <$> (Last <$> (o .:? "apiPort"))
<*> (Last <$> (o .:? "sysPort"))
<*> (Last <$> (o .:? "serverName"))
<*> (Last <$> (o .:? "log"))
readConfigFile :: FilePath -> IO RawConfig
readConfigFile file = either throwIO return =<< Yaml.decodeFileEither file
showConfig :: RawConfig -> BS.ByteString
showConfig = Yaml.encode
| orangefiredragon/bear | src/Serv/Server/Core/Config/ServerConfigData.hs | bsd-3-clause | 2,907 | 0 | 15 | 984 | 628 | 367 | 261 | 64 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Coordinate where
import Data.Data
import Data.Typeable
data Coordinates = Coordinates { x :: Float, y :: Float } deriving (Data, Typeable, Show)
| timorantalaiho/pong11 | src/Coordinate.hs | bsd-3-clause | 190 | 0 | 8 | 29 | 51 | 31 | 20 | 5 | 0 |
module Graphics.OpenGL.Basic (
module Graphics.OpenGL.Types
, Scope
, HasScope(..)
, OpenGL
, GLLoader
-- * OpenGL Initialization
, initGL
-- * Convenience Functions
, runGL
, ifM
, unlessM
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Trans
import Foreign.C.String
import Graphics.OpenGL.Internal.Scope
import Graphics.OpenGL.Types
type OpenGL m = ReaderT Scope m
-- | Load the OpenGL functions and query available extensions.
--
-- A valid OpenGL context must be made current before calling this function.
-- The given function is used to load the OpenGL functions, which is typically
-- provided by your windowing utility.
--
-- The scope is /only/ valid for the context it was initialized in. Any
-- attempt to use it with other contexts is undefined behaviour.
initGL :: GLLoader -> IO Scope
initGL = initScope
-- | Run the given sequence of OpenGL commands with the given scope.
runGL :: e -> ReaderT e m a -> m a
runGL = flip runReaderT
-- | Run the monadic action if the condition is met.
ifM :: Monad m => m Bool -> m () -> m ()
ifM c m = do { c' <- c; when c' m }
-- | Run the monadic action if the condition is not met.
unlessM :: Monad m => m Bool -> m () -> m ()
unlessM c m = do { c' <- c; when (not c') m }
| polarina/opengl-wrangler | Graphics/OpenGL/Basic.hs | bsd-3-clause | 1,275 | 2 | 9 | 255 | 282 | 159 | 123 | 25 | 1 |
-- |
-- Module: Control.Wire.Event
-- Copyright: (c) 2013 Ertugrul Soeylemez
-- License: BSD3
-- Maintainer: Ertugrul Soeylemez <es@ertes.de>
module Control.Wire.Event
( -- * Events
EventLike(toEvent),
Event,
UniqueEvent,
-- * Time-based
at,
never,
now,
periodic,
periodicList,
-- * Signal analysis
became,
noLonger,
-- * Extracting
onUEventM,
onU,
occurredU,
eventU,
-- * Modifiers
(<&),
(&>),
(<!>),
dropE,
dropWhileE,
filterE,
merge,
mergeL,
mergeR,
notYet,
once,
takeE,
takeWhileE,
-- * Scans
accumE,
accum1E,
iterateE,
-- ** Special scans
maximumE,
minimumE,
productE,
sumE
)
where
import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.Fix
import Control.Wire.Core
import Control.Wire.Session
import Control.Wire.Unsafe.Event
import Data.Fixed
import Data.Monoid
-- | Merge events with the leftmost event taking precedence. Equivalent
-- to using the monoid interface with 'First'. Infixl 5.
--
-- * Depends: now on both.
--
-- * Inhibits: when any of the two wires inhibit.
(<&) :: (Monad m, EventLike ev) => Wire s e m a (ev b) -> Wire s e m a (ev b) -> Wire s e m a (ev b)
(<&) = liftA2 mergeL
infixl 5 <&
-- | Merge events with the rightmost event taking precedence.
-- Equivalent to using the monoid interface with 'Last'. Infixl 5.
--
-- * Depends: now on both.
--
-- * Inhibits: when any of the two wires inhibit.
(&>) :: (Monad m, EventLike ev) => Wire s e m a (ev b) -> Wire s e m a (ev b) -> Wire s e m a (ev b)
(&>) = liftA2 mergeR
infixl 5 &>
-- | Merge events discarding their values. Infixl 5.
--
-- * Depends: now on both.
--
-- * Inhibits: when any of the two wires inhibit.
(<!>) :: (Monad m, EventLike ev) => Wire s e m a (ev e1) -> Wire s e m a (ev e2) -> Wire s e m a (ev ())
(<!>) = liftA2 mergeD
infixl 5 <!>
-- | Left scan for events. Each time an event occurs, apply the given
-- function.
--
-- * Depends: now.
accumE ::
(EventLike ev)
=> (b -> a -> b) -- ^ Fold function
-> b -- ^ Initial value.
-> Wire s e m (ev a) (ev b)
accumE f = loop
where
loop x' =
mkSFN $
event (fromEvent NoEvent, loop x')
(\y -> let x = f x' y in (fromEvent $ Event x, loop x))
-- | Left scan for events with no initial value. Each time an event
-- occurs, apply the given function. The first event is produced
-- unchanged.
--
-- * Depends: now.
accum1E ::
(EventLike ev)
=> (a -> a -> a) -- ^ Fold function
-> Wire s e m (ev a) (ev a)
accum1E f = initial
where
initial =
mkSFN $ event (fromEvent NoEvent, initial) (fromEvent . Event &&& accumE f)
-- | At the given point in time.
--
-- * Depends: now when occurring.
at ::
(HasTime t s)
=> t -- ^ Time of occurrence.
-> Wire s e m a (UniqueEvent a)
at t' =
mkSF $ \ds x ->
let t = t' - dtime ds
in if t <= 0
then (fromEvent $ Event x, never)
else (fromEvent NoEvent, at t)
-- | Occurs each time the predicate becomes true for the input signal,
-- for example each time a given threshold is reached.
--
-- * Depends: now.
became :: (a -> Bool) -> Wire s e m a (Event a)
became p = off
where
off = mkSFN $ \x -> if p x then (Event x, on) else (NoEvent, off)
on = mkSFN $ \x -> (NoEvent, if p x then on else off)
-- | Forget the first given number of occurrences.
--
-- * Depends: now.
dropE :: (EventLike ev) => Int -> Wire s e m (ev a) (ev a)
dropE n | n <= 0 = mkId
dropE n =
fix $ \again ->
mkSFN $ \mev ->
(fromEvent NoEvent, if occurred mev then dropE (pred n) else again)
-- | Forget all initial occurrences until the given predicate becomes
-- false.
--
-- * Depends: now.
dropWhileE :: (EventLike ev) => (a -> Bool) -> Wire s e m (ev a) (ev a)
dropWhileE p =
fix $ \again ->
mkSFN $ \mev ->
case toEvent mev of
Event x | not (p x) -> (mev, mkId)
_ -> (fromEvent NoEvent, again)
-- | Forget all occurrences for which the given predicate is false.
--
-- * Depends: now.
filterE :: (EventLike ev) => (a -> Bool) -> Wire s e m (ev a) (ev a)
filterE p =
mkSF_ $ \mev ->
case toEvent mev of
Event x | p x -> mev
_ -> fromEvent NoEvent
-- | On each occurrence, apply the function the event carries.
--
-- * Depends: now.
iterateE :: (EventLike ev) => a -> Wire s e m (ev (a -> a)) (ev a)
iterateE = accumE (\x f -> f x)
-- | Maximum of all events.
--
-- * Depends: now.
maximumE :: (EventLike ev, Ord a) => Wire s e m (ev a) (ev a)
maximumE = accum1E max
-- | Minimum of all events.
--
-- * Depends: now.
minimumE :: (EventLike ev, Ord a) => Wire s e m (ev a) (ev a)
minimumE = accum1E min
-- | Left-biased event merge.
mergeL :: (EventLike ev) => ev a -> ev a -> ev a
mergeL = merge const
-- | Right-biased event merge.
mergeR :: (EventLike ev) => ev a -> ev a -> ev a
mergeR = merge (const id)
-- | Event merge discarding data.
mergeD :: (EventLike ev) => ev a -> ev b -> ev ()
mergeD a b = mergeL (fmap (const ()) a) (fmap (const ()) b)
-- | Never occurs.
never :: (EventLike ev) => Wire s e m a (ev b)
never = mkConst (Right $ fromEvent NoEvent)
-- | Occurs each time the predicate becomes false for the input signal,
-- for example each time a given threshold is no longer exceeded.
--
-- * Depends: now.
noLonger :: (a -> Bool) -> Wire s e m a (Event a)
noLonger p = off
where
off = mkSFN $ \x -> if p x then (NoEvent, off) else (Event x, on)
on = mkSFN $ \x -> (NoEvent, if p x then off else on)
-- | Forget the first occurrence.
--
-- * Depends: now.
notYet :: (EventLike ev) => Wire s e m (ev a) (ev a)
notYet =
mkSFN $ event (fromEvent NoEvent, notYet) (const (fromEvent NoEvent, mkId))
-- | Occurs once immediately.
--
-- * Depends: now when occurring.
now :: Wire s e m a (UniqueEvent a)
now = mkSFN $ \x -> (fromEvent $ Event x, never)
-- | Forget all occurrences except the first.
--
-- * Depends: now when occurring.
once :: (EventLike ev) => Wire s e m (ev a) (UniqueEvent a)
once =
mkSFN $ \mev ->
(fromEvent $ toEvent mev, if occurred mev then never else once)
-- | Periodic occurrence with the given time period. First occurrence
-- is now.
--
-- * Depends: now when occurring.
periodic :: (HasTime t s) => t -> Wire s e m a (UniqueEvent a)
periodic int | int <= 0 = error "periodic: Non-positive interval"
periodic int = mkSFN $ \x -> (fromEvent $ Event x, loop int)
where
loop 0 = loop int
loop t' =
mkSF $ \ds x ->
let t = t' - dtime ds
in if t <= 0
then (fromEvent $ Event x, loop (mod' t int))
else (fromEvent NoEvent, loop t)
-- | Periodic occurrence with the given time period. First occurrence
-- is now. The event values are picked one by one from the given list.
-- When the list is exhausted, the event does not occur again.
periodicList :: (HasTime t s) => t -> [b] -> Wire s e m a (UniqueEvent b)
periodicList int _ | int <= 0 = error "periodic: Non-positive interval"
periodicList _ [] = never
periodicList int (x:xs) = mkSFN $ \_ -> (fromEvent $ Event x, loop int xs)
where
loop _ [] = never
loop 0 xs = loop int xs
loop t' xs0@(x:xs) =
mkSF $ \ds _ ->
let t = t' - dtime ds
in if t <= 0
then (fromEvent $ Event x, loop (mod' t int) xs)
else (fromEvent NoEvent, loop t xs0)
-- | Product of all events.
--
-- * Depends: now.
productE :: (EventLike ev, Num a) => Wire s e m (ev a) (ev a)
productE = accumE (*) 1
-- | Sum of all events.
--
-- * Depends: now.
sumE :: (EventLike ev, Num a) => Wire s e m (ev a) (ev a)
sumE = accumE (+) 0
-- | Forget all but the first given number of occurrences.
--
-- * Depends: now.
takeE :: (EventLike ev) => Int -> Wire s e m (ev a) (ev a)
takeE n | n <= 0 = never
takeE n =
fix $ \again ->
mkSFN $ \mev ->
(mev, if occurred mev then takeE (pred n) else again)
-- | Forget all but the initial occurrences for which the given
-- predicate is true.
--
-- * Depends: now.
takeWhileE :: (EventLike ev) => (a -> Bool) -> Wire s e m (ev a) (ev a)
takeWhileE p =
fix $ \again ->
mkSFN $ \mev ->
case toEvent mev of
Event x | not (p x) -> (fromEvent NoEvent, never)
_ -> (mev, again)
-- | Each time the given unique event occurs, perform the given action
-- with the value the event carries. The resulting event carries the
-- result of the action.
--
-- * Depends: now.
onUEventM :: (Monad m) => (a -> m b) -> Wire s e m (UniqueEvent a) (UniqueEvent b)
onUEventM = onEventM
-- | Emit an 'UniqueEvent's value when it arrives.
--
-- * Depends: now.
--
-- * Inhibits: while no event happens.
onU :: (Monoid e) => Wire s e m (UniqueEvent a) a
onU = onE
-- | Did the given unique event occur?
occurredU :: UniqueEvent a -> Bool
occurredU = occurred
-- | Fold the given unique event.
eventU :: b -> (a -> b) -> UniqueEvent a -> b
eventU = event
| abbradar/netwire | Control/Wire/Event.hs | bsd-3-clause | 9,267 | 0 | 17 | 2,612 | 3,003 | 1,628 | 1,375 | -1 | -1 |
-----------------------------------------------------------------------------
--
-- Module : MFlow.Hack.XHtml.All
-- Copyright :
-- License : BSD3
--
-- Maintainer : agocorona@gmail.com
-- Stability : experimental
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module MFlow.Hack.XHtml.All (
module Data.TCache
,module MFlow.Hack
,module MFlow.FileServer
,module MFlow.Forms
,module MFlow.Forms.XHtml
,module MFlow.Forms.Admin
,module MFlow.Hack.XHtml
,module MFlow.Forms.Widgets
,module Hack
,module Hack.Handler.SimpleServer
,module Text.XHtml.Strict
,module Control.Applicative
) where
import MFlow.Hack
import MFlow.FileServer
import MFlow.Forms
import MFlow.Forms.XHtml
import MFlow.Forms.Admin
import MFlow.Forms.Widgets
import MFlow.Hack.XHtml
import Hack(Env)
import Hack.Handler.SimpleServer
import Data.TCache
import Text.XHtml.Strict hiding (widget)
import Control.Applicative
| agocorona/MFlow | src/MFlow/Hack/XHtml/All.hs | bsd-3-clause | 975 | 0 | 5 | 114 | 174 | 121 | 53 | 25 | 0 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module Unique where
import Data.Serialize
import GHC.Generics
class HasUnique a where
type Unique a :: *
unique :: a -> Unique a
class HasUnique a => UnUnique a where
ununique :: Unique a -> a
| showpoint/refs | src/Unique.hs | bsd-3-clause | 322 | 0 | 8 | 69 | 73 | 40 | 33 | 11 | 0 |
module Evaluation where
import Syntax
data Result
= Bool Bool
| Num Int
| Neither
deriving Show
class NB x => Evaluate x
where eval :: x -> Result
instance Evaluate TrueB
where eval TrueB = Bool True
instance Evaluate FalseB
where eval FalseB = Bool False
instance (Evaluate c, Evaluate t, Evaluate e) => Evaluate (IfNB c t e)
where eval (IfNB c t e) = case (eval c) of
Bool x -> if x then eval t else eval e
_ -> Neither
instance Evaluate ZeroN
where eval ZeroN = Num 0
instance (Evaluate t) => Evaluate (SuccN t)
where eval (SuccN t) = case (eval t) of
Num x -> Num (x+1)
_ -> Neither
instance (Evaluate t) => Evaluate (PredN t)
where eval (PredN t) = case (eval t) of
Num x -> Num (x-1)
_ -> Neither
instance (Evaluate t) => Evaluate (IsZeroB t)
where eval (IsZeroB t) = case (eval t) of
Num x -> Bool (x==0)
_ -> Neither
| grammarware/slps | topics/implementation/nb/expression/Evaluation.hs | bsd-3-clause | 862 | 4 | 11 | 203 | 425 | 214 | 211 | 31 | 0 |
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module Purescript.Ide.Command
(parseCommand, Command(..), Level(..)) where
import Data.Text (Text)
import qualified Data.Text as T
import Text.Parsec
import Text.Parsec.Text
data Level
= File
| Project
| Pursuit
deriving (Show,Eq)
data Command
= TypeLookup Text
| Complete Text Level
| Load Text
| LoadDependencies Text
| Print
| Cwd
| Quit
deriving (Show,Eq)
parseCommand :: Text -> Either ParseError Command
parseCommand = parse parseCommand' ""
parseCommand' :: Parser Command
parseCommand' =
(string "print" >> return Print) <|> try (string "cwd" >> return Cwd) <|>
(string "quit" >> return Quit) <|>
try parseTypeLookup <|>
try parseComplete <|>
try parseLoad <|>
parseLoadDependencies
parseTypeLookup :: Parser Command
parseTypeLookup = do
string "typeLookup"
spaces
ident <- many1 anyChar
return (TypeLookup (T.pack ident))
parseComplete :: Parser Command
parseComplete = do
string "complete"
spaces
stub <- many1 (noneOf " ")
spaces
level <- parseLevel
return (Complete (T.pack stub) level)
parseLoad :: Parser Command
parseLoad = do
string "load"
spaces
module' <- many1 anyChar
return (Load (T.pack module'))
parseLoadDependencies :: Parser Command
parseLoadDependencies = do
string "dependencies"
spaces
module' <- many1 anyChar
return (LoadDependencies (T.pack module'))
parseLevel :: Parser Level
parseLevel =
(string "File" >> return File) <|>
(try (string "Project") >> return Project) <|>
(string "Pursuit" >> return Pursuit)
| passy/psc-ide | lib/Purescript/Ide/Command.hs | bsd-3-clause | 1,696 | 0 | 14 | 414 | 530 | 264 | 266 | 62 | 1 |
import Disorder.Core.Main
import qualified Test.Mismi.Autoscaling.Data
main :: IO ()
main =
disorderMain [
Test.Mismi.Autoscaling.Data.tests
]
| ambiata/mismi | mismi-autoscaling/test/test.hs | bsd-3-clause | 167 | 0 | 7 | 39 | 41 | 25 | 16 | 6 | 1 |
module Arhelk.Russian.Lemma.Particle(
particle
) where
import Arhelk.Core.Rule
import Arhelk.Russian.Lemma.Common
import Arhelk.Russian.Lemma.Data
import Control.Arrow (first)
import Control.Monad
import Data.List (nub, nubBy)
import Data.Maybe
import Data.Text as T
import Prelude as P hiding (Word)
import qualified Data.Foldable as F
import qualified Data.Text.IO as T
import System.IO.Unsafe (unsafePerformIO)
-- | Particle contains many words
type Particle = [Text]
-- | Build in list of particles
particles :: [Particle]
particles = unsafePerformIO $ do
ts <- T.readFile "config/particles.txt"
return $ T.words . T.strip <$> T.lines ts
{-# NOINLINE particles #-}
-- | Tries to find particles including multiword
particle :: SentenceClause SemiProcWord -> [SentenceClause SemiProcWord]
particle clause = glueLessSpecialized $ do
clause' <- makeSingleHypothesis clause
clause' : particle clause'
where
makeSingleHypothesis cl = catMaybes $ findParticle cl <$> particles
-- | Tries to find particle within unknown words in sentence
findParticle :: SentenceClause SemiProcWord -> Particle -> Maybe (SentenceClause SemiProcWord)
findParticle clause particle = let
(preClause', mpw, postClause', leftParticle) = F.foldl' go ([], Nothing, [], particle) clause
in case leftParticle of
[] -> case mpw of
Nothing -> Nothing
Just pw -> Just $ P.reverse preClause' ++ [GrammarParticle (SemiProcWord $ Right pw) ParticleProperties] ++ P.reverse postClause'
_ -> Nothing
where
go :: (SentenceClause SemiProcWord, Maybe Word, SentenceClause SemiProcWord, Particle)
-> Lemma SemiProcWord
-> (SentenceClause SemiProcWord, Maybe Word, SentenceClause SemiProcWord, Particle)
go (pre, pw, post, []) l = (pre, pw, l : post, [])
go (pre, Nothing, post, ps) l = case l of -- first particle part isn't met yet
UnknownWord (SemiProcWord (Left w)) -> if w `elem` ps
then (pre, Just (MultiWord [w]), post, P.filter (/= w) ps)
else (l : pre, Nothing, post , ps)
_ -> (l : pre, Nothing, post , ps)
go (pre, mpw@(Just (MultiWord pw)), post, ps) l = case l of -- already met particle parts
UnknownWord (SemiProcWord (Left w)) -> if w `elem` ps
then (pre, Just (MultiWord $ pw ++ [w]), post, P.filter (/= w) ps)
else (post, mpw, l : post, ps)
_ -> (post, mpw, l : post, ps) | Teaspot-Studio/arhelk-russian | src/Arhelk/Russian/Lemma/Particle.hs | bsd-3-clause | 2,397 | 0 | 19 | 485 | 803 | 450 | 353 | 47 | 9 |
module MyMain
( module Data.Char
-- , module Control.Arrow
, module Diagrams.Prelude
, module Diagrams.Backend.Cairo
, module Diagrams.TwoD.Path.Turtle) where
-- import Control.Arrow
import Data.Char
import Diagrams.Prelude
import Diagrams.Backend.Cairo
import Diagrams.TwoD.Path.Turtle
import Prelude
main = print $ 1 + 3 | mgsloan/panopti | MyMain.hs | bsd-3-clause | 335 | 0 | 6 | 51 | 74 | 49 | 25 | 11 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple
-- Copyright : Isaac Jones 2003-2005
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This is the command line front end to the Simple build system. When given
-- the parsed command-line args and package information, is able to perform
-- basic commands like configure, build, install, register, etc.
--
-- This module exports the main functions that Setup.hs scripts use. It
-- re-exports the 'UserHooks' type, the standard entry points like
-- 'defaultMain' and 'defaultMainWithHooks' and the predefined sets of
-- 'UserHooks' that custom @Setup.hs@ scripts can extend to add their own
-- behaviour.
--
-- This module isn't called \"Simple\" because it's simple. Far from
-- it. It's called \"Simple\" because it does complicated things to
-- simple software.
--
-- The original idea was that there could be different build systems that all
-- presented the same compatible command line interfaces. There is still a
-- "Distribution.Make" system but in practice no packages use it.
{-
Work around this warning:
libraries/Cabal/Distribution/Simple.hs:78:0:
Warning: In the use of `runTests'
(imported from Distribution.Simple.UserHooks):
Deprecated: "Please use the new testing interface instead!"
-}
{-# OPTIONS_GHC -fno-warn-deprecations #-}
module Distribution.Simple (
module Distribution.Package,
module Distribution.Version,
module Distribution.License,
module Distribution.Simple.Compiler,
module Language.Haskell.Extension,
-- * Simple interface
defaultMain, defaultMainNoRead, defaultMainArgs,
-- * Customization
UserHooks(..), Args,
defaultMainWithHooks, defaultMainWithHooksArgs,
defaultMainWithHooksNoRead,
-- ** Standard sets of hooks
simpleUserHooks,
autoconfUserHooks,
defaultUserHooks, emptyUserHooks,
-- ** Utils
defaultHookedPackageDesc
) where
import Prelude ()
import Distribution.Compat.Prelude
-- local
import Distribution.Simple.Compiler hiding (Flag)
import Distribution.Simple.UserHooks
import Distribution.Package
import Distribution.PackageDescription hiding (Flag)
import Distribution.PackageDescription.Parse
import Distribution.PackageDescription.Configuration
import Distribution.Simple.Program
import Distribution.Simple.Program.Db
import Distribution.Simple.PreProcess
import Distribution.Simple.Setup
import Distribution.Simple.Command
import Distribution.Simple.Build
import Distribution.Simple.SrcDist
import Distribution.Simple.Register
import Distribution.Simple.Configure
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Bench
import Distribution.Simple.BuildPaths
import Distribution.Simple.Test
import Distribution.Simple.Install
import Distribution.Simple.Haddock
import Distribution.Simple.Utils
import Distribution.Utils.NubList
import Distribution.Verbosity
import Language.Haskell.Extension
import Distribution.Version
import Distribution.License
import Distribution.Text
-- Base
import System.Environment (getArgs, getProgName)
import System.Directory (removeFile, doesFileExist
,doesDirectoryExist, removeDirectoryRecursive)
import System.Exit (exitWith,ExitCode(..))
import System.FilePath (searchPathSeparator)
import Distribution.Compat.Environment (getEnvironment)
import Distribution.Compat.GetShortPathName (getShortPathName)
import Data.List (unionBy, (\\))
-- | A simple implementation of @main@ for a Cabal setup script.
-- It reads the package description file using IO, and performs the
-- action specified on the command line.
defaultMain :: IO ()
defaultMain = getArgs >>= defaultMainHelper simpleUserHooks
-- | A version of 'defaultMain' that is passed the command line
-- arguments, rather than getting them from the environment.
defaultMainArgs :: [String] -> IO ()
defaultMainArgs = defaultMainHelper simpleUserHooks
-- | A customizable version of 'defaultMain'.
defaultMainWithHooks :: UserHooks -> IO ()
defaultMainWithHooks hooks = getArgs >>= defaultMainHelper hooks
-- | A customizable version of 'defaultMain' that also takes the command
-- line arguments.
defaultMainWithHooksArgs :: UserHooks -> [String] -> IO ()
defaultMainWithHooksArgs = defaultMainHelper
-- | Like 'defaultMain', but accepts the package description as input
-- rather than using IO to read it.
defaultMainNoRead :: GenericPackageDescription -> IO ()
defaultMainNoRead = defaultMainWithHooksNoRead simpleUserHooks
-- | A customizable version of 'defaultMainNoRead'.
defaultMainWithHooksNoRead :: UserHooks -> GenericPackageDescription -> IO ()
defaultMainWithHooksNoRead hooks pkg_descr =
getArgs >>=
defaultMainHelper hooks { readDesc = return (Just pkg_descr) }
defaultMainHelper :: UserHooks -> Args -> IO ()
defaultMainHelper hooks args = topHandler $
case commandsRun (globalCommand commands) commands args of
CommandHelp help -> printHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo (flags, commandParse) ->
case commandParse of
_ | fromFlag (globalVersion flags) -> printVersion
| fromFlag (globalNumericVersion flags) -> printNumericVersion
CommandHelp help -> printHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo action -> action
where
printHelp help = getProgName >>= putStr . help
printOptionsList = putStr . unlines
printErrors errs = do
putStr (intercalate "\n" errs)
exitWith (ExitFailure 1)
printNumericVersion = putStrLn $ display cabalVersion
printVersion = putStrLn $ "Cabal library version "
++ display cabalVersion
progs = addKnownPrograms (hookedPrograms hooks) defaultProgramDb
commands =
[configureCommand progs `commandAddAction`
\fs as -> configureAction hooks fs as >> return ()
,buildCommand progs `commandAddAction` buildAction hooks
,replCommand progs `commandAddAction` replAction hooks
,installCommand `commandAddAction` installAction hooks
,copyCommand `commandAddAction` copyAction hooks
,haddockCommand `commandAddAction` haddockAction hooks
,cleanCommand `commandAddAction` cleanAction hooks
,sdistCommand `commandAddAction` sdistAction hooks
,hscolourCommand `commandAddAction` hscolourAction hooks
,registerCommand `commandAddAction` registerAction hooks
,unregisterCommand `commandAddAction` unregisterAction hooks
,testCommand `commandAddAction` testAction hooks
,benchmarkCommand `commandAddAction` benchAction hooks
]
-- | Combine the preprocessors in the given hooks with the
-- preprocessors built into cabal.
allSuffixHandlers :: UserHooks
-> [PPSuffixHandler]
allSuffixHandlers hooks
= overridesPP (hookedPreProcessors hooks) knownSuffixHandlers
where
overridesPP :: [PPSuffixHandler] -> [PPSuffixHandler] -> [PPSuffixHandler]
overridesPP = unionBy (\x y -> fst x == fst y)
configureAction :: UserHooks -> ConfigFlags -> Args -> IO LocalBuildInfo
configureAction hooks flags args = do
distPref <- findDistPrefOrDefault (configDistPref flags)
let flags' = flags { configDistPref = toFlag distPref
, configArgs = args }
-- See docs for 'HookedBuildInfo'
pbi <- preConf hooks args flags'
(mb_pd_file, pkg_descr0) <- confPkgDescr hooks verbosity
(flagToMaybe (configCabalFilePath flags))
let epkg_descr = (pkg_descr0, pbi)
localbuildinfo0 <- confHook hooks epkg_descr flags'
-- remember the .cabal filename if we know it
-- and all the extra command line args
let localbuildinfo = localbuildinfo0 {
pkgDescrFile = mb_pd_file,
extraConfigArgs = args
}
writePersistBuildConfig distPref localbuildinfo
let pkg_descr = localPkgDescr localbuildinfo
postConf hooks args flags' pkg_descr localbuildinfo
return localbuildinfo
where
verbosity = fromFlag (configVerbosity flags)
confPkgDescr :: UserHooks -> Verbosity -> Maybe FilePath
-> IO (Maybe FilePath, GenericPackageDescription)
confPkgDescr hooks verbosity mb_path = do
mdescr <- readDesc hooks
case mdescr of
Just descr -> return (Nothing, descr)
Nothing -> do
pdfile <- case mb_path of
Nothing -> defaultPackageDesc verbosity
Just path -> return path
descr <- readPackageDescription verbosity pdfile
return (Just pdfile, descr)
buildAction :: UserHooks -> BuildFlags -> Args -> IO ()
buildAction hooks flags args = do
distPref <- findDistPrefOrDefault (buildDistPref flags)
let verbosity = fromFlag $ buildVerbosity flags
flags' = flags { buildDistPref = toFlag distPref }
lbi <- getBuildConfig hooks verbosity distPref
progs <- reconfigurePrograms verbosity
(buildProgramPaths flags')
(buildProgramArgs flags')
(withPrograms lbi)
hookedAction preBuild buildHook postBuild
(return lbi { withPrograms = progs })
hooks flags' { buildArgs = args } args
replAction :: UserHooks -> ReplFlags -> Args -> IO ()
replAction hooks flags args = do
distPref <- findDistPrefOrDefault (replDistPref flags)
let verbosity = fromFlag $ replVerbosity flags
flags' = flags { replDistPref = toFlag distPref }
lbi <- getBuildConfig hooks verbosity distPref
progs <- reconfigurePrograms verbosity
(replProgramPaths flags')
(replProgramArgs flags')
(withPrograms lbi)
-- As far as I can tell, the only reason this doesn't use
-- 'hookedActionWithArgs' is because the arguments of 'replHook'
-- takes the args explicitly. UGH. -- ezyang
pbi <- preRepl hooks args flags'
let pkg_descr0 = localPkgDescr lbi
sanityCheckHookedBuildInfo pkg_descr0 pbi
let pkg_descr = updatePackageDescription pbi pkg_descr0
lbi' = lbi { withPrograms = progs
, localPkgDescr = pkg_descr }
replHook hooks pkg_descr lbi' hooks flags' args
postRepl hooks args flags' pkg_descr lbi'
hscolourAction :: UserHooks -> HscolourFlags -> Args -> IO ()
hscolourAction hooks flags args = do
distPref <- findDistPrefOrDefault (hscolourDistPref flags)
let verbosity = fromFlag $ hscolourVerbosity flags
flags' = flags { hscolourDistPref = toFlag distPref }
hookedAction preHscolour hscolourHook postHscolour
(getBuildConfig hooks verbosity distPref)
hooks flags' args
haddockAction :: UserHooks -> HaddockFlags -> Args -> IO ()
haddockAction hooks flags args = do
distPref <- findDistPrefOrDefault (haddockDistPref flags)
let verbosity = fromFlag $ haddockVerbosity flags
flags' = flags { haddockDistPref = toFlag distPref }
lbi <- getBuildConfig hooks verbosity distPref
progs <- reconfigurePrograms verbosity
(haddockProgramPaths flags')
(haddockProgramArgs flags')
(withPrograms lbi)
hookedAction preHaddock haddockHook postHaddock
(return lbi { withPrograms = progs })
hooks flags' args
cleanAction :: UserHooks -> CleanFlags -> Args -> IO ()
cleanAction hooks flags args = do
distPref <- findDistPrefOrDefault (cleanDistPref flags)
let flags' = flags { cleanDistPref = toFlag distPref }
pbi <- preClean hooks args flags'
(_, ppd) <- confPkgDescr hooks verbosity Nothing
-- It might seem like we are doing something clever here
-- but we're really not: if you look at the implementation
-- of 'clean' in the end all the package description is
-- used for is to clear out @extra-tmp-files@. IMO,
-- the configure script goo should go into @dist@ too!
-- -- ezyang
let pkg_descr0 = flattenPackageDescription ppd
-- We don't sanity check for clean as an error
-- here would prevent cleaning:
--sanityCheckHookedBuildInfo pkg_descr0 pbi
let pkg_descr = updatePackageDescription pbi pkg_descr0
cleanHook hooks pkg_descr () hooks flags'
postClean hooks args flags' pkg_descr ()
where
verbosity = fromFlag (cleanVerbosity flags)
copyAction :: UserHooks -> CopyFlags -> Args -> IO ()
copyAction hooks flags args = do
distPref <- findDistPrefOrDefault (copyDistPref flags)
let verbosity = fromFlag $ copyVerbosity flags
flags' = flags { copyDistPref = toFlag distPref }
hookedAction preCopy copyHook postCopy
(getBuildConfig hooks verbosity distPref)
hooks flags' { copyArgs = args } args
installAction :: UserHooks -> InstallFlags -> Args -> IO ()
installAction hooks flags args = do
distPref <- findDistPrefOrDefault (installDistPref flags)
let verbosity = fromFlag $ installVerbosity flags
flags' = flags { installDistPref = toFlag distPref }
hookedAction preInst instHook postInst
(getBuildConfig hooks verbosity distPref)
hooks flags' args
sdistAction :: UserHooks -> SDistFlags -> Args -> IO ()
sdistAction hooks flags args = do
distPref <- findDistPrefOrDefault (sDistDistPref flags)
let flags' = flags { sDistDistPref = toFlag distPref }
pbi <- preSDist hooks args flags'
mlbi <- maybeGetPersistBuildConfig distPref
-- NB: It would be TOTALLY WRONG to use the 'PackageDescription'
-- store in the 'LocalBuildInfo' for the rest of @sdist@, because
-- that would result in only the files that would be built
-- according to the user's configure being packaged up.
-- In fact, it is not obvious why we need to read the
-- 'LocalBuildInfo' in the first place, except that we want
-- to do some architecture-independent preprocessing which
-- needs to be configured. This is totally awful, see
-- GH#130.
(_, ppd) <- confPkgDescr hooks verbosity Nothing
let pkg_descr0 = flattenPackageDescription ppd
sanityCheckHookedBuildInfo pkg_descr0 pbi
let pkg_descr = updatePackageDescription pbi pkg_descr0
mlbi' = fmap (\lbi -> lbi { localPkgDescr = pkg_descr }) mlbi
sDistHook hooks pkg_descr mlbi' hooks flags'
postSDist hooks args flags' pkg_descr mlbi'
where
verbosity = fromFlag (sDistVerbosity flags)
testAction :: UserHooks -> TestFlags -> Args -> IO ()
testAction hooks flags args = do
distPref <- findDistPrefOrDefault (testDistPref flags)
let verbosity = fromFlag $ testVerbosity flags
flags' = flags { testDistPref = toFlag distPref }
localBuildInfo <- getBuildConfig hooks verbosity distPref
let pkg_descr = localPkgDescr localBuildInfo
-- It is safe to do 'runTests' before the new test handler because the
-- default action is a no-op and if the package uses the old test interface
-- the new handler will find no tests.
runTests hooks args False pkg_descr localBuildInfo
hookedActionWithArgs preTest testHook postTest
(getBuildConfig hooks verbosity distPref)
hooks flags' args
benchAction :: UserHooks -> BenchmarkFlags -> Args -> IO ()
benchAction hooks flags args = do
distPref <- findDistPrefOrDefault (benchmarkDistPref flags)
let verbosity = fromFlag $ benchmarkVerbosity flags
flags' = flags { benchmarkDistPref = toFlag distPref }
hookedActionWithArgs preBench benchHook postBench
(getBuildConfig hooks verbosity distPref)
hooks flags' args
registerAction :: UserHooks -> RegisterFlags -> Args -> IO ()
registerAction hooks flags args = do
distPref <- findDistPrefOrDefault (regDistPref flags)
let verbosity = fromFlag $ regVerbosity flags
flags' = flags { regDistPref = toFlag distPref }
hookedAction preReg regHook postReg
(getBuildConfig hooks verbosity distPref)
hooks flags' { regArgs = args } args
unregisterAction :: UserHooks -> RegisterFlags -> Args -> IO ()
unregisterAction hooks flags args = do
distPref <- findDistPrefOrDefault (regDistPref flags)
let verbosity = fromFlag $ regVerbosity flags
flags' = flags { regDistPref = toFlag distPref }
hookedAction preUnreg unregHook postUnreg
(getBuildConfig hooks verbosity distPref)
hooks flags' args
hookedAction :: (UserHooks -> Args -> flags -> IO HookedBuildInfo)
-> (UserHooks -> PackageDescription -> LocalBuildInfo
-> UserHooks -> flags -> IO ())
-> (UserHooks -> Args -> flags -> PackageDescription
-> LocalBuildInfo -> IO ())
-> IO LocalBuildInfo
-> UserHooks -> flags -> Args -> IO ()
hookedAction pre_hook cmd_hook =
hookedActionWithArgs pre_hook (\h _ pd lbi uh flags ->
cmd_hook h pd lbi uh flags)
hookedActionWithArgs :: (UserHooks -> Args -> flags -> IO HookedBuildInfo)
-> (UserHooks -> Args -> PackageDescription -> LocalBuildInfo
-> UserHooks -> flags -> IO ())
-> (UserHooks -> Args -> flags -> PackageDescription
-> LocalBuildInfo -> IO ())
-> IO LocalBuildInfo
-> UserHooks -> flags -> Args -> IO ()
hookedActionWithArgs pre_hook cmd_hook post_hook
get_build_config hooks flags args = do
pbi <- pre_hook hooks args flags
lbi0 <- get_build_config
let pkg_descr0 = localPkgDescr lbi0
sanityCheckHookedBuildInfo pkg_descr0 pbi
let pkg_descr = updatePackageDescription pbi pkg_descr0
lbi = lbi0 { localPkgDescr = pkg_descr }
cmd_hook hooks args pkg_descr lbi hooks flags
post_hook hooks args flags pkg_descr lbi
sanityCheckHookedBuildInfo :: PackageDescription -> HookedBuildInfo -> IO ()
sanityCheckHookedBuildInfo PackageDescription { library = Nothing } (Just _,_)
= die $ "The buildinfo contains info for a library, "
++ "but the package does not have a library."
sanityCheckHookedBuildInfo pkg_descr (_, hookExes)
| not (null nonExistant)
= die $ "The buildinfo contains info for an executable called '"
++ "executable with that name."
where
pkgExeNames = nub (map exeName (executables pkg_descr))
hookExeNames = nub (map fst hookExes)
nonExistant = hookExeNames \\ pkgExeNames
sanityCheckHookedBuildInfo _ _ = return ()
getBuildConfig :: UserHooks -> Verbosity -> FilePath -> IO LocalBuildInfo
getBuildConfig hooks verbosity distPref = do
lbi_wo_programs <- getPersistBuildConfig distPref
-- Restore info about unconfigured programs, since it is not serialized
let lbi = lbi_wo_programs {
withPrograms = restoreProgramDb
(builtinPrograms ++ hookedPrograms hooks)
(withPrograms lbi_wo_programs)
}
case pkgDescrFile lbi of
Nothing -> return lbi
Just pkg_descr_file -> do
outdated <- checkPersistBuildConfigOutdated distPref pkg_descr_file
if outdated
then reconfigure pkg_descr_file lbi
else return lbi
where
reconfigure :: FilePath -> LocalBuildInfo -> IO LocalBuildInfo
reconfigure pkg_descr_file lbi = do
notice verbosity $ pkg_descr_file ++ " has been changed. "
++ "Re-configuring with most recently used options. "
++ "If this fails, please run configure manually.\n"
let cFlags = configFlags lbi
let cFlags' = cFlags {
-- Since the list of unconfigured programs is not serialized,
-- restore it to the same value as normally used at the beginning
-- of a configure run:
configPrograms_ = restoreProgramDb
(builtinPrograms ++ hookedPrograms hooks)
`fmap` configPrograms_ cFlags,
-- Use the current, not saved verbosity level:
configVerbosity = Flag verbosity
}
configureAction hooks cFlags' (extraConfigArgs lbi)
-- --------------------------------------------------------------------------
-- Cleaning
clean :: PackageDescription -> CleanFlags -> IO ()
clean pkg_descr flags = do
let distPref = fromFlagOrDefault defaultDistPref $ cleanDistPref flags
notice verbosity "cleaning..."
maybeConfig <- if fromFlag (cleanSaveConf flags)
then maybeGetPersistBuildConfig distPref
else return Nothing
-- remove the whole dist/ directory rather than tracking exactly what files
-- we created in there.
chattyTry "removing dist/" $ do
exists <- doesDirectoryExist distPref
when exists (removeDirectoryRecursive distPref)
-- Any extra files the user wants to remove
traverse_ removeFileOrDirectory (extraTmpFiles pkg_descr)
-- If the user wanted to save the config, write it back
traverse_ (writePersistBuildConfig distPref) maybeConfig
where
removeFileOrDirectory :: FilePath -> NoCallStackIO ()
removeFileOrDirectory fname = do
isDir <- doesDirectoryExist fname
isFile <- doesFileExist fname
if isDir then removeDirectoryRecursive fname
else when isFile $ removeFile fname
verbosity = fromFlag (cleanVerbosity flags)
-- --------------------------------------------------------------------------
-- Default hooks
-- | Hooks that correspond to a plain instantiation of the
-- \"simple\" build system
simpleUserHooks :: UserHooks
simpleUserHooks =
emptyUserHooks {
confHook = configure,
postConf = finalChecks,
buildHook = defaultBuildHook,
replHook = defaultReplHook,
copyHook = \desc lbi _ f -> install desc lbi f,
-- 'install' has correct 'copy' behavior with params
testHook = defaultTestHook,
benchHook = defaultBenchHook,
instHook = defaultInstallHook,
sDistHook = \p l h f -> sdist p l f srcPref (allSuffixHandlers h),
cleanHook = \p _ _ f -> clean p f,
hscolourHook = \p l h f -> hscolour p l (allSuffixHandlers h) f,
haddockHook = \p l h f -> haddock p l (allSuffixHandlers h) f,
regHook = defaultRegHook,
unregHook = \p l _ f -> unregister p l f
}
where
finalChecks _args flags pkg_descr lbi =
checkForeignDeps pkg_descr lbi (lessVerbose verbosity)
where
verbosity = fromFlag (configVerbosity flags)
-- | Basic autoconf 'UserHooks':
--
-- * 'postConf' runs @.\/configure@, if present.
--
-- * the pre-hooks 'preBuild', 'preClean', 'preCopy', 'preInst',
-- 'preReg' and 'preUnreg' read additional build information from
-- /package/@.buildinfo@, if present.
--
-- Thus @configure@ can use local system information to generate
-- /package/@.buildinfo@ and possibly other files.
{-# DEPRECATED defaultUserHooks
"Use simpleUserHooks or autoconfUserHooks, unless you need Cabal-1.2\n compatibility in which case you must stick with defaultUserHooks" #-}
defaultUserHooks :: UserHooks
defaultUserHooks = autoconfUserHooks {
confHook = \pkg flags -> do
let verbosity = fromFlag (configVerbosity flags)
warn verbosity
"defaultUserHooks in Setup script is deprecated."
confHook autoconfUserHooks pkg flags,
postConf = oldCompatPostConf
}
-- This is the annoying old version that only runs configure if it exists.
-- It's here for compatibility with existing Setup.hs scripts. See:
-- https://github.com/haskell/cabal/issues/158
where oldCompatPostConf args flags pkg_descr lbi
= do let verbosity = fromFlag (configVerbosity flags)
confExists <- doesFileExist "configure"
when confExists $
runConfigureScript verbosity
backwardsCompatHack flags lbi
pbi <- getHookedBuildInfo verbosity
sanityCheckHookedBuildInfo pkg_descr pbi
let pkg_descr' = updatePackageDescription pbi pkg_descr
lbi' = lbi { localPkgDescr = pkg_descr' }
postConf simpleUserHooks args flags pkg_descr' lbi'
backwardsCompatHack = True
autoconfUserHooks :: UserHooks
autoconfUserHooks
= simpleUserHooks
{
postConf = defaultPostConf,
preBuild = readHookWithArgs buildVerbosity,
preCopy = readHookWithArgs copyVerbosity,
preClean = readHook cleanVerbosity,
preInst = readHook installVerbosity,
preHscolour = readHook hscolourVerbosity,
preHaddock = readHook haddockVerbosity,
preReg = readHook regVerbosity,
preUnreg = readHook regVerbosity
}
where defaultPostConf :: Args -> ConfigFlags -> PackageDescription
-> LocalBuildInfo -> IO ()
defaultPostConf args flags pkg_descr lbi
= do let verbosity = fromFlag (configVerbosity flags)
confExists <- doesFileExist "configure"
if confExists
then runConfigureScript verbosity
backwardsCompatHack flags lbi
else die "configure script not found."
pbi <- getHookedBuildInfo verbosity
sanityCheckHookedBuildInfo pkg_descr pbi
let pkg_descr' = updatePackageDescription pbi pkg_descr
lbi' = lbi { localPkgDescr = pkg_descr' }
postConf simpleUserHooks args flags pkg_descr' lbi'
backwardsCompatHack = False
readHookWithArgs :: (a -> Flag Verbosity) -> Args -> a
-> IO HookedBuildInfo
readHookWithArgs get_verbosity _ flags = do
getHookedBuildInfo verbosity
where
verbosity = fromFlag (get_verbosity flags)
readHook :: (a -> Flag Verbosity) -> Args -> a -> IO HookedBuildInfo
readHook get_verbosity a flags = do
noExtraFlags a
getHookedBuildInfo verbosity
where
verbosity = fromFlag (get_verbosity flags)
runConfigureScript :: Verbosity -> Bool -> ConfigFlags -> LocalBuildInfo
-> IO ()
runConfigureScript verbosity backwardsCompatHack flags lbi = do
env <- getEnvironment
let programDb = withPrograms lbi
(ccProg, ccFlags) <- configureCCompiler verbosity programDb
ccProgShort <- getShortPathName ccProg
-- The C compiler's compilation and linker flags (e.g.
-- "C compiler flags" and "Gcc Linker flags" from GHC) have already
-- been merged into ccFlags, so we set both CFLAGS and LDFLAGS
-- to ccFlags
-- We don't try and tell configure which ld to use, as we don't have
-- a way to pass its flags too
let extraPath = fromNubList $ configProgramPathExtra flags
let cflagsEnv = maybe (unwords ccFlags) (++ (" " ++ unwords ccFlags))
$ lookup "CFLAGS" env
spSep = [searchPathSeparator]
pathEnv = maybe (intercalate spSep extraPath)
((intercalate spSep extraPath ++ spSep)++) $ lookup "PATH" env
overEnv = ("CFLAGS", Just cflagsEnv) :
[("PATH", Just pathEnv) | not (null extraPath)]
args' = args ++ ["CC=" ++ ccProgShort]
shProg = simpleProgram "sh"
progDb = modifyProgramSearchPath
(\p -> map ProgramSearchPathDir extraPath ++ p) emptyProgramDb
shConfiguredProg <- lookupProgram shProg
`fmap` configureProgram verbosity shProg progDb
case shConfiguredProg of
Just sh -> runProgramInvocation verbosity
(programInvocation (sh {programOverrideEnv = overEnv}) args')
Nothing -> die notFoundMsg
where
args = "./configure" : configureArgs backwardsCompatHack flags
notFoundMsg = "The package has a './configure' script. "
++ "If you are on Windows, This requires a "
++ "Unix compatibility toolchain such as MinGW+MSYS or Cygwin. "
++ "If you are not on Windows, ensure that an 'sh' command "
++ "is discoverable in your path."
getHookedBuildInfo :: Verbosity -> IO HookedBuildInfo
getHookedBuildInfo verbosity = do
maybe_infoFile <- defaultHookedPackageDesc
case maybe_infoFile of
Nothing -> return emptyHookedBuildInfo
Just infoFile -> do
info verbosity $ "Reading parameters from " ++ infoFile
readHookedBuildInfo verbosity infoFile
defaultTestHook :: Args -> PackageDescription -> LocalBuildInfo
-> UserHooks -> TestFlags -> IO ()
defaultTestHook args pkg_descr localbuildinfo _ flags =
test args pkg_descr localbuildinfo flags
defaultBenchHook :: Args -> PackageDescription -> LocalBuildInfo
-> UserHooks -> BenchmarkFlags -> IO ()
defaultBenchHook args pkg_descr localbuildinfo _ flags =
bench args pkg_descr localbuildinfo flags
defaultInstallHook :: PackageDescription -> LocalBuildInfo
-> UserHooks -> InstallFlags -> IO ()
defaultInstallHook pkg_descr localbuildinfo _ flags = do
let copyFlags = defaultCopyFlags {
copyDistPref = installDistPref flags,
copyDest = toFlag NoCopyDest,
copyVerbosity = installVerbosity flags
}
install pkg_descr localbuildinfo copyFlags
let registerFlags = defaultRegisterFlags {
regDistPref = installDistPref flags,
regInPlace = installInPlace flags,
regPackageDB = installPackageDB flags,
regVerbosity = installVerbosity flags
}
when (hasLibs pkg_descr) $ register pkg_descr localbuildinfo registerFlags
defaultBuildHook :: PackageDescription -> LocalBuildInfo
-> UserHooks -> BuildFlags -> IO ()
defaultBuildHook pkg_descr localbuildinfo hooks flags =
build pkg_descr localbuildinfo flags (allSuffixHandlers hooks)
defaultReplHook :: PackageDescription -> LocalBuildInfo
-> UserHooks -> ReplFlags -> [String] -> IO ()
defaultReplHook pkg_descr localbuildinfo hooks flags args =
repl pkg_descr localbuildinfo flags (allSuffixHandlers hooks) args
defaultRegHook :: PackageDescription -> LocalBuildInfo
-> UserHooks -> RegisterFlags -> IO ()
defaultRegHook pkg_descr localbuildinfo _ flags =
if hasLibs pkg_descr
then register pkg_descr localbuildinfo flags
else setupMessage (fromFlag (regVerbosity flags))
"Package contains no library to register:" (packageId pkg_descr)
| sopvop/cabal | Cabal/Distribution/Simple.hs | bsd-3-clause | 31,265 | 0 | 18 | 8,003 | 6,212 | 3,154 | 3,058 | 507 | 8 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
-- | Utilities share by both Typecheck and Liquid modules
module Language.Rsc.TypeUtilities (
idTy, idTys
, castTy
, arrayLitTy
, mkCondExprTy
, adjustCtxMut
, overloads
, expandOpts
) where
import Data.Default
import Data.List (partition)
import qualified Language.Fixpoint.Types as F
import Language.Fixpoint.Types.Names (symbolString)
import Language.Rsc.AST
import Language.Rsc.ClassHierarchy
import Language.Rsc.Environment
import Language.Rsc.Errors
import Language.Rsc.Liquid.Types
import Language.Rsc.Locations
import Language.Rsc.Names
import Language.Rsc.Pretty
import Language.Rsc.Typecheck.Sub (PPRE)
import Language.Rsc.Typecheck.Types
import Language.Rsc.Types
type CEnv r t = (CheckingEnvironment r t , Functor t)
-- type PPRE r = (ExprReftable F.Expr r, ExprReftable Int r, PPR r)
-- | setProp<A, M extends Mutable>(o: { f[M]: A }, x: A) => A
--
-- --------------------------------------------------------------------------------------------
-- setPropTy :: (F.Reftable r, F.Symbolic f) => f -> RType r
-- --------------------------------------------------------------------------------------------
-- setPropTy f = mkAll [bvt, bvm] ft
-- where
-- ft = TFun [b1, b2] t fTop
-- b1 = B (F.symbol "o") $ tRcvr tIM (tmFromFieldList [(f, FI Req m t)]) fTop
-- b2 = B (F.symbol "x") $ t
-- m = toTTV bvm :: F.Reftable r => RType r
-- t = toTTV bvt
-- bvt = BTV (F.symbol "A") def Nothing
-- bvm = BTV (F.symbol "M") def (Just tMU) :: F.Reftable r => BTVar r
-- toTTV :: F.Reftable r => BTVar r -> RType r
-- toTTV = (`TVar` fTop) . btvToTV
---------------------------------------------------------------------------------
idTy :: (ExprReftable F.Symbol r, F.Reftable r) => RTypeQ q r -> RTypeQ q r
idTys :: (ExprReftable F.Symbol r, F.Reftable r) => [RTypeQ q r] -> RTypeQ q r
---------------------------------------------------------------------------------
idTy t = mkFun ([], [B sx Req t], t `strengthen` uexprReft sx)
where
sx = F.symbol "x_"
idTys = tAnd . map idTy
---------------------------------------------------------------------------------
castTy :: (ExprReftable F.Symbol r, F.Reftable r) => RType r -> RType r
---------------------------------------------------------------------------------
castTy t = TFun [B sx Req t] (t `uSingleton` sx) fTop
where
sx = F.symbol "x"
---------------------------------------------------------------------------------
-- | Array literal types
---------------------------------------------------------------------------------
---------------------------------------------------------------------------------
arrayLitTy :: (Monad m, F.Reftable r, IsLocated l, PP r, PP a1, CheckingEnvironment r t)
=> l -> t r -> a1
-> Maybe (RType r)
-> Int
-> m (Either F.Error (RType r))
---------------------------------------------------------------------------------
arrayLitTy l g@(envCHA -> c) e (Just t0) n
| TRef nm _ <- t0 -- Get mutability from contextual type
, Just (Gen _ [m,t]) <- weaken c nm arrayName
= if isIM m then mkImmArrTy l g t n
else mkArrTy l g n
| otherwise
= return $ Left $ errorArrayLitType l e t0
arrayLitTy l g _ Nothing n = mkUniqueArrTy l g n
-- | mkIArray :: <A <: T>(x1: A, ... , xn: A) => {v: IArray<A> | len v = n }
--
mkImmArrTy l g t n = safeEnvFindTy l g ial >>= go
where
ial = builtinOpId BIImmArrayLit :: Id SrcSpan
go (TAll (BTV s l _) (TFun [B x_ o_ t_] tOut r))
= return $ Right $ mkAll [BTV s l (Just t)] (TFun (bs x_ o_ t_) (rt tOut) r)
go _ = return $ Left $ bugArrayBIType l ial t
bs x_ o_ t_ = [ B (tox x_ i) o_ t_ | i <- [1..n] ]
rt t_ = F.subst1 t_ (F.symbol numArgs, F.expr (n::Int))
tox x = F.symbol . ((symbolString x) ++) . show
numArgs = builtinOpId BINumArgs :: Id SrcSpan
-- | mkUArray :: <A>(a: A): Array<Unique, A>
--
mkUniqueArrTy l g n = safeEnvFindTy l g ual >>= go
where
ual = builtinOpId BIUniqueArrayLit :: Id SrcSpan
go (TAll α (TFun [B x_ o_ t_] rt r))
= return $ Right $ mkAll [α] (TFun (bs x_ o_ t_) rt r)
go t = return $ Left $ bugArrayBIType l ual t
bs x_ o_ t_ = [ B (tox x_ i) o_ t_ | i <- [1..n] ]
tox x = F.symbol . ((symbolString x) ++) . show
-- | mkArray :: <M,A>(a: A): Array<M,A>
--
mkArrTy l g n = safeEnvFindTy l g al >>= go
where
al = builtinOpId BIArrayLit :: Id SrcSpan
go (TAll μ (TAll α (TFun [B x_ Req t_] rt r)))
= return $ Right $ mkAll [μ,α] (TFun (bs x_ t_) rt r)
go t = return $ Left $ bugArrayBIType l al t
bs x_ t_ = [ B (tox x_ i) Req t_ | i <- [1..n] ]
tox x = F.symbol . ((symbolString x) ++) . show
-- --------------------------------------------------------------------------------
-- objLitTy :: (PPRE r, IsLocated l, CheckingEnvironment r t)
-- => l -> t r -> [Prop l] -> Maybe (RType r) -> ([Maybe (RType r)], RType r)
-- --------------------------------------------------------------------------------
-- objLitTy l g ps to = (ct, mkFun (concat bbs, bs, TObj (tmsFromList et) fTop))
-- where
-- (ct, bbs, bs, et) = unzip4 (map propToBind ps)
-- propToBind p = propParts l (F.symbol p) (F.lookupSEnv (F.symbol p) ctxTys)
-- ctxTys = maybe mempty (i_mems . typeMembersOfType (envCHA g)) to
--
-- --------------------------------------------------------------------------------
-- propParts :: (PPRE r, IsLocated l)
-- => l -> F.Symbol -> Maybe (TypeMember r)
-- -> (Maybe (RType r), [BTVar r], Bind r, TypeMember r)
-- -- ^^^^^^^^^^^^^^^
-- -- Contextual type
-- --
-- --------------------------------------------------------------------------------
-- propParts l p (Just (FI _ o m t)) = (Just t, [abtv], b, ot)
-- where
-- loc = srcPos l
-- aSym = F.symbol "A" `F.suffixSymbol` p -- TVar symbol
-- at = TV aSym loc
-- abtv = BTV aSym loc Nothing
-- b = B p ty
-- -- ot = FI p o m ty
-- ot = FI p o tUQ ty
-- ty = TVar at fTop
--
-- propParts l p Nothing = (Nothing, [abtv, pbtv], b, ot)
-- where
-- loc = srcPos l
-- aSym = F.symbol "A" `F.suffixSymbol` p
-- pSym = F.symbol "M" `F.suffixSymbol` p
-- at = TV aSym loc
-- abtv = BTV aSym loc Nothing
-- pt = TV pSym loc
-- pbtv = BTV pSym loc Nothing
-- -- pty = TVar pt fTop
-- b = B p ty
-- -- ot = FI p Req pty ty
-- ot = FI p Req tUQ ty
-- ty = TVar at fTop
mkCondExprTy l g t
= do opTy <- safeEnvFindTy l g (builtinOpId BICondExpr :: Id SrcSpan)
case bkAll opTy of
([c, BTV α la _, BTV β lb _], TFun [B c_ oc_ tc_, B a_ oa_ ta_, B b_ ob_ tb_] rt r') ->
return $ mkAll [c, BTV α la (Just t), BTV β lb (Just t)]
(TFun [B c_ oc_ tc_, B a_ oa_ ta_, B b_ ob_ tb_] (t `strengthen` rTypeR rt) r')
_ -> error "[BUG] mkCondExprTy"
-- `adjustCtxMut t ctxT`: adjust type `t` to the contextual type `tCtx`
-- (used for the type of NewExpr)
--------------------------------------------------------------------------------
adjustCtxMut :: F.Reftable r => RType r -> Maybe (RType r) -> RType r
--------------------------------------------------------------------------------
adjustCtxMut t (Just ctxT)
| TRef (Gen n (_ :ts)) r <- t
, TRef (Gen _ (m':_ )) _ <- ctxT
= TRef (Gen n (m':ts)) r
adjustCtxMut t Nothing
| TRef (Gen n (_ :ts)) r <- t
= TRef (Gen n (tUQ:ts)) r
adjustCtxMut t _ = t
-- | Expands (x1: T1, x2?: T2) => T to
--
-- [ (x1: T1 ) => T
-- , (x1: T1, x2: T2) => T ]
--
--------------------------------------------------------------------------------
overloads :: (CEnv r g, PPRE r) => g r -> RType r -> [IOverloadSig r]
--------------------------------------------------------------------------------
overloads γ = zip [0..] . go []
where
go αs (TFun ts t _) = expandOpts (αs, ts, t)
go αs (TAnd ts) = concatMap (go αs) (map snd ts)
go αs (TAll α t) = go (αs ++ [α]) t
go αs t@(TRef _ _) | Just t' <- expandType def (envCHA γ) t
= go αs t'
go αs (TObj _ ms _) | Just t <- tm_call ms
= go αs t
go _ _ = []
--------------------------------------------------------------------------------
expandOpts :: ([v], [Bind r], t) -> [([v], [Bind r], t)]
--------------------------------------------------------------------------------
expandOpts (αs, ts, t) = [(αs, args, t) | args <- argss]
where
(reqs, opts) = partition (( == Req) . b_opt) ts
opts' = map toReq opts
argss = [reqs ++ take n opts' | n <- [0 .. length opts]]
toReq (B s _ t) = B s Req t
| UCSD-PL/RefScript | src/Language/Rsc/TypeUtilities.hs | bsd-3-clause | 9,545 | 0 | 16 | 2,542 | 2,333 | 1,248 | 1,085 | 110 | 6 |
module Ex11 where
import Data.Vector (Vector)
import qualified Data.Vector as V
import Cards
nextCard :: Deck -> Maybe (Card, Deck)
nextCard d
| V.length d == 0 = Nothing
| otherwise = return (V.head d, V.tail d)
| bobbyrauchenberg/haskellCourse | src/Ex11.hs | bsd-3-clause | 228 | 0 | 10 | 52 | 94 | 50 | 44 | 8 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- | High-level access to TradeKing APIs
module Finance.TradeKing.Quotes (stockQuotes, stockInfos, streamQuotes) where
import Finance.TradeKing.Types
import Finance.TradeKing.Service (invokeSimple, streamQuotes')
import qualified Control.Exception.Lifted as E
import Control.Applicative
import Control.Monad
import Control.Monad.Trans.Resource (ResourceT)
import qualified Data.ByteString.Lazy.Char8 as LBS8
import qualified Data.ByteString.Char8 as BS
import qualified Data.Vector as V
import qualified Data.Text as T
import Data.Maybe
import Data.Conduit
import Data.Time
import Data.Time.Clock.POSIX
import Data.Monoid
import Data.Aeson ((.:), (.:?), eitherDecode, FromJSON, FromJSON(..), Value(..))
import Data.Aeson.Types (Parser)
import Network.OAuth.Http.Response
import Safe (readMay)
import System.Locale
newtype TKQuoteResponse fields = TKQuoteResponse { unTKQuoteResponse :: TKQuotes fields }
newtype TKQuotes field = TKQuotes { unTKQuotes :: [field] }
newtype TKStockQuote = TKStockQuote { unTKStockQuote :: StockQuote }
newtype TKStockInfo = TKStockInfo { unTKStockInfo :: StockInfo }
newtype TKPrice = TKPrice Fixed4
newtype TKFrequency = TKFrequency { unTKFrequency :: Period}
-- TKPrice always in USD
unTKPrice :: TKPrice -> Price
unTKPrice (TKPrice nominal) = Price USD nominal
instance FromJSON TKFrequency where
parseJSON (String t)
| t == "A" = return (TKFrequency Annually)
| t == "S" = return (TKFrequency SemiAnnually)
| t == "Q" = return (TKFrequency Quarterly)
| t == "M" = return (TKFrequency Monthly)
parseJSON _ = mzero
instance FromJSON TKPrice where
parseJSON (String t) = return (TKPrice . read . T.unpack $ t)
parseJSON _ = mzero
instance FromJSON fields => FromJSON (TKQuoteResponse fields) where
parseJSON (Object v) = do
response <- v .: "response"
quotes <- response .: "quotes"
TKQuoteResponse <$> quotes .: "quote"
parseJSON _ = mzero
instance FromJSON fields => FromJSON (TKQuotes fields) where
parseJSON o@(Object _) = do
quote <- parseJSON o
return (TKQuotes [quote])
parseJSON (Array v) = do
quotes <- V.toList <$> V.mapM parseJSON v
return (TKQuotes quotes)
parseJSON _ = mzero
adapt :: Read a => String -> Parser a
adapt = maybe mzero return . readMay
adaptMay :: Read a => Maybe String -> Parser (Maybe a)
adaptMay (Just s) = maybe mzero return . Just . readMay $ s
adaptMay Nothing = return Nothing
instance FromJSON StreamOutput where
parseJSON (Object v) = do
let parseQuote (Object v) =
do
timestamp <- (maybe mzero return . parseTime defaultTimeLocale "%FT%T%z") =<< v .: "datetime"
let day = localDay . zonedTimeToLocalTime $ timestamp
timeFormat = "%R"
timeZone = zonedTimeZone timestamp
StreamQuote <$> pure (zonedTimeToUTC timestamp)
<*> (Stock <$> v .: "symbol")
<*> (unTKPrice <$> v .: "ask")
<*> (adapt =<< v .: "asksz")
<*> (unTKPrice <$> v .: "bid")
<*> (adapt =<< v .: "bidsz")
<*> v .:? "qcond"
parseQuote _ = mzero
parseTrade (Object v) =
do
timestamp <- (maybe mzero return . parseTime defaultTimeLocale "%FT%T%z") =<< v .: "datetime"
let day = localDay . zonedTimeToLocalTime $ timestamp
timeFormat = "%R"
timeZone = zonedTimeZone timestamp
StreamTrade <$> pure (zonedTimeToUTC timestamp)
<*> (Stock <$> v .: "symbol")
<*> (unTKPrice <$> (maybe (v .: "hi") return =<< (v .:? "last")))
<*> (adapt =<< v .: "vl")
<*> (adapt =<< v .: "cvol")
<*> (adaptMay =<< v .:? "vwap")
<*> (v .:? "tcond")
<*> (Exchange <$> v .: "exch")
parseTrade _ = mzero
status <- v .:? "status"
quote <- v .:? "quote"
trade <- v .:? "trade"
case status of
Nothing -> case quote of
Nothing -> case trade of
Nothing -> mzero
Just t -> parseTrade t
Just q -> parseQuote q
Just s -> return (StreamStatus s)
parseJSON _ = mzero
instance FromJSON TKStockQuote where
parseJSON (Object v) = do
timestamp <- (maybe mzero return . parseTime defaultTimeLocale "%FT%T%z") =<< v .: "datetime"
let day = localDay . zonedTimeToLocalTime $ timestamp
timeFormat = "%R"
timeZone = zonedTimeZone timestamp
TKStockQuote <$> (
StockQuote <$>
(Stock <$> v .: "symbol") <*>
pure (zonedTimeToUTC timestamp) <*>
(unTKPrice <$> v .: "ask") <*>
(localTimeToUTC timeZone . LocalTime day <$> (maybe mzero return . parseTime defaultTimeLocale timeFormat =<< v .: "ask_time")) <*>
(adapt =<< v .: "asksz") <*>
(unTKPrice <$> v .: "bid") <*>
(localTimeToUTC timeZone . LocalTime day <$> (maybe mzero return . parseTime defaultTimeLocale timeFormat =<< v .: "bid_time")) <*>
(adapt =<< v .: "bidsz") <*>
(unTKPrice <$> v .: "last") <*>
(adapt =<< v .: "incr_vl") <*>
(adapt =<< v .: "vl"))
parseJSON _ = mzero
instance FromJSON TKStockInfo where
parseJSON o@(Object v) = do
timestamp <- (maybe mzero return . parseTime defaultTimeLocale "%FT%T%z") =<< v .: "datetime"
let parseDate = maybe mzero return . parseTime defaultTimeLocale "%Y%m%d"
timeZone = zonedTimeZone timestamp
TKStockInfo <$> (
StockInfo <$>
(Stock <$> v .: "symbol") <*>
pure (zonedTimeToUTC timestamp) <*>
v .: "name" <*>
(unTKPrice <$> v .: "pcls") <*>
(unTKPrice <$> v .: "popn") <*>
(unTKPrice <$> v .: "opn") <*>
(CUSIP <$> v .: "cusip") <*>
(maybe Nothing (Just . unTKPrice) <$> (v .:? "div")) <*>
(maybe (return Nothing) ((Just <$>) . parseDate) =<< (v .:? "divexdate")) <*>
(maybe Nothing (Just . unTKFrequency) <$> (v .:? "divfreq")) <*>
(maybe (return Nothing) ((Just <$>) . parseDate) =<< (v .:? "divpaydt")) <*>
(adapt . filter (/= ',') =<< v .: "sho") <*> -- Tradeking returns the number separated by commas, ew...
(maybe Nothing (Just . unTKPrice) <$> v .:? "eps") <*>
(Exchange <$> v .: "exch") <*>
(HighLow <$> (unTKPrice <$> v .: "phi") <*> (unTKPrice <$> v .: "plo")) <*>
(HighLow <$> ((,) <$> (parseDate =<< (v .: "wk52lodate")) <*> (unTKPrice <$> v .: "wk52lo"))
<*> ((,) <$> (parseDate =<< (v .: "wk52hidate")) <*> (unTKPrice <$> v .: "wk52hi"))) <*>
(maybe Nothing readMay <$> v .:? "pe") <*>
(unTKPrice <$> v .: "prbook") <*>
(unTKStockQuote <$> parseJSON o))
parseJSON _ = mzero
-- | Retrieve the stock quotes for the stocks specified.
stockQuotes :: TradeKingApp -> [Stock] -> IO [StockQuote]
stockQuotes app stocks = do
let command = Quote assets ["timestamp", "ask", "ask_time", "asksz",
"bid", "bid_time", "bidsz", "last",
"date", "incr_vl", "vl"]
assets = map StockAsset stocks
response <- invokeSimple app command JSON
case eitherDecode (rspPayload response) of
Left e -> fail ("Malformed data returned: " ++ e)
Right quoteData -> return (map unTKStockQuote . unTKQuotes . unTKQuoteResponse $ quoteData)
-- | Retrieve information on the stock symbols specified.
stockInfos :: TradeKingApp -> [Stock] -> IO [StockInfo]
stockInfos app stocks = do
let command = Quote assets []
assets = map StockAsset stocks
response <- invokeSimple app command JSON
case eitherDecode (rspPayload response) of
Left e -> fail ("Malformed data returned: " ++ e)
Right infoData -> return (map unTKStockInfo . unTKQuotes . unTKQuoteResponse $ infoData)
-- | Run a streaming operation on the stocks specified. This takes a function which will be passed a
-- `Source` from `Data.Conduit` that will yield the streaming quote information.
streamQuotes :: TradeKingApp -> [Stock] -> (Source (ResourceT IO) StreamOutput -> ResourceT IO b) -> IO b
streamQuotes app stocks f = streamQuotes' app stocks doStream
where doStream bsrc = do
(bsrc', finalizer) <- unwrapResumable bsrc
let decodeMessages a = await >>= \x ->
case x of
Nothing -> return ()
Just x -> case eitherDecode (LBS8.fromChunks (a [x])) of
Left e ->
-- Now we check to see if what we have is valid JSON. If it's not, we haven't read enough bytes in.
-- Otherwise, it's actually malfored, so we error out...
case (eitherDecode (LBS8.fromChunks (a [x])) :: Either String Value) of
-- The parse failed, so we just don't have enough JSON...
Left _ -> decodeMessages ((x:).a)
-- If the parse succeeeded, we have JSON, but we couldn't parse it.
Right _ -> fail ("Malformed data returned: " ++ e ++ "\nData was: " ++ BS.unpack x)
Right d -> do
yield d
decodeMessages id
f (bsrc' $= decodeMessages id) `E.finally` finalizer
| tathougies/hstradeking | src/Finance/TradeKing/Quotes.hs | bsd-3-clause | 9,994 | 0 | 32 | 3,257 | 2,852 | 1,477 | 1,375 | 183 | 4 |
{-# OPTIONS -fno-warn-name-shadowing #-}
{-# LANGUAGE NoMonoLocalBinds #-}
{-# LANGUAGE TypeFamilies #-}
module Language.Haskell.Names.Exports
( processExports
) where
import Fay.Compiler.ModuleT
import Language.Haskell.Names.GlobalSymbolTable as Global
import Language.Haskell.Names.ModuleSymbols
import Language.Haskell.Names.ScopeUtils
import Language.Haskell.Names.SyntaxUtils
import Language.Haskell.Names.Types (Error (..), GName (..), ModuleNameS, NameInfo (..),
Scoped (..), Symbols (..), mkTy, mkVal, st_origName)
import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.Writer
import Data.Data
import qualified Data.Map as Map
import qualified Data.Set as Set
import Language.Haskell.Exts.Annotated
processExports
:: (MonadModule m, ModuleInfo m ~ Symbols, Data l, Eq l)
=> Global.Table
-> Module l
-> m (Maybe (ExportSpecList (Scoped l)), Symbols)
processExports tbl m =
case getExportSpecList m of
Nothing ->
return (Nothing, moduleSymbols tbl m)
Just exp ->
liftM (first Just) $ resolveExportSpecList tbl exp
resolveExportSpecList
:: (MonadModule m, ModuleInfo m ~ Symbols)
=> Global.Table
-> ExportSpecList l
-> m (ExportSpecList (Scoped l), Symbols)
resolveExportSpecList tbl (ExportSpecList l specs) =
liftM (first $ ExportSpecList $ none l) $
runWriterT $
mapM (WriterT . resolveExportSpec tbl) specs
resolveExportSpec
:: (MonadModule m, ModuleInfo m ~ Symbols)
=> Global.Table
-> ExportSpec l
-> m (ExportSpec (Scoped l), Symbols)
resolveExportSpec tbl exp =
case exp of
EVar l ns@(NoNamespace {}) qn -> return $
case Global.lookupValue qn tbl of
Global.Error err ->
(scopeError err exp, mempty)
Global.Result i ->
let s = mkVal i
in
(EVar (Scoped (Export s) l)
(noScope ns)
(Scoped (GlobalValue i) <$> qn), s)
Global.Special {} -> error "Global.Special in export list?"
EVar _ (TypeNamespace {}) _ -> error "'type' namespace is not supported yet" -- FIXME
EAbs l qn -> return $
case Global.lookupType qn tbl of
Global.Error err ->
(scopeError err exp, mempty)
Global.Result i ->
let s = mkTy i
in
(EAbs (Scoped (Export s) l)
(Scoped (GlobalType i) <$> qn), s)
Global.Special {} -> error "Global.Special in export list?"
EThingAll l qn -> return $
case Global.lookupType qn tbl of
Global.Error err ->
(scopeError err exp, mempty)
Global.Result i ->
let
subs = mconcat
[ mkVal info
| info <- allValueInfos
, Just n' <- return $ sv_parent info
, n' == st_origName i ]
s = mkTy i <> subs
in
( EThingAll (Scoped (Export s) l) (Scoped (GlobalType i) <$> qn)
, s
)
Global.Special {} -> error "Global.Special in export list?"
EThingWith l qn cns -> return $
case Global.lookupType qn tbl of
Global.Error err ->
(scopeError err exp, mempty)
Global.Result i ->
let
(cns', subs) =
resolveCNames
(Global.toSymbols tbl)
(st_origName i)
(\cn -> ENotInScope (UnQual (ann cn) (unCName cn))) -- FIXME better error
cns
s = mkTy i <> subs
in
( EThingWith (Scoped (Export s) l) (Scoped (GlobalType i) <$> qn) cns'
, s
)
Global.Special {} -> error "Global.Special in export list?"
EModuleContents _ (ModuleName _ mod) ->
-- FIXME ambiguity check
let
filterByPrefix
:: Ord i
=> ModuleNameS
-> Map.Map GName (Set.Set i)
-> Set.Set i
filterByPrefix prefix m =
Set.unions
[ i | (GName { gModule = prefix' }, i) <- Map.toList m, prefix' == prefix ]
filterEntities
:: Ord i
=> Map.Map GName (Set.Set i)
-> Set.Set i
filterEntities ents =
Set.intersection
(filterByPrefix mod ents)
(filterByPrefix "" ents)
eVals = filterEntities $ Global.values tbl
eTyps = filterEntities $ Global.types tbl
s = Symbols eVals eTyps
in
return (Scoped (Export s) <$> exp, s)
where
allValueInfos =
Set.toList $ Map.foldl' Set.union Set.empty $ Global.values tbl
| beni55/fay | src/haskell-names/Language/Haskell/Names/Exports.hs | bsd-3-clause | 4,797 | 0 | 23 | 1,679 | 1,449 | 741 | 708 | 122 | 14 |
module VisibilityTest where
import Test.Framework (buildTest, defaultMain, testGroup)
import Test.Framework.Providers.HUnit
import Test.HUnit
import Geometry
import Visibility
main = defaultMain tests
tests = [testCalculateEndpoints, testSweep]
testCalculateEndpoints = testGroup "calculateEndpoints"
[ testCase "test1" test1
, testCase "test2" test2 ]
where segment = Segment (-1, 1) (1, 1)
test1 = calculateEndpoints (0, 0) segment @?=
[ Endpoint (-1, 1) (Segment (-1, 1) (1, 1)) 2.356194490192345 False
, Endpoint ( 1, 1) (Segment (-1, 1) (1, 1)) 0.7853981633974483 True ]
test2 = calculateEndpoints (0, 1) segment @?=
[ Endpoint (-1, 1) (Segment (-1, 1) (1, 1)) 3.141592653589793 False
, Endpoint ( 1, 1) (Segment (-1, 1) (1, 1)) 0.0 True ]
testSweep = testGroup "calculateVisibility"
[ testCase "test1" test1
, testCase "test2" test2
, testCase "test3" test3
, testCase "test4" test4 ]
where rectangles = [ Rectangle (-1, -1) ( 2, 2)
, Rectangle (-5, -5) (10, 10) ]
test1 = calculateVisibility (0, 0) rectangles @?=
[ Triangle (0, 0) ( 1, 1) (-1, 1)
, Triangle (0, 0) ( 1, -1) ( 1, 1)
, Triangle (0, 0) (-1, -1) ( 1, -1)
, Triangle (0, 0) (-1, 1) (-1, -1) ]
test2 = calculateVisibility (0, 1) rectangles @?=
[ Triangle (0, 1) (-1, 1) ( 1, 1)
, Triangle (0, 1) ( 1, -1) ( 1, 1)
, Triangle (0, 1) (-1, -1) ( 1, -1)
, Triangle (0, 1) (-1, 1) (-1, -1) ]
test3 = calculateVisibility (0, 2) rectangles @?=
[ Triangle (0, 2) ( 5, 5) (-5, 5)
, Triangle (0, 2) ( 5, -3) ( 5, 5)
, Triangle (0, 2) (-1, 1) ( 1, 1)
, Triangle (0, 2) (-5, 5) (-5, -3) ]
test4 = calculateVisibility (0, 4) rectangles @?=
[ Triangle (0, 4) ( 5, 5) (-5, 5)
, Triangle (0, 4) ( 5, -5) ( 5, 5)
, Triangle (0, 4) ( 3, -5) ( 5, -5)
, Triangle (0, 4) (-1, 1) ( 1, 1)
, Triangle (0, 4) (-5, -5) (-3, -5)
, Triangle (0, 4) (-5, 5) (-5, -5) ]
| nullobject/flatland-haskell | test/VisibilityTest.hs | bsd-3-clause | 2,162 | 0 | 13 | 694 | 1,062 | 617 | 445 | 47 | 1 |
{-# LANGUAGE TypeOperators #-}
-- |
-- Module : Data.Binding.Hobbits
-- Copyright : (c) 2011 Edwin Westbrook, Nicolas Frisby, and Paul Brauner
--
-- License : BSD3
--
-- Maintainer : emw4@rice.edu
-- Stability : experimental
-- Portability : GHC
--
-- This library implements multi-bindings as described in the paper
-- E. Westbrook, N. Frisby, P. Brauner, \"Hobbits for Haskell: A Library for
-- Higher-Order Encodings in Functional Programming Languages\".
module Data.Binding.Hobbits (
-- * Values under multi-bindings
module Data.Binding.Hobbits.Mb,
-- | The 'Data.Binding.Hobbits.Mb.Mb' type modeling multi-bindings is the
-- central abstract type of the library
-- * Closed terms
module Data.Binding.Hobbits.Closed,
-- | The 'Data.Binding.Hobbits.Closed.Cl' type models
-- super-combinators, which are safe functions to apply under
-- 'Data.Binding.Hobbits.Mb.Mb'.
-- * Pattern-matching multi-bindings and closed terms
module Data.Binding.Hobbits.QQ,
-- | The 'Data.Binding.Hobbits.QQ.nuP' and 'Data.Binding.Hobbits.QQ.nuMP'
-- quasiquoters allow safe pattern matching on 'Data.Binding.Hobbits.Mb.Mb'
-- values.
-- * Lifting values out of multi-bindings
module Data.Binding.Hobbits.Liftable,
-- * Ancilliary modules
module Data.Proxy, module Data.Type.Equality,
-- | Type lists track the types of bound variables.
--module Data.Type.RList,
RList, RNil, (:>), RAssign(..), Member(..), (:++:), Append(..),
-- | The "Data.Binding.Hobbits.NuMatching" module exposes the NuMatching
-- class, which allows pattern-matching on (G)ADTs in the bodies of
-- multi-bindings
module Data.Binding.Hobbits.NuMatching,
) where
import Data.Proxy
import Data.Type.Equality
import Data.Type.RList (RList, RNil, (:>), RAssign(..), Member(..), (:++:), Append(..))
import Data.Binding.Hobbits.Mb
import Data.Binding.Hobbits.Closed
import Data.Binding.Hobbits.QQ
import Data.Binding.Hobbits.Liftable
import Data.Binding.Hobbits.NuMatching
import Data.Binding.Hobbits.NuMatchingInstances ()
| eddywestbrook/hobbits | src/Data/Binding/Hobbits.hs | bsd-3-clause | 2,074 | 0 | 6 | 333 | 233 | 176 | 57 | 18 | 0 |
{-# LANGUAGE DeriveGeneric #-}
module Configuration where
import qualified Data.Text as T
import Data.Yaml
import GHC.Generics
import System.FilePath ()
data Configuration = Configuration
{ n4jHost :: T.Text
, n4jPort :: Int
, n4jUser :: T.Text
, n4jPass :: T.Text
} deriving (Eq, Generic, Show)
instance FromJSON Configuration
readConfFile :: FilePath -> IO (Either ParseException Configuration)
readConfFile filep = decodeFileEither filep
| vulgr/vulgr | src/Configuration.hs | bsd-3-clause | 466 | 0 | 9 | 85 | 123 | 71 | 52 | 15 | 1 |
{-# LANGUAGE CPP, MagicHash, RecordWildCards #-}
--
-- (c) The University of Glasgow 2002-2006
--
-- | ByteCodeGen: Generate bytecode from Core
module ByteCodeGen ( UnlinkedBCO, byteCodeGen, coreExprToBCOs ) where
#include "HsVersions.h"
import ByteCodeInstr
import ByteCodeAsm
import ByteCodeTypes
import GHCi
import GHCi.FFI
import GHCi.RemoteTypes
import BasicTypes
import DynFlags
import Outputable
import Platform
import Name
import MkId
import Id
import ForeignCall
import HscTypes
import CoreUtils
import CoreSyn
import PprCore
import Literal
import PrimOp
import CoreFVs
import Type
import Kind ( isLiftedTypeKind )
import DataCon
import TyCon
import Util
import VarSet
import TysPrim
import ErrUtils
import Unique
import FastString
import Panic
import StgCmmLayout ( ArgRep(..), toArgRep, argRepSizeW )
import SMRep
import Bitmap
import OrdList
import Maybes
import Data.List
import Foreign
import Control.Monad
import Data.Char
import UniqSupply
import Module
import Control.Arrow ( second )
import Data.Array
import Data.Map (Map)
import Data.IntMap (IntMap)
import qualified Data.Map as Map
import qualified Data.IntMap as IntMap
import qualified FiniteMap as Map
import Data.Ord
import GHC.Stack.CCS
-- -----------------------------------------------------------------------------
-- Generating byte code for a complete module
byteCodeGen :: HscEnv
-> Module
-> CoreProgram
-> [TyCon]
-> Maybe ModBreaks
-> IO CompiledByteCode
byteCodeGen hsc_env this_mod binds tycs mb_modBreaks
= withTiming (pure dflags)
(text "ByteCodeGen"<+>brackets (ppr this_mod))
(const ()) $ do
let flatBinds = [ (bndr, simpleFreeVars rhs)
| (bndr, rhs) <- flattenBinds binds]
us <- mkSplitUniqSupply 'y'
(BcM_State{..}, proto_bcos) <-
runBc hsc_env us this_mod mb_modBreaks $
mapM schemeTopBind flatBinds
when (notNull ffis)
(panic "ByteCodeGen.byteCodeGen: missing final emitBc?")
dumpIfSet_dyn dflags Opt_D_dump_BCOs
"Proto-BCOs" (vcat (intersperse (char ' ') (map ppr proto_bcos)))
assembleBCOs hsc_env proto_bcos tycs
(case modBreaks of
Nothing -> Nothing
Just mb -> Just mb{ modBreaks_breakInfo = breakInfo })
where dflags = hsc_dflags hsc_env
-- -----------------------------------------------------------------------------
-- Generating byte code for an expression
-- Returns: the root BCO for this expression
coreExprToBCOs :: HscEnv
-> Module
-> CoreExpr
-> IO UnlinkedBCO
coreExprToBCOs hsc_env this_mod expr
= withTiming (pure dflags)
(text "ByteCodeGen"<+>brackets (ppr this_mod))
(const ()) $ do
-- create a totally bogus name for the top-level BCO; this
-- should be harmless, since it's never used for anything
let invented_name = mkSystemVarName (mkPseudoUniqueE 0) (fsLit "ExprTopLevel")
invented_id = Id.mkLocalId invented_name (panic "invented_id's type")
-- the uniques are needed to generate fresh variables when we introduce new
-- let bindings for ticked expressions
us <- mkSplitUniqSupply 'y'
(BcM_State _dflags _us _this_mod _final_ctr mallocd _ _ , proto_bco)
<- runBc hsc_env us this_mod Nothing $
schemeTopBind (invented_id, simpleFreeVars expr)
when (notNull mallocd)
(panic "ByteCodeGen.coreExprToBCOs: missing final emitBc?")
dumpIfSet_dyn dflags Opt_D_dump_BCOs "Proto-BCOs" (ppr proto_bco)
assembleOneBCO hsc_env proto_bco
where dflags = hsc_dflags hsc_env
-- The regular freeVars function gives more information than is useful to
-- us here. simpleFreeVars does the impedence matching.
simpleFreeVars :: CoreExpr -> AnnExpr Id DVarSet
simpleFreeVars = go . freeVars
where
go :: AnnExpr Id FVAnn -> AnnExpr Id DVarSet
go (ann, e) = (freeVarsOfAnn ann, go' e)
go' :: AnnExpr' Id FVAnn -> AnnExpr' Id DVarSet
go' (AnnVar id) = AnnVar id
go' (AnnLit lit) = AnnLit lit
go' (AnnLam bndr body) = AnnLam bndr (go body)
go' (AnnApp fun arg) = AnnApp (go fun) (go arg)
go' (AnnCase scrut bndr ty alts) = AnnCase (go scrut) bndr ty (map go_alt alts)
go' (AnnLet bind body) = AnnLet (go_bind bind) (go body)
go' (AnnCast expr (ann, co)) = AnnCast (go expr) (freeVarsOfAnn ann, co)
go' (AnnTick tick body) = AnnTick tick (go body)
go' (AnnType ty) = AnnType ty
go' (AnnCoercion co) = AnnCoercion co
go_alt (con, args, expr) = (con, args, go expr)
go_bind (AnnNonRec bndr rhs) = AnnNonRec bndr (go rhs)
go_bind (AnnRec pairs) = AnnRec (map (second go) pairs)
-- -----------------------------------------------------------------------------
-- Compilation schema for the bytecode generator
type BCInstrList = OrdList BCInstr
type Sequel = Word -- back off to this depth before ENTER
-- Maps Ids to the offset from the stack _base_ so we don't have
-- to mess with it after each push/pop.
type BCEnv = Map Id Word -- To find vars on the stack
{-
ppBCEnv :: BCEnv -> SDoc
ppBCEnv p
= text "begin-env"
$$ nest 4 (vcat (map pp_one (sortBy cmp_snd (Map.toList p))))
$$ text "end-env"
where
pp_one (var, offset) = int offset <> colon <+> ppr var <+> ppr (bcIdArgRep var)
cmp_snd x y = compare (snd x) (snd y)
-}
-- Create a BCO and do a spot of peephole optimisation on the insns
-- at the same time.
mkProtoBCO
:: DynFlags
-> name
-> BCInstrList
-> Either [AnnAlt Id DVarSet] (AnnExpr Id DVarSet)
-> Int
-> Word16
-> [StgWord]
-> Bool -- True <=> is a return point, rather than a function
-> [FFIInfo]
-> ProtoBCO name
mkProtoBCO dflags nm instrs_ordlist origin arity bitmap_size bitmap is_ret ffis
= ProtoBCO {
protoBCOName = nm,
protoBCOInstrs = maybe_with_stack_check,
protoBCOBitmap = bitmap,
protoBCOBitmapSize = bitmap_size,
protoBCOArity = arity,
protoBCOExpr = origin,
protoBCOFFIs = ffis
}
where
-- Overestimate the stack usage (in words) of this BCO,
-- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit
-- stack check. (The interpreter always does a stack check
-- for iNTERP_STACK_CHECK_THRESH words at the start of each
-- BCO anyway, so we only need to add an explicit one in the
-- (hopefully rare) cases when the (overestimated) stack use
-- exceeds iNTERP_STACK_CHECK_THRESH.
maybe_with_stack_check
| is_ret && stack_usage < fromIntegral (aP_STACK_SPLIM dflags) = peep_d
-- don't do stack checks at return points,
-- everything is aggregated up to the top BCO
-- (which must be a function).
-- That is, unless the stack usage is >= AP_STACK_SPLIM,
-- see bug #1466.
| stack_usage >= fromIntegral iNTERP_STACK_CHECK_THRESH
= STKCHECK stack_usage : peep_d
| otherwise
= peep_d -- the supposedly common case
-- We assume that this sum doesn't wrap
stack_usage = sum (map bciStackUse peep_d)
-- Merge local pushes
peep_d = peep (fromOL instrs_ordlist)
peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)
= PUSH_LLL off1 (off2-1) (off3-2) : peep rest
peep (PUSH_L off1 : PUSH_L off2 : rest)
= PUSH_LL off1 (off2-1) : peep rest
peep (i:rest)
= i : peep rest
peep []
= []
argBits :: DynFlags -> [ArgRep] -> [Bool]
argBits _ [] = []
argBits dflags (rep : args)
| isFollowableArg rep = False : argBits dflags args
| otherwise = take (argRepSizeW dflags rep) (repeat True) ++ argBits dflags args
-- -----------------------------------------------------------------------------
-- schemeTopBind
-- Compile code for the right-hand side of a top-level binding
schemeTopBind :: (Id, AnnExpr Id DVarSet) -> BcM (ProtoBCO Name)
schemeTopBind (id, rhs)
| Just data_con <- isDataConWorkId_maybe id,
isNullaryRepDataCon data_con = do
dflags <- getDynFlags
-- Special case for the worker of a nullary data con.
-- It'll look like this: Nil = /\a -> Nil a
-- If we feed it into schemeR, we'll get
-- Nil = Nil
-- because mkConAppCode treats nullary constructor applications
-- by just re-using the single top-level definition. So
-- for the worker itself, we must allocate it directly.
-- ioToBc (putStrLn $ "top level BCO")
emitBc (mkProtoBCO dflags (getName id) (toOL [PACK data_con 0, ENTER])
(Right rhs) 0 0 [{-no bitmap-}] False{-not alts-})
| otherwise
= schemeR [{- No free variables -}] (id, rhs)
-- -----------------------------------------------------------------------------
-- schemeR
-- Compile code for a right-hand side, to give a BCO that,
-- when executed with the free variables and arguments on top of the stack,
-- will return with a pointer to the result on top of the stack, after
-- removing the free variables and arguments.
--
-- Park the resulting BCO in the monad. Also requires the
-- variable to which this value was bound, so as to give the
-- resulting BCO a name.
schemeR :: [Id] -- Free vars of the RHS, ordered as they
-- will appear in the thunk. Empty for
-- top-level things, which have no free vars.
-> (Id, AnnExpr Id DVarSet)
-> BcM (ProtoBCO Name)
schemeR fvs (nm, rhs)
{-
| trace (showSDoc (
(char ' '
$$ (ppr.filter (not.isTyVar).dVarSetElems.fst) rhs
$$ pprCoreExpr (deAnnotate rhs)
$$ char ' '
))) False
= undefined
| otherwise
-}
= schemeR_wrk fvs nm rhs (collect rhs)
collect :: AnnExpr Id DVarSet -> ([Var], AnnExpr' Id DVarSet)
collect (_, e) = go [] e
where
go xs e | Just e' <- bcView e = go xs e'
go xs (AnnLam x (_,e))
| UbxTupleRep _ <- repType (idType x)
= unboxedTupleException
| otherwise
= go (x:xs) e
go xs not_lambda = (reverse xs, not_lambda)
schemeR_wrk :: [Id] -> Id -> AnnExpr Id DVarSet -> ([Var], AnnExpr' Var DVarSet) -> BcM (ProtoBCO Name)
schemeR_wrk fvs nm original_body (args, body)
= do
dflags <- getDynFlags
let
all_args = reverse args ++ fvs
arity = length all_args
-- all_args are the args in reverse order. We're compiling a function
-- \fv1..fvn x1..xn -> e
-- i.e. the fvs come first
szsw_args = map (fromIntegral . idSizeW dflags) all_args
szw_args = sum szsw_args
p_init = Map.fromList (zip all_args (mkStackOffsets 0 szsw_args))
-- make the arg bitmap
bits = argBits dflags (reverse (map bcIdArgRep all_args))
bitmap_size = genericLength bits
bitmap = mkBitmap dflags bits
body_code <- schemeER_wrk szw_args p_init body
emitBc (mkProtoBCO dflags (getName nm) body_code (Right original_body)
arity bitmap_size bitmap False{-not alts-})
-- introduce break instructions for ticked expressions
schemeER_wrk :: Word -> BCEnv -> AnnExpr' Id DVarSet -> BcM BCInstrList
schemeER_wrk d p rhs
| AnnTick (Breakpoint tick_no fvs) (_annot, newRhs) <- rhs
= do code <- schemeE (fromIntegral d) 0 p newRhs
cc_arr <- getCCArray
this_mod <- moduleName <$> getCurrentModule
let idOffSets = getVarOffSets d p fvs
let breakInfo = CgBreakInfo
{ cgb_vars = idOffSets
, cgb_resty = exprType (deAnnotate' newRhs)
}
newBreakInfo tick_no breakInfo
dflags <- getDynFlags
let cc | interpreterProfiled dflags = cc_arr ! tick_no
| otherwise = toRemotePtr nullPtr
let breakInstr = BRK_FUN (fromIntegral tick_no) (getUnique this_mod) cc
return $ breakInstr `consOL` code
| otherwise = schemeE (fromIntegral d) 0 p rhs
getVarOffSets :: Word -> BCEnv -> [Id] -> [(Id, Word16)]
getVarOffSets d p = catMaybes . map (getOffSet d p)
getOffSet :: Word -> BCEnv -> Id -> Maybe (Id, Word16)
getOffSet d env id
= case lookupBCEnv_maybe id env of
Nothing -> Nothing
Just offset -> Just (id, trunc16 $ d - offset)
trunc16 :: Word -> Word16
trunc16 w
| w > fromIntegral (maxBound :: Word16)
= panic "stack depth overflow"
| otherwise
= fromIntegral w
fvsToEnv :: BCEnv -> DVarSet -> [Id]
-- Takes the free variables of a right-hand side, and
-- delivers an ordered list of the local variables that will
-- be captured in the thunk for the RHS
-- The BCEnv argument tells which variables are in the local
-- environment: these are the ones that should be captured
--
-- The code that constructs the thunk, and the code that executes
-- it, have to agree about this layout
fvsToEnv p fvs = [v | v <- dVarSetElems fvs,
isId v, -- Could be a type variable
v `Map.member` p]
-- -----------------------------------------------------------------------------
-- schemeE
returnUnboxedAtom :: Word -> Sequel -> BCEnv
-> AnnExpr' Id DVarSet -> ArgRep
-> BcM BCInstrList
-- Returning an unlifted value.
-- Heave it on the stack, SLIDE, and RETURN.
returnUnboxedAtom d s p e e_rep
= do (push, szw) <- pushAtom d p e
return (push -- value onto stack
`appOL` mkSLIDE szw (d-s) -- clear to sequel
`snocOL` RETURN_UBX e_rep) -- go
-- Compile code to apply the given expression to the remaining args
-- on the stack, returning a HNF.
schemeE :: Word -> Sequel -> BCEnv -> AnnExpr' Id DVarSet -> BcM BCInstrList
schemeE d s p e
| Just e' <- bcView e
= schemeE d s p e'
-- Delegate tail-calls to schemeT.
schemeE d s p e@(AnnApp _ _) = schemeT d s p e
schemeE d s p e@(AnnLit lit) = returnUnboxedAtom d s p e (typeArgRep (literalType lit))
schemeE d s p e@(AnnCoercion {}) = returnUnboxedAtom d s p e V
schemeE d s p e@(AnnVar v)
| isUnliftedType (idType v) = returnUnboxedAtom d s p e (bcIdArgRep v)
| otherwise = schemeT d s p e
schemeE d s p (AnnLet (AnnNonRec x (_,rhs)) (_,body))
| (AnnVar v, args_r_to_l) <- splitApp rhs,
Just data_con <- isDataConWorkId_maybe v,
dataConRepArity data_con == length args_r_to_l
= do -- Special case for a non-recursive let whose RHS is a
-- saturatred constructor application.
-- Just allocate the constructor and carry on
alloc_code <- mkConAppCode d s p data_con args_r_to_l
body_code <- schemeE (d+1) s (Map.insert x d p) body
return (alloc_code `appOL` body_code)
-- General case for let. Generates correct, if inefficient, code in
-- all situations.
schemeE d s p (AnnLet binds (_,body)) = do
dflags <- getDynFlags
let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])
AnnRec xs_n_rhss -> unzip xs_n_rhss
n_binds = genericLength xs
fvss = map (fvsToEnv p' . fst) rhss
-- Sizes of free vars
sizes = map (\rhs_fvs -> sum (map (fromIntegral . idSizeW dflags) rhs_fvs)) fvss
-- the arity of each rhs
arities = map (genericLength . fst . collect) rhss
-- This p', d' defn is safe because all the items being pushed
-- are ptrs, so all have size 1. d' and p' reflect the stack
-- after the closures have been allocated in the heap (but not
-- filled in), and pointers to them parked on the stack.
p' = Map.insertList (zipE xs (mkStackOffsets d (genericReplicate n_binds 1))) p
d' = d + fromIntegral n_binds
zipE = zipEqual "schemeE"
-- ToDo: don't build thunks for things with no free variables
build_thunk _ [] size bco off arity
= return (PUSH_BCO bco `consOL` unitOL (mkap (off+size) size))
where
mkap | arity == 0 = MKAP
| otherwise = MKPAP
build_thunk dd (fv:fvs) size bco off arity = do
(push_code, pushed_szw) <- pushAtom dd p' (AnnVar fv)
more_push_code <- build_thunk (dd + fromIntegral pushed_szw) fvs size bco off arity
return (push_code `appOL` more_push_code)
alloc_code = toOL (zipWith mkAlloc sizes arities)
where mkAlloc sz 0
| is_tick = ALLOC_AP_NOUPD sz
| otherwise = ALLOC_AP sz
mkAlloc sz arity = ALLOC_PAP arity sz
is_tick = case binds of
AnnNonRec id _ -> occNameFS (getOccName id) == tickFS
_other -> False
compile_bind d' fvs x rhs size arity off = do
bco <- schemeR fvs (x,rhs)
build_thunk d' fvs size bco off arity
compile_binds =
[ compile_bind d' fvs x rhs size arity n
| (fvs, x, rhs, size, arity, n) <-
zip6 fvss xs rhss sizes arities [n_binds, n_binds-1 .. 1]
]
body_code <- schemeE d' s p' body
thunk_codes <- sequence compile_binds
return (alloc_code `appOL` concatOL thunk_codes `appOL` body_code)
-- Introduce a let binding for a ticked case expression. This rule
-- *should* only fire when the expression was not already let-bound
-- (the code gen for let bindings should take care of that). Todo: we
-- call exprFreeVars on a deAnnotated expression, this may not be the
-- best way to calculate the free vars but it seemed like the least
-- intrusive thing to do
schemeE d s p exp@(AnnTick (Breakpoint _id _fvs) _rhs)
| isLiftedTypeKind (typeKind ty)
= do id <- newId ty
-- Todo: is emptyVarSet correct on the next line?
let letExp = AnnLet (AnnNonRec id (fvs, exp)) (emptyDVarSet, AnnVar id)
schemeE d s p letExp
| otherwise
= do -- If the result type is not definitely lifted, then we must generate
-- let f = \s . tick<n> e
-- in f realWorld#
-- When we stop at the breakpoint, _result will have an unlifted
-- type and hence won't be bound in the environment, but the
-- breakpoint will otherwise work fine.
--
-- NB (Trac #12007) this /also/ applies for if (ty :: TYPE r), where
-- r :: RuntimeRep is a variable. This can happen in the
-- continuations for a pattern-synonym matcher
-- match = /\(r::RuntimeRep) /\(a::TYPE r).
-- \(k :: Int -> a) \(v::T).
-- case v of MkV n -> k n
-- Here (k n) :: a :: Type r, so we don't know if it's lifted
-- or not; but that should be fine provided we add that void arg.
id <- newId (mkFunTy realWorldStatePrimTy ty)
st <- newId realWorldStatePrimTy
let letExp = AnnLet (AnnNonRec id (fvs, AnnLam st (emptyDVarSet, exp)))
(emptyDVarSet, (AnnApp (emptyDVarSet, AnnVar id)
(emptyDVarSet, AnnVar realWorldPrimId)))
schemeE d s p letExp
where
exp' = deAnnotate' exp
fvs = exprFreeVarsDSet exp'
ty = exprType exp'
-- ignore other kinds of tick
schemeE d s p (AnnTick _ (_, rhs)) = schemeE d s p rhs
schemeE d s p (AnnCase (_,scrut) _ _ []) = schemeE d s p scrut
-- no alts: scrut is guaranteed to diverge
schemeE d s p (AnnCase scrut bndr _ [(DataAlt dc, [bind1, bind2], rhs)])
| isUnboxedTupleCon dc
, UnaryRep rep_ty1 <- repType (idType bind1), UnaryRep rep_ty2 <- repType (idType bind2)
-- Convert
-- case .... of x { (# V'd-thing, a #) -> ... }
-- to
-- case .... of a { DEFAULT -> ... }
-- because the return convention for both are identical.
--
-- Note that it does not matter losing the void-rep thing from the
-- envt (it won't be bound now) because we never look such things up.
, Just res <- case () of
_ | VoidRep <- typePrimRep rep_ty1
-> Just $ doCase d s p scrut bind2 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-}
| VoidRep <- typePrimRep rep_ty2
-> Just $ doCase d s p scrut bind1 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-}
| otherwise
-> Nothing
= res
schemeE d s p (AnnCase scrut bndr _ [(DataAlt dc, [bind1], rhs)])
| isUnboxedTupleCon dc, UnaryRep _ <- repType (idType bind1)
-- Similarly, convert
-- case .... of x { (# a #) -> ... }
-- to
-- case .... of a { DEFAULT -> ... }
= --trace "automagic mashing of case alts (# a #)" $
doCase d s p scrut bind1 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-}
schemeE d s p (AnnCase scrut bndr _ [(DEFAULT, [], rhs)])
| Just (tc, tys) <- splitTyConApp_maybe (idType bndr)
, isUnboxedTupleTyCon tc
, Just res <- case tys of
[ty] | UnaryRep _ <- repType ty
, let bind = bndr `setIdType` ty
-> Just $ doCase d s p scrut bind [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-}
[ty1, ty2] | UnaryRep rep_ty1 <- repType ty1
, UnaryRep rep_ty2 <- repType ty2
-> case () of
_ | VoidRep <- typePrimRep rep_ty1
, let bind2 = bndr `setIdType` ty2
-> Just $ doCase d s p scrut bind2 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-}
| VoidRep <- typePrimRep rep_ty2
, let bind1 = bndr `setIdType` ty1
-> Just $ doCase d s p scrut bind1 [(DEFAULT, [], rhs)] (Just bndr){-unboxed tuple-}
| otherwise
-> Nothing
_ -> Nothing
= res
schemeE d s p (AnnCase scrut bndr _ alts)
= doCase d s p scrut bndr alts Nothing{-not an unboxed tuple-}
schemeE _ _ _ expr
= pprPanic "ByteCodeGen.schemeE: unhandled case"
(pprCoreExpr (deAnnotate' expr))
{-
Ticked Expressions
------------------
The idea is that the "breakpoint<n,fvs> E" is really just an annotation on
the code. When we find such a thing, we pull out the useful information,
and then compile the code as if it was just the expression E.
-}
-- Compile code to do a tail call. Specifically, push the fn,
-- slide the on-stack app back down to the sequel depth,
-- and enter. Four cases:
--
-- 0. (Nasty hack).
-- An application "GHC.Prim.tagToEnum# <type> unboxed-int".
-- The int will be on the stack. Generate a code sequence
-- to convert it to the relevant constructor, SLIDE and ENTER.
--
-- 1. The fn denotes a ccall. Defer to generateCCall.
--
-- 2. (Another nasty hack). Spot (# a::V, b #) and treat
-- it simply as b -- since the representations are identical
-- (the V takes up zero stack space). Also, spot
-- (# b #) and treat it as b.
--
-- 3. Application of a constructor, by defn saturated.
-- Split the args into ptrs and non-ptrs, and push the nonptrs,
-- then the ptrs, and then do PACK and RETURN.
--
-- 4. Otherwise, it must be a function call. Push the args
-- right to left, SLIDE and ENTER.
schemeT :: Word -- Stack depth
-> Sequel -- Sequel depth
-> BCEnv -- stack env
-> AnnExpr' Id DVarSet
-> BcM BCInstrList
schemeT d s p app
-- | trace ("schemeT: env in = \n" ++ showSDocDebug (ppBCEnv p)) False
-- = panic "schemeT ?!?!"
-- | trace ("\nschemeT\n" ++ showSDoc (pprCoreExpr (deAnnotate' app)) ++ "\n") False
-- = error "?!?!"
-- Case 0
| Just (arg, constr_names) <- maybe_is_tagToEnum_call app
= implement_tagToId d s p arg constr_names
-- Case 1
| Just (CCall ccall_spec) <- isFCallId_maybe fn
= if isSupportedCConv ccall_spec
then generateCCall d s p ccall_spec fn args_r_to_l
else unsupportedCConvException
-- Case 2: Constructor application
| Just con <- maybe_saturated_dcon,
isUnboxedTupleCon con
= case args_r_to_l of
[arg1,arg2] | isVAtom arg1 ->
unboxedTupleReturn d s p arg2
[arg1,arg2] | isVAtom arg2 ->
unboxedTupleReturn d s p arg1
_other -> unboxedTupleException
-- Case 3: Ordinary data constructor
| Just con <- maybe_saturated_dcon
= do alloc_con <- mkConAppCode d s p con args_r_to_l
return (alloc_con `appOL`
mkSLIDE 1 (d - s) `snocOL`
ENTER)
-- Case 4: Tail call of function
| otherwise
= doTailCall d s p fn args_r_to_l
where
-- Extract the args (R->L) and fn
-- The function will necessarily be a variable,
-- because we are compiling a tail call
(AnnVar fn, args_r_to_l) = splitApp app
-- Only consider this to be a constructor application iff it is
-- saturated. Otherwise, we'll call the constructor wrapper.
n_args = length args_r_to_l
maybe_saturated_dcon
= case isDataConWorkId_maybe fn of
Just con | dataConRepArity con == n_args -> Just con
_ -> Nothing
-- -----------------------------------------------------------------------------
-- Generate code to build a constructor application,
-- leaving it on top of the stack
mkConAppCode :: Word -> Sequel -> BCEnv
-> DataCon -- The data constructor
-> [AnnExpr' Id DVarSet] -- Args, in *reverse* order
-> BcM BCInstrList
mkConAppCode _ _ _ con [] -- Nullary constructor
= ASSERT( isNullaryRepDataCon con )
return (unitOL (PUSH_G (getName (dataConWorkId con))))
-- Instead of doing a PACK, which would allocate a fresh
-- copy of this constructor, use the single shared version.
mkConAppCode orig_d _ p con args_r_to_l
= ASSERT( dataConRepArity con == length args_r_to_l )
do_pushery orig_d (non_ptr_args ++ ptr_args)
where
-- The args are already in reverse order, which is the way PACK
-- expects them to be. We must push the non-ptrs after the ptrs.
(ptr_args, non_ptr_args) = partition isPtrAtom args_r_to_l
do_pushery d (arg:args)
= do (push, arg_words) <- pushAtom d p arg
more_push_code <- do_pushery (d + fromIntegral arg_words) args
return (push `appOL` more_push_code)
do_pushery d []
= return (unitOL (PACK con n_arg_words))
where
n_arg_words = trunc16 $ d - orig_d
-- -----------------------------------------------------------------------------
-- Returning an unboxed tuple with one non-void component (the only
-- case we can handle).
--
-- Remember, we don't want to *evaluate* the component that is being
-- returned, even if it is a pointed type. We always just return.
unboxedTupleReturn
:: Word -> Sequel -> BCEnv
-> AnnExpr' Id DVarSet -> BcM BCInstrList
unboxedTupleReturn d s p arg = returnUnboxedAtom d s p arg (atomRep arg)
-- -----------------------------------------------------------------------------
-- Generate code for a tail-call
doTailCall
:: Word -> Sequel -> BCEnv
-> Id -> [AnnExpr' Id DVarSet]
-> BcM BCInstrList
doTailCall init_d s p fn args
= do_pushes init_d args (map atomRep args)
where
do_pushes d [] reps = do
ASSERT( null reps ) return ()
(push_fn, sz) <- pushAtom d p (AnnVar fn)
ASSERT( sz == 1 ) return ()
return (push_fn `appOL` (
mkSLIDE (trunc16 $ d - init_d + 1) (init_d - s) `appOL`
unitOL ENTER))
do_pushes d args reps = do
let (push_apply, n, rest_of_reps) = findPushSeq reps
(these_args, rest_of_args) = splitAt n args
(next_d, push_code) <- push_seq d these_args
instrs <- do_pushes (next_d + 1) rest_of_args rest_of_reps
-- ^^^ for the PUSH_APPLY_ instruction
return (push_code `appOL` (push_apply `consOL` instrs))
push_seq d [] = return (d, nilOL)
push_seq d (arg:args) = do
(push_code, sz) <- pushAtom d p arg
(final_d, more_push_code) <- push_seq (d + fromIntegral sz) args
return (final_d, push_code `appOL` more_push_code)
-- v. similar to CgStackery.findMatch, ToDo: merge
findPushSeq :: [ArgRep] -> (BCInstr, Int, [ArgRep])
findPushSeq (P: P: P: P: P: P: rest)
= (PUSH_APPLY_PPPPPP, 6, rest)
findPushSeq (P: P: P: P: P: rest)
= (PUSH_APPLY_PPPPP, 5, rest)
findPushSeq (P: P: P: P: rest)
= (PUSH_APPLY_PPPP, 4, rest)
findPushSeq (P: P: P: rest)
= (PUSH_APPLY_PPP, 3, rest)
findPushSeq (P: P: rest)
= (PUSH_APPLY_PP, 2, rest)
findPushSeq (P: rest)
= (PUSH_APPLY_P, 1, rest)
findPushSeq (V: rest)
= (PUSH_APPLY_V, 1, rest)
findPushSeq (N: rest)
= (PUSH_APPLY_N, 1, rest)
findPushSeq (F: rest)
= (PUSH_APPLY_F, 1, rest)
findPushSeq (D: rest)
= (PUSH_APPLY_D, 1, rest)
findPushSeq (L: rest)
= (PUSH_APPLY_L, 1, rest)
findPushSeq _
= panic "ByteCodeGen.findPushSeq"
-- -----------------------------------------------------------------------------
-- Case expressions
doCase :: Word -> Sequel -> BCEnv
-> AnnExpr Id DVarSet -> Id -> [AnnAlt Id DVarSet]
-> Maybe Id -- Just x <=> is an unboxed tuple case with scrut binder, don't enter the result
-> BcM BCInstrList
doCase d s p (_,scrut) bndr alts is_unboxed_tuple
| UbxTupleRep _ <- repType (idType bndr)
= unboxedTupleException
| otherwise
= do
dflags <- getDynFlags
let
profiling
| gopt Opt_ExternalInterpreter dflags = gopt Opt_SccProfilingOn dflags
| otherwise = rtsIsProfiled
-- Top of stack is the return itbl, as usual.
-- underneath it is the pointer to the alt_code BCO.
-- When an alt is entered, it assumes the returned value is
-- on top of the itbl.
ret_frame_sizeW :: Word
ret_frame_sizeW = 2
-- The extra frame we push to save/restor the CCCS when profiling
save_ccs_sizeW | profiling = 2
| otherwise = 0
-- An unlifted value gets an extra info table pushed on top
-- when it is returned.
unlifted_itbl_sizeW :: Word
unlifted_itbl_sizeW | isAlgCase = 0
| otherwise = 1
-- depth of stack after the return value has been pushed
d_bndr = d + ret_frame_sizeW + fromIntegral (idSizeW dflags bndr)
-- depth of stack after the extra info table for an unboxed return
-- has been pushed, if any. This is the stack depth at the
-- continuation.
d_alts = d_bndr + unlifted_itbl_sizeW
-- Env in which to compile the alts, not including
-- any vars bound by the alts themselves
d_bndr' = fromIntegral d_bndr - 1
p_alts0 = Map.insert bndr d_bndr' p
p_alts = case is_unboxed_tuple of
Just ubx_bndr -> Map.insert ubx_bndr d_bndr' p_alts0
Nothing -> p_alts0
bndr_ty = idType bndr
isAlgCase = not (isUnliftedType bndr_ty) && isNothing is_unboxed_tuple
-- given an alt, return a discr and code for it.
codeAlt (DEFAULT, _, (_,rhs))
= do rhs_code <- schemeE d_alts s p_alts rhs
return (NoDiscr, rhs_code)
codeAlt alt@(_, bndrs, (_,rhs))
-- primitive or nullary constructor alt: no need to UNPACK
| null real_bndrs = do
rhs_code <- schemeE d_alts s p_alts rhs
return (my_discr alt, rhs_code)
| any (\bndr -> case repType (idType bndr) of UbxTupleRep _ -> True; _ -> False) bndrs
= unboxedTupleException
-- algebraic alt with some binders
| otherwise =
let
(ptrs,nptrs) = partition (isFollowableArg.bcIdArgRep) real_bndrs
ptr_sizes = map (fromIntegral . idSizeW dflags) ptrs
nptrs_sizes = map (fromIntegral . idSizeW dflags) nptrs
bind_sizes = ptr_sizes ++ nptrs_sizes
size = sum ptr_sizes + sum nptrs_sizes
-- the UNPACK instruction unpacks in reverse order...
p' = Map.insertList
(zip (reverse (ptrs ++ nptrs))
(mkStackOffsets d_alts (reverse bind_sizes)))
p_alts
in do
MASSERT(isAlgCase)
rhs_code <- schemeE (d_alts + size) s p' rhs
return (my_discr alt, unitOL (UNPACK (trunc16 size)) `appOL` rhs_code)
where
real_bndrs = filterOut isTyVar bndrs
my_discr (DEFAULT, _, _) = NoDiscr {-shouldn't really happen-}
my_discr (DataAlt dc, _, _)
| isUnboxedTupleCon dc
= unboxedTupleException
| otherwise
= DiscrP (fromIntegral (dataConTag dc - fIRST_TAG))
my_discr (LitAlt l, _, _)
= case l of MachInt i -> DiscrI (fromInteger i)
MachWord w -> DiscrW (fromInteger w)
MachFloat r -> DiscrF (fromRational r)
MachDouble r -> DiscrD (fromRational r)
MachChar i -> DiscrI (ord i)
_ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)
maybe_ncons
| not isAlgCase = Nothing
| otherwise
= case [dc | (DataAlt dc, _, _) <- alts] of
[] -> Nothing
(dc:_) -> Just (tyConFamilySize (dataConTyCon dc))
-- the bitmap is relative to stack depth d, i.e. before the
-- BCO, info table and return value are pushed on.
-- This bit of code is v. similar to buildLivenessMask in CgBindery,
-- except that here we build the bitmap from the known bindings of
-- things that are pointers, whereas in CgBindery the code builds the
-- bitmap from the free slots and unboxed bindings.
-- (ToDo: merge?)
--
-- NOTE [7/12/2006] bug #1013, testcase ghci/should_run/ghci002.
-- The bitmap must cover the portion of the stack up to the sequel only.
-- Previously we were building a bitmap for the whole depth (d), but we
-- really want a bitmap up to depth (d-s). This affects compilation of
-- case-of-case expressions, which is the only time we can be compiling a
-- case expression with s /= 0.
bitmap_size = trunc16 $ d-s
bitmap_size' :: Int
bitmap_size' = fromIntegral bitmap_size
bitmap = intsToReverseBitmap dflags bitmap_size'{-size-}
(sort (filter (< bitmap_size') rel_slots))
where
binds = Map.toList p
-- NB: unboxed tuple cases bind the scrut binder to the same offset
-- as one of the alt binders, so we have to remove any duplicates here:
rel_slots = nub $ map fromIntegral $ concat (map spread binds)
spread (id, offset) | isFollowableArg (bcIdArgRep id) = [ rel_offset ]
| otherwise = []
where rel_offset = trunc16 $ d - fromIntegral offset - 1
alt_stuff <- mapM codeAlt alts
alt_final <- mkMultiBranch maybe_ncons alt_stuff
let
alt_bco_name = getName bndr
alt_bco = mkProtoBCO dflags alt_bco_name alt_final (Left alts)
0{-no arity-} bitmap_size bitmap True{-is alts-}
-- trace ("case: bndr = " ++ showSDocDebug (ppr bndr) ++ "\ndepth = " ++ show d ++ "\nenv = \n" ++ showSDocDebug (ppBCEnv p) ++
-- "\n bitmap = " ++ show bitmap) $ do
scrut_code <- schemeE (d + ret_frame_sizeW + save_ccs_sizeW)
(d + ret_frame_sizeW + save_ccs_sizeW)
p scrut
alt_bco' <- emitBc alt_bco
let push_alts
| isAlgCase = PUSH_ALTS alt_bco'
| otherwise = PUSH_ALTS_UNLIFTED alt_bco' (typeArgRep bndr_ty)
return (push_alts `consOL` scrut_code)
-- -----------------------------------------------------------------------------
-- Deal with a CCall.
-- Taggedly push the args onto the stack R->L,
-- deferencing ForeignObj#s and adjusting addrs to point to
-- payloads in Ptr/Byte arrays. Then, generate the marshalling
-- (machine) code for the ccall, and create bytecodes to call that and
-- then return in the right way.
generateCCall :: Word -> Sequel -- stack and sequel depths
-> BCEnv
-> CCallSpec -- where to call
-> Id -- of target, for type info
-> [AnnExpr' Id DVarSet] -- args (atoms)
-> BcM BCInstrList
generateCCall d0 s p (CCallSpec target cconv safety) fn args_r_to_l
= do
dflags <- getDynFlags
let
-- useful constants
addr_sizeW :: Word16
addr_sizeW = fromIntegral (argRepSizeW dflags N)
-- Get the args on the stack, with tags and suitably
-- dereferenced for the CCall. For each arg, return the
-- depth to the first word of the bits for that arg, and the
-- ArgRep of what was actually pushed.
pargs _ [] = return []
pargs d (a:az)
= let UnaryRep arg_ty = repType (exprType (deAnnotate' a))
in case tyConAppTyCon_maybe arg_ty of
-- Don't push the FO; instead push the Addr# it
-- contains.
Just t
| t == arrayPrimTyCon || t == mutableArrayPrimTyCon
-> do rest <- pargs (d + fromIntegral addr_sizeW) az
code <- parg_ArrayishRep (fromIntegral (arrPtrsHdrSize dflags)) d p a
return ((code,AddrRep):rest)
| t == smallArrayPrimTyCon || t == smallMutableArrayPrimTyCon
-> do rest <- pargs (d + fromIntegral addr_sizeW) az
code <- parg_ArrayishRep (fromIntegral (smallArrPtrsHdrSize dflags)) d p a
return ((code,AddrRep):rest)
| t == byteArrayPrimTyCon || t == mutableByteArrayPrimTyCon
-> do rest <- pargs (d + fromIntegral addr_sizeW) az
code <- parg_ArrayishRep (fromIntegral (arrWordsHdrSize dflags)) d p a
return ((code,AddrRep):rest)
-- Default case: push taggedly, but otherwise intact.
_
-> do (code_a, sz_a) <- pushAtom d p a
rest <- pargs (d + fromIntegral sz_a) az
return ((code_a, atomPrimRep a) : rest)
-- Do magic for Ptr/Byte arrays. Push a ptr to the array on
-- the stack but then advance it over the headers, so as to
-- point to the payload.
parg_ArrayishRep :: Word16 -> Word -> BCEnv -> AnnExpr' Id DVarSet
-> BcM BCInstrList
parg_ArrayishRep hdrSize d p a
= do (push_fo, _) <- pushAtom d p a
-- The ptr points at the header. Advance it over the
-- header and then pretend this is an Addr#.
return (push_fo `snocOL` SWIZZLE 0 hdrSize)
code_n_reps <- pargs d0 args_r_to_l
let
(pushs_arg, a_reps_pushed_r_to_l) = unzip code_n_reps
a_reps_sizeW = fromIntegral (sum (map (primRepSizeW dflags) a_reps_pushed_r_to_l))
push_args = concatOL pushs_arg
d_after_args = d0 + a_reps_sizeW
a_reps_pushed_RAW
| null a_reps_pushed_r_to_l || head a_reps_pushed_r_to_l /= VoidRep
= panic "ByteCodeGen.generateCCall: missing or invalid World token?"
| otherwise
= reverse (tail a_reps_pushed_r_to_l)
-- Now: a_reps_pushed_RAW are the reps which are actually on the stack.
-- push_args is the code to do that.
-- d_after_args is the stack depth once the args are on.
-- Get the result rep.
(returns_void, r_rep)
= case maybe_getCCallReturnRep (idType fn) of
Nothing -> (True, VoidRep)
Just rr -> (False, rr)
{-
Because the Haskell stack grows down, the a_reps refer to
lowest to highest addresses in that order. The args for the call
are on the stack. Now push an unboxed Addr# indicating
the C function to call. Then push a dummy placeholder for the
result. Finally, emit a CCALL insn with an offset pointing to the
Addr# just pushed, and a literal field holding the mallocville
address of the piece of marshalling code we generate.
So, just prior to the CCALL insn, the stack looks like this
(growing down, as usual):
<arg_n>
...
<arg_1>
Addr# address_of_C_fn
<placeholder-for-result#> (must be an unboxed type)
The interpreter then calls the marshall code mentioned
in the CCALL insn, passing it (& <placeholder-for-result#>),
that is, the addr of the topmost word in the stack.
When this returns, the placeholder will have been
filled in. The placeholder is slid down to the sequel
depth, and we RETURN.
This arrangement makes it simple to do f-i-dynamic since the Addr#
value is the first arg anyway.
The marshalling code is generated specifically for this
call site, and so knows exactly the (Haskell) stack
offsets of the args, fn address and placeholder. It
copies the args to the C stack, calls the stacked addr,
and parks the result back in the placeholder. The interpreter
calls it as a normal C call, assuming it has a signature
void marshall_code ( StgWord* ptr_to_top_of_stack )
-}
-- resolve static address
maybe_static_target =
case target of
DynamicTarget -> Nothing
StaticTarget _ _ _ False ->
panic "generateCCall: unexpected FFI value import"
StaticTarget _ target _ True ->
Just (MachLabel target mb_size IsFunction)
where
mb_size
| OSMinGW32 <- platformOS (targetPlatform dflags)
, StdCallConv <- cconv
= Just (fromIntegral a_reps_sizeW * wORD_SIZE dflags)
| otherwise
= Nothing
let
is_static = isJust maybe_static_target
-- Get the arg reps, zapping the leading Addr# in the dynamic case
a_reps -- | trace (showSDoc (ppr a_reps_pushed_RAW)) False = error "???"
| is_static = a_reps_pushed_RAW
| otherwise = if null a_reps_pushed_RAW
then panic "ByteCodeGen.generateCCall: dyn with no args"
else tail a_reps_pushed_RAW
-- push the Addr#
(push_Addr, d_after_Addr)
| Just machlabel <- maybe_static_target
= (toOL [PUSH_UBX machlabel addr_sizeW],
d_after_args + fromIntegral addr_sizeW)
| otherwise -- is already on the stack
= (nilOL, d_after_args)
-- Push the return placeholder. For a call returning nothing,
-- this is a V (tag).
r_sizeW = fromIntegral (primRepSizeW dflags r_rep)
d_after_r = d_after_Addr + fromIntegral r_sizeW
r_lit = mkDummyLiteral r_rep
push_r = (if returns_void
then nilOL
else unitOL (PUSH_UBX r_lit r_sizeW))
-- generate the marshalling code we're going to call
-- Offset of the next stack frame down the stack. The CCALL
-- instruction needs to describe the chunk of stack containing
-- the ccall args to the GC, so it needs to know how large it
-- is. See comment in Interpreter.c with the CCALL instruction.
stk_offset = trunc16 $ d_after_r - s
conv = case cconv of
CCallConv -> FFICCall
StdCallConv -> FFIStdCall
_ -> panic "ByteCodeGen: unexpected calling convention"
-- the only difference in libffi mode is that we prepare a cif
-- describing the call type by calling libffi, and we attach the
-- address of this to the CCALL instruction.
let ffires = primRepToFFIType dflags r_rep
ffiargs = map (primRepToFFIType dflags) a_reps
hsc_env <- getHscEnv
token <- ioToBc $ iservCmd hsc_env (PrepFFI conv ffiargs ffires)
recordFFIBc token
let
-- do the call
do_call = unitOL (CCALL stk_offset token
(fromIntegral (fromEnum (playInterruptible safety))))
-- slide and return
wrapup = mkSLIDE r_sizeW (d_after_r - fromIntegral r_sizeW - s)
`snocOL` RETURN_UBX (toArgRep r_rep)
--trace (show (arg1_offW, args_offW , (map argRepSizeW a_reps) )) $
return (
push_args `appOL`
push_Addr `appOL` push_r `appOL` do_call `appOL` wrapup
)
primRepToFFIType :: DynFlags -> PrimRep -> FFIType
primRepToFFIType dflags r
= case r of
VoidRep -> FFIVoid
IntRep -> signed_word
WordRep -> unsigned_word
Int64Rep -> FFISInt64
Word64Rep -> FFIUInt64
AddrRep -> FFIPointer
FloatRep -> FFIFloat
DoubleRep -> FFIDouble
_ -> panic "primRepToFFIType"
where
(signed_word, unsigned_word)
| wORD_SIZE dflags == 4 = (FFISInt32, FFIUInt32)
| wORD_SIZE dflags == 8 = (FFISInt64, FFIUInt64)
| otherwise = panic "primTyDescChar"
-- Make a dummy literal, to be used as a placeholder for FFI return
-- values on the stack.
mkDummyLiteral :: PrimRep -> Literal
mkDummyLiteral pr
= case pr of
IntRep -> MachInt 0
WordRep -> MachWord 0
AddrRep -> MachNullAddr
DoubleRep -> MachDouble 0
FloatRep -> MachFloat 0
Int64Rep -> MachInt64 0
Word64Rep -> MachWord64 0
_ -> panic "mkDummyLiteral"
-- Convert (eg)
-- GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld
-- -> (# GHC.Prim.State# GHC.Prim.RealWorld, GHC.Prim.Int# #)
--
-- to Just IntRep
-- and check that an unboxed pair is returned wherein the first arg is V'd.
--
-- Alternatively, for call-targets returning nothing, convert
--
-- GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld
-- -> (# GHC.Prim.State# GHC.Prim.RealWorld #)
--
-- to Nothing
maybe_getCCallReturnRep :: Type -> Maybe PrimRep
maybe_getCCallReturnRep fn_ty
= let (_a_tys, r_ty) = splitFunTys (dropForAlls fn_ty)
maybe_r_rep_to_go
= if isSingleton r_reps then Nothing else Just (r_reps !! 1)
r_reps = case repType r_ty of
UbxTupleRep reps -> map typePrimRep reps
UnaryRep _ -> blargh
ok = ( ( r_reps `lengthIs` 2 && VoidRep == head r_reps)
|| r_reps == [VoidRep] )
&& case maybe_r_rep_to_go of
Nothing -> True
Just r_rep -> r_rep /= PtrRep
-- if it was, it would be impossible
-- to create a valid return value
-- placeholder on the stack
blargh :: a -- Used at more than one type
blargh = pprPanic "maybe_getCCallReturn: can't handle:"
(pprType fn_ty)
in
--trace (showSDoc (ppr (a_reps, r_reps))) $
if ok then maybe_r_rep_to_go else blargh
maybe_is_tagToEnum_call :: AnnExpr' Id DVarSet -> Maybe (AnnExpr' Id DVarSet, [Name])
-- Detect and extract relevant info for the tagToEnum kludge.
maybe_is_tagToEnum_call app
| AnnApp (_, AnnApp (_, AnnVar v) (_, AnnType t)) arg <- app
, Just TagToEnumOp <- isPrimOpId_maybe v
= Just (snd arg, extract_constr_Names t)
| otherwise
= Nothing
where
extract_constr_Names ty
| UnaryRep rep_ty <- repType ty
, Just tyc <- tyConAppTyCon_maybe rep_ty,
isDataTyCon tyc
= map (getName . dataConWorkId) (tyConDataCons tyc)
-- NOTE: use the worker name, not the source name of
-- the DataCon. See DataCon.hs for details.
| otherwise
= pprPanic "maybe_is_tagToEnum_call.extract_constr_Ids" (ppr ty)
{- -----------------------------------------------------------------------------
Note [Implementing tagToEnum#]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(implement_tagToId arg names) compiles code which takes an argument
'arg', (call it i), and enters the i'th closure in the supplied list
as a consequence. The [Name] is a list of the constructors of this
(enumeration) type.
The code we generate is this:
push arg
push bogus-word
TESTEQ_I 0 L1
PUSH_G <lbl for first data con>
JMP L_Exit
L1: TESTEQ_I 1 L2
PUSH_G <lbl for second data con>
JMP L_Exit
...etc...
Ln: TESTEQ_I n L_fail
PUSH_G <lbl for last data con>
JMP L_Exit
L_fail: CASEFAIL
L_exit: SLIDE 1 n
ENTER
The 'bogus-word' push is because TESTEQ_I expects the top of the stack
to have an info-table, and the next word to have the value to be
tested. This is very weird, but it's the way it is right now. See
Interpreter.c. We don't acutally need an info-table here; we just
need to have the argument to be one-from-top on the stack, hence pushing
a 1-word null. See Trac #8383.
-}
implement_tagToId :: Word -> Sequel -> BCEnv
-> AnnExpr' Id DVarSet -> [Name] -> BcM BCInstrList
-- See Note [Implementing tagToEnum#]
implement_tagToId d s p arg names
= ASSERT( notNull names )
do (push_arg, arg_words) <- pushAtom d p arg
labels <- getLabelsBc (genericLength names)
label_fail <- getLabelBc
label_exit <- getLabelBc
let infos = zip4 labels (tail labels ++ [label_fail])
[0 ..] names
steps = map (mkStep label_exit) infos
return (push_arg
`appOL` unitOL (PUSH_UBX MachNullAddr 1)
-- Push bogus word (see Note [Implementing tagToEnum#])
`appOL` concatOL steps
`appOL` toOL [ LABEL label_fail, CASEFAIL,
LABEL label_exit ]
`appOL` mkSLIDE 1 (d - s + fromIntegral arg_words + 1)
-- "+1" to account for bogus word
-- (see Note [Implementing tagToEnum#])
`appOL` unitOL ENTER)
where
mkStep l_exit (my_label, next_label, n, name_for_n)
= toOL [LABEL my_label,
TESTEQ_I n next_label,
PUSH_G name_for_n,
JMP l_exit]
-- -----------------------------------------------------------------------------
-- pushAtom
-- Push an atom onto the stack, returning suitable code & number of
-- stack words used.
--
-- The env p must map each variable to the highest- numbered stack
-- slot for it. For example, if the stack has depth 4 and we
-- tagged-ly push (v :: Int#) on it, the value will be in stack[4],
-- the tag in stack[5], the stack will have depth 6, and p must map v
-- to 5 and not to 4. Stack locations are numbered from zero, so a
-- depth 6 stack has valid words 0 .. 5.
pushAtom :: Word -> BCEnv -> AnnExpr' Id DVarSet -> BcM (BCInstrList, Word16)
pushAtom d p e
| Just e' <- bcView e
= pushAtom d p e'
pushAtom _ _ (AnnCoercion {}) -- Coercions are zero-width things,
= return (nilOL, 0) -- treated just like a variable V
pushAtom d p (AnnVar v)
| UnaryRep rep_ty <- repType (idType v)
, V <- typeArgRep rep_ty
= return (nilOL, 0)
| isFCallId v
= pprPanic "pushAtom: shouldn't get an FCallId here" (ppr v)
| Just primop <- isPrimOpId_maybe v
= return (unitOL (PUSH_PRIMOP primop), 1)
| Just d_v <- lookupBCEnv_maybe v p -- v is a local variable
= do dflags <- getDynFlags
let sz :: Word16
sz = fromIntegral (idSizeW dflags v)
l = trunc16 $ d - d_v + fromIntegral sz - 2
return (toOL (genericReplicate sz (PUSH_L l)), sz)
-- d - d_v the number of words between the TOS
-- and the 1st slot of the object
--
-- d - d_v - 1 the offset from the TOS of the 1st slot
--
-- d - d_v - 1 + sz - 1 the offset from the TOS of the last slot
-- of the object.
--
-- Having found the last slot, we proceed to copy the right number of
-- slots on to the top of the stack.
| otherwise -- v must be a global variable
= do dflags <- getDynFlags
let sz :: Word16
sz = fromIntegral (idSizeW dflags v)
MASSERT(sz == 1)
return (unitOL (PUSH_G (getName v)), sz)
pushAtom _ _ (AnnLit lit) = do
dflags <- getDynFlags
let code rep
= let size_host_words = fromIntegral (argRepSizeW dflags rep)
in return (unitOL (PUSH_UBX lit size_host_words),
size_host_words)
case lit of
MachLabel _ _ _ -> code N
MachWord _ -> code N
MachInt _ -> code N
MachWord64 _ -> code L
MachInt64 _ -> code L
MachFloat _ -> code F
MachDouble _ -> code D
MachChar _ -> code N
MachNullAddr -> code N
MachStr _ -> code N
-- No LitInteger's should be left by the time this is called.
-- CorePrep should have converted them all to a real core
-- representation.
LitInteger {} -> panic "pushAtom: LitInteger"
pushAtom _ _ expr
= pprPanic "ByteCodeGen.pushAtom"
(pprCoreExpr (deAnnotate' expr))
-- -----------------------------------------------------------------------------
-- Given a bunch of alts code and their discrs, do the donkey work
-- of making a multiway branch using a switch tree.
-- What a load of hassle!
mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt
-- a hint; generates better code
-- Nothing is always safe
-> [(Discr, BCInstrList)]
-> BcM BCInstrList
mkMultiBranch maybe_ncons raw_ways = do
lbl_default <- getLabelBc
let
mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList
mkTree [] _range_lo _range_hi = return (unitOL (JMP lbl_default))
-- shouldn't happen?
mkTree [val] range_lo range_hi
| range_lo == range_hi
= return (snd val)
| null defaults -- Note [CASEFAIL]
= do lbl <- getLabelBc
return (testEQ (fst val) lbl
`consOL` (snd val
`appOL` (LABEL lbl `consOL` unitOL CASEFAIL)))
| otherwise
= return (testEQ (fst val) lbl_default `consOL` snd val)
-- Note [CASEFAIL] It may be that this case has no default
-- branch, but the alternatives are not exhaustive - this
-- happens for GADT cases for example, where the types
-- prove that certain branches are impossible. We could
-- just assume that the other cases won't occur, but if
-- this assumption was wrong (because of a bug in GHC)
-- then the result would be a segfault. So instead we
-- emit an explicit test and a CASEFAIL instruction that
-- causes the interpreter to barf() if it is ever
-- executed.
mkTree vals range_lo range_hi
= let n = length vals `div` 2
vals_lo = take n vals
vals_hi = drop n vals
v_mid = fst (head vals_hi)
in do
label_geq <- getLabelBc
code_lo <- mkTree vals_lo range_lo (dec v_mid)
code_hi <- mkTree vals_hi v_mid range_hi
return (testLT v_mid label_geq
`consOL` (code_lo
`appOL` unitOL (LABEL label_geq)
`appOL` code_hi))
the_default
= case defaults of
[] -> nilOL
[(_, def)] -> LABEL lbl_default `consOL` def
_ -> panic "mkMultiBranch/the_default"
instrs <- mkTree notd_ways init_lo init_hi
return (instrs `appOL` the_default)
where
(defaults, not_defaults) = partition (isNoDiscr.fst) raw_ways
notd_ways = sortBy (comparing fst) not_defaults
testLT (DiscrI i) fail_label = TESTLT_I i fail_label
testLT (DiscrW i) fail_label = TESTLT_W i fail_label
testLT (DiscrF i) fail_label = TESTLT_F i fail_label
testLT (DiscrD i) fail_label = TESTLT_D i fail_label
testLT (DiscrP i) fail_label = TESTLT_P i fail_label
testLT NoDiscr _ = panic "mkMultiBranch NoDiscr"
testEQ (DiscrI i) fail_label = TESTEQ_I i fail_label
testEQ (DiscrW i) fail_label = TESTEQ_W i fail_label
testEQ (DiscrF i) fail_label = TESTEQ_F i fail_label
testEQ (DiscrD i) fail_label = TESTEQ_D i fail_label
testEQ (DiscrP i) fail_label = TESTEQ_P i fail_label
testEQ NoDiscr _ = panic "mkMultiBranch NoDiscr"
-- None of these will be needed if there are no non-default alts
(init_lo, init_hi)
| null notd_ways
= panic "mkMultiBranch: awesome foursome"
| otherwise
= case fst (head notd_ways) of
DiscrI _ -> ( DiscrI minBound, DiscrI maxBound )
DiscrW _ -> ( DiscrW minBound, DiscrW maxBound )
DiscrF _ -> ( DiscrF minF, DiscrF maxF )
DiscrD _ -> ( DiscrD minD, DiscrD maxD )
DiscrP _ -> ( DiscrP algMinBound, DiscrP algMaxBound )
NoDiscr -> panic "mkMultiBranch NoDiscr"
(algMinBound, algMaxBound)
= case maybe_ncons of
-- XXX What happens when n == 0?
Just n -> (0, fromIntegral n - 1)
Nothing -> (minBound, maxBound)
isNoDiscr NoDiscr = True
isNoDiscr _ = False
dec (DiscrI i) = DiscrI (i-1)
dec (DiscrW w) = DiscrW (w-1)
dec (DiscrP i) = DiscrP (i-1)
dec other = other -- not really right, but if you
-- do cases on floating values, you'll get what you deserve
-- same snotty comment applies to the following
minF, maxF :: Float
minD, maxD :: Double
minF = -1.0e37
maxF = 1.0e37
minD = -1.0e308
maxD = 1.0e308
-- -----------------------------------------------------------------------------
-- Supporting junk for the compilation schemes
-- Describes case alts
data Discr
= DiscrI Int
| DiscrW Word
| DiscrF Float
| DiscrD Double
| DiscrP Word16
| NoDiscr
deriving (Eq, Ord)
instance Outputable Discr where
ppr (DiscrI i) = int i
ppr (DiscrW w) = text (show w)
ppr (DiscrF f) = text (show f)
ppr (DiscrD d) = text (show d)
ppr (DiscrP i) = ppr i
ppr NoDiscr = text "DEF"
lookupBCEnv_maybe :: Id -> BCEnv -> Maybe Word
lookupBCEnv_maybe = Map.lookup
idSizeW :: DynFlags -> Id -> Int
idSizeW dflags = argRepSizeW dflags . bcIdArgRep
bcIdArgRep :: Id -> ArgRep
bcIdArgRep = toArgRep . bcIdPrimRep
bcIdPrimRep :: Id -> PrimRep
bcIdPrimRep = typePrimRep . bcIdUnaryType
isFollowableArg :: ArgRep -> Bool
isFollowableArg P = True
isFollowableArg _ = False
isVoidArg :: ArgRep -> Bool
isVoidArg V = True
isVoidArg _ = False
bcIdUnaryType :: Id -> UnaryType
bcIdUnaryType x = case repType (idType x) of
UnaryRep rep_ty -> rep_ty
UbxTupleRep [rep_ty] -> rep_ty
UbxTupleRep [rep_ty1, rep_ty2]
| VoidRep <- typePrimRep rep_ty1 -> rep_ty2
| VoidRep <- typePrimRep rep_ty2 -> rep_ty1
_ -> pprPanic "bcIdUnaryType" (ppr x $$ ppr (idType x))
-- See bug #1257
unboxedTupleException :: a
unboxedTupleException = throwGhcException (ProgramError
("Error: bytecode compiler can't handle unboxed tuples.\n"++
" Possibly due to foreign import/export decls in source.\n"++
" Workaround: use -fobject-code, or compile this module to .o separately."))
-- | Indicate if the calling convention is supported
isSupportedCConv :: CCallSpec -> Bool
isSupportedCConv (CCallSpec _ cconv _) = case cconv of
CCallConv -> True -- we explicitly pattern match on every
StdCallConv -> True -- convention to ensure that a warning
PrimCallConv -> False -- is triggered when a new one is added
JavaScriptCallConv -> False
CApiConv -> False
-- See bug #10462
unsupportedCConvException :: a
unsupportedCConvException = throwGhcException (ProgramError
("Error: bytecode compiler can't handle some foreign calling conventions\n"++
" Workaround: use -fobject-code, or compile this module to .o separately."))
mkSLIDE :: Word16 -> Word -> OrdList BCInstr
mkSLIDE n d
-- if the amount to slide doesn't fit in a word,
-- generate multiple slide instructions
| d > fromIntegral limit
= SLIDE n limit `consOL` mkSLIDE n (d - fromIntegral limit)
| d == 0
= nilOL
| otherwise
= if d == 0 then nilOL else unitOL (SLIDE n $ fromIntegral d)
where
limit :: Word16
limit = maxBound
splitApp :: AnnExpr' Var ann -> (AnnExpr' Var ann, [AnnExpr' Var ann])
-- The arguments are returned in *right-to-left* order
splitApp e | Just e' <- bcView e = splitApp e'
splitApp (AnnApp (_,f) (_,a)) = case splitApp f of
(f', as) -> (f', a:as)
splitApp e = (e, [])
bcView :: AnnExpr' Var ann -> Maybe (AnnExpr' Var ann)
-- The "bytecode view" of a term discards
-- a) type abstractions
-- b) type applications
-- c) casts
-- d) ticks (but not breakpoints)
-- Type lambdas *can* occur in random expressions,
-- whereas value lambdas cannot; that is why they are nuked here
bcView (AnnCast (_,e) _) = Just e
bcView (AnnLam v (_,e)) | isTyVar v = Just e
bcView (AnnApp (_,e) (_, AnnType _)) = Just e
bcView (AnnTick Breakpoint{} _) = Nothing
bcView (AnnTick _other_tick (_,e)) = Just e
bcView _ = Nothing
isVAtom :: AnnExpr' Var ann -> Bool
isVAtom e | Just e' <- bcView e = isVAtom e'
isVAtom (AnnVar v) = isVoidArg (bcIdArgRep v)
isVAtom (AnnCoercion {}) = True
isVAtom _ = False
atomPrimRep :: AnnExpr' Id ann -> PrimRep
atomPrimRep e | Just e' <- bcView e = atomPrimRep e'
atomPrimRep (AnnVar v) = bcIdPrimRep v
atomPrimRep (AnnLit l) = typePrimRep (literalType l)
atomPrimRep (AnnCoercion {}) = VoidRep
atomPrimRep other = pprPanic "atomPrimRep" (ppr (deAnnotate' other))
atomRep :: AnnExpr' Id ann -> ArgRep
atomRep e = toArgRep (atomPrimRep e)
isPtrAtom :: AnnExpr' Id ann -> Bool
isPtrAtom e = isFollowableArg (atomRep e)
-- Let szsw be the sizes in words of some items pushed onto the stack,
-- which has initial depth d'. Return the values which the stack environment
-- should map these items to.
mkStackOffsets :: Word -> [Word] -> [Word]
mkStackOffsets original_depth szsw
= map (subtract 1) (tail (scanl (+) original_depth szsw))
typeArgRep :: Type -> ArgRep
typeArgRep = toArgRep . typePrimRep
-- -----------------------------------------------------------------------------
-- The bytecode generator's monad
data BcM_State
= BcM_State
{ bcm_hsc_env :: HscEnv
, uniqSupply :: UniqSupply -- for generating fresh variable names
, thisModule :: Module -- current module (for breakpoints)
, nextlabel :: Word16 -- for generating local labels
, ffis :: [FFIInfo] -- ffi info blocks, to free later
-- Should be free()d when it is GCd
, modBreaks :: Maybe ModBreaks -- info about breakpoints
, breakInfo :: IntMap CgBreakInfo
}
newtype BcM r = BcM (BcM_State -> IO (BcM_State, r))
ioToBc :: IO a -> BcM a
ioToBc io = BcM $ \st -> do
x <- io
return (st, x)
runBc :: HscEnv -> UniqSupply -> Module -> Maybe ModBreaks -> BcM r
-> IO (BcM_State, r)
runBc hsc_env us this_mod modBreaks (BcM m)
= m (BcM_State hsc_env us this_mod 0 [] modBreaks IntMap.empty)
thenBc :: BcM a -> (a -> BcM b) -> BcM b
thenBc (BcM expr) cont = BcM $ \st0 -> do
(st1, q) <- expr st0
let BcM k = cont q
(st2, r) <- k st1
return (st2, r)
thenBc_ :: BcM a -> BcM b -> BcM b
thenBc_ (BcM expr) (BcM cont) = BcM $ \st0 -> do
(st1, _) <- expr st0
(st2, r) <- cont st1
return (st2, r)
returnBc :: a -> BcM a
returnBc result = BcM $ \st -> (return (st, result))
instance Functor BcM where
fmap = liftM
instance Applicative BcM where
pure = returnBc
(<*>) = ap
(*>) = thenBc_
instance Monad BcM where
(>>=) = thenBc
(>>) = (*>)
instance HasDynFlags BcM where
getDynFlags = BcM $ \st -> return (st, hsc_dflags (bcm_hsc_env st))
getHscEnv :: BcM HscEnv
getHscEnv = BcM $ \st -> return (st, bcm_hsc_env st)
emitBc :: ([FFIInfo] -> ProtoBCO Name) -> BcM (ProtoBCO Name)
emitBc bco
= BcM $ \st -> return (st{ffis=[]}, bco (ffis st))
recordFFIBc :: RemotePtr C_ffi_cif -> BcM ()
recordFFIBc a
= BcM $ \st -> return (st{ffis = FFIInfo a : ffis st}, ())
getLabelBc :: BcM Word16
getLabelBc
= BcM $ \st -> do let nl = nextlabel st
when (nl == maxBound) $
panic "getLabelBc: Ran out of labels"
return (st{nextlabel = nl + 1}, nl)
getLabelsBc :: Word16 -> BcM [Word16]
getLabelsBc n
= BcM $ \st -> let ctr = nextlabel st
in return (st{nextlabel = ctr+n}, [ctr .. ctr+n-1])
getCCArray :: BcM (Array BreakIndex (RemotePtr CostCentre))
getCCArray = BcM $ \st ->
let breaks = expectJust "ByteCodeGen.getCCArray" $ modBreaks st in
return (st, modBreaks_ccs breaks)
newBreakInfo :: BreakIndex -> CgBreakInfo -> BcM ()
newBreakInfo ix info = BcM $ \st ->
return (st{breakInfo = IntMap.insert ix info (breakInfo st)}, ())
newUnique :: BcM Unique
newUnique = BcM $
\st -> case takeUniqFromSupply (uniqSupply st) of
(uniq, us) -> let newState = st { uniqSupply = us }
in return (newState, uniq)
getCurrentModule :: BcM Module
getCurrentModule = BcM $ \st -> return (st, thisModule st)
newId :: Type -> BcM Id
newId ty = do
uniq <- newUnique
return $ mkSysLocal tickFS uniq ty
tickFS :: FastString
tickFS = fsLit "ticked"
| vTurbine/ghc | compiler/ghci/ByteCodeGen.hs | bsd-3-clause | 67,969 | 0 | 23 | 21,488 | 14,988 | 7,682 | 7,306 | -1 | -1 |
module StringCompressorKata.Day8Spec (spec) where
import Test.Hspec
import StringCompressorKata.Day8 (compress)
spec :: Spec
spec = do
it "compresses nothing to nothing" $ do
compress Nothing `shouldBe` Nothing
it "compresses an empty string to another empty string" $ do
compress (Just "") `shouldBe` Just ""
it "compresses a single character string" $ do
compress (Just "a") `shouldBe` Just "1a"
it "compresses a string of unique characters" $ do
compress (Just "abc") `shouldBe` Just "1a1b1c"
it "compresses a string of doubled characters" $ do
compress (Just "aabbcc") `shouldBe` Just "2a2b2c"
| Alex-Diez/haskell-tdd-kata | old-katas/test/StringCompressorKata/Day8Spec.hs | bsd-3-clause | 720 | 0 | 13 | 209 | 182 | 88 | 94 | 15 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
-- | <http://www.libtorrent.org/reference-Core.html#dht_settings dht_settings> for "Libtorrent"
module Network.Libtorrent.Session.DhtSettings (DhtSettings
, unDhtSettings
, newDhtSettings
, getMaxPeersReply
, setMaxPeersReply
, getSearchBranching
, setSearchBranching
, getMaxFailCount
, setMaxFailCount
, getMaxTorrents
, setMaxTorrents
, getMaxDhtItems
, setMaxDhtItems
, getMaxTorrentSearchReply
, setMaxTorrentSearchReply
, getRestrictRoutingIps
, setRestrictRoutingIps
, getRestrictSearchIps
, setRestrictSearchIps
, getExtendedRoutingTable
, setExtendedRoutingTable
, getAggressiveLookups
, setAggressiveLookups
, getPrivacyLookups
, setPrivacyLookups
, getEnforceNodeId
, setEnforceNodeId
, getIgnoreDarkInternet
, setIgnoreDarkInternet
) where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Foreign.C.Types (CInt)
import Foreign.ForeignPtr (ForeignPtr, withForeignPtr)
import Foreign.Marshal.Utils (fromBool, toBool)
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
import qualified Language.C.Inline.Unsafe as CU
import Network.Libtorrent.Inline
import Network.Libtorrent.Internal
import Network.Libtorrent.Types
C.context libtorrentCtx
C.include "<libtorrent/session_settings.hpp>"
C.using "namespace libtorrent"
C.using "namespace std"
newtype DhtSettings = DhtSettings { unDhtSettings :: ForeignPtr (CType DhtSettings)}
instance Show DhtSettings where
show _ = "DhtSettings"
instance Inlinable DhtSettings where
type (CType DhtSettings) = C'DhtSettings
instance FromPtr DhtSettings where
fromPtr = objFromPtr DhtSettings $ \ptr ->
[CU.exp| void { delete $(dht_settings * ptr); } |]
instance WithPtr DhtSettings where
withPtr (DhtSettings fptr) = withForeignPtr fptr
newDhtSettings :: MonadIO m => m DhtSettings
newDhtSettings =
liftIO $ fromPtr [CU.exp| dht_settings * { new dht_settings() }|]
getMaxPeersReply :: MonadIO m => DhtSettings -> m CInt
getMaxPeersReply ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(dht_settings * hoPtr)->max_peers_reply } |]
setMaxPeersReply :: MonadIO m => DhtSettings -> CInt -> m ()
setMaxPeersReply ho val =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| void { $(dht_settings * hoPtr)->max_peers_reply = $(int val)} |]
getSearchBranching :: MonadIO m => DhtSettings -> m CInt
getSearchBranching ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(dht_settings * hoPtr)->search_branching } |]
setSearchBranching :: MonadIO m => DhtSettings -> CInt -> m ()
setSearchBranching ho val =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| void { $(dht_settings * hoPtr)->search_branching = $(int val)} |]
getMaxFailCount :: MonadIO m => DhtSettings -> m CInt
getMaxFailCount ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(dht_settings * hoPtr)->max_fail_count } |]
setMaxFailCount :: MonadIO m => DhtSettings -> CInt -> m ()
setMaxFailCount ho val =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| void { $(dht_settings * hoPtr)->max_fail_count = $(int val)} |]
getMaxTorrents :: MonadIO m => DhtSettings -> m CInt
getMaxTorrents ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(dht_settings * hoPtr)->max_torrents } |]
setMaxTorrents :: MonadIO m => DhtSettings -> CInt -> m ()
setMaxTorrents ho val =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| void { $(dht_settings * hoPtr)->max_torrents = $(int val)} |]
getMaxDhtItems :: MonadIO m => DhtSettings -> m CInt
getMaxDhtItems ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(dht_settings * hoPtr)->max_dht_items } |]
setMaxDhtItems :: MonadIO m => DhtSettings -> CInt -> m ()
setMaxDhtItems ho val =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| void { $(dht_settings * hoPtr)->max_dht_items = $(int val)} |]
getMaxTorrentSearchReply :: MonadIO m => DhtSettings -> m CInt
getMaxTorrentSearchReply ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(dht_settings * hoPtr)->max_torrent_search_reply } |]
setMaxTorrentSearchReply :: MonadIO m => DhtSettings -> CInt -> m ()
setMaxTorrentSearchReply ho val =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| void { $(dht_settings * hoPtr)->max_torrent_search_reply = $(int val)} |]
getRestrictRoutingIps :: MonadIO m => DhtSettings -> m Bool
getRestrictRoutingIps ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(dht_settings * hoPtr)->restrict_routing_ips } |]
setRestrictRoutingIps :: MonadIO m => DhtSettings -> Bool -> m ()
setRestrictRoutingIps ho val =
liftIO . withPtr ho $ \hoPtr -> do
let val' = fromBool val
[CU.exp| void { $(dht_settings * hoPtr)->restrict_routing_ips = $(bool val')} |]
getRestrictSearchIps :: MonadIO m => DhtSettings -> m Bool
getRestrictSearchIps ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(dht_settings * hoPtr)->restrict_search_ips } |]
setRestrictSearchIps :: MonadIO m => DhtSettings -> Bool -> m ()
setRestrictSearchIps ho val =
liftIO . withPtr ho $ \hoPtr -> do
let val' = fromBool val
[CU.exp| void { $(dht_settings * hoPtr)->restrict_search_ips = $(bool val')} |]
getExtendedRoutingTable :: MonadIO m => DhtSettings -> m Bool
getExtendedRoutingTable ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(dht_settings * hoPtr)->extended_routing_table } |]
setExtendedRoutingTable :: MonadIO m => DhtSettings -> Bool -> m ()
setExtendedRoutingTable ho val =
liftIO . withPtr ho $ \hoPtr -> do
let val' = fromBool val
[CU.exp| void { $(dht_settings * hoPtr)->extended_routing_table = $(bool val')} |]
getAggressiveLookups :: MonadIO m => DhtSettings -> m Bool
getAggressiveLookups ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(dht_settings * hoPtr)->aggressive_lookups } |]
setAggressiveLookups :: MonadIO m => DhtSettings -> Bool -> m ()
setAggressiveLookups ho val =
liftIO . withPtr ho $ \hoPtr -> do
let val' = fromBool val
[CU.exp| void { $(dht_settings * hoPtr)->aggressive_lookups = $(bool val')} |]
getPrivacyLookups :: MonadIO m => DhtSettings -> m Bool
getPrivacyLookups ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(dht_settings * hoPtr)->privacy_lookups } |]
setPrivacyLookups :: MonadIO m => DhtSettings -> Bool -> m ()
setPrivacyLookups ho val =
liftIO . withPtr ho $ \hoPtr -> do
let val' = fromBool val
[CU.exp| void { $(dht_settings * hoPtr)->privacy_lookups = $(bool val')} |]
getEnforceNodeId :: MonadIO m => DhtSettings -> m Bool
getEnforceNodeId ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(dht_settings * hoPtr)->enforce_node_id } |]
setEnforceNodeId :: MonadIO m => DhtSettings -> Bool -> m ()
setEnforceNodeId ho val =
liftIO . withPtr ho $ \hoPtr -> do
let val' = fromBool val
[CU.exp| void { $(dht_settings * hoPtr)->enforce_node_id = $(bool val')} |]
getIgnoreDarkInternet :: MonadIO m => DhtSettings -> m Bool
getIgnoreDarkInternet ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(dht_settings * hoPtr)->ignore_dark_internet } |]
setIgnoreDarkInternet :: MonadIO m => DhtSettings -> Bool -> m ()
setIgnoreDarkInternet ho val =
liftIO . withPtr ho $ \hoPtr -> do
let val' = fromBool val
[CU.exp| void { $(dht_settings * hoPtr)->ignore_dark_internet = $(bool val')} |]
| eryx67/haskell-libtorrent | src/Network/Libtorrent/Session/DhtSettings.hs | bsd-3-clause | 8,688 | 0 | 12 | 2,527 | 1,894 | 1,016 | 878 | 172 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module Actions where
import Control.Applicative
import Control.Category
import Control.Lens
import Control.Monad.Reader as Reader
import Data.Maybe (fromJust, isJust, isNothing, listToMaybe)
import Debug.Trace
import Debug.Trace.Helpers
import GHC.Generics
import Prelude hiding (Either(..), id, (.))
import Coord
import Effects
import Entity
import Entity
import GameM
import GameState
data Action
= ActWait
| ActMoveBy DeltaCoord
| ActAttack TargetEntityRef
deriving (Show,Generic,Eq)
type ActionsByEntity = (EntityRef, [Action])
determineActionCost :: Action -> Int
determineActionCost _ = 100
returnActionsFor :: Entity -> [Action] -> ActionsByEntity
returnActionsFor entity actions = (entity ^. entityRef, actions)
-----
validateActions
:: ActionsByEntity -> GameM [Action]
validateActions (ref,actions) = do
e <- getEntity ref
case e of
Nothing -> return [] -- a non-existent entity can do nothing
(Just e') -> filterM (validActionBy e') actions
applyActions :: ActionsByEntity -> GameM EffectsToEntities
applyActions (_,[]) = return mempty
applyActions actionsByEntity@(ref,actions) = do
validActions <- validateActions actionsByEntity
effects <- mapM (applyAction ref) validActions
let cost =
returnEffectsForRef
ref
[EffSpendAP $ (sum <<< (fmap determineActionCost)) validActions]
return $ mconcat (cost : effects)
-----
validActionBy
:: Entity -> Action -> GameM Bool
validActionBy e (ActMoveBy delta) = traversableAt $ (e ^. position) + delta
validActionBy e (ActAttack ref) = isAttackableRef ref
validActionBy _ _ = return True
applyAction :: EntityRef -> Action -> GameM EffectsToEntities
applyAction ref ActWait = return $ returnEffectsForRef ref [EffPass]
applyAction ref (ActAttack aref) =
return $ returnEffectsForRef aref [EffDamaged 1]
applyAction ref (ActMoveBy delta) = do
e <- fromJust <$> getEntity ref
return (returnEffectsForRef ref [EffMoveTo $ (e ^. position) + delta])
applyAction ref _ = return mempty
| fros1y/umbral | src/Actions.hs | bsd-3-clause | 2,092 | 0 | 17 | 387 | 638 | 340 | 298 | 57 | 2 |
module TestType where
data TestType = TestType Int
data PolyType a = PolyType a
data TestTypeInt = TestTypeInt (PolyType Int)
type IntList = [Int]
data ListLike = ListLike
{
values :: IntList
}
deriving(Show, Eq) | jfischoff/specialize-th | tests/TestType.hs | bsd-3-clause | 241 | 0 | 8 | 63 | 73 | 43 | 30 | 8 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : Generics.Pointless.Bifctrable
-- Copyright : (c) 2009 University of Minho
-- License : BSD3
--
-- Maintainer : hpacheco@di.uminho.pt
-- Stability : experimental
-- Portability : non-portable
--
-- Pointless Haskell:
-- point-free programming with recursion patterns as hylomorphisms
--
-- This module defines a class of representable bifunctors.
--
-----------------------------------------------------------------------------
module Generics.Pointless.Bifctrable where
import Prelude hiding (Functor(..),fmap)
import Generics.Pointless.Bifunctors
import Generics.Pointless.Combinators
-- | Functor GADT for polytypic recursive bifunctions.
-- At the moment it does not rely on a @Typeable@ instance for constants.
data Bifctr (f :: * -> * -> *) where
BI :: Bifctr BId
BK :: Bifctr (BConst c)
BP :: Bifctr BPar
(:*!|) :: (Bifunctor f,Bifunctor g) => Bifctr f -> Bifctr g -> Bifctr (f :*| g)
(:+!|) :: (Bifunctor f,Bifunctor g) => Bifctr f -> Bifctr g -> Bifctr (f :+| g)
(:@!|) :: (Bifunctor f,Bifunctor g) => Bifctr f -> Bifctr g -> Bifctr (f :@| g)
-- | Class of representable bifunctors.
class (Bifunctor f) => Bifctrable (f :: * -> * -> *) where
bctr :: Bifctr f
instance Bifctrable BId where
bctr = BI
instance Bifctrable (BConst c) where
bctr = BK
instance Bifctrable BPar where
bctr = BP
instance (Bifunctor f,Bifctrable f,Bifunctor g,Bifctrable g) => Bifctrable (f :*| g) where
bctr = (:*!|) bctr bctr
instance (Bifunctor f,Bifctrable f,Bifunctor g,Bifctrable g) => Bifctrable (f :+| g) where
bctr = (:+!|) bctr bctr
-- | The fixpoint of a representable bifunctor.
fixB :: Bifctr f -> BFix f
fixB (_::Bifctr f) = (_L :: BFix f)
-- | The representation of the fixpoint of a representable functor.
fctrB :: Bifctrable f => BFix f -> Bifctr f
fctrB (_::BFix f) = bctr :: Bifctr f
| d-day/relation | include/pointfree-style/pointless-haskell-0.0.8/src/Generics/Pointless/Bifctrable.hs | bsd-3-clause | 1,955 | 0 | 10 | 366 | 524 | 290 | 234 | -1 | -1 |
{-# LANGUAGE PatternGuards #-}
module Ant.Square
( Square
, squareHill
, squareAnt
, isHill
, isAnt
, isVisible
, wasSeen
, isWater
, hasFood
, isLand
, squareChar
, charSquare
, setVisibility
, setContent
, waterSquare
, landSquare
, foodSquare
, unknownSquare
, antSquare
, hillSquare
)
where
import Ant.IO
import Foreign
import Data.Bits
import Data.Word
import Data.Char
data Square = Square
{ sAnt :: {-# UNPACK #-} !Word8
, sHill :: {-# UNPACK #-} !Word8
, sFlags :: {-# UNPACK #-} !Word16
} deriving Show
-- Instance so we can use Square in a Storable vector
instance Storable Square where
sizeOf _ = sizeOf (undefined :: Word8) * 4
alignment _ = alignment (undefined :: Word32)
{-# INLINE peek #-}
peek p = do
ant <- peekByteOff q 0
hill <- peekByteOff q 1
flags <- peekByteOff q 2
return (Square ant hill flags)
where
q = castPtr p
{-# INLINE poke #-}
poke p (Square ant hill flags) = do
pokeByteOff q 0 ant
pokeByteOff q 1 hill
pokeByteOff q 2 flags
where
q = castPtr p
withFlag :: Square -> Word16 -> Square
withFlag square flag = square { sFlags = (sFlags square) .|. flag }
{-# INLINE withFlag #-}
-- Constants
waterSquare, landSquare, foodSquare, unknownSquare :: Square
unknownSquare = Square noPlayer noPlayer 0
waterSquare = unknownSquare `withFlag` (seenFlag .|. waterFlag)
landSquare = unknownSquare `withFlag` seenFlag
foodSquare = landSquare `withFlag` foodFlag
antSquare, hillSquare :: Player -> Square
antSquare n = landSquare { sAnt = fromIntegral n }
hillSquare n = landSquare { sHill = fromIntegral n }
-- Interface getters for squares
squareHill, squareAnt :: Square -> Maybe Player
squareHill = maybePlayer . sHill
squareAnt = maybePlayer . sAnt
{-# INLINE squareHill #-}
{-# INLINE squareAnt #-}
isHill, isAnt, isVisible, wasSeen, isWater, hasFood, isLand :: Square -> Bool
isHill = isPlayer . sHill
isAnt = isPlayer . sAnt
isWater = (testFlag waterFlag) . sFlags
isVisible = (testFlag visibleFlag) . sFlags
wasSeen = (testFlag seenFlag) . sFlags
hasFood = (testFlag foodFlag) . sFlags
isLand sq = wasSeen sq && not (isWater sq)
{-# INLINE isHill #-}
{-# INLINE isWater #-}
{-# INLINE isAnt #-}
{-# INLINE isVisible #-}
{-# INLINE wasSeen #-}
{-# INLINE hasFood #-}
{-# INLINE isLand #-}
squareChar :: Square -> Char
squareChar square | not (wasSeen square) = '?'
| isWater square = '%'
| (Just ant) <- squareAnt square = chr(ord 'a' + ant)
| (Just hill) <- squareHill square = chr(ord '0' + hill)
| hasFood square = '#'
| isVisible square = 'o'
| otherwise = '.'
charSquare :: Char -> Square
charSquare c | c == '%' = waterSquare
| c == '.' = landSquare
| c == '.' = foodSquare
| isNumber c = hillSquare (ord c - ord '0')
| isLower c = antSquare (ord c - ord 'a')
| otherwise = unknownSquare
-- Interface setters for squares
setVisibility :: Bool -> Square -> Square
setVisibility True (Square _ _ flags) = Square noPlayer noPlayer (resetFlags flags)
where
resetFlags flags = (flags .|. seenFlag .|. visibleFlag) .&. (complement foodFlag)
setVisibility False (Square p h flags) = Square p h (flags .&. (complement visibleFlag))
{-# INLINE setVisibility #-}
setContent :: Content -> Square -> Square
setContent (Ant p) square = square { sAnt = (fromIntegral p) }
setContent (Hill p) square = square { sHill = (fromIntegral p) }
setContent Water square = square { sFlags = sFlags square .|. waterFlag }
setContent Food square = square { sFlags = sFlags square .|. foodFlag }
setContent _ square = square
-- Internal constants
visibleFlag, seenFlag, waterFlag :: Word16
visibleFlag = 1
seenFlag = 2
waterFlag = 4
foodFlag = 8
{-# INLINE waterFlag #-}
{-# INLINE visibleFlag #-}
{-# INLINE seenFlag #-}
{-# INLINE foodFlag #-}
noPlayer :: Word8
noPlayer = 255
{-# INLINE noPlayer #-}
-- Helper functions
maybePlayer :: Word8 -> Maybe Player
maybePlayer n | n == noPlayer = Nothing
| otherwise = Just (fromIntegral n)
{-# INLINE maybePlayer #-}
isPlayer :: Word8 -> Bool
isPlayer n = n /= noPlayer
{-# INLINE isPlayer #-}
testFlag :: Word16 -> Word16 -> Bool
testFlag flag1 = \flag2 -> (flag1 .&. flag2) > 0
{-# INLINE testFlag #-}
| Saulzar/Ants | Ant/Square.hs | bsd-3-clause | 4,808 | 0 | 10 | 1,451 | 1,299 | 694 | 605 | 127 | 1 |
module ValidatedAccSpec (spec) where
import Test.Hspec
import Data.Validated.Acc
import Control.Applicative
spec :: Spec
spec = do
describe "fmap" $ do
it "should answer valid for valid" $ do
fmap (+1) (Valid 1) `shouldBe` (Valid 2)
it "should answer invalid for invalid" $ do
fmap (+1) (Invalid ["foo", "bar"]) `shouldBe` (Invalid ["foo", "bar"])
it "should answer doubtful for doubtful" $ do
fmap (+1) (Doubtful 2 ["foo"]) `shouldBe` (Doubtful 3 ["foo"])
describe "pure" $ do
it "should answer valid" $ do
pure 1 `shouldBe` (Valid 1)
describe "<*>" $ do
it "should keep messages on doubtful" $ do
(Doubtful (+1) ["bar"]) <*> (Doubtful 1 ["foo"]) `shouldBe` (Doubtful 2 ["foo", "bar"])
it "should keep messages on invalid" $ do
(Invalid ["bar"]) <*> (Doubtful 1 ["foo"]) `shouldBe` (Invalid ["foo", "bar"] :: Validated Int)
it "should keep messages on doubtful" $ do
(Valid (+1)) <*> (Valid 1) `shouldBe` (Valid 2)
it "should integrate with liftA2" $ do
(liftA2 elem) (Valid 'a') (Valid "hello world") `shouldBe` (Valid False)
| arquitecturas-concurrentes/iasc-functors-sample-scala | spec/ValidatedAccSpec.hs | mit | 1,156 | 0 | 17 | 290 | 452 | 233 | 219 | 25 | 1 |
module Test.Chell.HUnit
( hunit
) where
import qualified Test.Chell as Chell
import Test.HUnit.Lang (Assertion, performTestCase)
-- | Convert a sequence of HUnit assertions (embedded in IO) to a Chell
-- 'Chell.Test'.
--
-- @
--import Test.Chell
--import Test.Chell.HUnit
--import Test.HUnit
--
--test_Addition :: Test
--test_addition = hunit \"addition\" $ do
-- 1 + 2 \@?= 3
-- 2 + 3 \@?= 5
-- @
hunit :: String -> Assertion -> Chell.Test
hunit name io = Chell.test name chell_io where
chell_io _ = do
result <- performTestCase io
return $ case result of
Nothing -> Chell.TestPassed []
Just err -> parseError err
parseError (True, msg) = Chell.TestFailed [] [Chell.failure { Chell.failureMessage = msg }]
parseError (False, msg) = Chell.TestAborted [] msg
| jmillikin/chell-hunit | lib/Test/Chell/HUnit.hs | mit | 791 | 4 | 14 | 153 | 200 | 112 | 88 | 13 | 3 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hi-IN">
<title>AdvFuzzer Add-On</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/fuzz/src/main/javahelp/org/zaproxy/zap/extension/fuzz/resources/help_hi_IN/helpset_hi_IN.hs | apache-2.0 | 962 | 79 | 67 | 157 | 413 | 209 | 204 | -1 | -1 |
module Distribution.Server.Features.HaskellPlatform (
PlatformFeature,
platformResource,
PlatformResource(..),
initPlatformFeature,
platformVersions,
platformPackageLatest,
setPlatform,
removePlatform
) where
import Distribution.Server.Acid (query, update)
import Distribution.Server.Framework
import Distribution.Server.Features.Core
import Distribution.Server.Packages.Platform
import Data.Function
import Distribution.Package
import Distribution.Version
import Distribution.Text
import qualified Data.Map as Map
import qualified Data.Set as Set
import Control.Monad (liftM)
import Control.Monad.Trans (MonadIO)
-- Note: this can be generalized into dividing Hackage up into however many
-- subsets of packages are desired. One could implement a Debian-esque system
-- with this sort of feature.
--
data PlatformFeature = PlatformFeature {
platformResource :: PlatformResource
}
data PlatformResource = PlatformResource {
platformPackage :: Resource,
platformPackages :: Resource,
platformPackageUri :: String -> PackageName -> String,
platformPackagesUri :: String -> String
}
instance IsHackageFeature PlatformFeature where
getFeatureInterface platform = (emptyHackageFeature "platform") {
featureResources = map ($platformResource platform) [platformPackage, platformPackages]
, featureDumpRestore = Nothing -- TODO
}
initPlatformFeature :: ServerEnv -> CoreFeature -> IO PlatformFeature
initPlatformFeature _ _ = do
return PlatformFeature
{ platformResource = fix $ \r -> PlatformResource
{ platformPackage = (resourceAt "/platform/package/:package.:format") { resourceGet = [], resourceDelete = [], resourcePut = [] }
, platformPackages = (resourceAt "/platform/.:format") { resourceGet = [], resourcePost = [] }
, platformPackageUri = \format pkgid -> renderResource (platformPackage r) [display pkgid, format]
, platformPackagesUri = \format -> renderResource (platformPackages r) [format]
-- and maybe "/platform/haskell-platform.cabal"
}
}
------------------------------------------
-- functionality: showing status for a single package, and for all packages, adding a package, deleting a package
platformVersions :: MonadIO m => PackageName -> m [Version]
platformVersions pkgname = liftM Set.toList $ query $ GetPlatformPackage pkgname
platformPackageLatest :: MonadIO m => m [(PackageName, Version)]
platformPackageLatest = liftM (Map.toList . Map.map Set.findMax . blessedPackages) $ query $ GetPlatformPackages
setPlatform :: MonadIO m => PackageName -> [Version] -> m ()
setPlatform pkgname versions = update $ SetPlatformPackage pkgname (Set.fromList versions)
removePlatform :: MonadIO m => PackageName -> m ()
removePlatform pkgname = update $ SetPlatformPackage pkgname Set.empty
| isomorphism/hackage2 | Distribution/Server/Features/HaskellPlatform.hs | bsd-3-clause | 2,867 | 0 | 17 | 478 | 629 | 357 | 272 | 48 | 1 |
module IRTS.BCImp where
-- Bytecode for a register/variable based VM (e.g. for generating code in an
-- imperative language where we let the language deal with GC)
import IRTS.Lang
import IRTS.Simplified
import Core.TT
data Reg = RVal | L Int
data BC = NOP
toBC :: (Name, SDecl) -> (Name, [BC])
toBC (n, SFun n' args locs exp)
= (n, bc RVal exp)
bc :: Reg -> SExp -> [BC]
bc = undefined
| christiaanb/Idris-dev | src/IRTS/BCImp.hs | bsd-3-clause | 397 | 0 | 7 | 83 | 121 | 71 | 50 | 11 | 1 |
{-# LANGUAGE CPP #-}
-- | Arrays, based on Data.Vector.Unboxed, indexed by @Point@.
module Game.LambdaHack.Common.PointArray
( Array
, (!), (//), replicateA, replicateMA, generateA, generateMA, sizeA
, foldlA, ifoldlA, mapA, imapA, mapWithKeyMA
, safeSetA, unsafeSetA, unsafeUpdateA
, minIndexA, minLastIndexA, minIndexesA, maxIndexA, maxLastIndexA, forceA
) where
import Control.Arrow ((***))
import Control.Monad
import Control.Monad.ST.Strict
import Data.Binary
import Data.Vector.Binary ()
#if MIN_VERSION_vector(0,11,0)
import qualified Data.Vector.Fusion.Bundle as Bundle
#else
import qualified Data.Vector.Fusion.Stream as Bundle
#endif
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as VM
import Game.LambdaHack.Common.Point
-- TODO: for now, until there's support for GeneralizedNewtypeDeriving
-- for Unboxed, there's a lot of @Word8@ in place of @c@ here
-- and a contraint @Enum c@ instead of @Unbox c@.
-- TODO: perhaps make them an instance of Data.Vector.Generic?
-- | Arrays indexed by @Point@.
data Array c = Array
{ axsize :: !X
, aysize :: !Y
, avector :: !(U.Vector Word8)
}
deriving Eq
instance Show (Array c) where
show a = "PointArray.Array with size " ++ show (sizeA a)
cnv :: (Enum a, Enum b) => a -> b
{-# INLINE cnv #-}
cnv = toEnum . fromEnum
pindex :: X -> Point -> Int
{-# INLINE pindex #-}
pindex xsize (Point x y) = x + y * xsize
punindex :: X -> Int -> Point
{-# INLINE punindex #-}
punindex xsize n = let (y, x) = n `quotRem` xsize
in Point x y
-- Note: there's no point specializing this to @Point@ arguments,
-- since the extra few additions in @fromPoint@ may be less expensive than
-- memory or register allocations needed for the extra @Int@ in @Point@.
-- | Array lookup.
(!) :: Enum c => Array c -> Point -> c
{-# INLINE (!) #-}
(!) Array{..} p = cnv $ avector U.! pindex axsize p
-- | Construct an array updated with the association list.
(//) :: Enum c => Array c -> [(Point, c)] -> Array c
{-# INLINE (//) #-}
(//) Array{..} l = let v = avector U.// map (pindex axsize *** cnv) l
in Array{avector = v, ..}
unsafeUpdateA :: Enum c => Array c -> [(Point, c)] -> Array c
{-# INLINE unsafeUpdateA #-}
unsafeUpdateA Array{..} l = runST $ do
vThawed <- U.unsafeThaw avector
mapM_ (\(p, c) -> VM.write vThawed (pindex axsize p) (cnv c)) l
vFrozen <- U.unsafeFreeze vThawed
return $! Array{avector = vFrozen, ..}
-- | Create an array from a replicated element.
replicateA :: Enum c => X -> Y -> c -> Array c
{-# INLINE replicateA #-}
replicateA axsize aysize c =
Array{avector = U.replicate (axsize * aysize) $ cnv c, ..}
-- | Create an array from a replicated monadic action.
replicateMA :: Enum c => Monad m => X -> Y -> m c -> m (Array c)
{-# INLINE replicateMA #-}
replicateMA axsize aysize m = do
v <- U.replicateM (axsize * aysize) $ liftM cnv m
return $! Array{avector = v, ..}
-- | Create an array from a function.
generateA :: Enum c => X -> Y -> (Point -> c) -> Array c
{-# INLINE generateA #-}
generateA axsize aysize f =
let g n = cnv $ f $ punindex axsize n
in Array{avector = U.generate (axsize * aysize) g, ..}
-- | Create an array from a monadic function.
generateMA :: Enum c => Monad m => X -> Y -> (Point -> m c) -> m (Array c)
{-# INLINE generateMA #-}
generateMA axsize aysize fm = do
let gm n = liftM cnv $ fm $ punindex axsize n
v <- U.generateM (axsize * aysize) gm
return $! Array{avector = v, ..}
-- | Content identifiers array size.
sizeA :: Array c -> (X, Y)
{-# INLINE sizeA #-}
sizeA Array{..} = (axsize, aysize)
-- | Fold left strictly over an array.
foldlA :: Enum c => (a -> c -> a) -> a -> Array c -> a
{-# INLINE foldlA #-}
foldlA f z0 Array{..} =
U.foldl' (\a c -> f a (cnv c)) z0 avector
-- | Fold left strictly over an array
-- (function applied to each element and its index).
ifoldlA :: Enum c => (a -> Point -> c -> a) -> a -> Array c -> a
{-# INLINE ifoldlA #-}
ifoldlA f z0 Array{..} =
U.ifoldl' (\a n c -> f a (punindex axsize n) (cnv c)) z0 avector
-- | Map over an array.
mapA :: (Enum c, Enum d) => (c -> d) -> Array c -> Array d
{-# INLINE mapA #-}
mapA f Array{..} = Array{avector = U.map (cnv . f . cnv) avector, ..}
-- | Map over an array (function applied to each element and its index).
imapA :: (Enum c, Enum d) => (Point -> c -> d) -> Array c -> Array d
{-# INLINE imapA #-}
imapA f Array{..} =
let v = U.imap (\n c -> cnv $ f (punindex axsize n) (cnv c)) avector
in Array{avector = v, ..}
-- | Set all elements to the given value, in place.
unsafeSetA :: Enum c => c -> Array c -> Array c
{-# INLINE unsafeSetA #-}
unsafeSetA c Array{..} = runST $ do
vThawed <- U.unsafeThaw avector
VM.set vThawed (cnv c)
vFrozen <- U.unsafeFreeze vThawed
return $! Array{avector = vFrozen, ..}
-- | Set all elements to the given value, in place, if possible.
safeSetA :: Enum c => c -> Array c -> Array c
{-# INLINE safeSetA #-}
safeSetA c Array{..} =
Array{avector = U.modify (\v -> VM.set v (cnv c)) avector, ..}
-- | Map monadically over an array (function applied to each element
-- and its index) and ignore the results.
mapWithKeyMA :: Enum c => Monad m
=> (Point -> c -> m ()) -> Array c -> m ()
{-# INLINE mapWithKeyMA #-}
mapWithKeyMA f Array{..} =
U.ifoldl' (\a n c -> a >> f (punindex axsize n) (cnv c))
(return ())
avector
-- | Yield the point coordinates of a minimum element of the array.
-- The array may not be empty.
minIndexA :: Enum c => Array c -> Point
{-# INLINE minIndexA #-}
minIndexA Array{..} = punindex axsize $ U.minIndex avector
-- | Yield the point coordinates of the last minimum element of the array.
-- The array may not be empty.
minLastIndexA :: Enum c => Array c -> Point
{-# INLINE minLastIndexA #-}
minLastIndexA Array{..} =
punindex axsize
$ fst . Bundle.foldl1' imin . Bundle.indexed . G.stream
$ avector
where
imin (i, x) (j, y) = i `seq` j `seq` if x >= y then (j, y) else (i, x)
-- | Yield the point coordinates of all the minimum elements of the array.
-- The array may not be empty.
minIndexesA :: Enum c => Array c -> [Point]
{-# INLINE minIndexesA #-}
minIndexesA Array{..} =
map (punindex axsize)
$ Bundle.foldl' imin [] . Bundle.indexed . G.stream
$ avector
where
imin acc (i, x) = i `seq` if x == minE then i : acc else acc
minE = cnv $ U.minimum avector
-- | Yield the point coordinates of the first maximum element of the array.
-- The array may not be empty.
maxIndexA :: Enum c => Array c -> Point
{-# INLINE maxIndexA #-}
maxIndexA Array{..} = punindex axsize $ U.maxIndex avector
-- | Yield the point coordinates of the last maximum element of the array.
-- The array may not be empty.
maxLastIndexA :: Enum c => Array c -> Point
{-# INLINE maxLastIndexA #-}
maxLastIndexA Array{..} =
punindex axsize
$ fst . Bundle.foldl1' imax . Bundle.indexed . G.stream
$ avector
where
imax (i, x) (j, y) = i `seq` j `seq` if x <= y then (j, y) else (i, x)
-- | Force the array not to retain any extra memory.
forceA :: Enum c => Array c -> Array c
{-# INLINE forceA #-}
forceA Array{..} = Array{avector = U.force avector, ..}
instance Binary (Array c) where
put Array{..} = do
put axsize
put aysize
put avector
get = do
axsize <- get
aysize <- get
avector <- get
return $! Array{..}
| Concomitant/LambdaHack | Game/LambdaHack/Common/PointArray.hs | bsd-3-clause | 7,423 | 0 | 15 | 1,596 | 2,466 | 1,312 | 1,154 | -1 | -1 |
{-# OPTIONS_GHC -fvectorise #-}
module Data.Array.Parallel.Prelude.Bool
( Bool(..)
, P.otherwise
, (P.&&), (P.||), P.not, andP, orP
, fromBool, toBool)
where
-- Primitives needed by the vectoriser.
import Data.Array.Parallel.Prim
import Data.Array.Parallel.PArr
import Data.Array.Parallel.Prelude.Base (Bool(..))
import Data.Array.Parallel.Prelude.Int as I (sumP, (==), (/=)) -- just temporary
import Data.Array.Parallel.Lifted (mapPP, lengthPP) -- just temporary
import Data.Array.Parallel.PArray.PRepr
import Data.Array.Parallel.PArray.PData.Base
import qualified Data.Array.Parallel.Unlifted as U
import Data.Bits
import qualified Prelude as P
import Prelude (Int)
-- and ------------------------------------------------------------------------
{-# VECTORISE (P.&&) = (&&*) #-}
(&&*) :: Bool :-> Bool :-> Bool
(&&*) = closure2 (P.&&) and_l
{-# INLINE (&&*) #-}
{-# NOVECTORISE (&&*) #-}
and_l :: PArray Bool -> PArray Bool -> PArray Bool
and_l (PArray n# bs) (PArray _ cs)
= PArray n# P.$
case bs of { PBool sel1 ->
case cs of { PBool sel2 ->
PBool P.$ U.tagsToSel2 (U.zipWith (.&.) (U.tagsSel2 sel1) (U.tagsSel2 sel2)) }}
{-# INLINE and_l #-}
{-# NOVECTORISE and_l #-}
-- or -------------------------------------------------------------------------
{-# VECTORISE (P.||) = (||*) #-}
(||*) :: Bool :-> Bool :-> Bool
(||*) = closure2 (P.||) or_l
{-# INLINE (||*) #-}
{-# NOVECTORISE (||*) #-}
or_l :: PArray Bool -> PArray Bool -> PArray Bool
or_l (PArray n# bs) (PArray _ cs)
= PArray n# P.$
case bs of { PBool sel1 ->
case cs of { PBool sel2 ->
PBool P.$ U.tagsToSel2 (U.zipWith (.|.) (U.tagsSel2 sel1) (U.tagsSel2 sel2)) }}
{-# INLINE or_l #-}
{-# NOVECTORISE or_l #-}
-- not ------------------------------------------------------------------------
{-# VECTORISE P.not = notPP #-}
notPP :: Bool :-> Bool
notPP = closure1 P.not notPP_l
{-# INLINE notPP #-}
{-# NOVECTORISE notPP #-}
notPP_l :: PArray Bool -> PArray Bool
notPP_l (PArray n# bs)
= PArray n# P.$
case bs of { PBool sel ->
PBool P.$ U.tagsToSel2 (U.map negate (U.tagsSel2 sel)) }
where
-- We must return 1 for True, 0 for False
negate i = (complement i) .&. 1
{-# NOVECTORISE notPP_l #-}
{-# INLINE notPP_l #-}
{- TODO: We can't do these because there is no Unboxes instance for Bool.
-- andP -----------------------------------------------------------------------
andP :: PArr Bool -> Bool
andP _ = True
{-# NOINLINE andP #-}
{-# VECTORISE andP = andPP #-}
andPP :: PArray Bool :-> Bool
andPP = L.closure1' (SC.fold (&&) True) (SC.folds (&&) True)
{-# INLINE andPP #-}
{-# NOVECTORISE andPP #-}
-- orP ------------------------------------------------------------------------
orP :: PArr Bool -> Bool
orP _ = True
{-# NOINLINE orP #-}
{-# VECTORISE orP = orPP #-}
orPP :: PArray Bool :-> Bool
orPP = L.closure1' (SC.fold (||) False) (SC.folds (||) False)
{-# INLINE orPP #-}
{-# NOVECTORISE orPP #-}
-}
-- Until we have Unboxes for Bool, we use the following definitions instead.
andP :: PArr Bool -> Bool
andP bs = I.sumP (mapP fromBool bs) I.== lengthP bs
orP :: PArr Bool -> Bool
orP bs = sumP (mapP fromBool bs) I./= 0
-- Defining 'mapP' and 'lengthP' here is just a kludge until the original definitions of
-- 'andP' and 'orP' work again.
mapP :: (a -> b) -> PArr a -> PArr b
mapP !_ !_ = emptyPArr
{-# NOINLINE mapP #-}
{-# VECTORISE mapP = mapPP #-}
lengthP :: PArr a -> Int
lengthP = lengthPArr
{-# NOINLINE lengthP #-}
{-# VECTORISE lengthP = lengthPP #-}
-- conversion functions --------------------------------------------------------
fromBool :: Bool -> Int
fromBool False = 0
fromBool True = 1
toBool :: Int -> Bool
toBool 0 = False
toBool _ = True
| mainland/dph | dph-lifted-vseg/Data/Array/Parallel/Prelude/Bool.hs | bsd-3-clause | 3,903 | 0 | 18 | 838 | 830 | 473 | 357 | -1 | -1 |
{-# OPTIONS -Wall #-}
module Test.Paraiso.Option (
cpp, cuda, fail, help,
cppc, cudac, argv, printHelp
) where
import Prelude hiding (fail)
import System.Environment (getArgs)
import System.IO.Unsafe (unsafePerformIO)
argv0 :: [String]
argv0 = unsafePerformIO $ getArgs
myArgvs :: [(String, String)]
myArgvs = [
("--cpp", "execute tests that invokes external c++ compiler"),
("--cuda", "execute tests that invokes external cuda compiler"),
("--fail", "all tests should fail instead of succeed when this flag is on")]
argv :: [String]
argv = filter (not . (`elem` map fst myArgvs)) argv0
cpp :: Bool
cpp = elem "--cpp" argv0
cuda :: Bool
cuda = elem "--cuda" argv0
fail :: Bool
fail = elem "--fail" argv0
help :: Bool
help = elem "--help" argv0
printHelp :: IO ()
printHelp = do
putStrLn $ unlines $ header:lins
where
len1 = maximum $ map ((+2) . length . fst) myArgvs
pad str = take len1 $ str ++ repeat ' '
paddy (opt, desc) = pad opt ++ desc
lins = map paddy myArgvs
header = "**** Custom test options ****"
cppc :: FilePath -- external c++ compiler to use.
cppc = "g++"
cudac :: FilePath -- external cuda compiler to use.
cudac = "nvcc" | nushio3/Paraiso | Test/Paraiso/Option.hs | bsd-3-clause | 1,198 | 0 | 12 | 253 | 364 | 210 | 154 | 36 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Hattis.Text.SourceFile (langs, FileExt, Language, name, verifyfiles, fromStr) where
import Control.Arrow
import Control.Monad
import Data.Char
import Data.Either
import System.Directory
import Hattis.Error
import System.FilePath
import qualified Data.List as L
type Files = [String]
data Language
= C
| CSharp
| Cpp
| Go
| Haskell
| Java
| JavaScript
| ObjectiveC
| PHP
| Prolog
| Python2
| Python3
| Ruby
deriving (Show, Eq, Enum, Ord)
class FileExt a where
exts :: a -> [String]
name :: a -> String
instance FileExt Language where
exts C = [".c", ".h"]
exts CSharp = [".cs"]
exts Cpp = [".cpp", ".cc", ".cxx", ".hpp", ".h"]
exts Go = [".go"]
exts Haskell = [".hs"]
exts Java = [".java"] --Todo: Find mainclass
exts JavaScript = [".js"]
exts ObjectiveC = [".m", ".h"]
exts PHP = [".php"]
exts Prolog = [".pl", ".prolog"]
exts Python2 = [".py"]
exts Python3 = [".py"] --Todo: Solve python-ambiguity
exts Ruby = [".rb"]
name CSharp = "C#"
name Cpp = "C++"
name ObjectiveC = "Objective-C"
name Python2 = "Python 2"
name Python3 = "Python 3"
name x = show x
fromStr :: (MonadError HattisError m) => String -> m Language
fromStr x = case filter ((==lower) . map toLower . snd) lang of
[] -> throwError $ UnknownLanguage x
(a,_):_ -> return a
where lang = map (id &&& name) langs
lower = map toLower x
langs :: [Language]
langs = enumFrom C
matches :: FileExt a => String -> a -> Bool
matches = (. exts) . elem
allfiles :: (MonadIO m1, MonadError HattisError m) => Files -> m1 (m Files)
allfiles x = liftIO $ do
full <- mapM getFullPath x
existing <- mapM doesFileExist full
let nonexisting = filter ((False==) . snd) $ zip x existing
return $ case nonexisting of
[] -> return full
l -> throwError . NotAFile $ map fst l
possiblelangs :: String -> [Language]
possiblelangs = flip filter langs . matches
getlangs :: (MonadError HattisError m) => Files -> m [[Language]]
getlangs = mapM $ fun . (id &&& (possiblelangs . takeExtension))
where fun (f, []) = throwError $ UnknownExtension f
fun (_, l) = return l
decidelang :: (MonadError HattisError m) => Files -> m Language
decidelang x = mul . (flip filter langs . possible) . join zip =<< getlangs x
where possible a b = all (elem b . snd) a
mul [a] = return a
mul a = throwError . MultipleLanguages . map name $ a
verifyfiles :: (MonadError HattisError m, MonadIO mio) => Files -> mio (m Language)
verifyfiles = liftIO . fmap (decidelang =<<) . allfiles
getFullPath :: String -> IO String
getFullPath s = case splitPath s of
"~/" : t -> joinPath . (: t) <$> getHomeDirectory
_ -> return s
| EmilGedda/hattis | src/Hattis/Text/SourceFile.hs | bsd-3-clause | 3,037 | 0 | 15 | 917 | 1,073 | 573 | 500 | 84 | 2 |
module Fib where
fib :: Int -- ^
-- >>> 23
-- 23
-> Int
fib _ = undefined
| snoyberg/doctest-haskell | test/integration/testDocumentationForArguments/Fib.hs | mit | 102 | 0 | 5 | 47 | 24 | 15 | 9 | 4 | 1 |
{-# LANGUAGE CPP #-}
module Main where
import HList
import Data.List
data Tree a = Node (Tree a) (Tree a) | Leaf a
{-# INLINE repR #-}
repR :: ([a] -> [a]) -> ([a] -> H a)
repR f = repH . f
{-# INLINE absR #-}
absR :: ([a] -> H a) -> ([a] -> [a])
absR g = absH . g
qsort :: Ord a => [a] -> [a]
qsort [] = []
qsort (a:as) = qsort bs ++ [a] ++ qsort cs
where
(bs , cs) = partition (< a) as
main :: IO ()
main = print (qsort [8,3,5,7,2,9,4,6,3,2])
-- Should be in a "List" module
{-# RULES "++ []" forall xs . xs ++ [] = xs #-}
{-# RULES "++ strict" (++) undefined = undefined #-}
-- The "Algebra" for repH
{-# RULES "repH ++" forall xs ys . repH (xs ++ ys) = repH xs . repH ys #-}
{-# RULES "repH []" repH [] = id #-}
{-# RULES "repH (:)" forall x xs . repH (x:xs) = ((:) x) . repH xs #-}
-- Needed because the fusion rule we generate isn't too useful yet.
{-# RULES "repH-absH-fusion" [~] forall h. repH (absH h) = h #-}
| beni55/hermit | examples/qsort/QSort.hs | bsd-2-clause | 1,028 | 0 | 8 | 314 | 290 | 167 | 123 | -1 | -1 |
module Idris.REPL.Commands where
import Idris.AbsSyntaxTree
import Idris.Colours
import Idris.Core.TT
import Idris.Options
-- | REPL commands
data Command = Quit
| Help
| Eval PTerm
| NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name.
| Undefine [Name]
| Check PTerm
| Core PTerm
| DocStr (Either Name Const) HowMuchDocs
| TotCheck Name
| Reload
| Watch
| Load FilePath (Maybe Int) -- up to maximum line number
| RunShellCommand FilePath
| ChangeDirectory FilePath
| ModImport String
| Edit
| Compile Codegen String
| Execute PTerm
| ExecVal PTerm
| Metavars
| Prove Bool Name -- ^ If false, use prover, if true, use elab shell
| AddProof (Maybe Name)
| RmProof Name
| ShowProof Name
| Proofs
| Universes
| LogLvl Int
| LogCategory [LogCat]
| Verbosity Int
| Spec PTerm
| WHNF PTerm
| TestInline PTerm
| Defn Name
| Missing Name
| DynamicLink FilePath
| ListDynamic
| Pattelab PTerm
| Search [String] PTerm
| CaseSplitAt Bool Int Name
| AddClauseFrom Bool Int Name
| AddProofClauseFrom Bool Int Name
| AddMissing Bool Int Name
| MakeWith Bool Int Name
| MakeCase Bool Int Name
| MakeLemma Bool Int Name
| DoProofSearch Bool -- update file
Bool -- recursive search
Int -- depth
Name -- top level name
[Name] -- hints
| SetOpt Opt
| UnsetOpt Opt
| NOP
| SetColour ColourType IdrisColour
| ColourOn
| ColourOff
| ListErrorHandlers
| SetConsoleWidth ConsoleWidth
| SetPrinterDepth (Maybe Int)
| Apropos [String] String
| WhoCalls Name
| CallsWho Name
| Browse [String]
| MakeDoc String -- IdrisDoc
| Warranty
| PrintDef Name
| PPrint OutputFmt Int PTerm
| TransformInfo Name
-- Debugging commands
| DebugInfo Name
| DebugUnify PTerm PTerm
| uuhan/Idris-dev | src/Idris/REPL/Commands.hs | bsd-3-clause | 2,689 | 0 | 8 | 1,275 | 448 | 270 | 178 | 75 | 0 |
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module NN.Examples.AlexNet(alexNetSmall, alexNet, main) where
import Control.Lens
import Control.Monad
import NN
import NN.Examples.ImageNet
alexTrain = train & cropSize' 227 & batchSize' 256 & mirror' True
alexTest = test & cropSize' 227 & batchSize' 50 & mirror' False
alexLrn = lrn & localSize' 5 & alphaLRN' 0.0001 & betaLRN' 0.75
alexConv = conv & param' alexMult & weightFillerC' (gaussian 0.01) & biasFillerC' zero
alexIP n = ip n & param' alexMult & weightFillerIP' (gaussian 0.005) & biasFillerIP' (constant 0.1)
alexPool = maxPool & sizeP' 3
alexMult = [def & lrMult' 1 & decayMult' 1, -- weights
def & lrMult' 2 & decayMult' 0] -- biases
-- |Model
conv1 = alexConv & numOutputC' 96 & kernelSizeC' 11 & strideC' 4
conv2 = alexConv & numOutputC' 256 & padC' 2 & kernelSizeC' 5 & groupC' 2
conv3 = alexConv & numOutputC' 384 & padC' 1 & kernelSizeC' 3
conv4 = alexConv & numOutputC' 384 & padC' 1 & kernelSizeC' 3 & groupC' 2 & biasFillerC' (constant 0.1)
conv5 = alexConv & numOutputC' 256 & padC' 1 & kernelSizeC' 3 & groupC' 2 & biasFillerC' (constant 0.1)
alexNetSmall :: NetBuilder ()
alexNetSmall = do
(input', representation) <- sequential [conv1, relu, alexPool & strideP' 3]
forM_ [alexTrain, alexTest] $ attach (To input')
forM_ [accuracy 1, accuracy 5, softmax] $ attach (From representation)
alexNet :: NetBuilder ()
alexNet = do
-- Set up the model
(input', representation) <-
sequential [
-- Convolutional Layers
conv1, relu, alexLrn, alexPool & strideP' 3,
conv2, relu, alexLrn, alexPool & strideP' 2,
conv3, relu,
conv4, relu,
conv5, relu, alexPool & strideP' 2,
-- FC Layers
alexIP 4096, relu, dropout 0.5,
alexIP 4096, relu, dropout 0.5,
alexIP 1000 & weightFillerIP' (gaussian 0.01) & biasFillerIP' zero]
forM_ [alexTrain, alexTest] $ attach (To input')
forM_ [accuracy 1, accuracy 5, softmax] $ attach (From representation)
main :: IO ()
main = cli alexNet
| sjfloat/dnngraph | NN/Examples/AlexNet.hs | bsd-3-clause | 2,126 | 0 | 14 | 504 | 762 | 381 | 381 | 40 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE Trustworthy #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.Posix.Types
-- Copyright : (c) The University of Glasgow 2002
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : non-portable (requires POSIX)
--
-- POSIX data types: Haskell equivalents of the types defined by the
-- @\<sys\/types.h>@ C header on a POSIX system.
--
-----------------------------------------------------------------------------
#include "HsBaseConfig.h"
module System.Posix.Types (
-- * POSIX data types
-- ** Platform differences
-- | This module contains platform specific information about types.
-- __/As such the types presented on this page reflect the platform
-- on which the documentation was generated and may not coincide with
-- the types on your platform./__
#if defined(HTYPE_DEV_T)
CDev(..),
#endif
#if defined(HTYPE_INO_T)
CIno(..),
#endif
#if defined(HTYPE_MODE_T)
CMode(..),
#endif
#if defined(HTYPE_OFF_T)
COff(..),
#endif
#if defined(HTYPE_PID_T)
CPid(..),
#endif
#if defined(HTYPE_SSIZE_T)
CSsize(..),
#endif
#if defined(HTYPE_GID_T)
CGid(..),
#endif
#if defined(HTYPE_NLINK_T)
CNlink(..),
#endif
#if defined(HTYPE_UID_T)
CUid(..),
#endif
#if defined(HTYPE_CC_T)
CCc(..),
#endif
#if defined(HTYPE_SPEED_T)
CSpeed(..),
#endif
#if defined(HTYPE_TCFLAG_T)
CTcflag(..),
#endif
#if defined(HTYPE_RLIM_T)
CRLim(..),
#endif
#if defined(HTYPE_BLKSIZE_T)
CBlkSize(..),
#endif
#if defined(HTYPE_BLKCNT_T)
CBlkCnt(..),
#endif
#if defined(HTYPE_CLOCKID_T)
CClockId(..),
#endif
#if defined(HTYPE_FSBLKCNT_T)
CFsBlkCnt(..),
#endif
#if defined(HTYPE_FSFILCNT_T)
CFsFilCnt(..),
#endif
#if defined(HTYPE_ID_T)
CId(..),
#endif
#if defined(HTYPE_KEY_T)
CKey(..),
#endif
#if defined(HTYPE_TIMER_T)
CTimer(..),
#endif
Fd(..),
-- See Note [Exporting constructors of marshallable foreign types]
-- in Foreign.Ptr for why the constructors for these newtypes are
-- exported.
#if defined(HTYPE_NLINK_T)
LinkCount,
#endif
#if defined(HTYPE_UID_T)
UserID,
#endif
#if defined(HTYPE_GID_T)
GroupID,
#endif
ByteCount,
ClockTick,
EpochTime,
FileOffset,
ProcessID,
ProcessGroupID,
DeviceID,
FileID,
FileMode,
Limit
) where
import Foreign
import Foreign.C
-- import Data.Bits
import GHC.Base
import GHC.Enum
import GHC.Num
import GHC.Real
-- import GHC.Prim
import GHC.Read
import GHC.Show
#include "CTypes.h"
#if defined(HTYPE_DEV_T)
INTEGRAL_TYPE(CDev,HTYPE_DEV_T)
#endif
#if defined(HTYPE_INO_T)
INTEGRAL_TYPE(CIno,HTYPE_INO_T)
#endif
#if defined(HTYPE_MODE_T)
INTEGRAL_TYPE_WITH_CTYPE(CMode,mode_t,HTYPE_MODE_T)
#endif
#if defined(HTYPE_OFF_T)
INTEGRAL_TYPE(COff,HTYPE_OFF_T)
#endif
#if defined(HTYPE_PID_T)
INTEGRAL_TYPE(CPid,HTYPE_PID_T)
#endif
#if defined(HTYPE_SSIZE_T)
INTEGRAL_TYPE(CSsize,HTYPE_SSIZE_T)
#endif
#if defined(HTYPE_GID_T)
INTEGRAL_TYPE(CGid,HTYPE_GID_T)
#endif
#if defined(HTYPE_NLINK_T)
INTEGRAL_TYPE(CNlink,HTYPE_NLINK_T)
#endif
#if defined(HTYPE_UID_T)
INTEGRAL_TYPE(CUid,HTYPE_UID_T)
#endif
#if defined(HTYPE_CC_T)
ARITHMETIC_TYPE(CCc,HTYPE_CC_T)
#endif
#if defined(HTYPE_SPEED_T)
ARITHMETIC_TYPE(CSpeed,HTYPE_SPEED_T)
#endif
#if defined(HTYPE_TCFLAG_T)
INTEGRAL_TYPE(CTcflag,HTYPE_TCFLAG_T)
#endif
#if defined(HTYPE_RLIM_T)
INTEGRAL_TYPE(CRLim,HTYPE_RLIM_T)
#endif
#if defined(HTYPE_BLKSIZE_T)
-- | @since 4.10.0.0
INTEGRAL_TYPE_WITH_CTYPE(CBlkSize,blksize_t,HTYPE_BLKSIZE_T)
#endif
#if defined(HTYPE_BLKCNT_T)
-- | @since 4.10.0.0
INTEGRAL_TYPE_WITH_CTYPE(CBlkCnt,blkcnt_t,HTYPE_BLKCNT_T)
#endif
#if defined(HTYPE_CLOCKID_T)
-- | @since 4.10.0.0
INTEGRAL_TYPE_WITH_CTYPE(CClockId,clockid_t,HTYPE_CLOCKID_T)
#endif
#if defined(HTYPE_FSBLKCNT_T)
-- | @since 4.10.0.0
INTEGRAL_TYPE_WITH_CTYPE(CFsBlkCnt,fsblkcnt_t,HTYPE_FSBLKCNT_T)
#endif
#if defined(HTYPE_FSFILCNT_T)
-- | @since 4.10.0.0
INTEGRAL_TYPE_WITH_CTYPE(CFsFilCnt,fsfilcnt_t,HTYPE_FSFILCNT_T)
#endif
#if defined(HTYPE_ID_T)
-- | @since 4.10.0.0
INTEGRAL_TYPE_WITH_CTYPE(CId,id_t,HTYPE_ID_T)
#endif
#if defined(HTYPE_KEY_T)
-- | @since 4.10.0.0
INTEGRAL_TYPE_WITH_CTYPE(CKey,key_t,HTYPE_KEY_T)
#endif
#if defined(HTYPE_TIMER_T)
-- | @since 4.10.0.0
OPAQUE_TYPE_WITH_CTYPE(CTimer,timer_t,HTYPE_TIMER_T)
#endif
-- Make an Fd type rather than using CInt everywhere
INTEGRAL_TYPE(Fd,CInt)
-- nicer names, and backwards compatibility with POSIX library:
#if defined(HTYPE_NLINK_T)
type LinkCount = CNlink
#endif
#if defined(HTYPE_UID_T)
type UserID = CUid
#endif
#if defined(HTYPE_GID_T)
type GroupID = CGid
#endif
type ByteCount = CSize
type ClockTick = CClock
type EpochTime = CTime
type DeviceID = CDev
type FileID = CIno
type FileMode = CMode
type ProcessID = CPid
type FileOffset = COff
type ProcessGroupID = CPid
type Limit = CLong
| ezyang/ghc | libraries/base/System/Posix/Types.hs | bsd-3-clause | 5,158 | 0 | 6 | 704 | 749 | 507 | 242 | -1 | -1 |
-- Tests pattern bindings that are generalised
module T5032 where
id1 :: a -> a
(id1) = id
foo = (id1 True, id1 'x')
g :: a -> a
h :: a -> a
(g, h) = (\x -> x, \y -> y)
too = (g (h True), g (h 'x'))
-- No type signature necessary;
-- the MR only strikes when overloading is involved
[id3] = [id]
noo = (id3 True, id3 'x')
| hferreiro/replay | testsuite/tests/typecheck/should_compile/T5032.hs | bsd-3-clause | 330 | 0 | 8 | 82 | 146 | 83 | 63 | 10 | 1 |
-- NMEA checksum
-- http://www.codewars.com/kata/54249c6bf132dcc661000495/
module NMEA where
import Data.Char (isHexDigit)
import Numeric (readHex)
import Data.Bits (xor)
check :: String -> Bool
check ('$':xs) | valid = (== (fst . head . readHex $ checksum)) . foldl1 xor . map fromEnum $ str
where (str, _:rest) = break (=='*') xs
(checksum, end) = span isHexDigit rest
valid = (end == "\r\n") && (length checksum == 2)
check x = False
| gafiatulin/codewars | src/5 kyu/NMEA.hs | mit | 465 | 0 | 13 | 98 | 179 | 98 | 81 | 10 | 1 |
{-# LANGUAGE ViewPatterns #-}
{- |
Module : Summoner.Tree
Copyright : (c) 2017-2022 Kowainik
SPDX-License-Identifier : MPL-2.0
Maintainer : Kowainik <xrom.xkov@gmail.com>
Stability : Stable
Portability : Portable
Data type for representing filesystem structure via tree.
-}
module Summoner.Tree
( TreeFs (..)
, traverseTree
, pathToTree
, insertTree
, showBoldTree
, showTree
) where
import Colourista.Short (b)
import System.Directory (createDirectoryIfMissing, withCurrentDirectory)
import System.FilePath (splitDirectories)
-- | Describes simple structure of filesystem tree.
data TreeFs
-- | Name of directory (relative) and its containing entries
= Dir !FilePath ![TreeFs]
-- | File name (relative) and file content
| File !FilePath !Text
deriving stock (Generic, Show, Eq, Ord)
-- | Walks through directory tree and write file contents, creating all
-- intermediate directories.
traverseTree :: TreeFs -> IO ()
traverseTree (File name content) = writeFileText name content
traverseTree (Dir name children) = do
createDirectoryIfMissing False name
withCurrentDirectory name $ for_ children traverseTree
{- | This function converts a string file path to the tree structure.
For a path like this: @".github/workflow/ci.yml"@
This function produces the following tree:
@
.github/
└── workflow/
└── ci.yml
@
-}
pathToTree :: FilePath -> Text -> TreeFs
pathToTree path content =
let pathParts = splitDirectories path
in case pathParts of
[] -> Dir path [] -- shouldn't happen
x:xs -> go x xs
where
go :: FilePath -> [FilePath] -> TreeFs
go p [] = File p content
go p (x:xs) = Dir p [go x xs]
{- | This functions inserts given 'TreeFs' node into the list of existing
'TreeFs' nodes. The behavior of this function is the following:
1. It merges duplicating directories.
2. It overrides existing 'File' with the given 'TreeFs' in case of duplicates.
-}
insertTree :: TreeFs -> [TreeFs] -> [TreeFs]
insertTree node [] = [node]
insertTree node (x:xs) = case (node, x) of
(Dir _ _, File _ _) -> x : insertTree node xs
(File _ _, Dir _ _) -> x : insertTree node xs
(File nodePath _, File curPath _)
| nodePath == curPath -> node : xs
| otherwise -> x : insertTree node xs
(Dir nodePath nodeChildren, Dir curPath curChildren)
| nodePath == curPath ->
Dir nodePath (foldr insertTree curChildren nodeChildren) : xs
| otherwise -> x : insertTree node xs
-- | Pretty shows the directory tree content.
showBoldTree :: TreeFs -> Text
showBoldTree = showTree True
-- | Pretty shows tree with options.
showTree
:: Bool -- ^ Print directories bold.
-> TreeFs -- ^ Given tree.
-> Text -- ^ Pretty output.
showTree isBold = unlines . showOne " " "" ""
where
showOne :: Text -> Text -> Text -> TreeFs -> [Text]
showOne leader tie arm (File fp _) = [leader <> arm <> tie <> toText fp]
showOne leader tie arm (Dir fp (sortWith treeFp -> trees)) =
nodeRep : showChildren trees (leader <> extension)
where
nodeRep :: Text
nodeRep = leader <> arm <> tie <> boldDir (fp <> "/")
where
boldDir :: FilePath -> Text
boldDir str = toText $ if isBold then b str else str
extension :: Text
extension = case arm of "" -> ""; "└" -> " "; _ -> "│ "
showChildren :: [TreeFs] -> Text -> [Text]
showChildren children leader =
let arms = replicate (length children - 1) "├" <> ["└"]
in concat (zipWith (showOne leader "── ") arms children)
-- | Extract 'TreeFs' path. Used for sorting in alphabetic order.
treeFp :: TreeFs -> FilePath
treeFp (Dir fp _) = fp
treeFp (File fp _) = fp
| vrom911/hs-init | summoner-cli/src/Summoner/Tree.hs | mit | 3,872 | 0 | 15 | 992 | 970 | 502 | 468 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | To run these tests:
--
-- * `cabal repl psc-publish`
-- * `:l psc-publish/tests/Test.hs`
-- * `test`
module Test where
import Control.Monad
import Control.Applicative
import Control.Exception
import System.Process
import System.Directory
import qualified Data.ByteString.Lazy as BL
import Data.ByteString.Lazy (ByteString)
import qualified Data.Aeson as A
import Data.Aeson.BetterErrors
import Main
import Language.PureScript.Docs
pkgName = "purescript-prelude"
packageUrl = "https://github.com/purescript/" ++ pkgName
packageDir = "tmp/" ++ pkgName
pushd :: forall a. FilePath -> IO a -> IO a
pushd dir act = do
original <- getCurrentDirectory
setCurrentDirectory dir
result <- try act :: IO (Either IOException a)
setCurrentDirectory original
either throwIO return result
clonePackage :: IO ()
clonePackage = do
createDirectoryIfMissing True packageDir
pushd packageDir $ do
exists <- doesDirectoryExist ".git"
unless exists $ do
putStrLn ("Cloning " ++ pkgName ++ " into " ++ packageDir ++ "...")
readProcess "git" ["clone", packageUrl, "."] "" >>= putStr
readProcess "git" ["tag", "v999.0.0"] "" >>= putStr
bowerInstall :: IO ()
bowerInstall =
pushd packageDir $
readProcess "bower" ["install"] "" >>= putStr
getPackage :: IO UploadedPackage
getPackage = do
clonePackage
bowerInstall
pushd packageDir preparePackage
data TestResult
= ParseFailed String
| Mismatch ByteString ByteString -- ^ encoding before, encoding after
| Pass ByteString
deriving (Show, Read)
-- | Test JSON encoding/decoding; parse the package, roundtrip to/from JSON,
-- and check we get the same string.
test :: IO TestResult
test = roundTrip <$> getPackage
roundTrip :: UploadedPackage -> TestResult
roundTrip pkg =
let before = A.encode pkg
in case A.eitherDecode before of
Left err -> ParseFailed err
Right parsed -> do
let after = A.encode (parsed :: UploadedPackage)
if before == after
then Pass before
else Mismatch before after
| michaelficarra/purescript | psc-publish/tests/Test.hs | mit | 2,178 | 0 | 18 | 413 | 532 | 275 | 257 | 60 | 3 |
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
import Data.List
lcmlist :: [Int] -> Int
lcmlist = foldl1' (\alcm num -> lcm alcm num)
main :: IO ()
main = do
_ <- getLine
nsstr <- getLine
putStrLn $ show $ lcmlist (map read . words $ nsstr)
| cbrghostrider/Hacking | HackerRank/FunctionalProgramming/AdHoc/jumpingBunnies.hs | mit | 619 | 0 | 12 | 113 | 103 | 54 | 49 | 8 | 1 |
-- stack runghc --package aeson --package bytestring-0.10.8.1 --package websockets --package conduit-extra --package conduit
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
import Control.Concurrent.Async
import Control.Monad
import Control.Monad.IO.Class
import Data.Aeson
import Data.Aeson.TH
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString as B hiding (unpack)
import qualified Data.ByteString.Char8 as B (unpack)
import Data.Char
import Data.Conduit
import qualified Data.Conduit.Binary as Conduit.Binary
import Data.Conduit.Process
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Text.Encoding
import qualified Network.WebSockets as WS
data Message = Message { msgType :: T.Text
, msgPayload :: T.Text
}
deriving(Show)
deriveJSON (defaultOptions { fieldLabelModifier = drop 3 . map toLower
}) ''Message
handler :: WS.Connection -> IO ()
handler conn = do
putStrLn "User joined"
let msgProducer = forever $ do
mmsg <- decode <$> liftIO (WS.receiveData conn :: IO BL.ByteString)
case mmsg of
Just (Message "RUN" payload) -> void $ liftIO $ do
T.writeFile "./tmp.hs" payload
WS.sendTextData conn $ encode $ object
[ "type" .= String "RUN_COMMAND"
, "payload" .= String "stack ghc ./tmp.hs"
]
(Inherited, out, err, cph) <- streamingProcess (shell "stack ghc ./tmp.hs")
let buildResultsSink = await >>= \case
Nothing -> return ()
Just l -> do
liftIO $ WS.sendTextData conn $ encode $ object
[ "type" .= String "RUN_COMPILE_LOG"
, "payload" .= String (decodeUtf8 l)
]
buildResultsSink
runConcurrently $
Concurrently (out $$ (Conduit.Binary.lines =$ buildResultsSink)) *>
Concurrently (err $$ (Conduit.Binary.lines =$ buildResultsSink)) *>
Concurrently (waitForStreamingProcess cph)
liftIO $ WS.sendTextData conn $ encode $ object
[ "type" .= String "COMPILE_DONE" ]
WS.sendTextData conn $ encode $ object
[ "type" .= String "RUN_COMMAND"
, "payload" .= String "./tmp"
]
(Inherited, out, err, cph) <- streamingProcess (shell "./tmp")
let runResultsSink = await >>= \case
Nothing -> return ()
Just l -> do
liftIO $ WS.sendTextData conn $ encode $ object
[ "type" .= String "RUN_LOG"
, "payload" .= String (decodeUtf8 l)
]
runResultsSink
runConcurrently $
Concurrently (out $$ (Conduit.Binary.lines =$ runResultsSink)) *>
Concurrently (err $$ (Conduit.Binary.lines =$ runResultsSink)) *>
Concurrently (waitForStreamingProcess cph)
liftIO $ WS.sendTextData conn $ encode $ object
[ "type" .= String "RUN_DONE" ]
Just (Message "LOAD_FILE" payload) -> do
liftIO $ T.writeFile "./tmp.hs" payload
yield (":load ./tmp.hs" <> "\n")
Just (Message "RUN_AUTO" payload) -> void $ liftIO $ do
T.writeFile "./tmp.hs" payload
WS.sendTextData conn $ encode $ object
[ "type" .= String "RUN_COMMAND"
, "payload" .= String "stack-run-auto ./tmp.hs --resolver lts-6.17"
]
(Inherited, out, err, cph) <- streamingProcess (shell "stack-run-auto ./tmp.hs")
let buildResultsSink h = await >>= \case
Nothing -> return ()
Just l -> do
liftIO $ WS.sendTextData conn $ encode $ object
[ "type" .= String "RUN_LOG"
, "payload" .= String (decodeUtf8 l)
, "handle" .= String h
]
buildResultsSink h
runConcurrently $
Concurrently (out $$ (Conduit.Binary.lines =$ buildResultsSink "stdout")) *>
Concurrently (err $$ (Conduit.Binary.lines =$ buildResultsSink "stderr")) *>
Concurrently (waitForStreamingProcess cph)
liftIO $ WS.sendTextData conn $ encode $ object
[ "type" .= String "RUN_DONE" ]
Just (Message "EVAL" payload) -> do
liftIO $ putStrLn ("<- \"" <> T.unpack payload <> "\"")
yield (encodeUtf8 payload <> "\n")
Nothing -> liftIO $ print mmsg
msgConsumer = await >>= \case
Just "> " -> do
liftIO $ putStrLn ("-> \"<DONE>\"")
liftIO $ WS.sendTextData conn ("{\"type\":\"EVAL_DONE\"}" :: ByteString)
msgConsumer
Just msg -> do
let msg' = fromMaybe msg (B.stripPrefix "> " msg)
liftIO $ putStrLn ("-> \"" <> B.unpack msg' <> "\"")
liftIO $ WS.sendTextData conn $ encode $ object $
[ "payload" .= String (decodeUtf8 msg')
, "type" .= String "EVAL_LOG"
]
msgConsumer
Nothing -> return ()
(inp, out, err, cph) <- streamingProcess (shell "ghci")
(yield ":set prompt \"> \\n\"\n") $$ inp
void $ runConcurrently $
Concurrently (msgProducer $$ inp) *>
Concurrently (out $$ (Conduit.Binary.lines =$ msgConsumer)) *>
Concurrently (err $$ (Conduit.Binary.lines =$ msgConsumer)) *>
Concurrently (waitForStreamingProcess cph)
main :: IO ()
main = do
putStrLn "Listening on 9160"
WS.runServer "0.0.0.0" 9160 $ \pendingConn -> do
conn <- WS.acceptRequest pendingConn
WS.forkPingThread conn 30
handler conn
| haskellbr/meetups | 09-2016/programas-como-linguagens/haskell-web-repl/backend.hs | mit | 6,906 | 0 | 34 | 2,913 | 1,623 | 808 | 815 | 123 | 10 |
{-# LANGUAGE RecordWildCards #-}
-- NOTE: Due to https://github.com/yesodweb/wai/issues/192, this module should
-- not use CPP.
module Network.Wai.Middleware.RequestLogger
( -- * Basic stdout logging
logStdout
, logStdoutDev
-- * Create more versions
, mkRequestLogger
, RequestLoggerSettings
, outputFormat
, autoFlush
, destination
, OutputFormat (..)
, OutputFormatter
, OutputFormatterWithDetails
, Destination (..)
, Callback
, IPAddrSource (..)
) where
import System.IO (Handle, hFlush, stdout)
import qualified Blaze.ByteString.Builder as B
import qualified Data.ByteString as BS
import Data.ByteString.Char8 (pack, unpack)
import Control.Monad (when)
import Control.Monad.IO.Class (liftIO)
import Network.Wai
( Request(..), requestBodyLength, RequestBodyLength(..)
, Middleware
, Response, responseStatus, responseHeaders
)
import System.Log.FastLogger
import Network.HTTP.Types as H
import Data.Maybe (fromMaybe)
import Data.Monoid (mconcat, (<>))
import Data.Time (getCurrentTime, diffUTCTime, NominalDiffTime)
import Network.Wai.Parse (sinkRequestBody, lbsBackEnd, fileName, Param, File
, getRequestBodyType)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Char8 as S8
import System.Console.ANSI
import Data.IORef.Lifted
import System.IO.Unsafe
import Network.Wai.Internal (Response (..))
import Data.Default.Class (Default (def))
import Network.Wai.Logger
import Network.Wai.Middleware.RequestLogger.Internal
import Network.Wai.Header (contentLength)
import Data.Text.Encoding (decodeUtf8')
data OutputFormat = Apache IPAddrSource
| Detailed Bool -- ^ use colors?
| CustomOutputFormat OutputFormatter
| CustomOutputFormatWithDetails OutputFormatterWithDetails
type OutputFormatter = ZonedDate -> Request -> Status -> Maybe Integer -> LogStr
type OutputFormatterWithDetails =
ZonedDate -> Request -> Status -> Maybe Integer -> NominalDiffTime -> [S8.ByteString] -> B.Builder -> LogStr
data Destination = Handle Handle
| Logger LoggerSet
| Callback Callback
type Callback = LogStr -> IO ()
-- | @RequestLoggerSettings@ is an instance of Default. See <https://hackage.haskell.org/package/data-default Data.Default> for more information.
--
-- @outputFormat@, @autoFlush@, and @destination@ are record fields
-- for the record type @RequestLoggerSettings@, so they can be used to
-- modify settings values using record syntax.
data RequestLoggerSettings = RequestLoggerSettings
{
-- | Default value: @Detailed@ @True@.
outputFormat :: OutputFormat
-- | Only applies when using the @Handle@ constructor for @destination@.
--
-- Default value: @True@.
, autoFlush :: Bool
-- | Default: @Handle@ @stdout@.
, destination :: Destination
}
instance Default RequestLoggerSettings where
def = RequestLoggerSettings
{ outputFormat = Detailed True
, autoFlush = True
, destination = Handle stdout
}
mkRequestLogger :: RequestLoggerSettings -> IO Middleware
mkRequestLogger RequestLoggerSettings{..} = do
let (callback, flusher) =
case destination of
Handle h -> (BS.hPutStr h . logToByteString, when autoFlush (hFlush h))
Logger l -> (pushLogStr l, when autoFlush (flushLogStr l))
Callback c -> (c, return ())
case outputFormat of
Apache ipsrc -> do
getdate <- getDateGetter flusher
apache <- initLogger ipsrc (LogCallback callback flusher) getdate
return $ apacheMiddleware apache
Detailed useColors -> detailedMiddleware
(\str -> callback str >> flusher)
useColors
CustomOutputFormat formatter -> do
getDate <- getDateGetter flusher
return $ customMiddleware callback getDate formatter
CustomOutputFormatWithDetails formatter -> do
getdate <- getDateGetter flusher
return $ customMiddlewareWithDetails callback getdate formatter
apacheMiddleware :: ApacheLoggerActions -> Middleware
apacheMiddleware ala app req sendResponse = app req $ \res -> do
let msize = contentLength (responseHeaders res)
apacheLogger ala req (responseStatus res) msize
sendResponse res
customMiddleware :: Callback -> IO ZonedDate -> OutputFormatter -> Middleware
customMiddleware cb getdate formatter app req sendResponse = app req $ \res -> do
date <- liftIO getdate
-- We use Nothing for the response size since we generally don't know it
liftIO $ cb $ formatter date req (responseStatus res) Nothing
sendResponse res
customMiddlewareWithDetails :: Callback -> IO ZonedDate -> OutputFormatterWithDetails -> Middleware
customMiddlewareWithDetails cb getdate formatter app req sendResponse = do
(req', reqBody) <- getRequestBody req
t0 <- getCurrentTime
app req' $ \res -> do
t1 <- getCurrentTime
date <- liftIO getdate
-- We use Nothing for the response size since we generally don't know it
builderIO <- newIORef $ B.fromByteString ""
res' <- recordChunks builderIO res
rspRcv <- sendResponse res'
_ <- liftIO . cb .
formatter date req' (responseStatus res') Nothing (t1 `diffUTCTime` t0) reqBody =<<
readIORef builderIO
return rspRcv
-- | Production request logger middleware.
{-# NOINLINE logStdout #-}
logStdout :: Middleware
logStdout = unsafePerformIO $ mkRequestLogger def { outputFormat = Apache FromSocket }
-- | Development request logger middleware.
--
-- Flushes 'stdout' on each request, which would be inefficient in production use.
-- Use "logStdout" in production.
{-# NOINLINE logStdoutDev #-}
logStdoutDev :: Middleware
logStdoutDev = unsafePerformIO $ mkRequestLogger def
-- | Prints a message using the given callback function for each request.
-- This is not for serious production use- it is inefficient.
-- It immediately consumes a POST body and fills it back in and is otherwise inefficient
--
-- Note that it logs the request immediately when it is received.
-- This meanst that you can accurately see the interleaving of requests.
-- And if the app crashes you have still logged the request.
-- However, if you are simulating 10 simultaneous users you may find this confusing.
--
-- This is lower-level - use 'logStdoutDev' unless you need greater control.
--
-- Example ouput:
--
-- > GET search
-- > Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
-- > Status: 200 OK 0.010555s
-- >
-- > GET static/css/normalize.css
-- > Params: [("LXwioiBG","")]
-- > Accept: text/css,*/*;q=0.1
-- > Status: 304 Not Modified 0.010555s
detailedMiddleware :: Callback -> Bool -> IO Middleware
detailedMiddleware cb useColors =
let (ansiColor, ansiMethod, ansiStatusCode) =
if useColors
then (ansiColor', ansiMethod', ansiStatusCode')
else (\_ t -> [t], (:[]), \_ t -> [t])
in return $ detailedMiddleware' cb ansiColor ansiMethod ansiStatusCode
ansiColor' :: Color -> BS.ByteString -> [BS.ByteString]
ansiColor' color bs =
[ pack $ setSGRCode [SetColor Foreground Dull color]
, bs
, pack $ setSGRCode [Reset]
]
-- | Tags http method with a unique color.
ansiMethod' :: BS.ByteString -> [BS.ByteString]
ansiMethod' m = case m of
"GET" -> ansiColor' Cyan m
"HEAD" -> ansiColor' Cyan m
"PUT" -> ansiColor' Green m
"POST" -> ansiColor' Yellow m
"DELETE" -> ansiColor' Red m
_ -> ansiColor' Magenta m
ansiStatusCode' :: BS.ByteString -> BS.ByteString -> [BS.ByteString]
ansiStatusCode' c t = case S8.take 1 c of
"2" -> ansiColor' Green t
"3" -> ansiColor' Yellow t
"4" -> ansiColor' Red t
"5" -> ansiColor' Magenta t
_ -> ansiColor' Blue t
recordChunks :: IORef B.Builder -> Response -> IO Response
recordChunks i (ResponseStream s h sb) =
return . ResponseStream s h $ (\send flush -> sb (\b -> modifyIORef i (<> b) >> send b) flush)
recordChunks i (ResponseBuilder s h b) =
modifyIORef i (<> b) >> (return $ ResponseBuilder s h b)
recordChunks _ r =
return r
getRequestBody :: Request -> IO (Request, [S8.ByteString])
getRequestBody req = do
let loop front = do
bs <- requestBody req
if S8.null bs
then return $ front []
else loop $ front . (bs:)
body <- loop id
-- logging the body here consumes it, so fill it back up
-- obviously not efficient, but this is the development logger
--
-- Note: previously, we simply used CL.sourceList. However,
-- that meant that you could read the request body in twice.
-- While that in itself is not a problem, the issue is that,
-- in production, you wouldn't be able to do this, and
-- therefore some bugs wouldn't show up during testing. This
-- implementation ensures that each chunk is only returned
-- once.
ichunks <- newIORef body
let rbody = atomicModifyIORef ichunks $ \chunks ->
case chunks of
[] -> ([], S8.empty)
x:y -> (y, x)
let req' = req { requestBody = rbody }
return (req', body)
detailedMiddleware' :: Callback
-> (Color -> BS.ByteString -> [BS.ByteString])
-> (BS.ByteString -> [BS.ByteString])
-> (BS.ByteString -> BS.ByteString -> [BS.ByteString])
-> Middleware
detailedMiddleware' cb ansiColor ansiMethod ansiStatusCode app req sendResponse = do
(req', body) <-
-- second tuple item should not be necessary, but a test runner might mess it up
case (requestBodyLength req, contentLength (requestHeaders req)) of
-- log the request body if it is small
(KnownLength len, _) | len <= 2048 -> getRequestBody req
(_, Just len) | len <= 2048 -> getRequestBody req
_ -> return (req, [])
let reqbodylog _ = if null body then [""] else ansiColor White " Request Body: " <> body <> ["\n"]
reqbody = concatMap (either (const [""]) reqbodylog . decodeUtf8') body
postParams <- if requestMethod req `elem` ["GET", "HEAD"]
then return []
else do postParams <- liftIO $ allPostParams body
return $ collectPostParams postParams
let getParams = map emptyGetParam $ queryString req
accept = fromMaybe "" $ lookup H.hAccept $ requestHeaders req
params = let par | not $ null postParams = [pack (show postParams)]
| not $ null getParams = [pack (show getParams)]
| otherwise = []
in if null par then [""] else ansiColor White " Params: " <> par <> ["\n"]
t0 <- getCurrentTime
app req' $ \rsp -> do
let isRaw =
case rsp of
ResponseRaw{} -> True
_ -> False
stCode = statusBS rsp
stMsg = msgBS rsp
t1 <- getCurrentTime
-- log the status of the response
cb $ mconcat $ map toLogStr $
ansiMethod (requestMethod req) ++ [" ", rawPathInfo req, "\n"] ++
params ++ reqbody ++
ansiColor White " Accept: " ++ [accept, "\n"] ++
if isRaw then [] else
ansiColor White " Status: " ++
ansiStatusCode stCode (stCode <> " " <> stMsg) ++
[" ", pack $ show $ diffUTCTime t1 t0, "\n"]
sendResponse rsp
where
allPostParams body =
case getRequestBodyType req of
Nothing -> return ([], [])
Just rbt -> do
ichunks <- newIORef body
let rbody = atomicModifyIORef ichunks $ \chunks ->
case chunks of
[] -> ([], S8.empty)
x:y -> (y, x)
sinkRequestBody lbsBackEnd rbt rbody
emptyGetParam :: (BS.ByteString, Maybe BS.ByteString) -> (BS.ByteString, BS.ByteString)
emptyGetParam (k, Just v) = (k,v)
emptyGetParam (k, Nothing) = (k,"")
collectPostParams :: ([Param], [File LBS.ByteString]) -> [Param]
collectPostParams (postParams, files) = postParams ++
map (\(k,v) -> (k, "FILE: " <> fileName v)) files
statusBS :: Response -> BS.ByteString
statusBS = pack . show . statusCode . responseStatus
msgBS :: Response -> BS.ByteString
msgBS = statusMessage . responseStatus
| rgrinberg/wai | wai-extra/Network/Wai/Middleware/RequestLogger.hs | mit | 12,549 | 0 | 21 | 3,249 | 3,034 | 1,612 | 1,422 | 225 | 11 |
module Main where
import Data.Word
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import qualified Data.ByteString
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Read as TR
import Data.Aeson
import Data.Aeson.Types (Pair)
import Data.Aeson.Lens
import Data.Maybe
import Data.List
import Data.Either
import Control.Applicative
import Control.Monad
import Control.Lens hiding ((.=))
import Control.Lens.TH
import System.Environment
import System.IO
import System.IO.Error
import System.Exit
import System.Directory
import System.FilePath
import Network.HTTP.Client
import Network.HostName
data LightCommand = LightCommand { _power :: Maybe Bool
, _brightness :: Maybe Word8
, _hue :: Maybe Word16
, _saturation :: Maybe Word8
, _ciexy :: Maybe (Float, Float)
, _colorTemp :: Maybe Word16
, _alert :: Maybe Text
, _effect :: Maybe Text
, _transitionTime :: Maybe Word16
}
makeLenses ''LightCommand
instance ToJSON LightCommand where
toJSON cmd = object . catMaybes . map ($ cmd) $
[ f "on" power
, f "bri" brightness
, f "hue" hue
, f "sat" saturation
, f "xy" ciexy
, f "ct" colorTemp
, f "alert" alert
, f "effect" effect
, f "transitiontime" transitionTime
]
where
f :: ToJSON a => Text -> (Lens' LightCommand (Maybe a)) -> LightCommand -> Maybe Pair
f name accessor cmd = case view accessor cmd of
Nothing -> Nothing
Just val -> Just (name .= val)
lightCommand :: LightCommand
lightCommand = LightCommand Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
nullaryCommands :: [(Text, LightCommand -> LightCommand)]
nullaryCommands = [ ("on", set power (Just True))
, ("off", set power (Just False))]
decimal :: Integral a => Text -> Either Text a
decimal t = case TR.decimal t of
Left err -> Left (T.pack err)
Right (val, "") -> Right val
Right (_, ts) -> Left . T.concat $ ["contains garbage: ", ts]
unaryCommands :: [(Text, Text -> Either Text (LightCommand -> LightCommand))]
unaryCommands = [ ("bri", fmap (set brightness . Just) . intRange 0 255)
, ("hue", fmap (set hue . Just) . intRange 0 65535)
, ("sat", fmap (set saturation . Just) . intRange 0 255)
, ("ct", fmap (set colorTemp . Just) . intRange 153 500)
, ("alert", fmap (set alert . Just) . limit ["none", "select", "lselect"])
, ("effect", fmap (set effect . Just) . limit ["none", "colorloop"])
, ("time", fmap (set transitionTime . Just) . intRange 0 65535)
]
where
intRange :: (Integral a, Show a) => Integer -> Integer -> Text -> Either Text a
intRange min max t =
do x <- decimal t
if min <= x && x <= max
then Right (fromInteger x)
else Left $ T.concat ["value ", t, " out of legal range ", T.pack . show $ min, "-", T.pack . show $ max]
limit :: [Text] -> Text -> Either Text Text
limit options input
| elem input options = Right input
| otherwise = Left . T.concat $ "illegal input \"":input:"\", expected one of: ":intersperse ", " options
parseCommand :: LightCommand -> [Text] -> Either Text LightCommand
parseCommand c [] = Right c
parseCommand c ((flip lookup nullaryCommands -> Just f):xs) = parseCommand (f c) xs
parseCommand c ((flip lookup unaryCommands -> Just p):arg:xs) = do
f <- p arg
parseCommand (f c) xs
parseCommand _ _ = Left "unrecognized command"
usage :: Text
usage = "Usage: hhue <config | lights | groups | scenes | user <create [key] | delete <key>> | light <light id> [name <name> | pointsymbol <pointsymbol id> <symbol> | <COMMAND>*] | group <create <name> <light id>* | update <group id> <name> <light id>* | delete <group id> | <group id> <scene <scene id> | symbol <symbolselection> <duration> | <COMMAND>*>> | scene <create <scene id> <name> <light id>* | update <scene id> <light id> <COMMAND>*>>\n\
\COMMAND := on | off | bri <0-255> | hue <0-65535> | sat <0-255> | ct <153-500> | alert <none|select|lselect> | effect <none|colorloop> | transitiontime <0-65535>\n\
\ct represents color temperature in mireds\n\
\transitiontime is in units of 100ms\n\
\Arbitrarily many commands may be specified simultaneously. When a command recurs, the rightmost instance dominates."
main :: IO ()
main = do
args <- getArgs
configDir <- (</> ".config/hhue") <$> getHomeDirectory
createDirectoryIfMissing True configDir
let keyFile = configDir </> "key"
key <- catchIOError (decodeUtf8 <$> BS.readFile keyFile) $ \err ->
case isDoesNotExistError err of
False -> ioError err
True -> do
result <- createUser Nothing
case result ^? nth 0 . key "error" . key "description" . _String of
Just reason -> do
hPutStr stderr "failed to create user: "
BS.hPut stderr (encodeUtf8 reason)
hPutStrLn stderr ""
exitFailure
Nothing ->
case result ^? nth 0 . key "success" . key "username" . _String of
Nothing -> hPutStrLn stderr "failed to parse user create result: " >> BSL.hPut stderr result >> exitFailure
Just freshKey -> BS.writeFile keyFile (encodeUtf8 freshKey) >> pure freshKey
case args of
["user", "create"] -> BSL.hPut stdout =<< createUser Nothing
["user", "create", name] -> BSL.hPut stdout =<< createUser (Just . T.pack $ name)
["user", "delete", user] -> BSL.hPut stdout =<< httpDelete [key, "config", "whitelist", T.pack user]
["config"] -> BSL.hPut stdout =<< httpGet [key, "config"]
["lights"] -> BSL.hPut stdout =<< httpGet [key, "lights"]
["light", number] -> BSL.hPut stdout =<< httpGet [key, "lights", T.pack number]
["light", number, "name", name] ->
BSL.hPut stdout =<< httpPut [key, "lights", T.pack number] (encode (object ["name" .= T.pack name]))
["light", number, "pointsymbol", symbolNumber, symbol] ->
BSL.hPut stdout =<< httpPut [key, "lights", T.pack number, "pointsymbol"]
(encode (object [T.pack symbolNumber .= T.pack symbol]))
"light":number:command ->
case parseCommand lightCommand (map T.pack command) of
Left err -> BS.hPut stderr (encodeUtf8 (T.concat ["couldn't parse light command: ", err])) >> hPutStrLn stderr ""
Right cmd -> BSL.hPut stdout =<< httpPut [key, "lights", T.pack number, "state"] (encode cmd)
["groups"] -> BSL.hPut stdout =<< httpGet [key, "groups"]
"group":"create":name:lights -> BSL.hPut stdout =<< httpPost [key, "groups"]
(encode $ object [ "name" .= T.pack name
, "lights" .= map T.pack lights])
"group":"update":number:name:lights ->
BSL.hPut stdout =<< httpPut [key, "groups", T.pack number]
(encode $ object [ "name" .= T.pack name
, "lights" .= map T.pack lights])
["group", "delete", number] -> BSL.hPut stdout =<< httpDelete [key, "groups", T.pack number]
["group", groupID, "scene", sceneID] -> BSL.hPut stdout =<< httpPut [key, "groups", T.pack groupID, "action"]
(encode $ object [ "scene" .= T.pack sceneID])
["group", groupID, "symbol", selection, duration] ->
case decimal (T.pack duration) of
Left err -> BS.hPut stderr (encodeUtf8 (T.concat ["couldn't parse duration: ", err])) >> hPutStrLn stderr ""
Right d -> BSL.hPut stdout =<< httpPut [key, "groups", T.pack groupID, "transmitsymbol"]
(encode $ object [ "symbolselection" .= selection, "duration" .= (d :: Word16)])
"group":number:command ->
case parseCommand lightCommand (map T.pack command) of
Left err -> BS.hPut stderr (encodeUtf8 (T.concat ["couldn't parse light command: ", err])) >> hPutStrLn stderr ""
Right cmd -> BSL.hPut stdout =<< httpPut [key, "groups", T.pack number, "action"] (encode cmd)
["scenes"] -> BSL.hPut stdout =<< httpGet [key, "scenes"]
"scene":"create":sceneID:name:lights -> BSL.hPut stdout =<< httpPut [key, "scenes", T.pack sceneID]
(encode $ object [ "name" .= T.pack name
, "lights" .= map T.pack lights])
"scene":"update":sceneID:lightNumber:command ->
case parseCommand lightCommand (map T.pack command) of
Left err -> BS.hPut stderr (encodeUtf8 (T.concat ["couldn't parse light command: ", err])) >> hPutStrLn stderr ""
Right cmd -> BSL.hPut stdout =<< httpPut [key, "scenes", T.pack sceneID, "lights", T.pack lightNumber, "state"]
(encode cmd)
["schedules"] -> BSL.hPut stdout =<< httpGet [key, "schedules"]
_ -> BS.hPut stderr . encodeUtf8 $ T.concat ["unrecognized command\n", usage, "\n"]
httpReq :: [Text] -> ByteString -> RequestBody -> IO BSL.ByteString
httpReq url method body = do
request <- parseUrl . T.unpack . T.concat . intersperse "/" $ "http://philips-hue/api" : url
response <- withManager defaultManagerSettings $ \mgr -> httpLbs (request { method = method
, requestBody = body
})
mgr
pure . responseBody $ response
httpGet :: [Text] -> IO BSL.ByteString
httpGet url = httpReq url "GET" (RequestBodyBS "")
httpPut :: [Text] -> BSL.ByteString -> IO BSL.ByteString
httpPut url body = httpReq url "PUT" (RequestBodyLBS body)
httpPost :: [Text] -> BSL.ByteString -> IO BSL.ByteString
httpPost url body = httpReq url "POST" (RequestBodyLBS body)
httpDelete :: [Text] -> IO BSL.ByteString
httpDelete url = httpReq url "DELETE" (RequestBodyBS "")
createUser :: Maybe Text -> IO BSL.ByteString
createUser Nothing = do
hostname <- getHostName
httpPost [] (encode (object [ "devicetype" .= T.concat ["hhue#", T.pack (take 19 hostname)]]))
createUser (Just name) = do
hostname <- getHostName
httpPost [] (encode (object [ "devicetype" .= T.concat ["hhue#", T.pack (take 19 hostname)]
, "username" .= name
]))
| Ralith/hhue | src/Main.hs | mit | 11,189 | 0 | 24 | 3,428 | 3,452 | 1,771 | 1,681 | -1 | -1 |
module Tables where
import qualified Data.Map as M
import Template
import Text.Printf
-- Switch the comments to select the small or big table.
--sinTable = [ (x, sin x) | x <- [0.0, 0.1 .. 10.0 ] ]
sinTable = [ (x, sin x) | x <- [0.0, 0.5 .. 10.0 ] ]
sinMap = M.fromList sinTable
sinTree = makeTree sinTable
targetFront = 0.0005
targetMiddle = 5.1
targetBack = 9.95
printTable :: [(Double,Double)] -> IO ()
printTable = mapM_ (\(a,b) -> printf "(%.2f, %.2f)\n" a b)
littleTable :: [(Double,Double)]
littleTable = [ (1,1), (2,4), (3,9) ]
| cmears/linear-interpolation-article | Tables.hs | mit | 543 | 0 | 8 | 102 | 187 | 113 | 74 | 14 | 1 |
module Parse.Date
(
getUnixTimeFromPostHtml
) where
import Data.ByteString.Char8 (ByteString, unpack)
import Data.Time.Format (formatTime, parseTimeOrError, defaultTimeLocale)
import Data.Time.LocalTime (LocalTime, TimeZone, localTimeToUTC)
import Text.HTML.TagSoup (innerText, Tag (TagOpen), (~==))
import qualified Data.ByteString.Char8 as BS (filter)
import Debug.Trace (trace)
import Parse.Post.Internal
getUnixTimeFromPostHtml :: TimeZone -> PostHtml -> Maybe Int
getUnixTimeFromPostHtml timeZone postHtml = case getDateFromPostHtml postHtml of
Nothing -> Nothing
Just xs -> Just $ getUnixTimeFromDate timeZone xs
getUnixTimeFromDate :: TimeZone -> LocalTime -> Int
getUnixTimeFromDate timeZone = (\x -> read x :: Int) . (formatTime defaultTimeLocale "%s") . (localTimeToUTC timeZone)
getDateFromPostHtml :: PostHtml -> Maybe LocalTime
getDateFromPostHtml (PostHtml header _) = case getDateStringFromPostHeader header of
Nothing -> Nothing
Just xs -> Just $ (getDateFromString . unpack) xs
getDateStringFromPostHeader :: PostHeaderHtml -> Maybe ByteString
getDateStringFromPostHeader (PostHeaderHtml headerHtml) = case dropWhile (not . tagHasDate) headerHtml of
[] -> trace ("Failed to find tag with date: " ++ (show headerHtml)) Nothing
xs -> case checkLength xs of
Nothing -> trace "Length of remaining tags not enough to get date" Nothing
Just as -> case (innerText . take 2) as of
"" -> trace ("Inner text got empty string on: " ++ (show as)) Nothing
bs -> case BS.filter (/= '\n') bs of
"" -> trace ("Filtered down to nothing in String: " ++ (show bs) ++ ", in tag: " ++ (show $ take 3 as)) Nothing
cs -> Just cs
where
checkLength ys
| (length ys) < 2 = trace "Failed to get enough tabs after finding date tag" Nothing
| otherwise = Just ys
tagHasDate :: Tag ByteString -> Bool
tagHasDate tag = tag ~== ("<a class=datePermalink>" :: String)
getDateFromString dateByteString = parseTimeOrError True defaultTimeLocale "%b %-d, %Y at %-I:%M %p" dateByteString :: LocalTime
| JacobLeach/xen-parsing | app/Parse/Date.hs | mit | 2,057 | 0 | 23 | 357 | 599 | 313 | 286 | 36 | 5 |
module Raindrops
( convert
) where
convert :: Int -> String
convert n
| null drops = show n
| otherwise = drops
where
divisibleBy d = n `rem` d == 0
drops = concat
[ if divisibleBy 3 then "Pling" else ""
, if divisibleBy 5 then "Plang" else ""
, if divisibleBy 7 then "Plong" else ""
]
| tfausak/exercism-solutions | haskell/raindrops/Raindrops.hs | mit | 363 | 0 | 10 | 137 | 117 | 62 | 55 | 11 | 4 |
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# LANGUAGE QuasiQuotes, TemplateHaskell, CPP, GADTs, TypeFamilies, OverloadedStrings, FlexibleContexts, EmptyDataDecls, FlexibleInstances, GeneralizedNewtypeDeriving, MultiParamTypeClasses #-}
module DataTypeTest (specs) where
import Test.QuickCheck.Arbitrary (Arbitrary, arbitrary)
import Test.QuickCheck.Gen (Gen(..))
import Test.QuickCheck.Instances ()
import Test.QuickCheck.Random (newQCGen)
import Database.Persist.TH
import Data.Char (generalCategory, GeneralCategory(..))
import qualified Data.Text as T
import qualified Data.ByteString as BS
import Data.Time (Day, UTCTime (..), fromGregorian, picosecondsToDiffTime,
TimeOfDay (TimeOfDay), timeToTimeOfDay, timeOfDayToTime)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds, posixSecondsToUTCTime)
import Data.IntMap (IntMap)
import Data.Fixed (Pico,Micro)
import Init
type Tuple a b = (a, b)
#ifdef WITH_NOSQL
mkPersist persistSettings [persistUpperCase|
#else
-- Test lower case names
share [mkPersist persistSettings, mkMigrate "dataTypeMigrate"] [persistLowerCase|
#endif
DataTypeTable no-json
text Text
textMaxLen Text maxlen=100
bytes ByteString
bytesTextTuple (Tuple ByteString Text)
bytesMaxLen ByteString maxlen=100
int Int
intList [Int]
intMap (IntMap Int)
double Double
bool Bool
day Day
#ifndef WITH_NOSQL
pico Pico
time TimeOfDay
#endif
utc UTCTime
#if defined(WITH_MYSQL) && !(defined(OLD_MYSQL))
-- For MySQL, provide extra tests for time fields with fractional seconds,
-- since the default (used above) is to have no fractional part. This
-- requires the server version to be at least 5.6.4, and should be switched
-- off for older servers by defining OLD_MYSQL.
timeFrac TimeOfDay sqltype=TIME(6)
utcFrac UTCTime sqltype=DATETIME(6)
#endif
|]
cleanDB :: (MonadIO m, PersistQuery backend, backend ~ PersistEntityBackend DataTypeTable) => ReaderT backend m ()
cleanDB = deleteWhere ([] :: [Filter DataTypeTable])
specs :: Spec
specs = describe "data type specs" $
it "handles all types" $ asIO $ runConn $ do
#ifndef WITH_NOSQL
_ <- runMigrationSilent dataTypeMigrate
-- Ensure reading the data from the database works...
_ <- runMigrationSilent dataTypeMigrate
#endif
rvals <- liftIO randomValues
forM_ (take 1000 rvals) $ \x -> do
key <- insert x
Just y <- get key
liftIO $ do
let check :: (Eq a, Show a) => String -> (DataTypeTable -> a) -> IO ()
check s f = (s, f x) @=? (s, f y)
-- Check floating-point near equality
let check' :: String -> (DataTypeTable -> Pico) -> IO ()
check' s f
| abs (f x - f y) < 0.000001 = return ()
| otherwise = (s, f x) @=? (s, f y)
-- Check individual fields for better error messages
check "text" dataTypeTableText
check "textMaxLen" dataTypeTableTextMaxLen
check "bytes" dataTypeTableBytes
check "bytesTextTuple" dataTypeTableBytesTextTuple
check "bytesMaxLen" dataTypeTableBytesMaxLen
check "int" dataTypeTableInt
check "intList" dataTypeTableIntList
check "intMap" dataTypeTableIntMap
check "bool" dataTypeTableBool
check "day" dataTypeTableDay
#ifndef WITH_NOSQL
check' "pico" dataTypeTablePico
check "time" (roundTime . dataTypeTableTime)
#endif
#if !(defined(WITH_NOSQL)) || (defined(WITH_NOSQL) && defined(HIGH_PRECISION_DATE))
check "utc" (roundUTCTime . dataTypeTableUtc)
#endif
#if defined(WITH_MYSQL) && !(defined(OLD_MYSQL))
check "timeFrac" (dataTypeTableTimeFrac)
check "utcFrac" (dataTypeTableUtcFrac)
#endif
-- Do a special check for Double since it may
-- lose precision when serialized.
when (getDoubleDiff (dataTypeTableDouble x)(dataTypeTableDouble y) > 1e-14) $
check "double" dataTypeTableDouble
where
normDouble :: Double -> Double
normDouble x | abs x > 1 = x / 10 ^ (truncate (logBase 10 (abs x)) :: Integer)
| otherwise = x
getDoubleDiff x y = abs (normDouble x - normDouble y)
roundFn :: RealFrac a => a -> Integer
#ifdef OLD_MYSQL
-- At version 5.6.4, MySQL changed the method used to round values for
-- date/time types - this is the same version which added support for
-- fractional seconds in the storage type.
roundFn = truncate
#else
roundFn = round
#endif
roundTime :: TimeOfDay -> TimeOfDay
#ifdef WITH_MYSQL
roundTime t = timeToTimeOfDay $ fromIntegral $ roundFn $ timeOfDayToTime t
#else
roundTime = id
#endif
roundUTCTime :: UTCTime -> UTCTime
#ifdef WITH_MYSQL
roundUTCTime t =
posixSecondsToUTCTime $ fromIntegral $ roundFn $ utcTimeToPOSIXSeconds t
#else
roundUTCTime = id
#endif
randomValues :: IO [DataTypeTable]
randomValues = do
g <- newQCGen
return $ map (unGen arbitrary g) [0..]
instance Arbitrary DataTypeTable where
arbitrary = DataTypeTable
<$> arbText -- text
<*> (T.take 100 <$> arbText) -- textManLen
<*> arbitrary -- bytes
<*> arbTuple arbitrary arbText -- bytesTextTuple
<*> (BS.take 100 <$> arbitrary) -- bytesMaxLen
<*> arbitrary -- int
<*> arbitrary -- intList
<*> arbitrary -- intMap
<*> arbitrary -- double
<*> arbitrary -- bool
<*> arbitrary -- day
#ifndef WITH_NOSQL
<*> arbitrary -- pico
<*> (truncateTimeOfDay =<< arbitrary) -- time
#endif
<*> (truncateUTCTime =<< arbitrary) -- utc
#if defined(WITH_MYSQL) && !(defined(OLD_MYSQL))
<*> (truncateTimeOfDay =<< arbitrary) -- timeFrac
<*> (truncateUTCTime =<< arbitrary) -- utcFrac
#endif
arbText :: Gen Text
arbText =
T.pack
. filter ((`notElem` forbidden) . generalCategory)
. filter (<= '\xFFFF') -- only BMP
. filter (/= '\0') -- no nulls
<$> arbitrary
where forbidden = [NotAssigned, PrivateUse]
arbTuple :: Gen a -> Gen b -> Gen (a, b)
arbTuple x y = (,) <$> x <*> y
-- truncate less significant digits
truncateToMicro :: Pico -> Pico
truncateToMicro p = let
p' = fromRational . toRational $ p :: Micro
in fromRational . toRational $ p' :: Pico
truncateTimeOfDay :: TimeOfDay -> Gen TimeOfDay
truncateTimeOfDay (TimeOfDay h m s) =
return $ TimeOfDay h m $ truncateToMicro s
truncateUTCTime :: UTCTime -> Gen UTCTime
truncateUTCTime (UTCTime d dift) = do
let pico = fromRational . toRational $ dift :: Pico
picoi= truncate . (*1000000000000) . toRational $ truncateToMicro pico :: Integer
-- https://github.com/lpsmith/postgresql-simple/issues/123
d' = max d $ fromGregorian 1950 1 1
return $ UTCTime d' $ picosecondsToDiffTime picoi
asIO :: IO a -> IO a
asIO = id
| psibi/persistent | persistent-test/src/DataTypeTest.hs | mit | 7,186 | 0 | 25 | 1,832 | 1,500 | 793 | 707 | 109 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module ZoomHub.Config.AWS
( Config (..),
S3BucketName (..),
fromEnv,
)
where
import Data.Text (Text)
import qualified Data.Text as T
import qualified Network.AWS as AWS
import System.Environment (getEnvironment)
newtype S3BucketName = S3BucketName {unS3BucketName :: Text}
deriving (Eq, Show)
data Config = Config
{ configAccessKeyId :: Text,
configSecretAccessKey :: Text,
configSourcesS3Bucket :: S3BucketName,
configRegion :: AWS.Region
}
fromEnv :: AWS.Region -> IO (Maybe Config)
fromEnv region = do
env <- getEnvironment
-- TODO: Refactor to use named instead of positional arguments:
return $
Config
<$> (T.pack <$> lookup "AWS_ACCESS_KEY_ID" env)
<*> (T.pack <$> lookup "AWS_SECRET_ACCESS_KEY" env)
<*> (S3BucketName . T.pack <$> lookup "S3_SOURCES_BUCKET" env)
<*> Just region
| zoomhub/zoomhub | src/ZoomHub/Config/AWS.hs | mit | 890 | 0 | 13 | 177 | 231 | 134 | 97 | 25 | 1 |
module Main where
import qualified Data.Text.IO as TIO (readFile, putStrLn)
import qualified Data.Text as T (words, unwords, append)
import Data.MarkovChain (run)
import System.Random (newStdGen, randomRIO, mkStdGen)
main :: IO ()
main = do
input0 <- TIO.readFile "b_04_06_2015.txt"
input1 <- TIO.readFile "b_05_06_2015.txt"
input2 <- TIO.readFile "b_08_06_2015.txt"
input3 <- TIO.readFile "b_09_06_2015.txt"
gen <- newStdGen
-- let gen = mkStdGen 123
index <- randomRIO (0,1000)
let input = T.words $ input0 `T.append` input1 `T.append` input2 `T.append` input3
let predSize = 1
let result = (T.unwords . take 30) (run predSize input index gen)
TIO.putStrLn result
| cirquit/Personal-Repository | Haskell/Playground/MarkovChain/text-processing/app/Main.hs | mit | 713 | 0 | 14 | 139 | 245 | 130 | 115 | 17 | 1 |
{-# LANGUAGE QuasiQuotes #-}
module Ocram.Analysis.CallGraph.Test (tests) where
-- imports {{{1
import Data.Maybe (isJust, fromJust)
import Ocram.Analysis.CallGraph (call_graph, call_chain, call_order, get_callees, get_callers)
import Ocram.Test.Lib (enrich, reduce, enumTestGroup, paste)
import Test.Framework (testGroup, Test)
import Test.HUnit ((@=?), (@?))
tests :: Test -- {{{1
tests = testGroup "CallGraph" [
test_call_graph
, test_call_chain
, test_call_order
, test_get_callees
, test_get_callers
]
test_call_graph :: Test -- {{{1
test_call_graph = enumTestGroup "call_graph" $ map runTest [
-- , 01 - minimal example {{{2
([paste|
__attribute__((tc_block)) void block();
__attribute__((tc_thread)) void start() {
block();
}
|], [("start", "block")])
, -- 02 - with critical function {{{2
([paste|
__attribute__((tc_block)) void block();
void critical() {
block();
}
__attribute__((tc_thread)) void start() {
critical();
}
|], [("critical", "block"), ("start", "critical")])
, -- 03 - chain of critical functions {{{2
([paste|
__attribute__((tc_block)) void block();
void c1() { c2(); }
void c2() { c3(); }
void c3() { c4(); }
void c4() { block(); }
__attribute__((tc_thread)) void start() {
c1();
}
|], [("c1", "c2"), ("c2", "c3"), ("c3", "c4"), ("c4", "block"), ("start", "c1")])
, -- 04 - additional non-critical function {{{2
([paste|
__attribute__((tc_block)) void block();
void non_critical() { }
__attribute__((tc_thread)) void start() {
non_critical();
block();
}
|], [("start", "block"), ("start", "non_critical")])
, -- 05 - ignore unused blocking functions {{{2
([paste|
__attribute__((tc_block)) void block_unused();
__attribute__((tc_block)) void block_used();
__attribute__((tc_thread)) void start () { block_used(); }
|], [("start", "block_used")])
, -- 06 - call of functions from external libraries {{{2
([paste|
__attribute__((tc_block)) void block();
int libfun();
__attribute__((tc_thread)) void start() {
libfun();
block();
}
|], [("start", "block")])
, -- 07 - two independant threads {{{2
([paste|
__attribute__((tc_block)) void block1();
__attribute__((tc_block)) void block2();
__attribute__((tc_thread)) void start1() {
block1();
}
__attribute__((tc_thread)) void start2() {
block2();
}
|], [("start1", "block1"), ("start2", "block2")])
, -- 08 - reentrance {{{2
([paste|
__attribute__((tc_block)) void block();
void critical() {
block();
}
__attribute__((tc_thread)) void start1() {
critical();
}
__attribute__((tc_thread)) void start2() {
critical();
}
|], [("critical", "block"), ("start1", "critical"), ("start2", "critical")])
]
where runTest (code, expected) = expected @=? reduce (call_graph (enrich code))
test_call_chain :: Test -- {{{1
test_call_chain = enumTestGroup "call_chain" $ map runTest [
([("a", "b")], ("a", "a"), ["a"])
, ([("a", "b")], ("a", "b"), ["a", "b"])
, ([("a", "b"), ("a", "c")], ("a", "b"), ["a", "b"])
, ([("a", "b"), ("a", "c")], ("a", "c"), ["a", "c"])
]
where
runTest (cg, (start, end), expected) = do
let result = call_chain (enrich cg) (enrich start) (enrich end)
isJust result @? "could not determine call chain."
expected @=? (reduce $ fromJust result)
test_call_order :: Test -- {{{1
test_call_order = enumTestGroup "call_order" $ map runTest [
([("a", "b")], "a", ["a", "b"])
, ([("a", "b"), ("b", "c")], "a", ["a", "b", "c"])
, ([("a", "b"), ("a", "c")], "a", ["a", "b", "c"])
]
where
runTest (cg, start, expected) = do
let result = call_order (enrich cg) (enrich start)
isJust result @? "could not determine call order"
expected @=? (reduce $ fromJust result)
test_get_callees :: Test -- {{{1
test_get_callees = enumTestGroup "get_callees" $ map runTest [
([("a", "b")], "a", ["b"])
, ([("a", "b")], "b", [])
, ([("a", "b"), ("b", "c")], "b", ["c"])
, ([("a", "c"), ("a", "b")], "a", ["c", "b"])
]
where
runTest (cg, function, expected) = do
let result = get_callees (enrich cg) (enrich function)
expected @=? (map fst result)
test_get_callers :: Test -- {{{1
test_get_callers = enumTestGroup "get_callers" $ map runTest [
([("a", "b")], "b", ["a"])
, ([("a", "b")], "a", [])
, ([("a", "b"), ("b", "c")], "b", ["a"])
, ([("a", "b"), ("c", "b")], "b", ["a", "c"])
]
where
runTest (cg, function, expected) = do
let result = get_callers (enrich cg) (enrich function)
expected @=? (map fst result)
| copton/ocram | ocram/src/Ocram/Analysis/CallGraph/Test.hs | gpl-2.0 | 4,848 | 0 | 14 | 1,160 | 1,309 | 814 | 495 | 70 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.Utils.ServerConnection
-- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GPL
--
-- Maintainer : maintainer@leksah.org
-- Stability : provisional
-- Portability :
--
-- | Server functionality
--
-----------------------------------------------------------------------------
module IDE.Utils.ServerConnection (
doServerCommand,
) where
import IDE.Core.State
import Network (connectTo,PortID(..))
import Network.Socket (PortNumber(..))
import IDE.Utils.Tool (runProcess)
import GHC.Conc(threadDelay)
import System.IO
import Control.Exception (SomeException(..), catch)
import Prelude hiding(catch)
import Control.Concurrent(forkIO, newEmptyMVar, putMVar, takeMVar, tryTakeMVar)
import Graphics.UI.Gtk(postGUIAsync)
import Control.Event(triggerEvent)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Reader (ask)
import System.Log.Logger (getLevel, getRootLogger, debugM)
import Control.Monad (void, forever)
import qualified Data.Text as T (pack, unpack)
import Data.Monoid ((<>))
doServerCommand :: ServerCommand -> (ServerAnswer -> IDEM ()) -> IDEAction
doServerCommand command cont = do
q' <- readIDE serverQueue
q <- case q' of
Just q -> return q
Nothing -> do
q <- liftIO $ newEmptyMVar
modifyIDE_ (\ ide -> ide{serverQueue = Just q})
ideR <- ask
liftIO . forkIO . forever $ do
debugM "leksah" $ "Ready for command"
(command, cont) <- takeMVar q
reflectIDE (doServerCommand' command cont) ideR
return q
liftIO $ do
tryTakeMVar q
debugM "leksah" $ "Queue new command " ++ show command
putMVar q (command, cont)
doServerCommand' :: ServerCommand -> (ServerAnswer -> IDEM ()) -> IDEAction
doServerCommand' command cont = do
server' <- readIDE server
case server' of
Just handle -> do
isOpen <- liftIO $ hIsOpen handle
if isOpen
then void (doCommand handle)
else do
modifyIDE_ (\ ide -> ide{server = Nothing})
doServerCommand command cont
Nothing -> do
prefs' <- readIDE prefs
handle <- reifyIDE $ \ideR ->
catch (connectTo (T.unpack $ serverIP prefs') (PortNumber(PortNum (fromIntegral $ serverPort prefs'))))
(\(exc :: SomeException) -> do
catch (startServer (serverPort prefs'))
(\(exc :: SomeException) -> throwIDE ("Can't start leksah-server" <> T.pack (show exc)))
mbHandle <- waitForServer prefs' 100
case mbHandle of
Just handle -> return handle
Nothing -> throwIDE "Can't connect to leksah-server")
modifyIDE_ (\ ide -> ide{server = Just handle})
doCommand handle
return ()
where
doCommand handle = do
postAsyncIDE . void $ triggerEventIDE (StatusbarChanged [CompartmentCollect True])
resp <- liftIO $ do
debugM "leksah" $ "Sending server command " ++ show command
hPrint handle command
hFlush handle
debugM "leksah" $ "Waiting on server command " ++ show command
hGetLine handle
liftIO . debugM "leksah" $ "Server result " ++ resp
postAsyncIDE $ do
triggerEventIDE (StatusbarChanged [CompartmentCollect False])
cont (read resp)
startServer :: Int -> IO ()
startServer port = do
logger <- getRootLogger
let verbosity = case getLevel logger of
Just level -> ["--verbosity=" ++ show level]
Nothing -> []
runProcess "leksah-server"
(["--server=" ++ show port, "+RTS", "-N2", "-RTS"] ++ verbosity)
Nothing Nothing Nothing Nothing Nothing
return ()
-- | s is in tenth's of seconds
waitForServer :: Prefs -> Int -> IO (Maybe Handle)
waitForServer _ 0 = return Nothing
waitForServer prefs s = do
threadDelay 100000 -- 0.1 second
catch (do
handle <- liftIO $ connectTo (T.unpack $ serverIP prefs) (PortNumber(PortNum (fromIntegral $ serverPort prefs)))
return (Just handle))
(\(exc :: SomeException) -> waitForServer prefs (s-1))
| 573/leksah | src/IDE/Utils/ServerConnection.hs | gpl-2.0 | 4,603 | 0 | 28 | 1,358 | 1,254 | 638 | 616 | 94 | 4 |
{-
A lewd IRC bot that does useless things.
Copyright (C) 2012 Shou
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE DoAndIfThenElse
, BangPatterns
#-}
{-# OPTIONS_HADDOCK prune #-}
module KawaiiBot.Bot where
import KawaiiBot.Types
import KawaiiBot.Utils
import Control.Applicative
import Control.Exception
import Control.Monad hiding (join)
import qualified Control.Monad as M
import Control.Monad.Reader hiding (join)
import qualified Data.Attoparsec.Text.Lazy as ATL
import Data.Char
import Data.List
import Data.Foldable (foldr')
import Data.Maybe
import Data.Ord
import Data.String.Utils
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.IO as TL
import Data.Time.Clock.POSIX
import Data.Tuple
import Debug.Trace
import Network.HTTP.Conduit
import Network.HTTP.Conduit.Browser
import System.Directory
import System.IO
import System.Process (readProcessWithExitCode)
import System.Random (randomRIO)
import Text.Regex
import Text.JSON
import Text.XML.Light
-- | Parse a string into Funa data then interpret it, returning the output
-- string. Example:
--
-- @
-- parser \".> I like bananas. -> .sed s\/banana\/apple\/\"
-- @
parser :: String
-> Memory (Message String)
parser x = interpret . toFuna $ split " " x
-- | Words to Funa data
toFuna :: [String] -> Funa
toFuna xs =
let (head', tail') = breakLate isFuna xs
len = length head'
in case () of
_ | len < 1 -> Void
| len == 1 -> Plain $ head head'
| len > 1 ->
let op = last head'
in if isFuna op
then (readFuna op) (unwords $ init head') $ toFuna tail'
else Plain $ unwords head'
where isFuna = (`elem` [">>", "++", "->", "$$"])
readFuna "++" = Add
readFuna "->" = Pipe
readFuna ">>" = Bind
readFuna "$$" = App
-- | Parse the Funa data and use `run' where necessary.
interpret :: Funa -> Memory (Message String)
interpret Void = return EmptyMsg
interpret (Plain s) = prefixesC . getConfig <$> ask >>= run s
interpret (Add s f) = allowThen allowAdd $ do
rs <- prefixesC . getConfig <$> ask >>= run s
ex <- interpret f
return $ rs `mergeMsg` ex
interpret (Bind s f) = allowThen allowBind $ interpret f
interpret (Pipe s f) = allowThen allowPipe $ do
prefixesC . getConfig <$> ask >>= run s >>= interpret . deepPipe f
interpret (App s f) = allowThen allowApp $ do
ex <- fmap fromMsg $ interpret f
prefixesC . getConfig <$> ask >>= run (s ++ ex)
-- | Run an IRC bot function and return the string.
--
-- @
-- run \".> I like bananas.\"
-- @
run :: String -> [Char] -> Memory (Message String)
run x px =
let (fcmd, fstring) = span (/= ' ') x
(cmd : args) = split ":" fcmd <|> ["", ""]
string = dropWhile (== ' ') fstring
in case () of
_ | cmd `isCmd` ">" -> -- Public message
allowThen allowEcho $
echo ChannelMsg args string
| cmd `isCmd` "<" -> -- Private message
allowThen allowEcho $
echo UserMsg args string
| cmd `isCmd` "^" -> -- Last message / message history
allowThen allowHistory $
findMsg args string
| cmd `isCmd` "$" -> -- Variable storing / fetching
allowThen allowVariable $
variable2 args string
| cmd `isCmd` "help" -> -- Help function
help args string
| cmd `isCmd` "ai" -> -- Current anime airtimes
allowThen allowAiring $
airing args string
| cmd `isCmd` "an" -> -- Recent anime releases
allowThen allowAnime $
anime args string
| cmd `isCmd` "isup" -> -- Website status
allowThen allowIsup $
isup args string
| cmd `isCmd` "lewd" -> -- Lewd message
allowThen allowLewd $
lewd args string
| cmd `isCmd` "sage" -> -- Sage a user
allowThen allowSage $
sage args string
| cmd `isCmd` "ma" -> -- Recent manga releases
allowThen allowManga $
manga args string
| cmd `isCmd` "ra" -> -- Random / choice
allowThen allowRandom $
random args string
| cmd `isCmd` "sed" -> -- Regular expression replace
allowThen allowSed $
sed args string
| cmd `isCmd` "tr" -> -- Translate
allowThen allowTranslate $
translate args string
| cmd `isCmd` "us" -> -- Userlist
allowThen allowUserlist $
userlist args string
| cmd `isCmd` "yuri" -> -- Yuri battle
allowThen allowYuri $
yuri args string
| cmd `isCmd` "we" -> -- Weather
allowThen allowWeather $
weather args string
| cmd `isCmd` "wiki" -> -- Wikipedia
allowThen allowWiki $
wiki args string
| cmd `isCmd` "e" -> -- Mueval
allowThen allowMueval $
heval args string
| cmd `isCmd` "slap" -> -- Slap
slap args string
| x `isCTCP` "VERSION" -> -- CTCP VERSION message
return . UserMsg $ "VERSION " ++ botversion
| otherwise -> return EmptyMsg
where isCmd (x:xs) cmd = and [x `elem` px, xs == cmd]
isCmd _ _ = False
isCTCP ('\SOH':xs) y = y `isPrefixOf` xs
isCTCP _ _ = False
-- | Append a string to a Funa's string.
deepPipe :: Funa -> Message String -> Funa
deepPipe Void _ = Void
deepPipe (Plain s) m = Plain $ unwords [s, fromMsg m]
deepPipe (Add s f) m = Add (unwords [s, fromMsg m]) f
deepPipe (Bind s f) m = Bind (unwords [s, fromMsg m]) f
deepPipe (Pipe s f) m = Pipe (unwords [s, fromMsg m]) f
deepPipe (App s f) m = App (unwords [s, fromMsg m]) f
echo :: (String -> Message String)
-> [String]
-> String
-> Memory (Message String)
echo f _ s = return (f s)
-- | Channel and user message functions.
channelMsg, userMsg :: [String] -> String -> Memory (Message String)
channelMsg = echo ChannelMsg
userMsg = echo UserMsg
-- | Regex replace function.
--
-- > .sed s\/banana\/apple\/
--
sed :: [String] -> String -> Memory (Message String)
sed _ ('s':x:xs) = do
let f :: (Bool, (Int, ((String, String), String)))
-> Char
-> (Bool, (Int, ((String, String), String)))
f (True, (n, ((a, b), c))) x'
| n == 1 && x' == x = (False, (n, ((a ++ [x'], b), c)))
| n == 1 = (False, (n, ((a ++ ['\\', x'], b), c)))
| n == 2 && x' == x = (False, (n, ((a, b ++ [x']), c)))
| n == 2 = (False, (n, ((a, b ++ ['\\', x']), c)))
| otherwise = (False, (n, ((a, b), c ++ ['\\', x'])))
f (False, (n, ((a, b), c))) x'
| n == 1 && x' == x = (False, (2, ((a, b), c)))
| n == 1 && x' == '\\' = (True, (n, ((a, b), c)))
| n == 1 = (False, (n, ((a ++ [x'], b), c)))
| n == 2 && x' == x = (False, (3, ((a, b), c)))
| n == 2 && x == '\\' = (True, (n, ((a, b), c)))
| n == 2 = (False, (n, ((a, b ++ [x']), c)))
| otherwise = (False, (n, ((a, b), c ++ [x'])))
(_, (_, ((match, replacement), string))) = foldl f (False, (1, (("", ""), ""))) xs
(ins, _:string') = break (== ' ') string
insensitive = ins /= "i"
regex = mkRegexWithOpts match False insensitive
liftIO $ print insensitive
e <- liftIO $ try (return $! subRegex regex string' replacement) :: Memory (Either SomeException String)
case e of
Right a -> return $ ChannelMsg a
Left e -> return EmptyMsg
sed _ _ = return EmptyMsg
-- No more folding ``please!''
sed3 :: String -> Memory (Message String)
sed3 _ = return EmptyMsg
heval :: [String] -> String -> Memory (Message String)
heval args str = do
debug <- asks (verbosityC . getConfig)
-- Time: 2; Inferred type; Execute: `str'.
let cargs = ["-t", "5", "-i", "-e", str]
(ex, o, e) <- liftIO $ readProcessWithExitCode "mueval" cargs ""
case lines o of
[horig, htype, hout] -> do
if any (`elem` args) ["t", "type", "T"]
then return $ ChannelMsg $ cut $ unwords [ horig, "::", htype ]
else return $ ChannelMsg $ cut $ hout
xs -> do
when (debug > 0) . liftIO . putStrLn $ "heval: " ++ show (lines o)
return $ ChannelMsg $ cut $ intercalate "; " xs
where cut = cutoff 400
-- | Low level anime releases function, instead returning a list of strings.
anime' :: [String] -> String -> Memory [String]
anime' args str = do
let (str', filters) = foldr' sepFilter ("", []) $ words str
burl = "http://www.nyaa.eu/?page=search&cats=1_37&filter=2&term="
html <- liftIO $ httpGetString (burl ++ urlEncode' str')
let elem' = fromMaybeElement $ parseXMLDoc html
qname = QName "td" Nothing Nothing
attrs = [Attr (QName "class" Nothing Nothing) "tlistname"]
elems = findElementsAttrs qname attrs elem'
animes = map (strip . elemsText) elems
animes' = filter (\x -> not . or $ map (`isInfixOf` x) filters) animes
amount = if length args > 1 then (args !! 1) `safeRead` 10 else 10
verbosity <- asks (verbosityC . getConfig)
liftIO . when (verbosity > 1) $ do
putStrLn $ "Filters: %(f); str': %(s)" % [("f", join ", " filters), ("s", str')]
return $ take amount animes'
-- | Anime releases function.
anime :: [String] -> String -> Memory (Message String)
anime args str = do
animes <- anime' args str
let animes' = map (replace "[" "[\ETX12" . replace "]" "\ETX]") animes
return . ChannelMsg $ joinUntil 400 ", " animes'
-- | Low level airing anime function, instead returning a list of Strings.
airing2 :: [String] -> String -> Memory [String]
airing2 args str = do
let (str', filters) = foldr' sepFilter ("", []) $ words str
amount = if length args > 1 then (args !! 1) `safeRead` 10 else 10 :: Int
url = "http://www.mahou.org/Showtime/?o=ET"
isSearch = not $ null str
content <- liftIO $ httpGetString url
let elem = fromMaybeElement $ parseXMLDoc content
qTable = QName "table" Nothing Nothing
aSummary = [Attr (QName "summary" Nothing Nothing) "Currently Airing"]
table = findElementsAttrs qTable aSummary elem
table2 = M.join $ fmap (findElementsIn qTable) table
qTr = QName "tr" Nothing Nothing
trs :: [Element]
trs = drop 1 . M.join $ fmap (findElements qTr) table2
tds :: [[String]]
tds = fmap (fmap elemsText . contentsToEls . elContent) trs
f (_ : series : season : station : company : time : eta : xs) acc =
let seri = "\ETX12" ++ series ++ "\ETX"
tim' = "\ETX08" ++ time ++ "\ETX"
eta' = "(" ++ istrip eta ++ ")"
nonSearch = unwords [seri, tim', eta']
proSearch = unwords [ "\ETX12Series\ETX:", series
, "\ETX12Season\ETX:", season
, "\ETX12Time\ETX:", time
, "\ETX12ETA\ETX:", istrip eta
, "\ETX12Station\ETX:", station
, "\ETX12Company\ETX:", company
]
in if isSearch then
let search = map (`isInfixOf` map toLower series)
in if or $ search filters then acc
else if and . search . words $ map toLower str'
then proSearch : acc
else acc
else nonSearch : acc
backup = guard isSearch >> ["No results."]
return . take amount $ foldr f [] tds <?> backup
-- | Airing anime function.
airing :: [String] -> String -> Memory (Message String)
airing args str = do
airs <- airing2 args str
if null airs
then return EmptyMsg
else return . ChannelMsg $ joinUntil 400 ", " airs
-- TODO: Make this more advanced by printing whether the function is allowed
-- in this channel or not.
-- | Print information about the IRC commands the bot provides.
help :: [String] -> String -> Memory (Message String)
help _ str = do
return . UserMsg $ getHelp str
where getHelp s
| s == "bind" = "Bind, or >>. It executes the function on the left but ignores the output, and continues parsing the right."
| s == "pipe" = "Pipe, or ->. It appends the output of the function on the left into the function on the right."
| s == "add" = "Add, or ++. It appends the string of the output on the right to the output on the left."
| s == "app" = "Application operator, or $$. It appends the output of the function on the right into the function on the left. The opposite of ->."
| s == ">" = "Prints a string to the channel. Ex: .> hey"
| s == "<" = "Prints a string to the user. Ex: .< hey"
| s == "^" = "Gets a message from the channel history. Ex: .^ 3"
| s == "$" = "Gets a stored variable. Ex: .$:immutable myVariableName My variable message."
| s == "ai" = "Prints airtimes for this season's anime. Ex: .ai:1 yuru yuri"
| s == "an" = "Prints recent anime releases, can also be used to search. Ex: .an:3 Last Exile -Commie"
| s == "lewd" = "Prints a lewd message."
| s == "ma" = "Prints recent manga releases, can also be used to search. Ex: .ma:5 Banana no Nana"
| s == "ra" = "Prints a number from a range or a string choice split by `|'. Ex: .ra 1000; Ex: .ra Yes | No"
| s == "sed" = "Replaces text using regular expressions. Ex: .sed /probably should/should not/ You probably should help it."
| s == "tr" = "Translate a string. Ex: .tr:ja:en 日本語"
| s == "we" = "Prints the weather for a specified location. Ex: .we Tokyo"
| s == "wiki" = "Prints the introduction to an article. Ex: .wiki haskell programming language."
| otherwise = "Try `.help' and a value. Functions: >, <, ^, $, sed, ai, an, ma, ra, tr, we. Operators: bind, pipe, add, app. More: http://github.com/Shou-/KawaiiBot-hs#readme"
-- | Find the nth matching message from the channel chatlog. Where n is the
-- first colon argument, and a number.
--
-- If there is no searching string, match against everything, returning the
-- nth message from the whole chatlog.
findMsg :: [String] -> String -> Memory (Message String)
findMsg args str = do
msgs <- logMsgs
let (strs, filters) = foldr' sepFilterText ([], []) . T.words $ T.pack str
searchF x = all (`T.isInfixOf` trd3 x) strs
filterF x = not $ any (`T.isInfixOf` trd3 x) filters
searchh :: [(T.Text, T.Text, T.Text)]
searchh = do
msg <- msgs
guard $ if not $ null strs then searchF msg else True
guard $ if not $ null filters then filterF msg else True
return msg
msg :: Message String
msg = do
let arg = fromJust $ listToMaybe args <|> Just "0"
n = safeRead arg 0
if length searchh > n
then return . T.unpack . trd3 $ searchh !! n
else EmptyMsg
return msg
leRandom :: [String] -> String -> Memory (Message String)
leRandom _ _ = do
msgs <- logMsgs
a <- liftIO $ randomRIO (0, length msgs - 1)
let m1 = T.words . trd3 $ msgs !! a
b <- liftIO $ randomRIO (0, length m1 - 4)
let w1 = T.unpack $ T.unwords $ take 3 $ drop b m1
c <- liftIO $ randomRIO (0, 5)
if c /= (0 :: Int)
then do
w2 <- fromMsg <$> leRandom [] []
return . ChannelMsg $ unwords [w1, w2]
else return $ ChannelMsg w1
logMsgs :: Memory [(T.Text, T.Text, T.Text)]
logMsgs = do
meta <- asks getMeta
logsPath <- asks (logsPathC . getConfig)
let path = logsPath ++ getServer meta ++ " " ++ getDestino meta
cs <- liftIO $ TL.readFile path
let msgs :: [(T.Text, T.Text, T.Text)]
msgs = do
line <- reverse $ TL.lines cs
let mresult = ATL.maybeResult . (flip ATL.parse) line $ do
time <- ATL.takeWhile1 (/= '\t')
ATL.char '\t'
nick <- ATL.takeWhile1 (/= '\t')
ATL.char '\t'
msg <- ATL.takeWhile1 (/= '\n')
return (time, nick, msg)
guard $ isJust mresult
return $ fromJust mresult
return msgs
-- | Print userlist
userlist :: [String] -> String -> Memory (Message String)
userlist _ _ = asks $ ChannelMsg . unwords . getUserlist . getMeta
slap :: [String] -> String -> Memory (Message String)
slap _ str = do
meta <- asks $ getMeta
slapPath <- asks (slapPathC . getConfig)
slaps <- liftIO . fmap lines $ readFile slapPath
let nonSlaps = do
(x, xs) <- parseConf slaps
guard . not $ x `insEq` "slaps"
guard $ length xs > 0
return (x, xs)
us = getUserlist meta
nick = getUsernick meta
nick2 = if str `insElem` us
then fromJust $ listToMaybe $ filter (insEq str) us
else str
obj <- fmap ([("nick1", nick), ("nick2", nick2)] ++) $ forM nonSlaps $ \(x, xs) -> do
n <- liftIO $ randomRIO (0, length xs - 1)
return $ (x, xs !! n)
let slaps' = fromJust $ lookup "slaps" (parseConf slaps) <|> Just []
ln <- liftIO $ randomRIO (0, length slaps' - 1)
case () of
_ | null slaps' -> return EmptyMsg
| otherwise -> return . ChannelMsg $ (slaps' !! ln) % obj
-- | Output lewd strings.
lewd :: [String] -> String -> Memory (Message String)
lewd args str = do
meta <- asks getMeta
lewdPath <- asks (lewdPathC . getConfig)
lewds <- liftIO . fmap lines $ readFile lewdPath
let nonLewds = do
(x, xs) <- parseConf lewds
guard . not $ x `insEq` "lewds"
guard $ length xs > 0
return (x, xs)
n = safeRead str 1
mnick = listToMaybe $ filter (not . null) args
nick = fromJust $ mnick <?> Just (getUsernick meta)
obj <- fmap (("nick", nick) :) $ forM nonLewds $ \(x, xs) -> do
n <- liftIO $ randomRIO (0, length xs - 1)
return $ (x, xs !! n)
let lewds' = fromJust $ lookup "lewds" (parseConf lewds) <|> Just []
ln <- liftIO $ randomRIO (0, length lewds' - 1)
case () of
_ | null lewds' -> return EmptyMsg
| n > 1 -> do
nlewd <- fmap fromMsg $ lewd args (show $ n - 1)
return . UserMsg $ unwords [((lewds' !! ln) % obj), nlewd]
| otherwise -> return . UserMsg $ (lewds' !! ln) % obj
-- Credit for this goes to whoever on Rizon created it.
-- | Sage a user.
sage :: [String] -> String -> Memory (Message String)
sage args str = do
meta <- asks getMeta
let server = getServer meta
snick = getUsernick meta
shost = getHostname meta
sagepath <- asks (sagePathC . getConfig)
msagerss <- fmap (map maybeRead . lines) . liftIO $ readFile $ sagepath ++ "rs"
let cstr = strip str
sagerss :: [Sages]
sagerss = map fromJust $ filter (/= Nothing) msagerss
f :: Sages -> Bool
f (Sages s _) = s `insEq` server
msagers :: Maybe Sages
nsagerss :: [Sages]
(msagers, nsagerss) = getWithList f sagerss
sagers :: Sages
sagers = fromJust $ msagers <?> Just (Sages server [])
msager :: Maybe (String, String, Int, Double)
nsagers :: [(String, String, Int, Double)]
(msager, nsagers) = getWithList (insEq cstr . fst4) $ getSagers sagers
g x = snd4 x == shost || fst4 x `insEq` snick
(smsager, snsagers) = getWithList g $ nsagers
userlist :: [String]
userlist = getUserlist meta
mnick :: Maybe String
mnick = fst $ getWithList (insEq cstr) userlist
jnick = fromJust $ mnick <?> Just []
(nick', host, ns, to) = fromJust $ msager <?> Just (jnick, "", 0, 0.0)
(snick', shost', sns, sto) = fromJust $ smsager <?> Just (snick, "", 0, 0.0)
time <- fmap realToFrac . liftIO $ getPOSIXTime
let ntime = time + 30
case mnick of
_ | snick `insEq` cstr || host == shost ->
return $ UserMsg "You can't sage yourself."
| sto > time -> return $ UserMsg "You can't sage too frequently."
Just nick -> do
let ns' = ns + 1
sager' = (nick', host, ns', to)
ssager' = if null shost'
then (snick', shost, sns, ntime)
else (snick', shost', sns, ntime)
sagers' = sager' : ssager' : snsagers
sagerss' = Sages server sagers' : nsagerss
isDoubles x = elem x $ takeWhile (<= x) $ do
x <- [0, 100 .. ]
y <- [11, 22 .. 99]
return $ x + y
count = case ns' of
_ | isDoubles ns' -> unwords [ show ns' ++ " times."
, "Check the doubles on this cunt."
]
| ns' >= 144 -> unwords [ show ns' ++ " times."
, "Request gline immediately."
]
| ns' >= 72 -> unwords [ show ns' ++ " times."
, "Fuck this guy."
]
| ns' >= 36 -> unwords [ show ns' ++ " times."
, "Someone ban this guy."
]
| ns' >= 18 -> unwords [ show ns' ++ " times."
, "What a faggot..."
]
| ns' >= 9 -> unwords [ show ns' ++ " times."
, "Kick this guy already."
]
| ns' >= 3 -> unwords [ show ns' ++ " times."
, "This guy is getting on my nerves..."
]
| ns' > 1 -> show ns' ++ " times. What a bro."
| ns' > 0 -> show ns' ++ " time. What a bro."
liftIO $ safeWriteFile (sagepath ++ "rs") $ unlines $ map show sagerss'
return $ ChannelMsg $ unwords [ nick'
, "has been \US\ETX12SAGED\ETX\US"
, count ]
Nothing -> do
return $ UserMsg $ cstr ++ " is not in the channel."
-- | Recent manga releases and searching function.
manga :: [String] -> String -> Memory (Message String)
manga cargs str = do
let burl = "https://www.mangaupdates.com/releases.html?act=archive&search="
html <- liftIO $ httpGetString (burl ++ urlEncode' str)
let elem' = fromMaybeElement $ parseXMLDoc html
qname = QName "td" Nothing Nothing
attrs = [Attr (QName "class" Nothing Nothing) "text pad"]
elems = findElementsAttrs qname attrs elem'
elems' = map elemsText elems
-- Generate a list of colored strings
genMangas :: [String] -> [String]
genMangas (date:mangatitle:vol:chp:group:rest) =
let mangaStr = unwords [ "\ETX12[" ++ strip group ++ "]\ETX"
, mangatitle
, "[Ch.\ETX08" ++ chp ++ "\ETX,"
, "Vol.\ETX08" ++ vol ++ "\ETX]"
, "(\ETX08" ++ date ++ "\ETX)"
]
in mangaStr : genMangas rest
genMangas _ = []
maybeAmount =
if length cargs > 1
then fmap fst . listToMaybe . reads $ cargs !! 1
else Just 10
amount = fromMaybe 10 maybeAmount
mangas = take amount $ genMangas elems'
return . ChannelMsg $ joinUntil 400 ", " mangas
-- | Pick a random choice or number.
random :: [String] -> String -> Memory (Message String)
random args str
| isDigits str = do
n <- liftIO (randomRIO (0, read str :: Integer))
return . ChannelMsg $ show n
| otherwise = do
let choices = split "|" str
len = length choices
n <- liftIO (randomRIO (0, len - 1))
if len > 0
then return . ChannelMsg $ choices !! n
else return EmptyMsg
-- | Website title function.
title :: String -> Memory (Message String)
title str = do
(contentResp, headers, _, _) <- liftIO $ httpGetResponse str
let contentTypeResp = headers `tupleListGet` "Content-Type"
if "text/html" `isInfixOf` strip contentTypeResp then do
let maybeElems = parseXMLDoc contentResp
elems = if isNothing maybeElems
then Element (QName "" Nothing Nothing) [] [] Nothing
else fromJust maybeElems
getTitle :: [Element]
getTitle = filterElements ((== "title") . qName . elName) elems
special = let f = fromJust $ specialElem <|> Just (\_ -> [])
in (cutoff 200) . (++ " ") . elemsText . head' $ f elems
pagetitle = ((special ++ " ") ++) . unwords . map elemsText $ getTitle
return . ChannelMsg . istrip . replace "\n" " " $ pagetitle
else do
return EmptyMsg
where specialElem :: Maybe (Element -> [Element])
specialElem
| '#' `elem` str =
let elemID = tail $ dropWhile (/= '#') str
attrs = [Attr (QName "id" Nothing Nothing) elemID]
f x = findElementsAttrs (QName "" Nothing Nothing) attrs x
in Just f
| let surl = split "/" str
in surl !! 2 == "boards.4chan.org" && surl !! 4 == "res" =
Just $ findElements (QName "blockquote" Nothing Nothing)
| otherwise = Nothing
head' :: [Element] -> Element
head' (x:_) = x
head' _ = Element (QName "" Nothing Nothing) [] [] Nothing
-- | Check if website is up.
isup :: [String] -> String -> Memory (Message String)
isup _ str = do
let url = "http://isup.me/" ++ removePrefixes ["https://", "http://"] str
title' <- fmap fromMsg $ title url
return . ChannelMsg . replace "Huh" "Nyaa" . unwords . take 4 . words $ title'
-- U FRUSTRATED U FRUSTRATED GOOGLE Y U SO MAAAAAAAAAAAAAAAAAAD
-- | Translate text to another language.
-- This does not work.
translate :: [String] -> String -> Memory (Message String)
translate args str = do
msAppId <- asks (msAppIdC . getConfig)
verbosity <- asks (verbosityC . getConfig)
case msAppId of
"" -> return EmptyMsg
_ -> do
let from = show $ if length args > 1 then args !! 1 else ""
to = show $ if length args > 2 then args !! 2 else "en"
str' = show [urlEncode' str]
url = concat [ "http://api.microsofttranslator.com/",
"v2/ajax.svc/TranslateArray",
"?appId=" ++ show msAppId,
"&texts=" ++ str',
"&from=" ++ from,
"&to=" ++ to ]
jsonStr <- liftIO $ ((\_ -> return "") :: SomeException -> IO String) `handle` httpGetString url
liftIO . when (verbosity > 1) $ putStrLn url >> putStrLn jsonStr
let jsonStr' = dropWhile (/= '[') jsonStr
result = decode jsonStr' :: Result [JSObject JSValue]
result' = fmap (lookup "TranslatedText" . fromJSObject . (!! 0)) result
text = fromMaybeString $ fmap fromJSString (getOut result')
return $ ChannelMsg text
where getOut (Ok (Just (JSString a))) = Just a
getOut _ = Nothing
-- TODO: Global variables
-- | Variable storing function.
variable2 :: [String] -> String -> Memory (Message String)
variable2 args str = do
varPath <- asks (variablePathC . getConfig)
nick <- asks (getUsernick . getMeta)
dest <- asks (getDestino . getMeta)
server <- asks (getServer . getMeta)
let nick' = (!! 0) $ args <|> [nick]
var :: Maybe (String, String, String)
var = do
let (varbegin, varcontent) = bisect (== '=') str
(vartype, varname) =
let temp = bisect (== ' ') varbegin
in take 20 . head . words <$> if null $ snd temp
then swap temp
else temp
guard . not $ null varname || null varcontent
return (vartype, varname, varcontent)
case var of
Nothing -> do -- read var
liftIO $ putStrLn "Reading vars..."
svars <- liftIO $ lines <$> readFile varPath
let (isGlobal, varname) =
let temp = bisect (== ' ') str
temp2 = if null $ snd temp then swap temp else temp
in (fst temp2 == "Global", snd temp2)
mvar :: Maybe String
mvar = listToMaybe $ do
v <- svars
let mvars = maybeRead v
guard $ isJust mvars
let var = fromJust mvars
guard $ readableVar server dest nick' varname var
guard $ if isGlobal then isGlobalVar var else True
return $ varContents var
case mvar of
Just x -> do
x' <- parser x
return $ if x' == EmptyMsg
then ChannelMsg x
else x'
Nothing -> do
return $ EmptyMsg
Just (vartype, varname, varcontent) -> do -- write var
liftIO $ putStrLn "Writing var..."
h <- liftIO $ openFile varPath ReadMode
svars <- liftIO $ lines <$> hGetContents h
let uvar = stringToVar vartype server dest nick' varname varcontent
isGlobal = fromJust $ (return . (== "Global") . head $ words str)
<|> Just False
isRemove = fromJust $ (return . (== "Remove") . head $ words str)
<|> Just False
mvar :: [String]
!mvar = do
v <- svars
let mvars = maybeRead v
guard $ isJust mvars
let var = fromJust mvars
guard . not $ writableVar server dest nick' varname var
return $ show var
vars = if isRemove then mvar else show uvar : mvar
liftIO $ do
hClose h
writeFile varPath $ unlines vars
return EmptyMsg
variable3 :: [String] -> String -> Memory (Message String)
variable3 args str = return EmptyMsg
-- | Battle yuri function.
yuri :: [String] -> String -> Memory (Message String)
yuri args str = do
debug <- asks (verbosityC . getConfig)
meta <- asks getMeta
let serverurl = getServer meta
dest = getDestino meta
userlist = getUserlist meta
cstr = strip str
margs = listToMaybe args
yuripath <- asks $ yuriPathC . getConfig
mphrases <- fmap maybeRead . liftIO . readFile $ yuripath ++ " actions"
myuriss <- fmap (map maybeRead . lines) . liftIO . readFile $ yuripath ++ " yuris"
let nick1 = getUsernick meta
host1 = getHostname meta
fighters = map strip $ split "<|>" str
yuriphrases :: [YuriAction]
yuriphrases = fromJust $ mphrases <?> Just []
yuriss :: [Yuris]
yuriss = map fromJust $ filter (/= Nothing) myuriss
myuris :: Maybe Yuris
nyuriss :: [Yuris]
(myuris, nyuriss) = getWithList (isYuris serverurl dest) yuriss
yuris :: Yuris
yuris = fromJust $ myuris <?> Just (Yuris serverurl dest [])
owners :: [YuriOwner]
owners = yuriOwners yuris
mowner :: Maybe YuriOwner
nowners :: [YuriOwner]
(mowner, nowners) = getWithList (isOwner nick1) $ owners
owner :: YuriOwner
owner = fromJust $ mowner <?> Just (YuriOwner nick1 host1 0 [])
globalExists x =
any (any (insEq x . yuriName) . ownerYuris) $ yuriOwners yuris
ownerExists x =
any ((insEq x) . yuriName) $ ownerYuris owner
time <- liftIO $ fmap realToFrac getPOSIXTime
let ntime = time + 9 * 60
remtime = ceiling (ownerTime owner - time)
(mintime, sectime) = remtime `divMod` 60
timestr = case () of
_ | mintime == 0 -> show sectime ++ " second(s)."
| sectime == 0 -> show mintime ++ " minute(s)."
| otherwise -> unwords [ show mintime
, "minute(s) and"
, show sectime
, "second(s)." ]
timeoutMsg = UserMsg $ unwords [ "Please wait"
, timestr ]
case margs of
_ | any (== Nothing) myuriss -> do
when (debug > 0) . liftIO $ do
print $ length $ filter (== Nothing) myuriss
return $ ChannelMsg $ "An error occurred (%s actions)" % yuripath
| "fight" `maybeInsEq` margs -> case () of
_ | time < ownerTime owner -> return timeoutMsg
| length fighters < 2 -> do
return $ UserMsg $ unwords [
"Incorrect syntax."
, ".yuri:fight [yuri name] <|> [opponent yuri]"
]
| not . all (globalExists . strip) $ fighters -> do
let yuri1 = strip $ fighters !! 0
yuri2 = strip $ fighters !! 1
case () of
_ | not $ globalExists yuri1 ->
return $ UserMsg $ yuri1 ++ " doesn't exist."
| not $ globalExists yuri2 ->
return $ UserMsg $ yuri2 ++ " doesn't exist."
| otherwise ->
return $ UserMsg "Everything exploded in your face."
| length yuriphrases - 1 < 0 -> do
when (debug > 0) . liftIO $ do
putStrLn $ unwords [ "There is most likely an error with"
, "your `" ++ yuripath ++ " actions' file."
]
return $ ChannelMsg "An error occurred (fight)."
| otherwise -> do
let yuri1n = strip $ fighters !! 0
yuri2n = strip $ fighters !! 1
oyuris = ownerYuris owner
(moyuri, onyuris) = getWithList (insEq yuri1n . yuriName) oyuris
oyuri = fromJust $ moyuri <?> Just (Yuri [] "" Nothing (0,0,0))
(meowner, enowner) = getWithList (any (insEq yuri2n . yuriName) . ownerYuris) owners
eowner = fromJust $ meowner <?> Just (YuriOwner [] [] 0 [])
enick = ownerName eowner
ehost = ownerHost eowner
etime = ownerTime eowner
eyuris = ownerYuris eowner
(meyuri, enyuris) = getWithList (insEq yuri2n . yuriName) eyuris
eyuri = fromJust $ meyuri <?> Just (Yuri [] "" Nothing (0,0,0))
woystats = yuriStats oyuri `applyWep` yuriWeapon oyuri
weystats = yuriStats eyuri `applyWep` yuriWeapon eyuri
(moe1, lewd1, str1) =
woystats `statsMinus` weystats
(moe2, lewd2, str2) =
weystats `statsMinus` woystats
phrases = filter (not . (`insElem` ["steal", "esteal"]) . actionName) yuriphrases
omoephs =
take moe1 . safeCycle $ filter (insEq "moe" . actionName) phrases
olewdphs =
take lewd1 . safeCycle $ filter (insEq "lewd" . actionName) phrases
ostrphs =
take str1 . safeCycle $ filter (insEq "str" . actionName) phrases
emoephs =
take moe2 . safeCycle $ filter (insEq "emoe" . actionName) phrases
elewdphs =
take lewd2 . safeCycle $ filter (insEq "elewd" . actionName) phrases
estrphs =
take str2 . safeCycle $ filter (insEq "estr" . actionName) phrases
newphs = concat [ omoephs
, olewdphs
, ostrphs
, emoephs
, elewdphs
, estrphs
, phrases
]
ostealphs =
let f | length oyuris < 6 =
(insEq "steal" . actionName)
| otherwise = \_ -> False
amount = (moe1 + lewd1 + str1) `div` 4
in take amount . safeCycle $ filter f yuriphrases
estealphs =
let f | length eyuris < 6 =
(insEq "esteal" . actionName)
| otherwise = \_ -> False
amount = (moe2 + lewd2 + str2) `div` 4
in take amount . safeCycle $ filter f yuriphrases
stealphs =
let f | length oyuris < 6 && length eyuris < 6 =
((`insElem` ["steal", "esteal"]) . actionName)
| length oyuris < 6 =
(insEq "steal" . actionName)
| length eyuris < 6 =
(insEq "esteal" . actionName)
| otherwise = (\_ -> False)
in filter f yuriphrases
finalphs = concat [ostealphs, estealphs, stealphs, newphs]
stats = totalStats oyuri - totalStats eyuri
n <- liftIO $ randomRIO (0, length finalphs - 1)
when (debug > 1) . liftIO $ do
putStrLn $ unlines [ unwords [ "Moe phs:"
, show (length omoephs)
, "+"
, show (length emoephs)
, "/"
, show (length finalphs)
]
, unwords [ "Lewd phs:"
, show (length olewdphs)
, "+"
, show (length elewdphs)
, "/"
, show (length finalphs)
]
, unwords [ "Str phs:"
, show (length ostrphs)
, "+"
, show (length estrphs)
, "/"
, show (length finalphs)
]
, unwords [ "Steal phs:"
, show (length stealphs)
, "+"
, show (length ostealphs)
, "+"
, show (length estealphs)
, "/"
, show (length finalphs)
]
, unwords [ "Yuri1 vs Yuri2:"
, show woystats
, "vs"
, show weystats
]
]
case () of
_ | yuriName oyuri == [] -> do
return $ UserMsg $ unwords [ yuriName oyuri
, "isn't owned by you."
]
-- what the hell is this
| n < 0 || n >= length finalphs -> do
liftIO $ do
putStrLn $ "N: " ++ show n
putStrLn $ "Len phs: " ++ show (length finalphs)
return $ EmptyMsg
--
| stats `notElem` [-10 .. 10] -> do
let status | stats > 10 = "too high"
| stats < (-10) = "too low"
name = yuriName eyuri
return $ UserMsg $ unwords [ yuriName oyuri ++ "'s"
, "stats are %s" % status
, "to fight %s." % name
, "Max 10 stat difference."
]
| otherwise -> do
let mphrase = finalphs !! n
msgs = actionMsgs mphrase
yuri1s = yuriName oyuri
yuri2s = yuriName eyuri
yimg1 = " <" >|< yuriImage oyuri >|< ">"
yimg2 = " <" >|< yuriImage eyuri >|< ">"
lewdnick = if isPrefixOf "E" $ actionName mphrase
then yuri2s
else yuri1s
n' <- liftIO $ randomRIO (0, length msgs - 1)
lewdmsg <- fmap fromMsg $ lewd [lewdnick] ""
let stats1 = actionYuri1 mphrase
stats2 = actionYuri2 mphrase
obj = [ ("yuri1", yuri1s)
, ("yuri2", yuri2s)
, ("nick1", nick1)
, ("nick2", enick)
, ("img1", yimg1)
, ("img2", yimg2)
, ("lewd", lewdmsg)
]
msg = (msgs !! n') % obj
oyuri' = applyStats stats1 oyuri
eyuri' = applyStats stats2 eyuri
oyuris' = case actionName mphrase of
"Steal" -> eyuri' : oyuri' : onyuris
"ESteal" -> onyuris
_ -> oyuri' : onyuris
eyuris' = case actionName mphrase of
"Steal" -> enyuris
"ESteal" -> oyuri' : eyuri' : enyuris
_ -> eyuri' : enyuris
owner' = YuriOwner nick1 host1 ntime oyuris'
eowner' = YuriOwner enick ehost etime eyuris'
nowners' = filter ((/= enick) . ownerName) nowners
owners' = owner' : eowner' : nowners'
yuris' = addOwners yuris owners'
yuriss' = yuris' : nyuriss
case () of
_ | enick `insEq` nick1 -> do
return $ UserMsg "You can't fight your own yuri!"
| otherwise -> do
writeYuriss yuriss'
return $ ChannelMsg msg
| "spawn" `maybeInsEq` margs -> case () of
_ | time < ownerTime owner -> return timeoutMsg
| otherwise -> do
let poorest = sortBy (comparing (length . ownerYuris)) owners
poorest' = let f g x y = (g x, g y)
g x y = uncurry (<=) $ f (length . ownerYuris) x y
in map ownerName $ takeWhileOrd g poorest
userlist' = filter (`elem` userlist) poorest' <?> userlist
n <- liftIO $ randomRIO (0, length userlist' - 1)
let rnick = userlist' !! n
(mo', no') = getWithList (isOwner rnick) owners
(_, no'') = getWithList (isOwner nick1) no'
o' = fromJust $ mo' <?> Just (YuriOwner rnick [] 0 [])
(name' : img : _) = (fighters <?> [cstr, ""]) ++ [""]
yurixs = Yuri name' img Nothing (0, 0, 0) : ownerYuris o'
otime = ownerTime o'
ohost = ownerHost o'
owner' = YuriOwner rnick ohost otime yurixs
myowner = ownerModTime owner ntime
twowners = if rnick == nick1
then [YuriOwner rnick ohost ntime yurixs]
else [owner', myowner]
yuris' = addOwners yuris $ twowners ++ no''
yuriss = yuris' : nyuriss
case () of
_ | globalExists name' ->
return $ UserMsg $ name' ++ " already exists."
| null img -> do
return $ UserMsg $ unwords [ "Image URL required."
, ":spawn yuri name"
, "<|>"
, "image URL"
]
| length name' > 60 -> do
return $ UserMsg "Name is too long. 60 chars is max."
| length img > 37 -> do
return $ UserMsg "Image URL too long. 37 chars is max."
| length yurixs <= 6 -> do
writeYuriss yuriss
return $ ChannelMsg $ unwords [ name'
, "<" ++ img ++ ">"
, "was given to"
, rnick ++ "." ]
| length yurixs >= 6 -> do
return $ UserMsg $ unwords [ rnick
, "has too many yuri."
, "Six is max."
]
| otherwise -> return $ ChannelMsg $ "An error occurred (spawn)."
| "find" `maybeInsEq` margs -> do
let matcher f xs = do
owner' <- xs
let yuris = filter f $ ownerYuris owner'
nick' = ownerName owner'
guard $ not $ null yuris
let mkMatch (Yuri n i w s) = unwords [n, s `showApplyWep` w]
yuris' = intercalate ", " $ map mkMatch yuris
return $ unwords [nick', "has", yuris']
ematches = matcher (insEq cstr . yuriName) owners
pmatches = matcher (insIsInfixOf cstr . yuriName) owners
matches = joinUntil 400 "; " . (ematches ++) $ do
x <- pmatches
guard $ x `notElem` ematches
return x
case matches of
[] -> return $ UserMsg $ "No matches against `" ++ cstr ++ "'."
_ -> return $ ChannelMsg $ matches
| "list" `maybeInsEq` margs -> do
let nick' = if null cstr then nick1 else cstr
mowner' = fst . getWithList ((insEq nick') . ownerName) $ owners
noyuris = if nick' `insEq` nick1
then "You don't have any Yuri!"
else nick' ++ " doesn't have any Yuri!"
case mowner' of
Just owner' -> do
let stats :: Yuri -> String
stats hyu@(Yuri n i w s) = unwords [ n, showWep hyu]
yurisstr = intercalate ", " $ map stats $ ownerYuris owner'
if null yurisstr then do
return $ UserMsg $ noyuris
else return $ ChannelMsg yurisstr
Nothing -> return $ UserMsg $ noyuris
| "drop" `maybeInsEq` margs -> case () of
_ | not $ ownerExists cstr -> do
return $ UserMsg $ cstr ++ " doesn't exist."
| otherwise -> do
let yurixs = filter (not . insEq cstr . yuriName) $ ownerYuris owner
owner' = YuriOwner nick1 host1 ntime yurixs
yuris' = addOwners yuris $ owner' : nowners
yuriss = yuris' : nyuriss
writeYuriss yuriss
return $ ChannelMsg $ unwords [ cstr
, "was dropped by"
, nick1 ++ "." ]
| "rank" `maybeInsEq` margs -> do
let mn = maybeRead . dropWhile (not . isDigit) $ cstr :: Maybe Int
jn = fromJust $ mn <?> Just 0
moder [] = (>= jn)
moder (x:_) | x == '>' = (> jn)
| x == '<' = (< jn)
| x == '=' = (== jn)
| x == '~' = \y -> y > jn - 10 && y < jn + 10
| otherwise = (>= jn)
mf = moder $ take 1 cstr
yurixs = concatMap ownerYuris owners
yurixs' = filter (mf . totalStats) $ case () of
_ | cstr `insElem` ["moe", "fst"] ->
sortBy (comparing (oneStat fst3)) yurixs
| cstr `insElem` ["lewd", "snd", "lewdness"] ->
sortBy (comparing (oneStat snd3)) yurixs
| cstr `insElem` ["str", "trd", "strength"] ->
sortBy (comparing (oneStat trd3)) yurixs
| cstr `insElem` ["min", "weak"] ->
reverse $ sortBy (comparing totalStats) yurixs
| otherwise ->
sortBy (comparing totalStats) yurixs
yren y = unwords [ yuriName y
, yuriStats y `showApplyWep` yuriWeapon y
]
yurixstr =
joinUntil 400 ", " . take 15 . reverse $ map yren yurixs'
return $ ChannelMsg yurixstr
| "wgive" `maybeInsEq` margs -> do
let (name : wep : _) = (fighters <?> [cstr, ""]) ++ [""]
oyuris = ownerYuris owner
(myuri, nyuris) = getWithList (insEq name . yuriName) oyuris
fyuri = listToMaybe $ do
o <- owners
let mm = fst $ getWithList (insEq name . yuriName) $ ownerYuris o
guard $ isJust mm
return $ fromJust mm
yuri = fromJust $ myuri <?> fyuri <?> Just (Yuri "" "" Nothing (0,0,0))
amn <- liftIO $ randomRIO (0, 2)
let (rmoe : rlewd : rstr : _) = case () of
_ | isNothing (yuriWeapon yuri) || not (null wep) ->
take 3 . drop amn $ cycle [0, 0, 1]
| otherwise -> getBonusStat $ yuriWeapon yuri
chance = 2 ^ getWeaponStat (yuriWeapon yuri)
mwn <- liftIO $ randomRIO (1, chance)
let isWin = 0 == [0 .. chance - 1] !! (mwn - 1)
newstats =
let (x, y, z) = getWepStats $ yuriWeapon yuri
in (x + rmoe, y + rlewd, z + rstr)
wep' = wep <?> wepName (yuriWeapon yuri)
weapon = if isWin
then Just (wep', newstats)
else Just (wep', getWepStats $ yuriWeapon yuri)
case () of
_ | time < ownerTime owner -> do
return timeoutMsg
| null $ yuriName yuri -> do
return $ UserMsg $ name ++ " doesn't exist."
| not $ ownerExists name -> do
return $ UserMsg $ "You don't own " ++ name ++ "."
| otherwise -> do
let (Yuri name' img' _ stats') = yuri
yuri' :: Yuri
yuri' = Yuri name' img' weapon stats'
yurixs :: [Yuri]
yurixs = yuri' : nyuris
owner' :: YuriOwner
owner' = YuriOwner nick1 host1 ntime yurixs
owners' :: [YuriOwner]
owners' = owner' : nowners
yuris' :: Yuris
yuris' = addOwners yuris $ owners'
yuriss :: [Yuris]
yuriss = yuris' : nyuriss
sta = if isWin then "succeeded" else "failed"
msg = if null wep
then "Weapon upgrade %s!" % sta
else "%s was given to %s." % [wep', yuriName yuri']
liftIO $ do
putStrLn $ concat ["Chance: 1 / ", show chance]
writeYuriss yuriss
return $ ChannelMsg $ unwords [ "Weapon upgrade %s!" % sta
, yuriName yuri'
, showWep yuri'
]
| "look" `maybeInsEq` margs -> do
let (name : img : _) = (fighters <?> [cstr, ""]) ++ [""]
oyuris = ownerYuris owner
(myuri, nyuris) = getWithList (insEq name . yuriName) oyuris
fyuri = listToMaybe $ do
o <- owners
let mm = fst $ getWithList (insEq name . yuriName) $ ownerYuris o
guard $ isJust mm
return $ fromJust mm
yuri = fromJust $ myuri <?> fyuri <?> Just (Yuri "" "" Nothing (0,0,0))
case () of
_ | null $ yuriName yuri -> do
return $ UserMsg $ name ++ " doesn't exist."
| length img > 37 -> do
return $ UserMsg "Image URL is too long. 37 chars is max."
| null img -> do
return $ ChannelMsg $ unwords [
yuriName yuri
, show (yuriStats yuri)
, yuriImage yuri
]
| not $ ownerExists name -> do
return $ UserMsg $ "You don't own " ++ name ++ "."
| otherwise -> do
let (Yuri name' _ wep' stats') = yuri
yuri' :: Yuri
yuri' = Yuri name' img wep' stats'
yurixs :: [Yuri]
yurixs = yuri' : nyuris
owner' :: YuriOwner
owner' = YuriOwner nick1 host1 (ownerTime owner) yurixs
owners' :: [YuriOwner]
owners' = owner' : nowners
yuris' :: Yuris
yuris' = addOwners yuris $ owners'
yuriss :: [Yuris]
yuriss = yuris' : nyuriss
writeYuriss yuriss
return EmptyMsg
_ -> return $ UserMsg $ unwords [
"Please give an argument like:"
, ":fight yuri name <|> opponent yuri,"
, ":spawn yuri name <|> image URL,"
, ":find yuri name,"
, ":list [IRC nick],"
, ":drop yuri name,"
, ":rank [stat name],"
, ":wgive yuri name [<|> weapon name],"
, ":look yuri name [<|> Yuri image URL],"
]
-- TODO: Store last location.
-- | Weather printing function.
weather :: [String] -> String -> Memory (Message String)
weather _ str = do
let burl = "http://www.google.com/ig/api?weather="
xml <- liftIO $ httpGetString (burl ++ urlEncode' str)
let weatherElem = fromMaybeElement $ parseXMLDoc xml
eCity = findElement (QName "city" Nothing Nothing) weatherElem
eCurrent = findElements (QName "current_conditions" Nothing Nothing) weatherElem
eForecast = findElements (QName "forecast_conditions" Nothing Nothing) weatherElem
city = getData . fromMaybeElement $ eCity
condition = map formatCondition . getConditionData $ eCurrent
forecasts = map formatForecast . getConditionData $ eForecast
return . ChannelMsg . join "; " $ condition ++ forecasts
where getData element = fromMaybeString $ findAttr (QName "data" Nothing Nothing) element
getConditionData elems = map (map getData . onlyElems . elContent) elems
formatCondition [condition, tempF, tempC, humidity, _, wind] =
concat ["\ETX12Today\ETX: ", tempF, "\176F / ", tempC, "\176C, ",
join ", " [condition, humidity, wind]]
formatCondition _ = []
formatForecast [day, _, _, _, condition] = "\ETX12" ++ day ++ "\ETX: " ++ condition
formatForecast _ = []
-- | Wikipedia intro printing function.
wiki :: [String] -> String -> Memory (Message String)
wiki args s = do
let burl = "https://en.wikipedia.org/w/index.php?search=%s&title=Special%3ASearch"
html <- liftIO $ httpGetString (burl % (replace "+" "%20" . urlEncode') s)
let xml = fromMaybeElement $ parseXMLDoc html
qDiv = QName "div" (Just "http://www.w3.org/1999/xhtml") Nothing
qMwcontent = [Attr (QName "id" Nothing Nothing) "mw-content-text"]
element = fromMaybeElement $ findElementAttrs qDiv qMwcontent xml
qPar = QName "p" (Just "http://www.w3.org/1999/xhtml") Nothing
intro = findChild qPar element
qMwsearch = [Attr (QName "class" Nothing Nothing) "mw-search-createlink"]
search = findElementAttrs (QName "p" Nothing Nothing) qMwsearch element
text = strip $ elemsText . fromMaybeElement $ search <|> intro
if null text
then return EmptyMsg
else return . ChannelMsg . (cutoff 400) $ text
-------------------------------------------------------------------------------
-- Non-IRC bot functions / event functions ------------------------------------
-------------------------------------------------------------------------------
diff :: [String] -> Memory String
diff xs = do
temp <- asks (getUserlist . getMeta)
let xs' = filter (not . (`elem` temp)) xs
return $ joinUntil 400 ", " xs'
| Shou/KawaiiBot-hs | KawaiiBot/Bot.hs | gpl-2.0 | 60,423 | 0 | 31 | 25,559 | 16,987 | 8,625 | 8,362 | 1,114 | 17 |
{-# LANGUAGE CPP #-}
module Darcs.Test.Patch.Properties.Check ( Check(..), checkAPatch ) where
import Control.Monad ( liftM )
import Darcs.Test.Patch.Check ( PatchCheck,
checkMove, removeDir, createDir,
isValid, insertLine, fileEmpty, fileExists,
deleteLine, modifyFile, createFile, removeFile,
doCheck, FileContents(..)
)
import Darcs.Patch.RegChars ( regChars )
import Darcs.Util.ByteString ( linesPS )
import qualified Data.ByteString as B ( ByteString, null, concat )
import qualified Data.ByteString.Char8 as BC ( break, pack )
import Darcs.Util.Path ( fn2fp )
import qualified Data.Map as M ( mapMaybe )
import Darcs.Patch ( invert,
effect )
import Darcs.Patch.Invert ( Invert )
import Darcs.Patch.V1 ()
import qualified Darcs.Patch.V1.Core as V1 ( Patch(..) )
import Darcs.Patch.V1.Core ( isMerger )
import Darcs.Patch.Prim.V1 ()
import Darcs.Patch.Prim.V1.Core ( Prim(..), DirPatchType(..), FilePatchType(..) )
import Darcs.Patch.Witnesses.Ordered
#include "impossible.h"
class Check p where
checkPatch :: p wX wY -> PatchCheck Bool
instance Check p => Check (FL p) where
checkPatch NilFL = isValid
checkPatch (p :>: ps) = checkPatch p >> checkPatch ps
checkAPatch :: (Invert p, Check p) => p wX wY -> Bool
checkAPatch p = doCheck $ do _ <- checkPatch p
checkPatch $ invert p
instance Check (V1.Patch Prim) where
checkPatch p | isMerger p = do
checkPatch $ effect p
checkPatch (V1.Merger _ _ _ _) = impossible
checkPatch (V1.Regrem _ _ _ _) = impossible
checkPatch (V1.PP p) = checkPatch p
instance Check Prim where
checkPatch (FP f RmFile) = removeFile $ fn2fp f
checkPatch (FP f AddFile) = createFile $ fn2fp f
checkPatch (FP f (Hunk line old new)) = do
_ <- fileExists $ fn2fp f
mapM_ (deleteLine (fn2fp f) line) old
mapM_ (insertLine (fn2fp f) line) (reverse new)
isValid
checkPatch (FP f (TokReplace t old new)) =
modifyFile (fn2fp f) (tryTokPossibly t old new)
-- note that the above isn't really a sure check, as it leaves PSomethings
-- and PNothings which may have contained new...
checkPatch (FP f (Binary o n)) = do
_ <- fileExists $ fn2fp f
mapM_ (deleteLine (fn2fp f) 1) (linesPS o)
_ <- fileEmpty $ fn2fp f
mapM_ (insertLine (fn2fp f) 1) (reverse $ linesPS n)
isValid
checkPatch (DP d AddDir) = createDir $ fn2fp d
checkPatch (DP d RmDir) = removeDir $ fn2fp d
checkPatch (Move f f') = checkMove (fn2fp f) (fn2fp f')
checkPatch (ChangePref _ _ _) = return True
tryTokPossibly :: String -> String -> String
-> (Maybe FileContents) -> (Maybe FileContents)
tryTokPossibly t o n = liftM $ \contents ->
let lines' = M.mapMaybe (liftM B.concat
. tryTokInternal t (BC.pack o) (BC.pack n))
(fcLines contents)
in contents { fcLines = lines' }
tryTokInternal :: String -> B.ByteString -> B.ByteString
-> B.ByteString -> Maybe [B.ByteString]
tryTokInternal _ _ _ s | B.null s = Just []
tryTokInternal t o n s =
case BC.break (regChars t) s of
(before,s') ->
case BC.break (not . regChars t) s' of
(tok,after) ->
case tryTokInternal t o n after of
Nothing -> Nothing
Just rest ->
if tok == o
then Just $ before : n : rest
else if tok == n
then Nothing
else Just $ before : tok : rest
| DavidAlphaFox/darcs | harness/Darcs/Test/Patch/Properties/Check.hs | gpl-2.0 | 3,711 | 0 | 18 | 1,124 | 1,278 | 674 | 604 | 80 | 4 |
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE helpset
PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 1.0//EN"
"http://java.sun.com/products/javahelp/helpset_1_0.dtd">
<helpset version="1.0">
<!-- title -->
<title>Hilfe zum Modul EBNF / Syntaxdiagramme</title>
<!-- maps -->
<maps>
<homeID>ebnf</homeID>
<mapref location="map.jhm"/>
</maps>
<!-- presentations -->
<presentation default=true>
<name>main window</name>
<size width="920" height="450" />
<location x="150" y="150" />
<image>mainicon</image>
<toolbar>
<helpaction>javax.help.BackAction</helpaction>
<helpaction>javax.help.ForwardAction</helpaction>
<helpaction>javax.help.ReloadAction</helpaction>
<helpaction>javax.help.SeparatorAction</helpaction>
<helpaction image="Startseite">javax.help.HomeAction</helpaction>
<helpaction>javax.help.SeparatorAction</helpaction>
<helpaction>javax.help.PrintAction</helpaction>
<helpaction>javax.help.PrintSetupAction</helpaction>
</toolbar>
</presentation>
<!-- views -->
<view mergetype="javax.help.UniteAppendMerge">
<name>TOC</name>
<label>Inhaltsverzeichnis</label>
<type>javax.help.TOCView</type>
<data>ebnfTOC.xml</data>
</view>
<view mergetype="javax.help.SortMerge">
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>ebnfIndex.xml</data>
</view>
<view xml:lang="de">
<name>Search</name>
<label>Suche</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
</helpset> | jurkov/j-algo-mod | res/module/ebnf/help/jhelp/ebnf_help.hs | gpl-2.0 | 1,639 | 124 | 90 | 220 | 649 | 324 | 325 | -1 | -1 |
module Cryptography.SystemAlgebra.AbstractSystems.Macro where
import Types
import Macro.Arrows
import Macro.Math
import Macro.MetaMacro
import Functions.Application.Macro
-- | Concrete set of systems
syss_ :: Note
syss_ = phiu
-- | Concrete set of labels
labs_ :: Note
labs_ = lambdau
-- | Concrete Label assignment function
laf_ :: Note
laf_ = lambda
-- | Application of concrete Label assignment function
la :: Note -> Note
la = fn laf_
-- | Concrete system merging operation
smo_ :: Note
smo_ = comm0 "bigvee"
-- | System merging operation
sm :: Note -> Note -> Note
sm = binop smo_
-- | Interface connection operation
ico :: Note -- ^ System
-> Note -- ^ Interface 1
-> Note -- ^ Interface 2
-> Note
ico s i1 i2 = s ^ (i1 <> "-" <> i2)
-- | System with empty interface label set
emptysys :: Note
emptysys = comm0 "blacksquare"
-- | Merging interfaces
mio :: Note -- ^ System
-> Note -- ^ Interface set
-> Note -- ^ Resulting interface
-> Note
mio s l j = s ^ (l <> rightarrow <> j)
-- | Merging interfaces inverse operation
mioi :: Note -- ^ System
-> Note -- ^ Interface set
-> Note -- ^ Resulting interface
-> Note
mioi s j l = s ^ (sqbrac $ j <> rightarrow <> l)
-- | Convert resource with converter
conv :: Note -- ^ Converter
-> Note -- ^ Converted interface
-> Note -- ^ Resource
-> Note
conv a i s = a ^ i <> s
-- | Convert 1-resource with converter
conv_ :: Note -- ^ Converter
-> Note -- ^ Resource
-> Note
conv_ a s = a <> s
| NorfairKing/the-notes | src/Cryptography/SystemAlgebra/AbstractSystems/Macro.hs | gpl-2.0 | 1,573 | 0 | 9 | 418 | 352 | 203 | 149 | 44 | 1 |
elemToTuple :: Element -> (String, String, Int)
elemToTuple e = (name e, symbol e, atomicNumber e) | hmemcpy/milewski-ctfp-pdf | src/content/1.6/code/haskell/snippet17.hs | gpl-3.0 | 98 | 0 | 6 | 15 | 45 | 24 | 21 | 2 | 1 |
-- Math.NumberTheory.Utils
{-# LANGUAGE CPP, MagicHash, UnboxedTuples, BangPatterns, FlexibleContexts #-}
#include "MachDeps.h"
import GHC.Base
#if __GLASGOW_HASKELL__ < 705
import GHC.Word -- Word and its constructor moved to GHC.Types
#endif
import GHC.Integer
import GHC.Integer.GMP.Internals
import Data.Bits
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.Base (unsafeAt, unsafeWrite)
#if WORD_SIZE_IN_BITS == 64
#define m5 0x5555555555555555
#define m3 0x3333333333333333
#define mf 0x0F0F0F0F0F0F0F0F
#define m1 0x0101010101010101
#define sd 56
#define WSHIFT 6
#define MMASK 63
#else
#define m5 0x55555555
#define m3 0x33333333
#define mf 0x0F0F0F0F
#define m1 0x01010101
#define sd 24
#define WSHIFT 5
#define MMASK 31
#endif
uncheckedShiftR :: Word -> Int -> Word
uncheckedShiftR (W# w#) (I# i#) = W# (uncheckedShiftRL# w# i#)
-- | Remove factors of @2@ and count them. If
-- @n = 2^k*m@ with @m@ odd, the result is @(k, m)@.
-- Precondition: argument not @0@ (not checked).
{-# RULES
"shiftToOddCount/Int" shiftToOddCount = shiftOCInt
"shiftToOddCount/Word" shiftToOddCount = shiftOCWord
"shiftToOddCount/Integer" shiftToOddCount = shiftOCInteger
#-}
{-# INLINE [1] shiftToOddCount #-}
shiftToOddCount :: (Integral a, Bits a) => a -> (Int, a)
shiftToOddCount n = case shiftOCInteger (fromIntegral n) of
(z, o) -> (z, fromInteger o)
-- | Specialised version for @'Word'@.
-- Precondition: argument strictly positive (not checked).
shiftOCWord :: Word -> (Int, Word)
shiftOCWord (W# w#) = case shiftToOddCount# w# of
(# z# , u# #) -> (I# z#, W# u#)
-- | Specialised version for @'Int'@.
-- Precondition: argument nonzero (not checked).
shiftOCInt :: Int -> (Int, Int)
shiftOCInt (I# i#) = case shiftToOddCount# (int2Word# i#) of
(# z#, u# #) -> (I# z#, I# (word2Int# u#))
-- | Specialised version for @'Integer'@.
-- Precondition: argument nonzero (not checked).
shiftOCInteger :: Integer -> (Int, Integer)
shiftOCInteger n@(S# i#) =
case shiftToOddCount# (int2Word# i#) of
(# z#, w# #)
| isTrue# (z# ==# 0#) -> (0, n)
| otherwise -> (I# z#, S# (word2Int# w#))
#if __GLASGOW_HASKELL__ < 709
shiftOCInteger n@(J# _ ba#) = case count 0# 0# of
#else
shiftOCInteger n@(Jp# bn#) = case bigNatZeroCount bn# of
0# -> (0, n)
z# -> (I# z#, n `shiftRInteger` z#)
shiftOCInteger n@(Jn# bn#) = case bigNatZeroCount bn# of
#endif
0# -> (0, n)
z# -> (I# z#, n `shiftRInteger` z#)
#if __GLASGOW_HASKELL__ < 709
where
count a# i# =
case indexWordArray# ba# i# of
0## -> count (a# +# WORD_SIZE_IN_BITS#) (i# +# 1#)
w# -> a# +# trailZeros# w#
#endif
#if __GLASGOW_HASKELL__ >= 709
-- | Count trailing zeros in a @'BigNat'@.
-- Precondition: argument nonzero (not checked, Integer invariant).
bigNatZeroCount :: BigNat -> Int#
bigNatZeroCount bn# = count 0# 0#
where
count a# i# =
case indexBigNat# bn# i# of
0## -> count (a# +# WORD_SIZE_IN_BITS#) (i# +# 1#)
w# -> a# +# trailZeros# w#
#endif
-- | Remove factors of @2@. If @n = 2^k*m@ with @m@ odd, the result is @m@.
-- Precondition: argument not @0@ (not checked).
{-# RULES
"shiftToOdd/Int" shiftToOdd = shiftOInt
"shiftToOdd/Word" shiftToOdd = shiftOWord
"shiftToOdd/Integer" shiftToOdd = shiftOInteger
#-}
{-# INLINE [1] shiftToOdd #-}
shiftToOdd :: (Integral a, Bits a) => a -> a
shiftToOdd n = fromInteger (shiftOInteger (fromIntegral n))
-- | Specialised version for @'Int'@.
-- Precondition: argument nonzero (not checked).
shiftOInt :: Int -> Int
shiftOInt (I# i#) = I# (word2Int# (shiftToOdd# (int2Word# i#)))
-- | Specialised version for @'Word'@.
-- Precondition: argument nonzero (not checked).
shiftOWord :: Word -> Word
shiftOWord (W# w#) = W# (shiftToOdd# w#)
-- | Specialised version for @'Int'@.
-- Precondition: argument nonzero (not checked).
shiftOInteger :: Integer -> Integer
shiftOInteger (S# i#) = S# (word2Int# (shiftToOdd# (int2Word# i#)))
#if __GLASGOW_HASKELL__ < 709
shiftOInteger n@(J# _ ba#) = case count 0# 0# of
#else
shiftOInteger n@(Jn# bn#) = case bigNatZeroCount bn# of
0# -> n
z# -> n `shiftRInteger` z#
shiftOInteger n@(Jp# bn#) = case bigNatZeroCount bn# of
#endif
0# -> n
z# -> n `shiftRInteger` z#
#if __GLASGOW_HASKELL__ < 709
where
count a# i# =
case indexWordArray# ba# i# of
0## -> count (a# +# WORD_SIZE_IN_BITS#) (i# +# 1#)
w# -> a# +# trailZeros# w#
#endif
-- | Shift argument right until the result is odd.
-- Precondition: argument not @0@, not checked.
shiftToOdd# :: Word# -> Word#
shiftToOdd# w# = case trailZeros# w# of
k# -> uncheckedShiftRL# w# k#
-- | Like @'shiftToOdd#'@, but count the number of places to shift too.
shiftToOddCount# :: Word# -> (# Int#, Word# #)
shiftToOddCount# w# = case trailZeros# w# of
k# -> (# k#, uncheckedShiftRL# w# k# #)
-- | Number of 1-bits in a @'Word#'@.
bitCountWord# :: Word# -> Int#
bitCountWord# w# = case bitCountWord (W# w#) of
I# i# -> i#
-- | Number of 1-bits in a @'Word'@.
bitCountWord :: Word -> Int
#if __GLASGOW_HASKELL__ >= 703
bitCountWord = popCount
-- should yield a machine instruction
#else
bitCountWord w = case w - (shiftR w 1 .&. m5) of
!w1 -> case (w1 .&. m3) + (shiftR w1 2 .&. m3) of
!w2 -> case (w2 + shiftR w2 4) .&. mf of
!w3 -> fromIntegral (shiftR (w3 * m1) sd)
#endif
-- | Number of 1-bits in an @'Int'@.
bitCountInt :: Int -> Int
#if __GLASGOW_HASKELL__ >= 703
bitCountInt = popCount
-- should yield a machine instruction
#else
bitCountInt (I# i#) = bitCountWord (W# (int2Word# i#))
#endif
-- | Number of trailing zeros in a @'Word#'@, wrong for @0@.
{-# INLINE trailZeros# #-}
trailZeros# :: Word# -> Int#
trailZeros# w =
case xor# w (w `minusWord#` 1##) `uncheckedShiftRL#` 1# of
v0 ->
case v0 `minusWord#` (uncheckedShiftRL# v0 1# `and#` m5##) of
v1 ->
case (v1 `and#` m3##) `plusWord#` (uncheckedShiftRL# v1 2# `and#` m3##) of
v2 ->
case (v2 `plusWord#` uncheckedShiftRL# v2 4#) `and#` mf## of
v3 -> word2Int# (uncheckedShiftRL# (v3 `timesWord#` m1##) sd#)
-- {-# SPECIALISE splitOff :: Integer -> Integer -> (Int, Integer),
-- Int -> Int -> (Int, Int),
-- Word -> Word -> (Int, Word)
-- #-}
#if __GLASGOW_HASKELL__ >= 700
{-# INLINABLE splitOff #-}
#else
{-# INLINE splitOff #-}
#endif
splitOff :: Integral a => a -> a -> (Int, a)
splitOff p n = go 0 n
where
go !k m = case m `quotRem` p of
(q,r) | r == 0 -> go (k+1) q
| otherwise -> (k,m)
#if __GLASGOW_HASKELL__ < 707
-- The times they are a-changing. The types of primops too :(
isTrue# :: Bool -> Bool
isTrue# = id
#endif
-- Math.NumberTheory.Logarithms.Internal
-- | Calculate the integer base 2 logarithm of an 'Integer'.
-- The calculation is much more efficient than for the general case.
--
-- The argument must be strictly positive, that condition is /not/ checked.
integerLog2# :: Integer -> Int#
integerLog2# (S# i) = wordLog2# (int2Word# i)
integerLog2# (J# s ba) = check (s -# 1#)
where
check i = case indexWordArray# ba i of
0## -> check (i -# 1#)
w -> wordLog2# w +# (uncheckedIShiftL# i WSHIFT#)
-- | This function calculates the integer base 2 logarithm of a 'Word#'.
-- @'wordLog2#' 0## = -1#@.
{-# INLINE wordLog2# #-}
wordLog2# :: Word# -> Int#
wordLog2# w =
case leadingZeros of
BA lz ->
let zeros u = indexInt8Array# lz (word2Int# u) in
#if WORD_SIZE_IN_BITS == 64
case uncheckedShiftRL# w 56# of
a ->
if a `neWord#` 0##
then 64# -# zeros a
else
case uncheckedShiftRL# w 48# of
b ->
if b `neWord#` 0##
then 56# -# zeros b
else
case uncheckedShiftRL# w 40# of
c ->
if c `neWord#` 0##
then 48# -# zeros c
else
case uncheckedShiftRL# w 32# of
d ->
if d `neWord#` 0##
then 40# -# zeros d
else
#endif
case uncheckedShiftRL# w 24# of
e ->
if e `neWord#` 0##
then 32# -# zeros e
else
case uncheckedShiftRL# w 16# of
f ->
if f `neWord#` 0##
then 24# -# zeros f
else
case uncheckedShiftRL# w 8# of
g ->
if g `neWord#` 0##
then 16# -# zeros g
else 8# -# zeros w
-- Lookup table
data BA = BA ByteArray#
leadingZeros :: BA
leadingZeros =
let mkArr s =
case newByteArray# 256# s of
(# s1, mba #) ->
case writeInt8Array# mba 0# 9# s1 of
s2 ->
let fillA lim val idx st =
if idx ==# 256#
then st
else if idx <# lim
then case writeInt8Array# mba idx val st of
nx -> fillA lim val (idx +# 1#) nx
else fillA (2# *# lim) (val -# 1#) idx st
in case fillA 2# 8# 1# s2 of
s3 -> case unsafeFreezeByteArray# mba s3 of
(# _, ba #) -> ba
in case mkArr realWorld# of
b -> BA b
-- Math.NumberTheory.Powers.Squares
-- | Calculate the integer square root of a nonnegative number @n@,
-- that is, the largest integer @r@ with @r*r <= n@.
-- Throws an error on negative input.
{-# SPECIALISE integerSquareRoot :: Int -> Int,
Word -> Word,
Integer -> Integer
#-}
integerSquareRoot :: Integral a => a -> a
integerSquareRoot n
| n < 0 = error "integerSquareRoot: negative argument"
| otherwise = integerSquareRoot' n
-- | Calculate the integer square root of a nonnegative number @n@,
-- that is, the largest integer @r@ with @r*r <= n@.
-- The precondition @n >= 0@ is not checked.
{-# RULES
"integerSquareRoot'/Int" integerSquareRoot' = isqrtInt'
"integerSquareRoot'/Word" integerSquareRoot' = isqrtWord
#-}
{-# INLINE [1] integerSquareRoot' #-}
integerSquareRoot' :: Integral a => a -> a
integerSquareRoot' = isqrtA
-- | Returns 'Nothing' if the argument is not a square,
-- @'Just' r@ if @r*r == n@ and @r >= 0@. Avoids the expensive calculation
-- of the square root if @n@ is recognized as a non-square
-- before, prevents repeated calculation of the square root
-- if only the roots of perfect squares are needed.
-- Checks for negativity and 'isPossibleSquare'.
{-# SPECIALISE exactSquareRoot :: Int -> Maybe Int,
Word -> Maybe Word,
Integer -> Maybe Integer
#-}
exactSquareRoot :: Integral a => a -> Maybe a
exactSquareRoot n
| n < 0 = Nothing
| isPossibleSquare n && r*r == n = Just r
| otherwise = Nothing
where
r = integerSquareRoot' n
-- | Test whether the argument is a square.
-- After a number is found to be positive, first 'isPossibleSquare'
-- is checked, if it is, the integer square root is calculated.
{-# SPECIALISE isSquare :: Int -> Bool,
Word -> Bool,
Integer -> Bool
#-}
isSquare :: Integral a => a -> Bool
isSquare n = n >= 0 && isSquare' n
-- | Test whether the input (a nonnegative number) @n@ is a square.
-- The same as 'isSquare', but without the negativity test.
-- Faster if many known positive numbers are tested.
--
-- The precondition @n >= 0@ is not tested, passing negative
-- arguments may cause any kind of havoc.
{-# SPECIALISE isSquare' :: Int -> Bool,
Word -> Bool,
Integer -> Bool
#-}
isSquare' :: Integral a => a -> Bool
isSquare' n = isPossibleSquare n && let r = integerSquareRoot' n in r*r == n
-- | Test whether a non-negative number may be a square.
-- Non-negativity is not checked, passing negative arguments may
-- cause any kind of havoc.
--
-- First the remainder modulo 256 is checked (that can be calculated
-- easily without division and eliminates about 82% of all numbers).
-- After that, the remainders modulo 9, 25, 7, 11 and 13 are tested
-- to eliminate altogether about 99.436% of all numbers.
--
-- This is the test used by 'exactSquareRoot'. For large numbers,
-- the slower but more discriminating test 'isPossibleSqure2' is
-- faster.
{-# SPECIALISE isPossibleSquare :: Int -> Bool,
Integer -> Bool,
Word -> Bool
#-}
isPossibleSquare :: Integral a => a -> Bool
isPossibleSquare n =
unsafeAt sr256 ((fromIntegral n) .&. 255)
&& unsafeAt sr693 (fromIntegral (n `rem` 693))
&& unsafeAt sr325 (fromIntegral (n `rem` 325))
-- | Test whether a non-negative number may be a square.
-- Non-negativity is not checked, passing negative arguments may
-- cause any kind of havoc.
--
-- First the remainder modulo 256 is checked (that can be calculated
-- easily without division and eliminates about 82% of all numbers).
-- After that, the remainders modulo several small primes are tested
-- to eliminate altogether about 99.98954% of all numbers.
--
-- For smallish to medium sized numbers, this hardly performs better
-- than 'isPossibleSquare', which uses smaller arrays, but for large
-- numbers, where calculating the square root becomes more expensive,
-- it is much faster (if the vast majority of tested numbers aren't squares).
{-# SPECIALISE isPossibleSquare2 :: Int -> Bool,
Integer -> Bool,
Word -> Bool
#-}
isPossibleSquare2 :: Integral a => a -> Bool
isPossibleSquare2 n =
unsafeAt sr256 ((fromIntegral n) .&. 255)
&& unsafeAt sr819 (fromIntegral (n `rem` 819))
&& unsafeAt sr1025 (fromIntegral (n `rem` 1025))
&& unsafeAt sr2047 (fromIntegral (n `rem` 2047))
&& unsafeAt sr4097 (fromIntegral (n `rem` 4097))
&& unsafeAt sr341 (fromIntegral (n `rem` 341))
-----------------------------------------------------------------------------
-- Auxiliary Stuff
-- Find approximation to square root in 'Integer', then
-- find the integer square root by the integer variant
-- of Heron's method. Takes only a handful of steps
-- unless the input is really large.
{-# SPECIALISE isqrtA :: Integer -> Integer #-}
isqrtA :: Integral a => a -> a
isqrtA 0 = 0
isqrtA n = heron n (fromInteger . appSqrt . fromIntegral $ n)
-- Heron's method for integers. First make one step to ensure
-- the value we're working on is @>= r@, then we have
-- @k == r@ iff @k <= step k@.
{-# SPECIALISE heron :: Integer -> Integer -> Integer #-}
heron :: Integral a => a -> a -> a
heron n a = go (step a)
where
step k = (k + n `quot` k) `quot` 2
go k
| m < k = go m
| otherwise = k
where
m = step k
-- threshold for shifting vs. direct fromInteger
-- we shift when we expect more than 256 bits
#if WORD_SIZE_IN_BITS == 64
#define THRESH 5
#else
#define THRESH 9
#endif
-- Find a fairly good approximation to the square root.
-- At most one off for small Integers, about 48 bits should be correct
-- for large Integers.
appSqrt :: Integer -> Integer
appSqrt (S# i#) = S# (double2Int# (sqrtDouble# (int2Double# i#)))
#if __GLASGOW_HASKELL__ < 709
appSqrt n@(J# s# _)
| isTrue# (s# <# THRESH#) = floor (sqrt $ fromInteger n :: Double)
#else
appSqrt n@(Jp# bn#)
| isTrue# ((sizeofBigNat# bn#) <# THRESH#) =
floor (sqrt $ fromInteger n :: Double)
#endif
| otherwise = case integerLog2# n of
l# -> case uncheckedIShiftRA# l# 1# -# 47# of
h# -> case shiftRInteger n (2# *# h#) of
m -> case floor (sqrt $ fromInteger m :: Double) of
r -> shiftLInteger r h#
#if __GLASGOW_HASKELL__ >= 709
-- There's already a check for negative in integerSquareRoot,
-- but integerSquareRoot' is exported directly too.
appSqrt _ = error "integerSquareRoot': negative argument"
#endif
-- Auxiliaries
-- Make an array indicating whether a remainder is a square remainder.
sqRemArray :: Int -> UArray Int Bool
sqRemArray md = runSTUArray $ do
arr <- newArray (0,md-1) False
let !stop = (md `quot` 2) + 1
fill k
| k < stop = unsafeWrite arr ((k*k) `rem` md) True >> fill (k+1)
| otherwise = return arr
unsafeWrite arr 0 True
unsafeWrite arr 1 True
fill 2
sr256 :: UArray Int Bool
sr256 = sqRemArray 256
sr819 :: UArray Int Bool
sr819 = sqRemArray 819
sr4097 :: UArray Int Bool
sr4097 = sqRemArray 4097
sr341 :: UArray Int Bool
sr341 = sqRemArray 341
sr1025 :: UArray Int Bool
sr1025 = sqRemArray 1025
sr2047 :: UArray Int Bool
sr2047 = sqRemArray 2047
sr693 :: UArray Int Bool
sr693 = sqRemArray 693
sr325 :: UArray Int Bool
sr325 = sqRemArray 325
-- Specialisations for Int and Word
-- For @n <= 2^64@, the result of
--
-- > truncate (sqrt $ fromIntegral n)
--
-- is never too small and never more than one too large.
-- The multiplication doesn't overflow for 32 or 64 bit Ints.
isqrtInt' :: Int -> Int
isqrtInt' n
| n < r*r = r-1
| otherwise = r
where
!r = (truncate :: Double -> Int) . sqrt $ fromIntegral n
-- With -O2, that should be translated to the below
{-
isqrtInt' n@(I# i#)
| r# *# r# ># i# = I# (r# -# 1#)
| otherwise = I# r#
where
!r# = double2Int# (sqrtDouble# (int2Double# i#))
-}
-- Same for Word.
isqrtWord :: Word -> Word
isqrtWord n
| n < (r*r)
#if WORD_SIZE_IN_BITS == 64
|| r == 4294967296
-- Double interprets values near maxBound as 2^64, we don't have that problem for 32 bits
#endif
= r-1
| otherwise = r
where
!r = (fromIntegral :: Int -> Word) . (truncate :: Double -> Int) . sqrt $ fromIntegral n
| anthonybrice/euler94 | Daniel/NumberTheory.hs | gpl-3.0 | 18,874 | 3 | 39 | 5,701 | 3,483 | 1,866 | 1,617 | 247 | 4 |
{-# OPTIONS_GHC -XTypeSynonymInstances -XFlexibleInstances #-}
module Folsolver.HasPretty
( HasPretty(..)
, module Pretty
) where
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Map as Map
import Data.Map (Map)
import Text.PrettyPrint.HughesPJ as Pretty
class HasPretty a where
pretty :: a -> Pretty.Doc
instance (HasPretty a) => HasPretty [a] where
pretty as = Pretty.brackets $ Pretty.cat $ (Pretty.punctuate Pretty.comma) $ map pretty as
instance (HasPretty a, HasPretty b) => HasPretty (a,b) where
pretty (a,b) = Pretty.parens $ pretty a <> Pretty.comma <> pretty b
instance (HasPretty a) => HasPretty (Set a) where
pretty as = pretty $ Set.toList as
instance (HasPretty a, HasPretty b) => HasPretty (Map a b) where
pretty as = pretty $ Map.toList as
instance HasPretty Int where
pretty i = Pretty.text $ show i
instance HasPretty String where
pretty s = Pretty.text $ s
| traeger/fol-solver | Folsolver/HasPretty.hs | gpl-3.0 | 931 | 0 | 10 | 165 | 343 | 185 | 158 | 23 | 0 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- |
-- Copyright : (c) 2011 Simon Meier
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Simon Meier <iridcode@gmail.com>
-- Portability : portable
--
-- Pretty-printing with support for HTML markup and proper HTML escaping.
module Text.PrettyPrint.Html (
-- * HtmlDocument class
HtmlDocument(..)
, withTag
, withTagNonEmpty
, closedTag
, module Text.PrettyPrint.Highlight
-- * HtmlDoc: adding HTML markup
, HtmlDoc
, htmlDoc
, getHtmlDoc
, postprocessHtmlDoc
, renderHtmlDoc
-- * NoHtmlDoc: ignoring HTML markup
, noHtmlDoc
, getNoHtmlDoc
) where
import Data.Char (isSpace)
import Data.Traversable (sequenceA)
import Data.Monoid
import Control.Arrow (first)
import Control.Applicative
import Control.Monad.Identity
import Control.DeepSeq
import Text.PrettyPrint.Class
import Text.PrettyPrint.Highlight
------------------------------------------------------------------------------
-- HtmlDocument class
------------------------------------------------------------------------------
class HighlightDocument d => HtmlDocument d where
-- | @unescapedText str@ converts the 'String' @str@ to a document without
-- performing any escaping.
unescapedText :: String -> d
-- | @unescapedZeroWidthText str@ converts the 'String' @str@ to a document
-- with zero width without performing any escaping.
unescapedZeroWidthText :: String -> d
-- | @withTag tag attrs inner@ adds the tag @tag@ with the attributes
-- @attrs@ around the @inner@ document.
withTag :: HtmlDocument d => String -> [(String,String)] -> d -> d
withTag tag attrs inner =
unescapedZeroWidthText open <> inner <> unescapedZeroWidthText close
where
open = "<" ++ tag ++ concatMap attribute attrs ++ ">"
close = "</" ++ tag ++ ">"
-- | @closedTag tag attrs@ builds the closed tag @tag@ with the attributes
-- @attrs@; e.g.,
--
-- > closedTag "img" "href" "here" = HtmlDoc (text "<img href=\"here\"/>)
--
closedTag :: HtmlDocument d => String -> [(String,String)] -> d
closedTag tag attrs =
unescapedZeroWidthText $ "<" ++ tag ++ concatMap attribute attrs ++ "/>"
-- | @withTagNonEmpty tag attrs inner@ adds the tag @tag@ with the attributes
-- @attrs@ around the @inner@ document iff @inner@ is a non-empty document.
withTagNonEmpty :: HtmlDocument d => String -> [(String,String)] -> d -> d
withTagNonEmpty tag attrs inner =
caseEmptyDoc inner emptyDoc $ withTag tag attrs inner
-- | Render an attribute.
attribute :: (String, String) -> String
attribute (key,value) = " " ++ key ++ "=\"" ++ escapeHtmlEntities value ++ "\""
------------------------------------------------------------------------------
-- HtmlDoc: adding HTML markup
------------------------------------------------------------------------------
-- | A 'Document' transformer that adds proper HTML escaping.
newtype HtmlDoc d = HtmlDoc { getHtmlDoc :: d }
deriving( Monoid )
-- | Wrap a document such that HTML markup can be added without disturbing the
-- layout.
htmlDoc :: d -> HtmlDoc d
htmlDoc = HtmlDoc
instance NFData d => NFData (HtmlDoc d) where
rnf = rnf . getHtmlDoc
instance Document d => Document (HtmlDoc d) where
char = HtmlDoc . text . escapeHtmlEntities . return
text = HtmlDoc . text . escapeHtmlEntities
zeroWidthText = HtmlDoc . zeroWidthText . escapeHtmlEntities
HtmlDoc d1 <-> HtmlDoc d2 = HtmlDoc $ d1 <-> d2
hcat = HtmlDoc . hcat . map getHtmlDoc
hsep = HtmlDoc . hsep . map getHtmlDoc
HtmlDoc d1 $$ HtmlDoc d2 = HtmlDoc $ d1 $$ d2
HtmlDoc d1 $-$ HtmlDoc d2 = HtmlDoc $ d1 $-$ d2
vcat = HtmlDoc . vcat . map getHtmlDoc
sep = HtmlDoc . sep . map getHtmlDoc
cat = HtmlDoc . cat . map getHtmlDoc
fsep = HtmlDoc . fsep . map getHtmlDoc
fcat = HtmlDoc . fcat . map getHtmlDoc
nest i = HtmlDoc . nest i . getHtmlDoc
caseEmptyDoc (HtmlDoc d1) (HtmlDoc d2) (HtmlDoc d3) =
HtmlDoc $ caseEmptyDoc d1 d2 d3
instance Document d => HtmlDocument (HtmlDoc d) where
unescapedText = HtmlDoc . text
unescapedZeroWidthText = HtmlDoc . zeroWidthText
instance Document d => HighlightDocument (HtmlDoc d) where
highlight hlStyle =
withTag "span" [("class", hlClass hlStyle)]
where
hlClass Comment = "hl_comment"
hlClass Keyword = "hl_keyword"
hlClass Operator = "hl_operator"
-- | Escape HTML entities in a string
--
-- Copied from 'blaze-html'.
escapeHtmlEntities :: String -- ^ String to escape
-> String -- ^ Resulting string
escapeHtmlEntities [] = []
escapeHtmlEntities (c:cs) = case c of
'<' -> "<" ++ escapeHtmlEntities cs
'>' -> ">" ++ escapeHtmlEntities cs
'&' -> "&" ++ escapeHtmlEntities cs
'"' -> """ ++ escapeHtmlEntities cs
'\'' -> "'" ++ escapeHtmlEntities cs
x -> x : escapeHtmlEntities cs
-- | @renderHtmlDoc = 'postprocessHtmlDoc' . 'render' . 'getHtmlDoc'@
renderHtmlDoc :: HtmlDoc Doc -> String
renderHtmlDoc = postprocessHtmlDoc . render . getHtmlDoc
-- | @postprocessHtmlDoc cs@ converts the line-breaks of @cs@ to @<br>@ tags and
-- the prefixed spaces in every line of @cs@ by non-breaing HTML spaces @ @.
postprocessHtmlDoc :: String -> String
postprocessHtmlDoc =
unlines . map (addBreak . indent) . lines
where
addBreak = (++"<br/>")
indent = uncurry (++) . (first $ concatMap (const " ")) . span isSpace
------------------------------------------------------------------------------
-- NoHtmlDoc: ignoring HTML markup
------------------------------------------------------------------------------
-- | A 'Document' transformer that ignores all 'HtmlDocument' specific methods.
newtype NoHtmlDoc d = NoHtmlDoc { unNoHtmlDoc :: Identity d }
deriving( Functor, Applicative )
-- | Wrap a document such that all 'HtmlDocument' specific methods are ignored.
noHtmlDoc :: d -> NoHtmlDoc d
noHtmlDoc = NoHtmlDoc . Identity
-- | Extract the wrapped document.
getNoHtmlDoc :: NoHtmlDoc d -> d
getNoHtmlDoc = runIdentity . unNoHtmlDoc
instance NFData d => NFData (NoHtmlDoc d) where
rnf = rnf . getNoHtmlDoc
instance Monoid d => Monoid (NoHtmlDoc d) where
mempty = pure mempty
mappend = liftA2 mappend
instance Document d => Document (NoHtmlDoc d) where
char = pure . char
text = pure . text
zeroWidthText = pure . zeroWidthText
(<->) = liftA2 (<->)
hcat = liftA hcat . sequenceA
hsep = liftA hsep . sequenceA
($$) = liftA2 ($$)
($-$) = liftA2 ($-$)
vcat = liftA vcat . sequenceA
sep = liftA sep . sequenceA
cat = liftA cat . sequenceA
fsep = liftA fsep . sequenceA
fcat = liftA fcat . sequenceA
nest = liftA2 nest . pure
caseEmptyDoc = liftA3 caseEmptyDoc
instance Document d => HtmlDocument (NoHtmlDoc d) where
unescapedText = noHtmlDoc . text
unescapedZeroWidthText = noHtmlDoc . zeroWidthText
instance Document d => HighlightDocument (NoHtmlDoc d) where
highlight _ = id
| ekr/tamarin-prover | lib/utils/src/Text/PrettyPrint/Html.hs | gpl-3.0 | 7,040 | 0 | 13 | 1,430 | 1,570 | 843 | 727 | 120 | 6 |
module Reducer
(
reduceToNormalForm,
limitSteps,
Strategy (..),
normalOrder,
applicativeOrder,
callByName,
callByValue,
Passing (..),
Context (..),
defaultContext,
noDefs
)
where
import Prelude hiding (lookup)
import Data.Monoid
import LambdaAST
import LambdaAST.Path
import Reducer.DefinitionTable
import Reducer.Step
import Reducer.Renderer
data Passing = ByName | ByValue
type Strategy = TraversalOrder
data Context = Context { strategy :: Strategy,
table :: DefinitionTable,
renderer :: RendererSpec,
evalStepLimit :: Int }
normalOrder = outermostFirst
applicativeOrder = innermostFirst
callByName = outermostFirstNoLambda
callByValue = innermostFirstNoLambda
defaultStrategy = normalOrder
defaultContext = Context { strategy = defaultStrategy,
table = noDefs,
renderer = clRendererSpec,
evalStepLimit = 0 }
betaReduce :: Strategy -> LambdaTerm -> ReductionStep
betaReduce s t =
case findRedex s t of
Nothing -> NoReduction t
Just p ->
let Just a = findNodeByPath p t
step = (lambdaApply p a) in
Beta (path step) $ replaceByPath (path step) (newTerm step) t
lambdaApply :: Path -> LambdaTerm -> ReductionStep
lambdaApply p (Application (Lambda parameter term) argument) =
Beta p $ replaceWithSubtree parameter argument term
lambdaApply _ _ = undefined
deltaReduce :: Strategy -> DefinitionTable -> LambdaTerm -> ReductionStep
deltaReduce s d t = case findFreeOccurrence s (keySet d) t of
Nothing -> NoReduction t
Just p ->
let Just key = (findNodeByPath p t)
Just replacement = (lookup key d) in
Delta p $ replaceByPath p replacement t
reduce :: Strategy -> DefinitionTable -> LambdaTerm -> ReductionStep
reduce s d t = case betaReduce s t of
b@Beta {} -> b
NoReduction {} -> deltaReduce s d t
reduceToNormalForm :: Strategy -> DefinitionTable -> LambdaTerm -> (DefinitionTable, Trace)
reduceToNormalForm s d t@(Definition name value) = (insert (Variable name) value d, Trace t [])
reduceToNormalForm s d t = (d, Trace t $ takeWhile reducible (trace t))
where
trace t =
let step = reduce s d t in
step:(trace $ newTerm step)
limitSteps :: Int -> Trace -> Trace
limitSteps 0 t = t
limitSteps n t = t { steps =
let s' = take n $ steps t
l = length $ s' in
if l < n
then s'
else s' ++ [Timeout] }
| sirius94/lambdai | src/Reducer.hs | gpl-3.0 | 2,759 | 0 | 13 | 907 | 797 | 421 | 376 | 72 | 2 |
module HFlint.NMod
( NMod(..)
, ReifiesNModContext
, withNModContext
, withNModContextM
, FlintLimb
, HasLimbHeight(..)
, ToNMod(..)
, ToNModMay(..)
, Modulus(..)
, modulus
, modulusIntegral
, ChineseRemainder(..)
)
where
import HFlint.NMod.FFI
import HFlint.NMod.Algebra ()
import HFlint.NMod.Arithmetic ()
import HFlint.NMod.Base ()
import HFlint.NMod.Context
import HFlint.NMod.Reduction
import HFlint.NMod.Vector ()
import HFlint.NMod.Tasty.QuickCheck ()
import HFlint.NMod.Tasty.SmallCheck ()
| martinra/hflint | src/HFlint/NMod.hs | gpl-3.0 | 533 | 0 | 5 | 87 | 142 | 97 | 45 | 22 | 0 |
{-# LANGUAGE BangPatterns, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module PB.KRPC.Tuple (Tuple(..)) where
import Prelude ((+), (/))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data Tuple = Tuple{items :: !(P'.Seq P'.ByteString)}
deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable Tuple where
mergeAppend (Tuple x'1) (Tuple y'1) = Tuple (P'.mergeAppend x'1 y'1)
instance P'.Default Tuple where
defaultValue = Tuple P'.defaultValue
instance P'.Wire Tuple where
wireSize ft' self'@(Tuple x'1)
= case ft' of
10 -> calc'Size
11 -> P'.prependMessageSize calc'Size
_ -> P'.wireSizeErr ft' self'
where
calc'Size = (P'.wireSizeRep 1 12 x'1)
wirePut ft' self'@(Tuple x'1)
= case ft' of
10 -> put'Fields
11 -> do
P'.putSize (P'.wireSize 10 self')
put'Fields
_ -> P'.wirePutErr ft' self'
where
put'Fields
= do
P'.wirePutRep 10 12 x'1
wireGet ft'
= case ft' of
10 -> P'.getBareMessageWith update'Self
11 -> P'.getMessageWith update'Self
_ -> P'.wireGetErr ft'
where
update'Self wire'Tag old'Self
= case wire'Tag of
10 -> Prelude'.fmap (\ !new'Field -> old'Self{items = P'.append (items old'Self) new'Field}) (P'.wireGet 12)
_ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
instance P'.MessageAPI msg' (msg' -> Tuple) Tuple where
getVal m' f' = f' m'
instance P'.GPB Tuple
instance P'.ReflectDescriptor Tuple where
getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [10])
reflectDescriptorInfo _
= Prelude'.read
"DescriptorInfo {descName = ProtoName {protobufName = FIName \".krpc.schema.Tuple\", haskellPrefix = [MName \"PB\"], parentModule = [MName \"KRPC\"], baseName = MName \"Tuple\"}, descFilePath = [\"PB\",\"KRPC\",\"Tuple.hs\"], isGroup = False, fields = fromList [FieldInfo {fieldName = ProtoFName {protobufName' = FIName \".krpc.schema.Tuple.items\", haskellPrefix' = [MName \"PB\"], parentModule' = [MName \"KRPC\",MName \"Tuple\"], baseName' = FName \"items\", baseNamePrefix' = \"\"}, fieldNumber = FieldId {getFieldId = 1}, wireTag = WireTag {getWireTag = 10}, packedTag = Nothing, wireTagLength = 1, isPacked = False, isRequired = False, canRepeat = True, mightPack = False, typeCode = FieldType {getFieldType = 12}, typeName = Nothing, hsRawDefault = Nothing, hsDefault = Nothing}], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
instance P'.TextType Tuple where
tellT = P'.tellSubMessage
getT = P'.getSubMessage
instance P'.TextMsg Tuple where
textPut msg
= do
P'.tellT "items" (items msg)
textGet
= do
mods <- P'.sepEndBy (P'.choice [parse'items]) P'.spaces
Prelude'.return (Prelude'.foldl (\ v f -> f v) P'.defaultValue mods)
where
parse'items
= P'.try
(do
v <- P'.getT "items"
Prelude'.return (\ o -> o{items = P'.append (items o) v})) | Cahu/krpc-hs | src/PB/KRPC/Tuple.hs | gpl-3.0 | 3,434 | 0 | 19 | 743 | 799 | 411 | 388 | 66 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Genomics.Variants.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets a variant by ID. For the definitions of variants and other genomics
-- resources, see [Fundamentals of Google
-- Genomics](https:\/\/cloud.google.com\/genomics\/fundamentals-of-google-genomics)
--
-- /See:/ <https://cloud.google.com/genomics Genomics API Reference> for @genomics.variants.get@.
module Network.Google.Resource.Genomics.Variants.Get
(
-- * REST Resource
VariantsGetResource
-- * Creating a Request
, variantsGet
, VariantsGet
-- * Request Lenses
, vgXgafv
, vgUploadProtocol
, vgPp
, vgAccessToken
, vgUploadType
, vgBearerToken
, vgVariantId
, vgCallback
) where
import Network.Google.Genomics.Types
import Network.Google.Prelude
-- | A resource alias for @genomics.variants.get@ method which the
-- 'VariantsGet' request conforms to.
type VariantsGetResource =
"v1" :>
"variants" :>
Capture "variantId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Variant
-- | Gets a variant by ID. For the definitions of variants and other genomics
-- resources, see [Fundamentals of Google
-- Genomics](https:\/\/cloud.google.com\/genomics\/fundamentals-of-google-genomics)
--
-- /See:/ 'variantsGet' smart constructor.
data VariantsGet = VariantsGet'
{ _vgXgafv :: !(Maybe Xgafv)
, _vgUploadProtocol :: !(Maybe Text)
, _vgPp :: !Bool
, _vgAccessToken :: !(Maybe Text)
, _vgUploadType :: !(Maybe Text)
, _vgBearerToken :: !(Maybe Text)
, _vgVariantId :: !Text
, _vgCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'VariantsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vgXgafv'
--
-- * 'vgUploadProtocol'
--
-- * 'vgPp'
--
-- * 'vgAccessToken'
--
-- * 'vgUploadType'
--
-- * 'vgBearerToken'
--
-- * 'vgVariantId'
--
-- * 'vgCallback'
variantsGet
:: Text -- ^ 'vgVariantId'
-> VariantsGet
variantsGet pVgVariantId_ =
VariantsGet'
{ _vgXgafv = Nothing
, _vgUploadProtocol = Nothing
, _vgPp = True
, _vgAccessToken = Nothing
, _vgUploadType = Nothing
, _vgBearerToken = Nothing
, _vgVariantId = pVgVariantId_
, _vgCallback = Nothing
}
-- | V1 error format.
vgXgafv :: Lens' VariantsGet (Maybe Xgafv)
vgXgafv = lens _vgXgafv (\ s a -> s{_vgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
vgUploadProtocol :: Lens' VariantsGet (Maybe Text)
vgUploadProtocol
= lens _vgUploadProtocol
(\ s a -> s{_vgUploadProtocol = a})
-- | Pretty-print response.
vgPp :: Lens' VariantsGet Bool
vgPp = lens _vgPp (\ s a -> s{_vgPp = a})
-- | OAuth access token.
vgAccessToken :: Lens' VariantsGet (Maybe Text)
vgAccessToken
= lens _vgAccessToken
(\ s a -> s{_vgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
vgUploadType :: Lens' VariantsGet (Maybe Text)
vgUploadType
= lens _vgUploadType (\ s a -> s{_vgUploadType = a})
-- | OAuth bearer token.
vgBearerToken :: Lens' VariantsGet (Maybe Text)
vgBearerToken
= lens _vgBearerToken
(\ s a -> s{_vgBearerToken = a})
-- | The ID of the variant.
vgVariantId :: Lens' VariantsGet Text
vgVariantId
= lens _vgVariantId (\ s a -> s{_vgVariantId = a})
-- | JSONP
vgCallback :: Lens' VariantsGet (Maybe Text)
vgCallback
= lens _vgCallback (\ s a -> s{_vgCallback = a})
instance GoogleRequest VariantsGet where
type Rs VariantsGet = Variant
type Scopes VariantsGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/genomics",
"https://www.googleapis.com/auth/genomics.readonly"]
requestClient VariantsGet'{..}
= go _vgVariantId _vgXgafv _vgUploadProtocol
(Just _vgPp)
_vgAccessToken
_vgUploadType
_vgBearerToken
_vgCallback
(Just AltJSON)
genomicsService
where go
= buildClient (Proxy :: Proxy VariantsGetResource)
mempty
| rueshyna/gogol | gogol-genomics/gen/Network/Google/Resource/Genomics/Variants/Get.hs | mpl-2.0 | 5,328 | 0 | 18 | 1,327 | 862 | 502 | 360 | 121 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.TagManager.Accounts.Containers.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a Container.
--
-- /See:/ <https://developers.google.com/tag-manager/api/v1/ Tag Manager API Reference> for @tagmanager.accounts.containers.delete@.
module Network.Google.Resource.TagManager.Accounts.Containers.Delete
(
-- * REST Resource
AccountsContainersDeleteResource
-- * Creating a Request
, accountsContainersDelete
, AccountsContainersDelete
-- * Request Lenses
, acdContainerId
, acdAccountId
) where
import Network.Google.Prelude
import Network.Google.TagManager.Types
-- | A resource alias for @tagmanager.accounts.containers.delete@ method which the
-- 'AccountsContainersDelete' request conforms to.
type AccountsContainersDeleteResource =
"tagmanager" :>
"v1" :>
"accounts" :>
Capture "accountId" Text :>
"containers" :>
Capture "containerId" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Deletes a Container.
--
-- /See:/ 'accountsContainersDelete' smart constructor.
data AccountsContainersDelete = AccountsContainersDelete'
{ _acdContainerId :: !Text
, _acdAccountId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AccountsContainersDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acdContainerId'
--
-- * 'acdAccountId'
accountsContainersDelete
:: Text -- ^ 'acdContainerId'
-> Text -- ^ 'acdAccountId'
-> AccountsContainersDelete
accountsContainersDelete pAcdContainerId_ pAcdAccountId_ =
AccountsContainersDelete'
{ _acdContainerId = pAcdContainerId_
, _acdAccountId = pAcdAccountId_
}
-- | The GTM Container ID.
acdContainerId :: Lens' AccountsContainersDelete Text
acdContainerId
= lens _acdContainerId
(\ s a -> s{_acdContainerId = a})
-- | The GTM Account ID.
acdAccountId :: Lens' AccountsContainersDelete Text
acdAccountId
= lens _acdAccountId (\ s a -> s{_acdAccountId = a})
instance GoogleRequest AccountsContainersDelete where
type Rs AccountsContainersDelete = ()
type Scopes AccountsContainersDelete =
'["https://www.googleapis.com/auth/tagmanager.delete.containers"]
requestClient AccountsContainersDelete'{..}
= go _acdAccountId _acdContainerId (Just AltJSON)
tagManagerService
where go
= buildClient
(Proxy :: Proxy AccountsContainersDeleteResource)
mempty
| rueshyna/gogol | gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Delete.hs | mpl-2.0 | 3,353 | 0 | 14 | 727 | 386 | 232 | 154 | 63 | 1 |
module Problem019 where
main =
print $ length $ f (Day 1 1 1901 1) []
where f day@(Day d m y w) c
| d == 1 && m == 1 && y == 2000 = c
| d == 1 && w == 7 = f (next day) (day:c)
| otherwise = f (next day) c
data Day d = Day { day :: Int
, month :: Int
, year :: Int
, dayOfWeek :: Int
} deriving (Show)
next (Day d m y w)
| d == 30 && (m == 4 || m == 6 || m == 9 || m == 11) = Day 1 (m + 1) y w'
| d == 31 && (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10) = Day 1 (m + 1) y w'
| d == 31 && m == 12 = Day 1 1 (y + 1) w'
| d == 28 && m == 2 && not (leap y) = Day 1 3 y w'
| d == 29 && m == 2 = Day 1 3 y w'
| otherwise = Day (d + 1) m y w'
where w' = w `mod` 7 + 1
leap y
| y `rem` 4 /= 0 = False
| y `rem` 100 /= 0 = True
| y `rem` 400 /= 0 = False
| otherwise = True
| vasily-kartashov/playground | euler/problem-019.hs | apache-2.0 | 1,228 | 0 | 20 | 698 | 573 | 289 | 284 | 25 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="pt-BR">
<title>DOM XSS Active Scan Rule | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | 0xkasun/security-tools | src/org/zaproxy/zap/extension/domxss/resources/help_pt_BR/helpset_pt_BR.hs | apache-2.0 | 986 | 80 | 66 | 163 | 421 | 213 | 208 | -1 | -1 |
module CI.Docker.Parse
( getFroms
, getFrom
, Language.Dockerfile.parseString
, Language.Dockerfile.parseFile
, Language.Dockerfile.prettyPrint
, Language.Dockerfile.prettyPrintInstructionPos
, Language.Dockerfile.Dockerfile
, Language.Dockerfile.InstructionPos(..)
, Language.Dockerfile.Instruction(..)
, Language.Dockerfile.BaseImage(..)
, Language.Dockerfile.Tag
) where
import Data.Maybe
import Language.Dockerfile
getFroms :: Dockerfile -> [BaseImage]
getFroms = mapMaybe getFrom
getFrom :: InstructionPos -> Maybe BaseImage
getFrom (InstructionPos (From b) _ _) = Just b
getFrom _ = Nothing
| lancelet/bored-robot | src/CI/Docker/Parse.hs | apache-2.0 | 648 | 0 | 9 | 109 | 158 | 95 | 63 | 19 | 1 |
module Problem023 where
import Data.List
main = print $ fetch (descent 999999) [0..]
fetch is as = fetch' is as []
where fetch' [] as bs = reverse bs
fetch' (i:is) as bs = fetch' is as' (b:bs)
where b = as !! i
as' = take i as ++ drop (i + 1) as
descent x = descent' x 9 []
where descent' x 0 bs = reverse (x:bs)
descent' x i bs = descent' r (i - 1) (q:bs)
where (q, r) = x `quotRem` (factorial !! i)
factorial = 1 : scanl1 (*) [1..]
| vasily-kartashov/playground | euler/problem-024.hs | apache-2.0 | 551 | 0 | 12 | 214 | 260 | 136 | 124 | 13 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Data.FastPack.Get
( GetData (..)
, runFastUnpack
) where
import Data.FastPack.TH
import Data.FastPack.Types
import qualified Data.List as DL
import GHC.Err (error)
import Language.Haskell.TH.Syntax
data GetData
= GetNum PackNumType
| GetBs Int
deriving (Eq, Show)
runFastUnpack :: String -> String -> [GetData] -> Q Exp
runFastUnpack inputBS ctor xs = do
let (len, exs) = DL.mapAccumL (peekGetData "ptr") 0 xs
let tailexpr = construct ctor exs
pure $ LetE [ValD (TupP (DL.map mkVarP ["fp", "offset", "len"]))
(NormalB (AppE (mkVarE "Data.FastPack.Functions.bsInternals") (mkVarE inputBS))) []]
(CondE (InfixE (Just (mkVarE "len")) (mkVarE "Data.FastPack.Functions.numLess") (Just (mkLitIntE len)))
(AppE (mkVarE "Data.FastPack.Functions.left") (mkLitStrE "FastPack.getBenchWord"))
(AppE (mkVarE "Data.FastPack.Functions.right") (AppE (mkVarE "Data.FastPack.Functions.unsafeDupablePerformIO")
(AppE (AppE (mkVarE "Data.FastPack.Functions.withForeignPtr") (mkVarE "fp"))
(LamE [mkVarP "srcptr"]
(LetE [ValD (mkVarP "ptr") (NormalB (AppE (AppE plusPtrE (mkVarE "srcptr"))
(mkVarE "offset"))) []] tailexpr))))))
construct :: String -> [Exp] -> Exp
construct _ [] = error "construct"
construct ctor [x] = AppE (AppE fmapE (mkVarE ctor)) x
construct ctor (x:xs) =
let outer = AppE (AppE fmapE (mkConE ctor)) x in
mkInner outer xs
where
mkInner e [] = e
mkInner e (y:ys) =
let outer = AppE (AppE apE e) y in
mkInner outer ys
peekGetData :: String -> Int -> GetData -> (Int, Exp)
peekGetData pname offset getdata =
case getdata of
GetNum t -> (offset + sizePackNumType t, fmapEndian t (peekPtrE pname offset))
GetBs len -> (offset + len, peekByteStringE pname offset len)
fmapEndian :: PackNumType -> Exp -> Exp
fmapEndian t expr =
case t of
PackW8 -> expr
PackW16 end -> endian end "Data.FastPack.Functions.bswapW16"
PackW32 end -> endian end "Data.FastPack.Functions.bswapW32"
PackW64 end -> endian end "Data.FastPack.Functions.bswapW64"
where
endian end fname
| end == systemEndianness = expr
| otherwise = AppE (AppE fmapE (mkVarE fname)) expr
sizePackNumType :: PackNumType -> Int
sizePackNumType t =
case t of
PackW8 {}-> 1
PackW16 {} -> 2
PackW32 {} -> 4
PackW64 {} -> 8
peekByteStringE :: String -> Int -> Int -> Exp
peekByteStringE pname offset len =
AppE (AppE (AppE funcE (mkVarE pname)) (mkLitIntE offset)) (mkLitIntE len)
where
funcE = mkVarE "Data.FastPack.Functions.peekByteString"
peekPtrE :: String -> Int -> Exp
peekPtrE ptr offset =
AppE peekE (AppE castPtrE target)
where
target
| offset <= 0 = mkVarE ptr
| otherwise = AppE (AppE plusPtrE (mkVarE ptr)) (mkLitIntE offset)
peekE :: Exp
peekE = mkVarE "Data.FastPack.Functions.peek"
castPtrE :: Exp
castPtrE = mkVarE "Data.FastPack.Functions.castPtr"
plusPtrE :: Exp
plusPtrE = mkVarE "Data.FastPack.Functions.plusPtr"
fmapE :: Exp
fmapE = mkVarE "Data.FastPack.Functions.fmap"
apE :: Exp
apE = mkVarE "Data.FastPack.Functions.ap"
| erikd/fastpack | src/Data/FastPack/Get.hs | bsd-2-clause | 3,317 | 0 | 30 | 794 | 1,131 | 573 | 558 | 78 | 4 |
fromIntegral :: (Num b, Integral a) => a -> b
函数名 TypeClass type parameters return value type
| sharkspeed/dororis | languages/haskell/LYHGG/3-types-and-typeclasses/2-type-variables.hs | bsd-2-clause | 117 | 2 | 6 | 34 | 41 | 20 | 21 | -1 | -1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
module Duckling.Engine.Regex
( matchAll
, matchOnce
) where
import Text.Regex.Base (matchAll, matchOnce)
| rfranek/duckling | Duckling/Engine/Regex.hs | bsd-3-clause | 415 | 0 | 5 | 74 | 35 | 25 | 10 | 4 | 0 |
module Advent.Day3 where
import qualified Data.Text as T
import Data.List
import Text.Parsec
import Control.Lens
import qualified Data.MultiSet as MultiSet
import Control.Arrow ((>>>))
data Direction = North | South | East | West deriving (Eq, Show)
type House = (Int, Int)
parseDirections :: T.Text -> Either ParseError [Direction]
parseDirections =
parse directionsP ""
where
directionsP = many1 $ choice [n, s, e, w]
n = North <$ char '^'
s = South <$ char 'v'
e = East <$ char '>'
w = West <$ char '<'
totalDelivered :: [Direction] -> Int
totalDelivered = length . visits
visits :: [Direction] -> [House]
visits =
scanl move (0,0)
where
move = flip delta
delta North = _2 +~ 1
delta South = _2 +~ -1
delta West = _1 +~ -1
delta East = _1 +~ 1
visitedHouses :: [House] -> Int
visitedHouses =
MultiSet.fromList
>>> MultiSet.toOccurList
>>> length
split :: [a] -> ([a], [a])
split xs =
let ith = zip ([0..] :: [Int]) xs
(l, r) = partition (\(i,_) -> i `mod` 2 == 0) ith
strip = fmap snd
in (strip l, strip r)
totalVisitedWithRobo :: [Direction] -> Int
totalVisitedWithRobo =
split
>>> (\(l, r) -> visits l ++ visits r)
>>> visitedHouses
| screamish/adventofhaskellcode | src/Advent/Day3.hs | bsd-3-clause | 1,223 | 0 | 13 | 289 | 504 | 283 | 221 | 43 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Network.IRC.Bot.Part.Hello where
import Control.Monad.Trans (liftIO)
import Data.Maybe (fromMaybe)
import Data.ByteString (ByteString)
import Data.Monoid ((<>))
import Network.IRC.Bot.Log (LogLevel(Debug))
import Network.IRC.Bot.BotMonad (BotMonad(..), maybeZero)
import Network.IRC.Bot.Commands (PrivMsg(..),askSenderNickName, replyTo, sendCommand)
import Network.IRC.Bot.Parsec (botPrefix, parsecPart)
import System.Random (randomRIO)
import Text.Parsec (ParsecT, (<|>), string, try)
helloPart :: (BotMonad m) => m ()
helloPart = parsecPart helloCommand
helloCommand :: (BotMonad m) => ParsecT ByteString () m ()
helloCommand =
do try $ botPrefix >> string "hello"
logM Debug "helloPart"
target <- maybeZero =<< replyTo
logM Debug $ "target: " <> target
mNick <- askSenderNickName
let greetings = ["Hello", "Howdy", "Greetings", "Word up"]
n <- liftIO $ randomRIO (0, length greetings - 1)
let msg = greetings!!n <> ", " <> (fromMaybe "stranger" mNick)
sendCommand (PrivMsg Nothing [target] msg)
<|> return ()
| eigengrau/haskell-ircbot | Network/IRC/Bot/Part/Hello.hs | bsd-3-clause | 1,193 | 0 | 13 | 268 | 377 | 212 | 165 | 26 | 1 |
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses, FlexibleContexts #-}
-- This alternate, much simpler syntax, is aimed at unifying our current
-- interpreters, so as to lessen the code duplication in the tests.
-- It is not meant to be 'general', that is what Syntax is for.
module Language.Hakaru.Syntax2 where
-- We want to our own Real
import Prelude hiding (Real)
import Data.Dynamic (Typeable)
-- The syntax
import Language.Hakaru.Lambda
import qualified Language.Hakaru.Distribution as D
-- TODO: The pretty-printing semantics
-- import qualified Text.PrettyPrint as PP
-- The importance-sampling semantics
import qualified Language.Hakaru.Types as T
-- import qualified Data.Number.LogFloat as LF
import qualified Language.Hakaru.ImportanceSampler as IS
-- The Metropolis-Hastings semantics
import qualified Language.Hakaru.Metropolis as MH
-- The syntax
data Prob
data Measure a
data Dist a
-- A language of distributions
class Distrib d where
type Real d :: *
dirac :: Eq a => a -> d a
categorical :: Eq a => [(a, Real d)] -> d a
bern :: Real d -> d Bool
beta :: Real d -> Real d -> d Double
normal, uniform :: Real d -> Real d -> d (Real d)
poisson :: Real d -> d Integer
uniformD :: Integer -> Integer -> d Integer
-- Measures m 'over' distributions d
class (Monad m) => Meas m where
type D m :: * -> *
conditioned, unconditioned :: (Typeable a, Distrib (D m)) => D m a -> m a
instance Distrib T.Dist where
type Real T.Dist = Double
dirac = D.dirac
categorical = D.categorical
bern = D.bern
uniform = D.uniform
uniformD = D.uniformD
normal = D.normal
poisson = D.poisson
beta = D.beta
-- The importance-sampling semantics
instance Meas IS.Measure where
type D IS.Measure = T.Dist
conditioned = IS.conditioned
unconditioned = IS.unconditioned
-- The Metropolis-Hastings semantics
instance Meas MH.Measure where
type D MH.Measure = T.Dist
conditioned = MH.conditioned
unconditioned = MH.unconditioned
{-
-- TODO: The pretty-printing semantics
newtype PP a = PP (Int -> PP.Doc)
-- TODO: The initial (AST) "semantics"
data AST (repr :: * -> *) a where
eval :: (Mochastic repr) => AST repr a -> repr a
eval (Real x) = real x
eval (Unbool b x y) = unbool (eval b) (eval x) (eval y)
eval (Categorical xps) = categorical (eval xps)
-- ...
-}
| zaxtax/hakaru-old | Language/Hakaru/Syntax2.hs | bsd-3-clause | 2,351 | 0 | 11 | 480 | 480 | 275 | 205 | -1 | -1 |
module Day16 where
import Data.Bits
import Data.ByteString as BS
import qualified Data.List as List
import Data.List.Split
import Data.Monoid
import Data.Word
type BS = BS.ByteString
type BB = [Bool]
input = "11101000110010100"
len1 :: Int
len1 = 272
len2 :: Int
len2 = 35651584
toBS :: String -> BS
toBS = pack . List.map (\c -> if c == '1' then 1 else 0)
bs2bb :: BS -> BB
bs2bb = List.map (== 1) . BS.unpack
bb2str :: BB -> String
bb2str = List.map (\c -> if c then '1' else '0')
fromBS :: BS -> String
fromBS = List.map (\c -> if c == 1 then '1' else '0') . unpack
dragon :: BS -> BS
dragon s = s <> singleton 0 <> BS.reverse (BS.map (1 -) s)
produce :: BS -> Int -> BS
produce s len = BS.take len $ List.last $ List.unfoldr foo s
where
foo s = if BS.length s >= len then Nothing else Just (s', s')
where
s' = dragon s
merge :: BS -> BS
merge s = go s empty
where
go s acc = if BS.null s then acc
else go (BS.drop 2 s) (snoc acc z)
where
x = BS.head s
y = BS.head $ BS.tail s
z = if x == y then 1 else 0
checksum :: BB -> BB
checksum s
| odd (List.length s) = s
| otherwise = checksum $ List.map same $ chunksOf 2 s
where
same [a, b] = a == b
solve = bb2str . checksum . bs2bb. produce (toBS input)
| mbernat/aoc16-haskell | src/Day16.hs | bsd-3-clause | 1,302 | 0 | 11 | 359 | 592 | 318 | 274 | 41 | 3 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TemplateHaskell #-}
-- |
-- Module : Data.Array.Accelerate.CUDA.Analysis.Launch
-- Copyright : [2008..2014] Manuel M T Chakravarty, Gabriele Keller
-- [2009..2014] Trevor L. McDonell
-- License : BSD3
--
-- Maintainer : Trevor L. McDonell <tmcdonell@cse.unsw.edu.au>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
module Data.Array.Accelerate.CUDA.Analysis.Launch (
launchConfig, determineOccupancy
) where
-- friends
import Data.Array.Accelerate.AST
import Data.Array.Accelerate.Error
import Data.Array.Accelerate.Trafo
import Data.Array.Accelerate.Analysis.Type
import Data.Array.Accelerate.Analysis.Shape
-- library
import qualified Foreign.CUDA.Analysis as CUDA
import qualified Foreign.CUDA.Driver as CUDA
-- |
-- Determine kernel launch parameters for the given array computation (as well
-- as compiled function module). This consists of the thread block size, number
-- of blocks, and dynamically allocated shared memory (bytes), respectively.
--
-- For most operations, this selects the minimum block size that gives maximum
-- occupancy, and the grid size limited to the maximum number of physically
-- resident blocks. Hence, kernels may need to process multiple elements per
-- thread. Scan operations select the largest block size of maximum occupancy.
--
launchConfig
:: DelayedOpenAcc aenv a
-> CUDA.DeviceProperties -- the device being executed on
-> CUDA.Occupancy -- kernel occupancy information
-> ( Int -- block size
, Int -> Int -- number of blocks for input problem size (grid)
, Int ) -- shared memory (bytes)
launchConfig Delayed{} _ _ = $internalError "launchConfig" "encountered delayed array"
launchConfig (Manifest acc) dev occ =
let cta = CUDA.activeThreads occ `div` CUDA.activeThreadBlocks occ
maxGrid = CUDA.multiProcessorCount dev * CUDA.activeThreadBlocks occ
smem = sharedMem dev acc cta
in
(cta, \n -> maxGrid `min` gridSize dev acc n cta, smem)
-- |
-- Determine maximal occupancy statistics for the given kernel / device
-- combination.
--
determineOccupancy
:: DelayedOpenAcc aenv a
-> CUDA.DeviceProperties
-> CUDA.Fun -- corresponding __global__ entry function
-> Int -- maximum number of threads per block
-> IO CUDA.Occupancy
determineOccupancy Delayed{} _ _ _ = $internalError "determineOccupancy" "encountered delayed array"
determineOccupancy (Manifest acc) dev fn maxBlock = do
registers <- CUDA.requires fn CUDA.NumRegs
static_smem <- CUDA.requires fn CUDA.SharedSizeBytes -- static memory only
return . snd $ blockSize dev acc maxBlock registers (\threads -> static_smem + dynamic_smem threads)
where
dynamic_smem = sharedMem dev acc
-- |
-- Determine an optimal thread block size for a given array computation. Fold
-- requires blocks with a power-of-two number of threads. Scans select the
-- largest size thread block possible, because if only one thread block is
-- needed we can calculate the scan in a single pass, rather than three.
--
blockSize
:: CUDA.DeviceProperties
-> PreOpenAcc DelayedOpenAcc aenv a
-> Int -- maximum number of threads per block
-> Int -- number of registers used
-> (Int -> Int) -- shared memory as a function of thread block size (bytes)
-> (Int, CUDA.Occupancy)
blockSize dev acc lim regs smem =
CUDA.optimalBlockSizeBy dev (filter (<= lim) . strategy) (const regs) smem
where
strategy = case acc of
Fold _ _ _ -> CUDA.incPow2
Fold1 _ _ -> CUDA.incPow2
Scanl _ _ _ -> CUDA.incWarp
Scanl' _ _ _ -> CUDA.incWarp
Scanl1 _ _ -> CUDA.incWarp
Scanr _ _ _ -> CUDA.incWarp
Scanr' _ _ _ -> CUDA.incWarp
Scanr1 _ _ -> CUDA.incWarp
_ -> CUDA.decWarp
-- |
-- Determine the number of blocks of the given size necessary to process the
-- given array expression. This should understand things like #elements per
-- thread for the various kernels.
--
-- The 'size' parameter is typically the number of elements in the array, except
-- for the following instances:
--
-- * foldSeg: the number of segments; require one warp per segment
--
-- * fold: for multidimensional reductions, this is the size of the shape tail
-- for 1D reductions this is the total number of elements
--
gridSize :: CUDA.DeviceProperties -> PreOpenAcc DelayedOpenAcc aenv a -> Int -> Int -> Int
gridSize p acc@(FoldSeg _ _ _ _) size cta = split acc (size * CUDA.warpSize p) cta
gridSize p acc@(Fold1Seg _ _ _) size cta = split acc (size * CUDA.warpSize p) cta
gridSize _ acc@(Fold _ _ _) size cta = if preAccDim delayedDim acc == 0 then split acc size cta else max 1 size
gridSize _ acc@(Fold1 _ _) size cta = if preAccDim delayedDim acc == 0 then split acc size cta else max 1 size
gridSize _ acc size cta = split acc size cta
split :: acc aenv a -> Int -> Int -> Int
split acc size cta = (size `between` eltsPerThread acc) `between` cta
where
between arr n = 1 `max` ((n + arr - 1) `div` n)
eltsPerThread _ = 1
-- |
-- Analyse the given array expression, returning an estimate of dynamic shared
-- memory usage as a function of thread block size. This can be used by the
-- occupancy calculator to optimise kernel launch shape.
--
sharedMem :: CUDA.DeviceProperties -> PreOpenAcc DelayedOpenAcc aenv a -> Int -> Int
-- non-computation forms
sharedMem _ Alet{} _ = $internalError "sharedMem" "Let"
sharedMem _ Avar{} _ = $internalError "sharedMem" "Avar"
sharedMem _ Apply{} _ = $internalError "sharedMem" "Apply"
sharedMem _ Acond{} _ = $internalError "sharedMem" "Acond"
sharedMem _ Awhile{} _ = $internalError "sharedMem" "Awhile"
sharedMem _ Atuple{} _ = $internalError "sharedMem" "Atuple"
sharedMem _ Aprj{} _ = $internalError "sharedMem" "Aprj"
sharedMem _ Use{} _ = $internalError "sharedMem" "Use"
sharedMem _ Unit{} _ = $internalError "sharedMem" "Unit"
sharedMem _ Reshape{} _ = $internalError "sharedMem" "Reshape"
sharedMem _ Aforeign{} _ = $internalError "sharedMem" "Aforeign"
-- skeleton nodes
sharedMem _ Generate{} _ = 0
sharedMem _ Transform{} _ = 0
sharedMem _ Replicate{} _ = 0
sharedMem _ Slice{} _ = 0
sharedMem _ Map{} _ = 0
sharedMem _ ZipWith{} _ = 0
sharedMem _ Permute{} _ = 0
sharedMem _ Backpermute{} _ = 0
sharedMem _ Stencil{} _ = 0
sharedMem _ Stencil2{} _ = 0
sharedMem _ (Fold _ x _) blockDim = sizeOf (delayedExpType x) * blockDim
sharedMem _ (Scanl _ x _) blockDim = sizeOf (delayedExpType x) * blockDim
sharedMem _ (Scanr _ x _) blockDim = sizeOf (delayedExpType x) * blockDim
sharedMem _ (Scanl' _ x _) blockDim = sizeOf (delayedExpType x) * blockDim
sharedMem _ (Scanr' _ x _) blockDim = sizeOf (delayedExpType x) * blockDim
sharedMem _ (Fold1 _ a) blockDim = sizeOf (delayedAccType a) * blockDim
sharedMem _ (Scanl1 _ a) blockDim = sizeOf (delayedAccType a) * blockDim
sharedMem _ (Scanr1 _ a) blockDim = sizeOf (delayedAccType a) * blockDim
sharedMem p (FoldSeg _ x _ _) blockDim =
(blockDim `div` CUDA.warpSize p) * 8 + blockDim * sizeOf (delayedExpType x) -- TLM: why 8? I can't remember...
sharedMem p (Fold1Seg _ a _) blockDim =
(blockDim `div` CUDA.warpSize p) * 8 + blockDim * sizeOf (delayedAccType a)
| kumasento/accelerate-cuda | Data/Array/Accelerate/CUDA/Analysis/Launch.hs | bsd-3-clause | 7,775 | 0 | 12 | 1,937 | 1,865 | 970 | 895 | 99 | 9 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
module Lib
where
import qualified Data.ByteString.Char8 as BS
import Data.ByteString (ByteString)
import Data.Monoid
import Debug.Trace
findLT :: ByteString -> ByteString -> Int
findLT db w = lowerbound db w 0 top
where top = BS.length db
-- lb points to a word
-- return first word in [lb, ub) which is >= w
--
-- Uncomment the `tr $` in the definition of w' to
-- trace execution of the binary search.
lowerbound db w lb ub
| mid <= lb = linsearch db w lb ub
| w'end >= ub = linsearch db w lb ub
| w' < w = lowerbound db w w'end ub
| otherwise = lowerbound db w lb w'end
where
mid = backup db $ quot (lb + ub) 2
w' = {- tr $ -} takeWord db mid
w'end = mid + BS.length w' + 1
tr x = trace msg x
where msg = "lb: " ++ show (lb, lbw) ++ " mid: " ++ show (mid, x) ++ " ub: " ++ show (ub, ubw)
lbw = takeWord db lb
ubw = takeWord db ub
-- perform a linear search for w in the range [lb, ub)
linsearch db w lb ub
| lb >= ub = ub
| w' >= w = lb
| otherwise = linsearch db w (lb + BS.length w' + 1) ub
where w' = takeWord db lb
-- backup p to the beginning of a word
backup db p
| p <= 0 = 0
| BS.index db (p-1) == '\n' = p
| otherwise = backup db (p-1)
-- advance p to the next word
advance db top p
| p >= top = top
| BS.index db p == '\n' = p+1
| otherwise = advance db top (p+1)
-- extract the word at position p
-- assume p < length of db
takeWord db p = BS.takeWhile (/= '\n') $ BS.drop p db
test db w = do
let p = findLT db w
w' = takeWord db p
BS.putStrLn $ "lowerbound " <> w <> " -> " <> w' <> " at position: " <> BS.pack (show p)
| erantapaa/hoggle | src/Lib.hs | bsd-3-clause | 1,782 | 0 | 15 | 548 | 650 | 325 | 325 | 40 | 1 |
module EditorCommands where
import MT(MT(..))
import System(system,getArgs)
import IO(hPutStrLn
,hGetLine
,hClose
,hSetBuffering
,BufferMode(..)
,IOMode(..)
,Handle
,stdin
,stderr)
import Control.OldException as Exception
import Foreign
import Foreign.C
import Network hiding (listenOn,connectTo,accept)
import Network.BSD(getProtocolNumber
,getHostByName
,getHostByAddr
,hostAddress
,HostEntry(..))
import Network.Socket(Family(..)
,SocketType(..)
,SockAddr(..)
,SocketOption(..)
,socket
,sClose
,setSocketOption
,bindSocket
,listen
,connect
,socketToHandle
,iNADDR_ANY
,maxListenQueue
,inet_ntoa
,recv
,send
)
import qualified Network.Socket as Socket(accept)
data EditorCmds = EditorCmds
{ getEditorCmd :: IO String
, sendEditorMsg :: Bool -> String -> IO () -- False: just log,
-- True: make visible
, sendEditorModified :: String -> IO ()
}
-- default, useful for testing
commandlineCmds =
EditorCmds{getEditorCmd={- hSetBuffering stdin LineBuffering >> -} getLine
,sendEditorModified= \f->hPutStrLn stderr $ "modified: "++f
,sendEditorMsg= \d m-> if d then hPutStrLn stderr $ "message: "++m
else hPutStrLn stderr m}
-- refactorer is asynchronous subprocess of emacs,
-- which controls refactorers stdin and stdout;
-- seems to be relatively portable; emacs side will
-- need to interpret backchannel as editor-commands
emacsCmds =
EditorCmds{getEditorCmd=getLine
,sendEditorModified= \f->hPutStrLn stderr $ "modified: "++f
,sendEditorMsg= \d m-> if d then hPutStrLn stderr $ "message: "++m
else hPutStrLn stderr m}
-- refactorer is independent process started from vim;
-- we listen on socket for commands from vim (via refactoring
-- client), and answer with direct editor-commands, using
-- vim's clientserver functionality
mkVimCmds vimPath vimServerName = lift $ withSocketsDo $ do
s <- listenOn $ PortNumber 9000
return EditorCmds{
getEditorCmd=getInput s
,sendEditorModified= \f-> do
let cmd = vim_remote $
"call Haskell_refac_modified("++squote f++")"
hPutStrLn stderr cmd
system cmd
return ()
,sendEditorMsg= \b s-> do
let dialog = if b then "1" else "0"
cmd = vim_remote $
"call Haskell_refac_msg("++dialog++","++dquote s++")"
hPutStrLn stderr cmd
system cmd
return ()
}
where
-- which vim to call?? the caller will tell us,
-- but in case it's a gvim, we need to avoid pop-up dialogs
vim_remote cmd = vimPath++" --servername "++vimServerName
++" --remote-send \":silent "++cmd++" | silent redraw <cr>\""
squote s = "'"++concatMap del_quotes s++"'" -- no quotes or special chars in single quotes..:-((
dquote s = "'"++concatMap del_quotes s++"'" -- vim remote in win98 reads any " as comment start:-(
del_quotes c | c `elem` "'\"" = " "
| c == '\n' = "\\n"
| otherwise = [c]
getInput s = do
(h,host,portnr) <- accept s
hSetBuffering h LineBuffering
l <- hGetLine h
hPutStrLn h "<ack>"
putStrLn $ "SERVER: '"++l++"'"
-- hClose h
return l
clientCmd :: IO ()
clientCmd = withSocketsDo $ do
args <- getArgs
h <- connectTo "localhost" $ PortNumber 9000
hSetBuffering h LineBuffering
hPutStrLn stderr $ "(stderr) CLIENT SEND: "++unwords args
putStrLn $ "(stdout) CLIENT SEND: "++unwords args
hPutStrLn h $ unwords args
hGetLine h -- wait for acknowledgement
return ()
-- | Creates the server side socket which has been bound to the
-- specified port.
--
-- NOTE: To avoid the \"Address already in use\"
-- problems popped up several times on the GHC-Users mailing list we
-- set the 'ReuseAddr' socket option on the listening socket. If you
-- don't want this behaviour, please use the lower level
-- 'Network.Socket.listen' instead.
{-
foreign import stdcall unsafe "WSAGetLastError"
c_getLastError :: IO CInt
foreign import ccall unsafe "getWSErrorDescr"
c_getWSError :: CInt -> IO (Ptr CChar)
-}
listenOn :: PortID -- ^ Port Identifier
-> IO Socket -- ^ Connected Socket
listenOn (PortNumber port) = do
-- proto <- getProtocolNumber "tcp"
-- putStrLn $ "tcp: "++show proto
let proto = 6 -- bug in ghc's getProtocolNumber..
EditorCommands.bracketOnError
(Exception.catch (socket AF_INET Stream proto)
(\e-> do
-- errCode <- c_getLastError
-- perr <- c_getWSError errCode
-- err <- peekCString perr
-- putStrLn $ "WSAGetLastError: "++show errCode
throw e))
(sClose)
(\sock -> do
setSocketOption sock ReuseAddr 1
bindSocket sock (SockAddrInet port iNADDR_ANY)
listen sock maxListenQueue
return sock
)
bracketOnError
:: IO a -- ^ computation to run first (\"acquire resource\")
-> (a -> IO b) -- ^ computation to run last (\"release resource\")
-> (a -> IO c) -- ^ computation to run in-between
-> IO c -- returns the value from the in-between computation
bracketOnError before after thing =
block (do
a <- before
r <- Exception.catch
(unblock (thing a))
(\e -> do { after a; throw e })
return r
)
-- | Calling 'connectTo' creates a client side socket which is
-- connected to the given host and port. The Protocol and socket type is
-- derived from the given port identifier. If a port number is given
-- then the result is always an internet family 'Stream' socket.
connectTo :: HostName -- Hostname
-> PortID -- Port Identifier
-> IO Handle -- Connected Socket
connectTo hostname (PortNumber port) = do
-- proto <- getProtocolNumber "tcp"
-- putStrLn $ "tcp: "++show proto
let proto = 6 -- bug in ghc's getProtocolNumber..
EditorCommands.bracketOnError
(Exception.catch (socket AF_INET Stream proto)
(\e-> do
-- errCode <- c_getLastError
-- putStrLn $ "WSAGetLastError: "++show errCode
throw e))
(sClose) -- only done if there's an error
(\sock -> do
he <- getHostByName hostname
connect sock (SockAddrInet port (hostAddress he))
socketToHandle sock ReadWriteMode
)
-- -----------------------------------------------------------------------------
-- accept
-- | Accept a connection on a socket created by 'listenOn'. Normal
-- I\/O opertaions (see "System.IO") can be used on the 'Handle'
-- returned to communicate with the client.
-- Notice that although you can pass any Socket to Network.accept, only
-- sockets of either AF_UNIX or AF_INET will work (this shouldn't be a problem,
-- though). When using AF_UNIX, HostName will be set to the path of the socket
-- and PortNumber to -1.
--
accept :: Socket -- ^ Listening Socket
-> IO (Handle, -- Socket, -- should be: Handle,
HostName,
PortNumber) -- ^ Triple of: read\/write 'Handle' for
-- communicating with the client,
-- the 'HostName' of the peer socket, and
-- the 'PortNumber' of the remote connection.
accept sock {- @(MkSocket _ AF_INET _ _ _) -} = do
~(sock', (SockAddrInet port haddr)) <- Socket.accept sock
peer <- Exception.catchJust ioErrors
(do
(HostEntry peer _ _ _) <- getHostByAddr AF_INET haddr
return peer
)
(\e -> inet_ntoa haddr)
-- if getHostByName fails, we fall back to the IP address
-- return (sock', peer, port)
handle <- socketToHandle sock' ReadWriteMode
return (handle, peer, port)
| forste/haReFork | refactorer/EditorCommands.hs | bsd-3-clause | 8,081 | 69 | 23 | 2,322 | 1,475 | 820 | 655 | 146 | 2 |
module HTML where
mainHTML :: Int -> Int -> String -> String -- generate the main HTML file with a canvas of given width and height
mainHTML width height javascriptFileName =
"<!doctype html>\n"
++ "<html lang=\"en\">\n"
++ "<head charset=\"UTF-8\">\n"
++ "<title>This is my first canvas</title>\n"
++ "</head>\n"
++ "<body>\n"
++ " <div style=\"position: absolute; top: 50px; left: 50px\">\n"
++ " <canvas id=\"canvasOne\" width=\"" ++(show width) ++ "\" height=\""++(show height) ++"\">\n"
++ " Your browser does not support HTML5 canvas!\n"
++ " </canvas>\n"
++ " </div>\n"
++ "</body>\n"
++ "<script type=\"text/javascript\" src=\"" ++ javascriptFileName ++ ".js\"></script>\n"
++ "<script type=\"text/javascript\" src=\"actionList.js\"></script>\n"
++ "</html>\n"
mainJS :: Int -> String -- Return a JS that loops through the action list once in given number of milliseconds
mainJS milliSecondInterval =
"var theCanvas;\n"
++ "var theContext;\n"
++ "window.onload = function() {\n"
++ " canvasApp();\n"
++ "}\n"
++ "\n"
++ "function canvasApp() {\n"
++ " function drawScreen() {\n"
++ " theCanvas = document.getElementById(\"canvasOne\");\n"
++ " theContext = theCanvas.getContext(\"2d\");\n"
++ " if (!canvasSupport) {\n"
++ " alert(\"Could not get the canvas!\");\n"
++ " return;\n"
++ " }\n"
++ "\n"
++ " setInterval(animator, " ++ (show milliSecondInterval) ++ ");\n"
++ " }\n"
++ "\n"
++ " var ctr=0;\n"
++ " function animator(){\n"
++ " theContext.clearRect(0,0,500,500);\n"
++ " theCanvas.width=theCanvas.width;\n"
++ " theContext.lineWidth=2;\n"
++ " actionList[ctr](theContext);\n"
++ " theContext.stroke();\n"
++ " ctr++;\n"
++ " if(ctr==actionList.length)ctr=0;\n"
++ " \n"
++ " }\n"
++ "\n"
++ " function canvasSupport() {\n"
++ " return !!document.createElement(\"testCanvas\").getContext;\n"
++ " }\n"
++ "\n"
++ " drawScreen();\n"
++ "}\n"
generateHTML :: Int -> Int -> String -> IO ()
generateHTML width height htmlFileName = do
writeFile (htmlFileName ++ ".html") (mainHTML width height htmlFileName)
writeFile (htmlFileName ++ ".js") (mainJS 100)
| ckkashyap/Dancer | HTML.hs | bsd-3-clause | 2,332 | 0 | 41 | 543 | 378 | 191 | 187 | 60 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
module AuthServer where
import System.Random
import Control.Monad.Trans.Except
import Control.Monad.Trans.Resource
import Control.Monad.IO.Class
import Data.Aeson
import Data.Aeson.TH
import Data.Bson.Generic
import Data.List.Split
import Crypto.BCrypt
import Crypto.Cipher.AES
import Crypto.Random.DRBG
import Codec.Crypto.RSA
import GHC.Generics
import Network.Wai hiding(Response)
import Network.Wai.Handler.Warp
import Network.Wai.Logger
import Servant
import Servant.API
import Servant.Client
import System.IO
import System.Directory
import System.Environment (getArgs, getProgName, lookupEnv)
import System.Log.Formatter
import System.Log.Handler (setFormatter)
import System.Log.Handler.Simple
import System.Log.Handler.Syslog
import System.Log.Logger
import Data.Bson.Generic
import qualified Data.List as DL
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (catMaybes, fromJust)
import Data.Text (pack, unpack)
import Data.Time.Clock (UTCTime, getCurrentTime)
import Data.Time.Format (defaultTimeLocale, formatTime)
import Database.MongoDB
import Control.Monad (when)
import Network.HTTP.Client (newManager, defaultManagerSettings)
import Data.UUID.V1
import Data.UUID hiding (null)
import Data.Time
import Crypto.Types.PubKey.RSA
import OpenSSL.EVP.PKey
data Response = Response{
response :: String
} deriving (Eq, Show, Generic)
instance ToJSON Response
instance FromJSON Response
data KeyMapping = KeyMapping{
auth :: String,
publickey :: String,
privatekey :: String
}deriving (Eq, Show, Generic)
instance ToJSON KeyMapping
instance FromJSON KeyMapping
instance ToBSON KeyMapping
instance FromBSON KeyMapping
data User = User{
uusername :: String,
upassword :: String,
timeout :: String,
utoken :: String
} deriving (Eq, Show, Generic)
instance ToJSON User
instance FromJSON User
instance ToBSON User
instance FromBSON User
data Signin = Signin{
susername :: String,
spassword :: String
} deriving (Eq, Show, Generic)
instance ToJSON Signin
instance FromJSON Signin
instance ToBSON Signin
instance FromBSON Signin
type ApiHandler = ExceptT ServantErr IO
serverport :: String
serverport = "8082"
serverhost :: String
serverhost = "localhost"
type AuthApi =
"signin" :> ReqBody '[JSON] Signin :> Post '[JSON] User :<|>
"register" :> ReqBody '[JSON] Signin :> Post '[JSON] Response :<|>
"isvalid" :> ReqBody '[JSON] User :> Post '[JSON] Response :<|>
"extend" :> ReqBody '[JSON] User :> Post '[JSON] Response
authApi :: Proxy AuthApi
authApi = Proxy
server :: Server AuthApi
server =
login :<|>
newuser :<|>
checkToken :<|>
extendToken
authApp :: Application
authApp = serve authApi server
mkApp :: IO()
mkApp = do
run (read (serverport) ::Int) authApp
login :: Signin -> ApiHandler User
login signin@(Signin uName psswrd) = liftIO $ do
decryptedpassword <- decryptPassword psswrd
warnLog $ "Decrypted password: " ++ decryptedpassword ++ ", For user: " ++ uName
user <- withMongoDbConnection $ do
docs <- find (select ["_id" =: uName] "USER_RECORD") >>= drainCursor
return $ catMaybes $ DL.map (\ b -> fromBSON b :: Maybe Signin) docs
let thisuser = head $ user
let isvalid = checkPassword thisuser decryptedpassword
case isvalid of
False -> return (User "" "" "" "")
True -> do a <- nextUUID
let sessionKey = Data.UUID.toString $ fromJust a
currentTime <- getCurrentTime
currentZone <- getCurrentTimeZone
let fiveMinutes = 5 * 60
let newTime = addUTCTime fiveMinutes currentTime
let timeouter = utcToLocalTime currentZone newTime
let finaltimeout = show timeouter
warnLog $ "Storing Session key under key " ++ uName ++ "."
let session = (User (susername thisuser) "" finaltimeout sessionKey)
withMongoDbConnection $ upsert (select ["_id" =: uName] "SESSION_RECORD") $ toBSON session
warnLog $ "Session Successfully Stored."
return (session)
newuser :: Signin -> ApiHandler Response
newuser v@(Signin uName psswrd) = liftIO $ do
warnLog $ "Registering account: " ++ uName
warnLog $ "Encrypted password: " ++ psswrd
unencrypted <- decryptPassword psswrd
warnLog $ "Decrypted password: " ++ unencrypted
withMongoDbConnection $ do
docs <- findOne (select ["_id" =: uName] "USER_RECORD")
case docs of
Just _ -> return (Response "Account already exists")
Nothing -> liftIO $ do
hash <- hashPasswordUsingPolicy slowerBcryptHashingPolicy (BS.pack unencrypted)
let hashedpsswrd = BS.unpack $ fromJust hash
liftIO $ do
warnLog $ "Storing new user: " ++ uName ++ ". With hashed password: " ++ hashedpsswrd
let newaccount = (Signin uName hashedpsswrd)
withMongoDbConnection $ upsert (select ["_id" =: uName] "USER_RECORD") $ toBSON newaccount
return (Response "Success")
checkToken :: User -> ApiHandler Response
checkToken user = liftIO $ do
let uname = uusername user
let tokener = utoken user
warnLog $ "Searching for user: " ++ uname
session <- withMongoDbConnection $ do
docs <- find (select ["_id" =: uname] "SESSION_RECORD") >>= drainCursor
return $ catMaybes $ DL.map (\ b -> fromBSON b :: Maybe User) docs
warnLog $ "User found" ++ (show session)
let thissession = head $ session
let senttoken = utoken user
let storedtoken = utoken thissession
case senttoken == storedtoken of
False -> return (Response "Token not valid")
True -> do let tokentimeout = timeout thissession
currentTime <- getCurrentTime
currentZone <- getCurrentTimeZone
let localcurrentTime = show (utcToLocalTime currentZone currentTime)
let tokentimeoutsplit = splitOn " " $ tokentimeout
let localcurrentTimesplit = splitOn " " $ localcurrentTime
case ((tokentimeoutsplit !! 0) == (localcurrentTimesplit !! 0)) of
False -> return (Response "Current date not equal to token date")
True -> do let localcurrenthours = localcurrentTimesplit !! 1
let tokenhours = tokentimeoutsplit !! 1
let localhour = read(((splitOn ":" $ localcurrenthours) !! 0))
let tokenhour = read(((splitOn ":" $ tokenhours) !! 0))
let tokenminutes = read(((splitOn ":" $ tokenhours) !! 1))
let currentminutes = read(((splitOn ":" $ localcurrenthours) !! 1))
let totaltokenminutes = (tokenhour * 60) + tokenminutes
let totalcurrentminutes = (localhour * 60) + currentminutes
case totaltokenminutes > totalcurrentminutes of
False -> return (Response "Token Timeout")
True -> return (Response "Token is Valid")
extendToken :: User -> ApiHandler Response
extendToken user = liftIO $ do
currentTime <- getCurrentTime
currentZone <- getCurrentTimeZone
let fiveMinutes = 5 * 60
let newTime = addUTCTime fiveMinutes currentTime
let timeouter = utcToLocalTime currentZone newTime
let finaltimeout = show timeouter
warnLog $ "Storing Session key under key " ++ (uusername user) ++ "."
let session = (User (uusername user) "" finaltimeout (utoken user))
withMongoDbConnection $ upsert (select ["_id" =: (uusername user)] "SESSION_RECORD") $ toBSON session
warnLog $ "Session Successfully Stored."
return (Response "Success")
loadOrGenPublicKey :: ApiHandler Response
loadOrGenPublicKey = liftIO $ do
withMongoDbConnection $ do
let auth= "auth" :: String
docs <- find (select ["_id" =: auth] "KEY_RECORD") >>= drainCursor
let key = catMaybes $ DL.map (\ b -> fromBSON b :: Maybe KeyMapping) docs
case key of
[(KeyMapping _ publickey privatekey)]-> return (Response publickey)
[] -> liftIO $ do
r1 <- newGenIO :: IO HashDRBG
let (publickey,privatekey,g2) = generateKeyPair r1 1024
--let strPublicKey = fromPublicKey publickey
--let strPublicKey = (PublicKeyInfo (show(key_size publickey)) (show(n publickey)) (show(e publickey)))
--let strPrivateKey = fromPrivateKey privatekey
--let strPrivateKey = (PrivateKeyInfo (PublicKeyInfo (show(key_size (private_pub privatekey)))) (show(n (private_pub privatekey))) (show(e (private_pub privatekey))))
let key = (KeyMapping auth (show publickey) (show privatekey))
withMongoDbConnection $ upsert (select ["_id" =: auth] "KEY_RECORD") $ toBSON key
return (Response (show publickey))
decryptPassword :: String -> IO String
decryptPassword psswrd = do
withMongoDbConnection $ do
let auth= "auth" :: String
keypair <- find (select ["_id" =: auth] "KEY_RECORD") >>= drainCursor
let [(KeyMapping _ publickey privatekey)]= catMaybes $ DL.map (\ b -> fromBSON b :: Maybe KeyMapping) keypair
let prvKey = toPrivateKey privatekey
let password = C.pack psswrd
let decryptedpassword = decrypt privateKey password
return $ C.unpack decryptedpassword
checkPassword :: Signin -> String -> Bool
checkPassword val@(Signin _ hash) password = validatePassword (BS.pack hash) (BS.pack password)
-- | Logging stuff
iso8601 :: UTCTime -> String
iso8601 = formatTime defaultTimeLocale "%FT%T%q%z"
-- global loggin functions
debugLog, warnLog, errorLog :: String -> IO ()
debugLog = doLog debugM
warnLog = doLog warningM
errorLog = doLog errorM
noticeLog = doLog noticeM
doLog f s = getProgName >>= \ p -> do
t <- getCurrentTime
f p $ (iso8601 t) ++ " " ++ s
withLogging act = withStdoutLogger $ \aplogger -> do
lname <- getProgName
llevel <- logLevel
updateGlobalLogger lname
(setLevel $ case llevel of
"WARNING" -> WARNING
"ERROR" -> ERROR
_ -> DEBUG)
act aplogger
-- | Mongodb helpers...
-- | helper to open connection to mongo database and run action
-- generally run as follows:
-- withMongoDbConnection $ do ...
--
withMongoDbConnection :: Action IO a -> IO a
withMongoDbConnection act = do
ip <- mongoDbIp
port <- mongoDbPort
database <- mongoDbDatabase
pipe <- connect (host ip)
ret <- runResourceT $ liftIO $ access pipe master (pack database) act
Database.MongoDB.close pipe
return ret
-- | helper method to ensure we force extraction of all results
-- note how it is defined recursively - meaning that draincursor' calls itself.
-- the purpose is to iterate through all documents returned if the connection is
-- returning the documents in batch mode, meaning in batches of retruned results with more
-- to come on each call. The function recurses until there are no results left, building an
-- array of returned [Document]
drainCursor :: Cursor -> Action IO [Document]
drainCursor cur = drainCursor' cur []
where
drainCursor' cur res = do
batch <- nextBatch cur
if null batch
then return res
else drainCursor' cur (res ++ batch)
-- | Environment variable functions, that return the environment variable if set, or
-- default values if not set.
-- | The IP address of the mongoDB database that devnostics-rest uses to store and access data
mongoDbIp :: IO String
mongoDbIp = defEnv "MONGODB_IP" Prelude.id "127.0.0.1" True
-- | The port number of the mongoDB database that devnostics-rest uses to store and access data
mongoDbPort :: IO Integer
mongoDbPort = defEnv "MONGODB_PORT" read 27017 False -- 27017 is the default mongodb port
-- | The name of the mongoDB database that devnostics-rest uses to store and access data
mongoDbDatabase :: IO String
mongoDbDatabase = defEnv "MONGODB_DATABASE" Prelude.id "USEHASKELLDB" True
-- | Determines log reporting level. Set to "DEBUG", "WARNING" or "ERROR" as preferred. Loggin is
-- provided by the hslogger library.
logLevel :: IO String
logLevel = defEnv "LOG_LEVEL" Prelude.id "DEBUG" True
-- | Helper function to simplify the setting of environment variables
-- function that looks up environment variable and returns the result of running funtion fn over it
-- or if the environment variable does not exist, returns the value def. The function will optionally log a
-- warning based on Boolean tag
defEnv :: Show a
=> String -- Environment Variable name
-> (String -> a) -- function to process variable string (set as 'id' if not needed)
-> a -- default value to use if environment variable is not set
-> Bool -- True if we should warn if environment variable is not set
-> IO a
defEnv env fn def doWarn = lookupEnv env >>= \ e -> case e of
Just s -> return $ fn s
Nothing -> do
when doWarn (doLog warningM $ "Environment variable: " ++ env ++
" is not set. Defaulting to " ++ (show def))
return def
| Garygunn94/DFS | AuthServer/.stack-work/intero/intero15053Txj.hs | bsd-3-clause | 14,188 | 309 | 18 | 3,828 | 3,224 | 1,744 | 1,480 | 278 | 4 |
{-# LANGUAGE QuasiQuotes #-}
{-@ LIQUID "--no-termination "@-}
{-@ LIQUID "--diff "@-}
import LiquidHaskell
import Language.Haskell.Liquid.Prelude
data RBTree a = Leaf
| Node Color a !(RBTree a) !(RBTree a)
deriving (Show)
data Color = B -- ^ Black
| R -- ^ Red
deriving (Eq,Show)
---------------------------------------------------------------------------
-- | Add an element -------------------------------------------------------
---------------------------------------------------------------------------
[lq| add :: (Ord a) => a -> RBT a -> RBT a |]
add x s = makeBlack (ins x s)
[lq| ins :: (Ord a) => a -> t:RBT a -> {v: ARBTN a {bh t} | IsB t => isRB v} |]
ins kx Leaf = Node R kx Leaf Leaf
ins kx s@(Node B x l r) = case compare kx x of
LT -> let t = lbal x (ins kx l) r in t
GT -> let t = rbal x l (ins kx r) in t
EQ -> s
ins kx s@(Node R x l r) = case compare kx x of
LT -> Node R x (ins kx l) r
GT -> Node R x l (ins kx r)
EQ -> s
---------------------------------------------------------------------------
-- | Delete an element ----------------------------------------------------
---------------------------------------------------------------------------
[lq| remove :: (Ord a) => a -> RBT a -> RBT a |]
remove x t = makeBlack (del x t)
[lq| predicate HDel T V = bh V = if (isB T) then (bh T) - 1 else bh T |]
[lq| del :: (Ord a) => a -> t:RBT a -> {v:ARBT a | HDel t v && (isB t || isRB v)} |]
del x Leaf = Leaf
del x (Node _ y a b) = case compare x y of
EQ -> append y a b
LT -> case a of
Leaf -> Node R y Leaf b
Node B _ _ _ -> lbalS y (del x a) b
_ -> let t = Node R y (del x a) b in t
GT -> case b of
Leaf -> Node R y a Leaf
Node B _ _ _ -> rbalS y a (del x b)
_ -> Node R y a (del x b)
[lq| append :: y:a -> l:RBT {v:a | v < y} -> r:RBTN {v:a | y < v} {bh l} -> ARBT2 a l r |]
append :: a -> RBTree a -> RBTree a -> RBTree a
append _ Leaf r = r
append _ l Leaf = l
append piv (Node R lx ll lr) (Node R rx rl rr) = case append piv lr rl of
Node R x lr' rl' -> Node R x (Node R lx ll lr') (Node R rx rl' rr)
lrl -> Node R lx ll (Node R rx lrl rr)
append piv (Node B lx ll lr) (Node B rx rl rr) = case append piv lr rl of
Node R x lr' rl' -> Node R x (Node B lx ll lr') (Node B rx rl' rr)
lrl -> lbalS lx ll (Node B rx lrl rr)
append piv l@(Node B _ _ _) (Node R rx rl rr) = Node R rx (append piv l rl) rr
append piv l@(Node R lx ll lr) r@(Node B _ _ _) = Node R lx ll (append piv lr r)
---------------------------------------------------------------------------
-- | Delete Minimum Element -----------------------------------------------
---------------------------------------------------------------------------
[lq| deleteMin :: RBT a -> RBT a |]
deleteMin (Leaf) = Leaf
deleteMin (Node _ x l r) = makeBlack t
where
(_, t) = deleteMin' x l r
[lq| deleteMin' :: k:a -> l:RBT {v:a | v < k} -> r:RBTN {v:a | k < v} {bh l} -> (a, ARBT2 a l r) |]
deleteMin' k Leaf r = (k, r)
deleteMin' x (Node R lx ll lr) r = (k, Node R x l' r) where (k, l') = deleteMin' lx ll lr
deleteMin' x (Node B lx ll lr) r = (k, lbalS x l' r ) where (k, l') = deleteMin' lx ll lr
---------------------------------------------------------------------------
-- | Rotations ------------------------------------------------------------
---------------------------------------------------------------------------
[lq| lbalS :: k:a -> l:ARBT {v:a | v < k} -> r:RBTN {v:a | k < v} {1 + bh l} -> {v: ARBTN a {1 + bh l} | IsB r => isRB v} |]
lbalS k (Node R x a b) r = Node R k (Node B x a b) r
lbalS k l (Node B y a b) = let t = rbal k l (Node R y a b) in t
lbalS k l (Node R z (Node B y a b) c) = Node R y (Node B k l a) (rbal z b (makeRed c))
lbalS k l r = liquidError "nein"
[lq| rbalS :: k:a -> l:RBT {v:a | v < k} -> r:ARBTN {v:a | k < v} {bh l - 1} -> {v: ARBTN a {bh l} | IsB l => isRB v} |]
rbalS k l (Node R y b c) = Node R k l (Node B y b c)
rbalS k (Node B x a b) r = let t = lbal k (Node R x a b) r in t
rbalS k (Node R x a (Node B y b c)) r = Node R y (lbal x (makeRed a) b) (Node B k c r)
rbalS k l r = liquidError "nein"
[lq| lbal :: k:a -> l:ARBT {v:a | v < k} -> RBTN {v:a | k < v} {bh l} -> RBTN a {1 + bh l} |]
lbal k (Node R y (Node R x a b) c) r = Node R y (Node B x a b) (Node B k c r)
lbal k (Node R x a (Node R y b c)) r = Node R y (Node B x a b) (Node B k c r)
lbal k l r = Node B k l r
[lq| rbal :: k:a -> l:RBT {v:a | v < k} -> ARBTN {v:a | k < v} {bh l} -> RBTN a {1 + bh l} |]
rbal x a (Node R y b (Node R z c d)) = Node R y (Node B x a b) (Node B z c d)
rbal x a (Node R z (Node R y b c) d) = Node R y (Node B x a b) (Node B z c d)
rbal x l r = Node B x l r
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
[lq| type BlackRBT a = {v: RBT a | IsB v && bh v > 0} |]
[lq| makeRed :: l:BlackRBT a -> ARBTN a {bh l - 1} |]
makeRed (Node B x l r) = Node R x l r
makeRed _ = liquidError "nein"
[lq| makeBlack :: ARBT a -> RBT a |]
makeBlack Leaf = Leaf
makeBlack (Node _ x l r) = Node B x l r
---------------------------------------------------------------------------
-- | Specifications -------------------------------------------------------
---------------------------------------------------------------------------
-- | Ordered Red-Black Trees
[lq| type ORBT a = RBTree <{\root v -> v < root }, {\root v -> v > root}> a |]
-- | Red-Black Trees
[lq| type RBT a = {v: ORBT a | isRB v && isBH v } |]
[lq| type RBTN a N = {v: RBT a | bh v = N } |]
[lq| type ORBTL a X = RBT {v:a | v < X} |]
[lq| type ORBTG a X = RBT {v:a | X < v} |]
[lq| measure isRB :: RBTree a -> Prop
isRB (Leaf) = true
isRB (Node c x l r) = isRB l && isRB r && (c == R => (IsB l && IsB r))
|]
-- | Almost Red-Black Trees
[lq| type ARBT a = {v: ORBT a | isARB v && isBH v} |]
[lq| type ARBTN a N = {v: ARBT a | bh v = N } |]
[lq| measure isARB :: (RBTree a) -> Prop
isARB (Leaf) = true
isARB (Node c x l r) = (isRB l && isRB r)
|]
-- | Conditionally Red-Black Tree
[lq| type ARBT2 a L R = {v:ARBTN a {bh L} | (IsB L && IsB R) => isRB v} |]
-- | Color of a tree
[lq| measure col :: RBTree a -> Color
col (Node c x l r) = c
col (Leaf) = B
|]
[lq| measure isB :: RBTree a -> Prop
isB (Leaf) = false
isB (Node c x l r) = c == B
|]
[lq| predicate IsB T = not (col T == R) |]
-- | Black Height
[lq| measure isBH :: RBTree a -> Prop
isBH (Leaf) = true
isBH (Node c x l r) = (isBH l && isBH r && bh l = bh r)
|]
[lq| measure bh :: RBTree a -> Int
bh (Leaf) = 0
bh (Node c x l r) = bh l + if (c == R) then 0 else 1
|]
-- | Binary Search Ordering
[lq| data RBTree a <l :: a -> a -> Prop, r :: a -> a -> Prop>
= Leaf
| Node (c :: Color)
(key :: a)
(left :: RBTree <l, r> (a <l key>))
(right :: RBTree <l, r> (a <r key>))
|]
-------------------------------------------------------------------------------
-- Auxiliary Invariants -------------------------------------------------------
-------------------------------------------------------------------------------
[lq| predicate Invs V = Inv1 V && Inv2 V && Inv3 V |]
[lq| predicate Inv1 V = (isARB V && IsB V) => isRB V |]
[lq| predicate Inv2 V = isRB v => isARB v |]
[lq| predicate Inv3 V = 0 <= bh v |]
[lq| invariant {v: Color | v = R || v = B} |]
[lq| invariant {v: RBTree a | Invs v} |]
[lq| inv :: RBTree a -> {v:RBTree a | Invs v} |]
inv Leaf = Leaf
inv (Node c x l r) = Node c x (inv l) (inv r)
[lq| invc :: t:RBTree a -> {v:RBTree a | Invs t } |]
invc Leaf = Leaf
invc (Node c x l r) = Node c x (invc l) (invc r)
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/RBTree.hs | bsd-3-clause | 8,985 | 21 | 17 | 3,132 | 2,435 | 1,219 | 1,216 | 113 | 7 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
module Lib
( startApp
) where
import Control.Monad.Trans.Either
import Data.Aeson
import Data.Aeson.TH
import Data.Text as T
import Network.Wai
import Network.Wai.Handler.Warp
import Servant
import Debug.Trace
data User = User
{ userId :: Int
, userFirstName :: String
, userLastName :: String
} deriving (Eq, Show)
data GradleDependencySpec = GradleDependencySpec
{ gDepName :: T.Text
, gDepDesc :: Maybe T.Text
, gDepConfigs :: [Configuration]
, gDepVersion :: Maybe T.Text -- FIXME: SemVer?
} deriving (Eq, Show)
instance FromJSON GradleDependencySpec where
parseJSON (Object o) = GradleDependencySpec
<$> o .: "name"
<*> o .:? "description"
<*> o .: "configurations"
<*> o .:? "version"
data Configuration = Configuration
{ confName :: T.Text
, confDesc :: T.Text
, confDeps :: Maybe [Dependency]
-- , confModuleInsights :: Maybe [ModuleInsights] ignore for now
} deriving (Eq, Show)
instance FromJSON Configuration where
parseJSON (Object o) = Configuration
<$> o .: "name"
<*> o .: "description"
<*> o .: "dependencies"
data Dependency = Dependency
{ depModule :: T.Text
, depName :: T.Text
, depResolvable :: Bool
, depHasConflict :: Maybe Bool
, depAlreadyRendered :: Bool
, depChildren :: Maybe [Dependency]
} deriving (Eq, Show)
instance FromJSON Dependency where
parseJSON (Object o) = Dependency
<$> o .: "module"
<*> o .: "name"
<*> o .: "resolvable"
<*> o .:? "hasConfict"
<*> o .: "alreadyRendered"
<*> o .: "children"
$(deriveJSON defaultOptions ''User)
type API = "dependencies" :> Capture "appName" T.Text
:> Capture "version" T.Text
:> ReqBody '[JSON] GradleDependencySpec
:> Post '[JSON] T.Text
startApp :: IO ()
startApp = run 8080 app
app :: Application
app = serve api server
api :: Proxy API
api = Proxy
server :: Server API
server = deps
users :: [User]
users = [ User 1 "Isaac" "Newton"
, User 2 "Albert" "Einstein"
]
deps :: T.Text -> T.Text-> GradleDependencySpec -> EitherT ServantErr IO T.Text
deps appName version gdeps= traceShow (show gdeps) $ return appName
| vulgr/vulgr-simple | src/Lib.hs | bsd-3-clause | 2,493 | 0 | 17 | 698 | 668 | 366 | 302 | 75 | 1 |
{- |
Module : Database.HDBC.Sqlite3
Copyright : Copyright (C) 2005-2011 John Goerzen
License : BSD3
Maintainer : John Goerzen <jgoerzen@complete.org>
Stability : provisional
Portability: portable
HDBC driver interface for Sqlite 3.x.
Written by John Goerzen, jgoerzen\@complete.org
-}
module Database.HDBC.Sqlite3
(
-- * Sqlite3 Basics
connectSqlite3, connectSqlite3Raw, Connection(), setBusyTimeout,
-- * Sqlite3 Error Consts
module Database.HDBC.Sqlite3.Consts
)
where
import Database.HDBC.Sqlite3.Connection(connectSqlite3, connectSqlite3Raw, Connection())
import Database.HDBC.Sqlite3.ConnectionImpl(setBusyTimeout)
import Database.HDBC.Sqlite3.Consts
| hdbc/hdbc-sqlite3 | Database/HDBC/Sqlite3.hs | bsd-3-clause | 714 | 0 | 6 | 123 | 75 | 52 | 23 | 9 | 0 |
--------------------------------------------------------------------------------
{-# LANGUAGE ExistentialQuantification #-}
module Hakyll.Web.Template.Context
( ContextField (..)
, Context (..)
, field
, constField
, listField
, functionField
, mapContext
, defaultContext
, bodyField
, metadataField
, urlField
, pathField
, titleField
, dateField
, dateFieldWith
, getItemUTC
, modificationTimeField
, modificationTimeFieldWith
, teaserField
, missingField
) where
--------------------------------------------------------------------------------
import Control.Applicative (Alternative (..), (<$>))
import Control.Monad (msum)
import Data.List (intercalate)
import qualified Data.Map as M
import Data.Monoid (Monoid (..))
import Data.Time.Clock (UTCTime (..))
import Data.Time.Format (formatTime, parseTime)
import System.FilePath (takeBaseName, takeFileName)
import System.Locale (TimeLocale, defaultTimeLocale)
--------------------------------------------------------------------------------
import Hakyll.Core.Compiler
import Hakyll.Core.Compiler.Internal
import Hakyll.Core.Identifier
import Hakyll.Core.Item
import Hakyll.Core.Metadata
import Hakyll.Core.Provider
import Hakyll.Core.Util.String (splitAll, needlePrefix)
import Hakyll.Web.Html
--------------------------------------------------------------------------------
-- | Mostly for internal usage
data ContextField
= StringField String
| forall a. ListField (Context a) [Item a]
--------------------------------------------------------------------------------
newtype Context a = Context
{ unContext :: String -> Item a -> Compiler ContextField
}
--------------------------------------------------------------------------------
instance Monoid (Context a) where
mempty = missingField
mappend (Context f) (Context g) = Context $ \k i -> f k i <|> g k i
--------------------------------------------------------------------------------
field' :: String -> (Item a -> Compiler ContextField) -> Context a
field' key value = Context $ \k i -> if k == key then value i else empty
--------------------------------------------------------------------------------
field :: String -> (Item a -> Compiler String) -> Context a
field key value = field' key (fmap StringField . value)
--------------------------------------------------------------------------------
constField :: String -> String -> Context a
constField key = field key . const . return
--------------------------------------------------------------------------------
listField :: String -> Context a -> Compiler [Item a] -> Context b
listField key c xs = field' key $ \_ -> fmap (ListField c) xs
--------------------------------------------------------------------------------
functionField :: String -> ([String] -> Item a -> Compiler String) -> Context a
functionField name value = Context $ \k i -> case words k of
[] -> empty
(n : args)
| n == name -> StringField <$> value args i
| otherwise -> empty
--------------------------------------------------------------------------------
mapContext :: (String -> String) -> Context a -> Context a
mapContext f (Context c) = Context $ \k i -> do
fld <- c k i
case fld of
StringField str -> return $ StringField (f str)
ListField _ _ -> fail $
"Hakyll.Web.Template.Context.mapContext: " ++
"can't map over a ListField!"
--------------------------------------------------------------------------------
defaultContext :: Context String
defaultContext =
bodyField "body" `mappend`
metadataField `mappend`
urlField "url" `mappend`
pathField "path" `mappend`
titleField "title" `mappend`
missingField
--------------------------------------------------------------------------------
teaserSeparator :: String
teaserSeparator = "<!--more-->"
--------------------------------------------------------------------------------
bodyField :: String -> Context String
bodyField key = field key $ return . itemBody
--------------------------------------------------------------------------------
-- | Map any field to its metadata value, if present
metadataField :: Context a
metadataField = Context $ \k i -> do
value <- getMetadataField (itemIdentifier i) k
maybe empty (return . StringField) value
--------------------------------------------------------------------------------
-- | Absolute url to the resulting item
urlField :: String -> Context a
urlField key = field key $
fmap (maybe empty toUrl) . getRoute . itemIdentifier
--------------------------------------------------------------------------------
-- | Filepath of the underlying file of the item
pathField :: String -> Context a
pathField key = field key $ return . toFilePath . itemIdentifier
--------------------------------------------------------------------------------
-- | This title field takes the basename of the underlying file by default
titleField :: String -> Context a
titleField = mapContext takeBaseName . pathField
--------------------------------------------------------------------------------
-- | When the metadata has a field called @published@ in one of the
-- following formats then this function can render the date.
--
-- * @Mon, 06 Sep 2010 00:01:00 +0000@
--
-- * @Mon, 06 Sep 2010 00:01:00 UTC@
--
-- * @Mon, 06 Sep 2010 00:01:00@
--
-- * @2010-09-06T00:01:00+0000@
--
-- * @2010-09-06T00:01:00Z@
--
-- * @2010-09-06T00:01:00@
--
-- * @2010-09-06 00:01:00+0000@
--
-- * @2010-09-06 00:01:00@
--
-- * @September 06, 2010 00:01 AM@
--
-- Following date-only formats are supported too (@00:00:00@ for time is
-- assumed)
--
-- * @2010-09-06@
--
-- * @September 06, 2010@
--
-- Alternatively, when the metadata has a field called @path@ in a
-- @folder/yyyy-mm-dd-title.extension@ format (the convention for pages)
-- and no @published@ metadata field set, this function can render
-- the date.
dateField :: String -- ^ Key in which the rendered date should be placed
-> String -- ^ Format to use on the date
-> Context a -- ^ Resulting context
dateField = dateFieldWith defaultTimeLocale
--------------------------------------------------------------------------------
-- | This is an extended version of 'dateField' that allows you to
-- specify a time locale that is used for outputting the date. For more
-- details, see 'dateField'.
dateFieldWith :: TimeLocale -- ^ Output time locale
-> String -- ^ Destination key
-> String -- ^ Format to use on the date
-> Context a -- ^ Resulting context
dateFieldWith locale key format = field key $ \i -> do
time <- getItemUTC locale $ itemIdentifier i
return $ formatTime locale format time
--------------------------------------------------------------------------------
-- | Parser to try to extract and parse the time from the @published@
-- field or from the filename. See 'dateField' for more information.
-- Exported for user convenience.
getItemUTC :: MonadMetadata m
=> TimeLocale -- ^ Output time locale
-> Identifier -- ^ Input page
-> m UTCTime -- ^ Parsed UTCTime
getItemUTC locale id' = do
metadata <- getMetadata id'
let tryField k fmt = M.lookup k metadata >>= parseTime' fmt
fn = takeFileName $ toFilePath id'
maybe empty' return $ msum $
[tryField "published" fmt | fmt <- formats] ++
[tryField "date" fmt | fmt <- formats] ++
[parseTime' "%Y-%m-%d" $ intercalate "-" $ take 3 $ splitAll "-" fn]
where
empty' = fail $ "Hakyll.Web.Template.Context.getItemUTC: " ++
"could not parse time for " ++ show id'
parseTime' = parseTime locale
formats =
[ "%a, %d %b %Y %H:%M:%S %Z"
, "%Y-%m-%dT%H:%M:%S%Z"
, "%Y-%m-%d %H:%M:%S%Z"
, "%Y-%m-%d"
, "%B %e, %Y %l:%M %p"
, "%B %e, %Y"
, "%b %d, %Y"
]
--------------------------------------------------------------------------------
modificationTimeField :: String -- ^ Key
-> String -- ^ Format
-> Context a -- ^ Resuting context
modificationTimeField = modificationTimeFieldWith defaultTimeLocale
--------------------------------------------------------------------------------
modificationTimeFieldWith :: TimeLocale -- ^ Time output locale
-> String -- ^ Key
-> String -- ^ Format
-> Context a -- ^ Resulting context
modificationTimeFieldWith locale key fmt = field key $ \i -> do
provider <- compilerProvider <$> compilerAsk
let mtime = resourceModificationTime provider $ itemIdentifier i
return $ formatTime locale fmt mtime
--------------------------------------------------------------------------------
-- | A context with "teaser" key which contain a teaser of the item.
-- The item is loaded from the given snapshot (which should be saved
-- in the user code before any templates are applied).
teaserField :: String -- ^ Key to use
-> Snapshot -- ^ Snapshot to load
-> Context String -- ^ Resulting context
teaserField key snapshot = field key $ \item -> do
body <- itemBody <$> loadSnapshot (itemIdentifier item) snapshot
case needlePrefix teaserSeparator body of
Nothing -> fail $
"Hakyll.Web.Template.Context: no teaser defined for " ++
show (itemIdentifier item)
Just t -> return t
--------------------------------------------------------------------------------
missingField :: Context a
missingField = Context $ \k i -> fail $
"Missing field $" ++ k ++ "$ in context for item " ++
show (itemIdentifier i)
| freizl/freizl.github.com-old | src/Hakyll/Web/Template/Context.hs | bsd-3-clause | 10,303 | 0 | 15 | 2,414 | 1,770 | 961 | 809 | 152 | 2 |
{-# LANGUAGE CPP, OverloadedStrings, TypeSynonymInstances,StandaloneDeriving,DeriveDataTypeable,ScopedTypeVariables, MultiParamTypeClasses, PatternGuards, NamedFieldPuns, TupleSections, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- |
-- Module : Language.Haskell.BuildWrapper.GHC
-- Copyright : (c) JP Moresmau 2011
-- License : BSD3
--
-- Maintainer : jpmoresmau@gmail.com
-- Stability : beta
-- Portability : portable
--
-- Load relevant module in the GHC AST and get GHC messages and thing at point info. Also use the GHC lexer for syntax highlighting.
module Language.Haskell.BuildWrapper.GHC where
import Language.Haskell.BuildWrapper.Base hiding (Target,ImportExportType(..))
import Language.Haskell.BuildWrapper.GHCStorage
import Prelude hiding (readFile, writeFile)
import Control.Applicative ((<$>))
import Data.Char
import Data.Generics hiding (Fixity, typeOf, empty)
import Data.Maybe
import Data.Monoid
import Data.Aeson
import Data.IORef
import qualified Data.List as List
import Data.Ord (comparing)
import qualified Data.Text as T
import qualified Data.Map as DM
import qualified Data.Set as DS
import qualified Data.HashMap.Lazy as HM
import qualified Data.ByteString.Lazy as BS
import qualified Data.ByteString.Lazy.Char8 as BSC
import DynFlags
import ErrUtils
( ErrMsg(..), WarnMsg, mkPlainErrMsg,Messages,ErrorMessages,WarningMessages
#if __GLASGOW_HASKELL__ > 704
, MsgDoc
#else
, Message
#endif
)
import GHC
import GHC.Paths ( libdir )
import HscTypes (srcErrorMessages, SourceError, GhcApiError, extendInteractiveContext, hsc_IC)
import Outputable
import FastString (FastString,unpackFS,concatFS,fsLit,mkFastString, lengthFS)
import Lexer hiding (loc)
import Bag
import Linker
import RtClosureInspect
#if __GLASGOW_HASKELL__ >= 707
import ConLike
import PatSyn (patSynType)
#endif
import GhcMonad
import Id
import Var hiding (varName)
import UniqSupply
import PprTyThing
#if __GLASGOW_HASKELL__ >= 702
import SrcLoc
#endif
#if __GLASGOW_HASKELL__ >= 610
import StringBuffer
#endif
import System.FilePath
import qualified MonadUtils as GMU
import Name (isTyVarName,isDataConName,isVarName,isTyConName, mkInternalName)
import Control.Monad (when, liftM, liftM2)
import qualified Data.Vector as V (foldr)
import Module (moduleNameFS)
-- import System.Time (getClockTime, diffClockTimes, timeDiffToString)
import System.IO (hFlush, stdout, stderr)
import System.Directory (getModificationTime)
#if __GLASGOW_HASKELL__ < 706
import System.Time (ClockTime(TOD))
#else
import Data.Time.Clock (UTCTime(UTCTime))
import Data.Time.Calendar (Day(ModifiedJulianDay))
#endif
import Control.Exception (SomeException)
import Exception (gtry)
import Control.Arrow ((&&&))
import Unsafe.Coerce (unsafeCoerce)
import OccName (mkOccName, varName)
-- | a function taking the file name and typechecked module as parameters
type GHCApplyFunction a=FilePath -> TypecheckedModule -> Ghc a
-- | get the GHC typechecked AST
getAST :: FilePath -- ^ the source file
-> FilePath -- ^ the base directory
-> String -- ^ the module name
-> [String] -- ^ the GHC options
-> IO (OpResult (Maybe TypecheckedSource))
getAST fp base_dir modul opts=do
(a,n)<-withASTNotes (\_ -> return . tm_typechecked_source) id base_dir (SingleFile fp modul) opts
return (listToMaybe a,n)
-- | perform an action on the GHC Typechecked module
withAST :: (TypecheckedModule -> Ghc a) -- ^ the action
-> FilePath -- ^ the source file
-> FilePath -- ^ the base directory
-> String -- ^ the module name
-> [String] -- ^ the GHC options
-> IO (Maybe a)
withAST f fp base_dir modul options= do
(a,_)<-withASTNotes (const f) id base_dir (SingleFile fp modul) options
return $ listToMaybe a
-- | perform an action on the GHC JSON AST
withJSONAST :: (Value -> IO a) -- ^ the action
-> FilePath -- ^ the source file
-> FilePath -- ^ the base directory
-> String -- ^ the module name
-> [String] -- ^ the GHC options
-> IO (Maybe a)
withJSONAST f fp base_dir modul options=do
mv<-readGHCInfo fp
case mv of
Just v-> fmap Just (f v)
Nothing->do
mv2<-withAST gen fp base_dir modul options
case mv2 of
Just v2->fmap Just (f v2)
Nothing-> return Nothing
where gen tc=do
df<-getSessionDynFlags
env<-getSession
GMU.liftIO $ generateGHCInfo df env tc
-- | the main method loading the source contents into GHC
withASTNotes :: GHCApplyFunction a -- ^ the final action to perform on the result
-> (FilePath -> FilePath) -- ^ transform given file path to find bwinfo path
-> FilePath -- ^ the base directory
-> LoadContents -- ^ what to load
-> [String] -- ^ the GHC options
-> IO (OpResult [a])
withASTNotes f ff base_dir contents =initGHC (ghcWithASTNotes f ff base_dir contents True)
-- | init GHC session
initGHC :: Ghc a
-> [String] -- ^ the GHC options
-> IO a
initGHC f options= do
-- http://hackage.haskell.org/trac/ghc/ticket/7380#comment:1 : -O2 is removed from the options
let cleaned=filter (not . List.isInfixOf "-O") options
let lflags=map noLoc cleaned
-- print cleaned
(_leftovers, _) <- parseStaticFlags lflags
runGhc (Just libdir) $ do
flg <- getSessionDynFlags
(flg', _, _) <- parseDynamicFlags flg _leftovers
GHC.defaultCleanupHandler flg' $ do
-- our options here
-- if we use OneShot, we need the other modules to be built
-- so we can't use hscTarget = HscNothing
-- and it takes a while to actually generate the o and hi files for big modules
-- if we use CompManager, it's slower for modules with lots of dependencies but we can keep hscTarget= HscNothing which makes it better for bigger modules
-- we use target interpreted so that it works with TemplateHaskell
-- LinkInMemory needed for evaluation after reload
setSessionDynFlags flg' {hscTarget = HscInterpreted, ghcLink = LinkInMemory , ghcMode = CompManager}
f
-- | run a GHC action and get results with notes
ghcWithASTNotes ::
GHCApplyFunction a -- ^ the final action to perform on the result
-> (FilePath -> FilePath) -- ^ transform given file path to find bwinfo path
-> FilePath -- ^ the base directory
-> LoadContents -- ^ what to load
-> Bool -- ^ add the target?
-> Ghc (OpResult [a])
ghcWithASTNotes f ff base_dir contents shouldAddTargets= do
ref <- GMU.liftIO $ newIORef []
cflg <- getSessionDynFlags
#if __GLASGOW_HASKELL__ > 704
setSessionDynFlags cflg {log_action = logAction ref }
#else
setSessionDynFlags cflg {log_action = logAction ref cflg }
#endif
-- $ dopt_set (flg' { ghcLink = NoLink , ghcMode = CompManager }) Opt_ForceRecomp
let fps=getLoadFiles contents
when shouldAddTargets
(mapM_ (\(fp,_)-> addTarget Target { targetId = TargetFile fp Nothing, targetAllowObjCode = False, targetContents = Nothing }) fps)
--c1<-GMU.liftIO getClockTime
-- let howMuch=case contents of
-- SingleFile{lmModule=m}->LoadUpTo $ mkModuleName m
-- MultipleFile{}->LoadAllTargets
let howMuch=LoadAllTargets
-- GMU.liftIO $ putStrLn "Loading..."
sf<-load howMuch
`gcatch` (\(e :: SourceError) -> handle_error ref e)
`gcatch` (\(ae :: GhcApiError) -> do
dumpError ref contents ae
return Failed)
`gcatch` (\(se :: SomeException) -> do
dumpError ref contents se
return Failed)
-- GMU.liftIO $ putStrLn "Loaded..."
--(warns, errs) <- GMU.liftIO $ readIORef ref
--let notes = ghcMessagesToNotes base_dir (warns, errs)
--c2<-GMU.liftIO getClockTime
--GMU.liftIO $ putStrLn ("load all targets: " ++ (timeDiffToString $ diffClockTimes c2 c1))
-- GMU.liftIO $ print fps
a<-case sf of
Failed-> return []
_ -> catMaybes <$> mapM (\(fp,m)->(do
modSum <- getModSummary $ mkModuleName m
Just <$> workOnResult f fp modSum)
`gcatch` (\(se :: SourceError) -> do
dumpError ref contents se
return Nothing)
`gcatch` (\(ae :: GhcApiError) -> do
dumpError ref contents ae
return Nothing)
`gcatch` (\(se :: SomeException) -> do
dumpError ref contents se
return Nothing)
) fps
notes <- GMU.liftIO $ readIORef ref
#if __GLASGOW_HASKELL__ < 702
warns <- getWarnings
df <- getSessionDynFlags
return (a,List.nub $ notes ++ reverse (ghcMessagesToNotes df base_dir (warns, emptyBag)))
#else
return (a,List.nub notes)
#endif
where
processError :: LoadContents -> String -> Bool
processError MultipleFile{} "Module not part of module graph"=False -- we ignore the error when we process several files and some we can't find
processError _ _=True
dumpError :: (Show a)=> IORef [BWNote] -> LoadContents -> a -> Ghc ()
dumpError ref conts ae= when (processError conts (show ae)) (do
GMU.liftIO $ print conts
GMU.liftIO $ print ae
case conts of
(SingleFile fp _)->do
let relfp=makeRelative base_dir $ normalise fp
let notes=[BWNote BWError (show ae) (BWLocation relfp 1 1 1 1)]
GMU.liftIO $ modifyIORef ref $
\ ns -> ns ++ notes
_->return ()
)
workOnResult :: GHCApplyFunction a -> FilePath -> ModSummary -> Ghc a
workOnResult f2 fp modSum= do
p <- parseModule modSum
t <- typecheckModule p
d <- desugarModule t -- to get warnings
l <- loadModule d
--c3<-GMU.liftIO getClockTime
-- GMU.liftIO $ putStrLn "Set context..."
#if __GLASGOW_HASKELL__ < 704
setContext [ms_mod modSum] []
#else
#if __GLASGOW_HASKELL__ < 706
setContext [IIModule $ ms_mod modSum]
#else
setContext [IIModule $ moduleName $ ms_mod modSum]
#endif
#endif
let fullfp=ff fp
-- use the dyn flags including pragmas from module, etc.
let opts=ms_hspp_opts modSum
setSessionDynFlags opts
env <- getSession
-- GMU.liftIO $ putStrLn ("writing " ++ fullfp)
GMU.liftIO $ storeGHCInfo opts env fullfp (dm_typechecked_module l)
-- GMU.liftIO $ putStrLn ("written " ++ fullfp)
--GMU.liftIO $ putStrLn ("parse, typecheck load: " ++ (timeDiffToString $ diffClockTimes c3 c2))
f2 fp $ dm_typechecked_module l
add_warn_err :: GhcMonad m => IORef [BWNote] -> WarningMessages -> ErrorMessages -> m()
add_warn_err ref warns errs = do
df <- getSessionDynFlags
let notes = ghcMessagesToNotes df base_dir (warns, errs)
GMU.liftIO $ modifyIORef ref $
\ ns -> ns ++ notes
handle_error :: GhcMonad m => IORef [BWNote] -> SourceError -> m SuccessFlag
handle_error ref e = do
let errs = srcErrorMessages e
add_warn_err ref emptyBag errs
return Failed
#if __GLASGOW_HASKELL__ > 704
logAction :: IORef [BWNote] -> DynFlags -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO ()
#else
logAction :: IORef [BWNote] -> DynFlags -> Severity -> SrcSpan -> PprStyle -> Message -> IO ()
#endif
logAction ref df s loc style msg
| (Just status)<-bwSeverity df s=do
let n=BWNote { bwnLocation = ghcSpanToBWLocation base_dir loc
, bwnStatus = status
, bwnTitle = removeBaseDir base_dir $ removeStatus status $ showSDUser (qualName style,qualModule style) df msg
}
modifyIORef ref $ \ ns -> ns ++ [n]
| otherwise=return ()
bwSeverity :: DynFlags -> Severity -> Maybe BWNoteStatus
bwSeverity df SevWarning = Just (if isWarnIsError df then BWError else BWWarning)
bwSeverity _ SevError = Just BWError
bwSeverity _ SevFatal = Just BWError
bwSeverity _ _ = Nothing
-- | do we have -Werror
isWarnIsError :: DynFlags -> Bool
#if __GLASGOW_HASKELL__ >= 707
isWarnIsError df = gopt Opt_WarnIsError df
#else
isWarnIsError df = dopt Opt_WarnIsError df
#endif
-- | Convert 'GHC.Messages' to '[BWNote]'.
--
-- This will mix warnings and errors, but you can split them back up
-- by filtering the '[BWNote]' based on the 'bw_status'.
ghcMessagesToNotes :: DynFlags ->
FilePath -- ^ base directory
-> Messages -- ^ GHC messages
-> [BWNote]
ghcMessagesToNotes df base_dir (warns, errs) = map_bag2ms (ghcWarnMsgToNote df base_dir) warns ++
map_bag2ms (ghcErrMsgToNote df base_dir) errs
where
map_bag2ms f = map f . Bag.bagToList
-- | get all names in scope
getGhcNamesInScope :: FilePath -- ^ source path
-> FilePath -- ^ base directory
-> String -- ^ module name
-> [String] -- ^ build options
-> IO [String]
getGhcNamesInScope f base_dir modul options=do
names<-withAST (\_->do
--c1<-GMU.liftIO getClockTime
names<-getNamesInScope
df<-getSessionDynFlags
--c2<-GMU.liftIO getClockTime
--GMU.liftIO $ putStrLn ("getNamesInScope: " ++ (timeDiffToString $ diffClockTimes c2 c1))
return $ map (showSDDump df . ppr ) names) f base_dir modul options
return $ fromMaybe[] names
-- | get all names in scope, packaged in NameDefs
getGhcNameDefsInScope :: FilePath -- ^ source path
-> FilePath -- ^ base directory
-> String -- ^ module name
-> [String] -- ^ build options
-> IO (OpResult (Maybe [NameDef]))
getGhcNameDefsInScope fp base_dir modul options=do
-- c0<-getClockTime
(nns,ns)<-withASTNotes (\_ _->do
-- c1<-GMU.liftIO getClockTime
-- GMU.liftIO $ putStrLn "getGhcNameDefsInScope"
names<-getNamesInScope
df<-getSessionDynFlags
-- c2<-GMU.liftIO getClockTime
-- GMU.liftIO $ putStrLn ("getNamesInScope: " ++ (timeDiffToString $ diffClockTimes c2 c1))
mapM (name2nd df) names) id base_dir (SingleFile fp modul) options
-- c4<-getClockTime
-- putStrLn ("getNamesInScopeAll: " ++ (timeDiffToString $ diffClockTimes c4 c0))
return $ case nns of
(x:_)->(Just x,ns)
_->(Nothing, ns)
-- | get all names in scope, packaged in NameDefs, and keep running a loop listening to commands
getGhcNameDefsInScopeLongRunning :: FilePath -- ^ source path
-> FilePath -- ^ base directory
-> String -- ^ module name
-> [String] -- ^ build options
-> IO ()
getGhcNameDefsInScopeLongRunning fp0 base_dir modul0 =
#if __GLASGOW_HASKELL__ < 706
initGHC (go (fp0,modul0) (TOD 0 0))
#else
initGHC (go (fp0,modul0) (UTCTime (ModifiedJulianDay 0) 0))
#endif
where
#if __GLASGOW_HASKELL__ < 706
go :: (FilePath,String) -> ClockTime -> Ghc ()
#else
go :: (FilePath,String) -> UTCTime -> Ghc ()
#endif
go (fp,modul) t1 = do
let hasLoaded=case t1 of
#if __GLASGOW_HASKELL__ < 706
TOD 0 _ -> False
#else
UTCTime (ModifiedJulianDay 0) _ -> False
#endif
_ -> True
t2<- GMU.liftIO $ getModificationTime fp
(ns1,add2)<-if hasLoaded && t2==t1 then -- modification time is only precise to the second in GHC 7.6 or above, see http://hackage.haskell.org/trac/ghc/ticket/7473
(do
-- GMU.liftIO $ print "reloading"
removeTarget (TargetFile fp Nothing)
load LoadAllTargets
return ([],True)
) `gcatch` (\(e :: SourceError) -> do
let errs = srcErrorMessages e
df <- getSessionDynFlags
return (ghcMessagesToNotes df base_dir (emptyBag, errs),True)
)
else return ([],not hasLoaded)
(nns,ns)<- ghcWithASTNotes (\_ _->do
names<-getNamesInScope
df<-getSessionDynFlags
mapM (name2nd df) names) id base_dir (SingleFile fp modul) add2
let res=case nns of
(x:_) -> (Just x,ns1 ++ ns)
_ -> (Nothing,ns1 ++ ns)
GMU.liftIO $ BSC.putStrLn $ BS.append "build-wrapper-json:" $ encode res
GMU.liftIO $ hFlush stdout
r1 (fp,modul) t2
r1 (fp,modul) t2=do
l<- GMU.liftIO getLine
case l of
"q"->return ()
-- eval an expression
'e':' ':expr->do
s<-getEvalResults expr
GMU.liftIO $ do
let js=encode (s,[]::[BWNote])
-- ensure streams are flushed, and prefix and start of the line
hFlush stdout
hFlush stderr
BSC.putStrLn ""
BSC.putStrLn $ BS.append "build-wrapper-json:" js
hFlush stdout
r1 (fp,modul) t2
-- token types
"t"->do
input<- GMU.liftIO $ readFile fp
ett<-tokenTypesArbitrary' fp input (".lhs" == takeExtension fp)
let ret= case ett of
Right tt-> (tt,[])
Left bw -> ([],[bw])
GMU.liftIO $ do
BSC.putStrLn $ BS.append "build-wrapper-json:" $ encode ret
hFlush stdout
r1 (fp,modul) t2
-- occurrences
'o':xs->do
input<- GMU.liftIO $ readFile fp
ett<-occurrences' fp input (T.pack xs) (".lhs" == takeExtension fp)
let ret= case ett of
Right tt-> (tt,[])
Left bw -> ([],[bw])
GMU.liftIO $ do
BSC.putStrLn $ BS.append "build-wrapper-json:" $ encode ret
hFlush stdout
r1 (fp,modul) t2
-- thing at point
'p':xs->do
GMU.liftIO $ do
let (line,col)=read xs
mv<-readGHCInfo fp
let mm=case mv of
Just v->let
f=overlap line (scionColToGhcCol col)
mf=findInJSON f v
in findInJSONData mf
_-> Nothing
BSC.putStrLn $ BS.append "build-wrapper-json:" $ encode (mm,[]::[BWNote])
hFlush stdout
r1 (fp,modul) t2
-- locals
'l':xs->do
GMU.liftIO $ do
let (sline,scol,eline,ecol)=read xs
mv<-readGHCInfo fp
let mm=case mv of
Just v->let
cont=contains sline (scionColToGhcCol scol) eline (scionColToGhcCol ecol)
isVar=isGHCType "Var"
mf=findAllInJSON (\x->cont x && isVar x) v
in mapMaybe (findInJSONData . Just) mf
_-> []
BSC.putStrLn $ BS.append "build-wrapper-json:" $ encode (mm,[]::[BWNote])
hFlush stdout
r1 (fp,modul) t2
-- change current
'c':xs -> do
-- removeTarget (TargetFile fp Nothing)
let (fp1,modul1) = read xs
tgt<-GMU.liftIO $ getTargetPath' fp1 base_dir
t3<- GMU.liftIO $ getModificationTime tgt
go (tgt,modul1) t3
_ -> go (fp,modul) t2
-- | evaluate expression in the GHC monad
getEvalResults :: forall (m :: * -> *).
GhcMonad m =>
String -> m [EvalResult]
getEvalResults expr=handleSourceError (\e->return [EvalResult Nothing Nothing (Just $ show e)])
(do
df<-getSessionDynFlags
-- GMU.liftIO $ print $ xopt Opt_OverloadedStrings df
do
-- setSessionDynFlags $ xopt_set df Opt_OverloadedStrings
rr<- runStmt expr RunToCompletion
case rr of
RunOk ns->do
let q=(qualName &&& qualModule) defaultUserStyle
mapM (\n->do
mty<-lookupName n
case mty of
Just (AnId aid)->do
#if __GLASGOW_HASKELL__ >= 707
let pprTyp = (pprTypeForUser . idType) aid
#else
let pprTyp = (pprTypeForUser True . idType) aid
#endif
t<-gtry $ GHC.obtainTermFromId maxBound True aid
evalDoc<-case t of
Right term -> showTerm term
Left exn -> return (text "*** Exception:" <+>
text (show (exn :: SomeException)))
return $ EvalResult (Just $ showSDUser q df pprTyp) (Just $ showSDUser neverQualify df evalDoc) Nothing
_->return $ EvalResult Nothing Nothing Nothing
) ns
RunException e ->return [EvalResult Nothing Nothing (Just $ show e)]
_->return []
`gfinally`
setSessionDynFlags df)
where
-- A custom Term printer to enable the use of Show instances
-- this is a copy of the GHC Debugger.hs code
-- except that we force evaluation and always use show
showTerm :: GhcMonad m => Term -> m SDoc
showTerm =
cPprTerm (liftM2 (++) (const [cPprShowable]) cPprTermBase)
cPprShowable prec Term{ty=ty, val=val} =
do
hsc_env <- getSession
dflags <- GHC.getSessionDynFlags
do
(new_env, bname) <- bindToFreshName hsc_env ty "showme"
setSession new_env
let exprS = "show " ++ showPpr dflags bname
txt_ <- withExtendedLinkEnv [(bname, val)]
(GHC.compileExpr exprS)
let myprec = 10 -- application precedence. TODO Infix constructors
let txt = unsafeCoerce txt_
return $ if not (null txt)
then Just $ cparen (prec >= myprec && needsParens txt)
(text txt)
else Nothing
`gfinally`
setSession hsc_env
cPprShowable prec NewtypeWrap{ty=new_ty,wrapped_term=t} =
cPprShowable prec t{ty=new_ty}
cPprShowable _ _ = return Nothing
needsParens ('"':_) = False -- some simple heuristics to see whether parens
-- are redundant in an arbitrary Show output
needsParens ('(':_) = False
needsParens txt = ' ' `elem` txt
bindToFreshName hsc_env ty userName = do
name <- newGrimName userName
let mkid = AnId $ mkVanillaGlobal name ty
new_ic = extendInteractiveContext (hsc_IC hsc_env) [mkid]
return (hsc_env {hsc_IC = new_ic }, name)
-- Create new uniques and give them sequentially numbered names
newGrimName :: GMU.MonadIO m => String -> m Name
newGrimName userName = do
us <- liftIO $ mkSplitUniqSupply 'b'
let unique = uniqFromSupply us
occname = mkOccName varName userName
name = mkInternalName unique occname noSrcSpan
return name
-- | convert a Name int a NameDef
name2nd :: GhcMonad m=> DynFlags -> Name -> m NameDef
name2nd df n=do
#if __GLASGOW_HASKELL__ >= 707
m<- getInfo False n -- filters like the old function if False, all info if True
let ty=case m of
Just (tyt,_,_,_)->ty2t tyt
#else
m<- getInfo n
let ty=case m of
Just (tyt,_,_)->ty2t tyt
#endif
Nothing->Nothing
return $ NameDef (T.pack $ showSDDump df $ ppr n) (name2t n) ty
where
name2t :: Name -> [OutlineDefType]
name2t n2
| isTyVarName n2=[Type]
| isTyConName n2=[Type]
| isDataConName n2 = [Constructor]
| isVarName n2 = [Function]
| otherwise =[]
ty2t :: TyThing -> Maybe T.Text
#if __GLASGOW_HASKELL__ >= 707
ty2t (AnId aid)=Just $ T.pack $ showSD False df $ pprTypeForUser $ varType aid
ty2t (AConLike(RealDataCon dc))=Just $ T.pack $ showSD False df $ pprTypeForUser $ dataConUserType dc
ty2t (AConLike(PatSynCon ps))=Just $ T.pack $ showSD False df $ pprTypeForUser $ patSynType ps
#else
ty2t (AnId aid)=Just $ T.pack $ showSD False df $ pprTypeForUser True $ varType aid
ty2t (ADataCon dc)=Just $ T.pack $ showSD False df $ pprTypeForUser True $ dataConUserType dc
#endif
ty2t _ = Nothing
-- | get the "thing" at a particular point (line/column) in the source
-- this is using the saved JSON info if available
getThingAtPointJSON :: Int -- ^ line
-> Int -- ^ column
-- -> Bool ^ do we want the result qualified by the module
-- -> Bool ^ do we want the full type or just the haddock type
-> FilePath -- ^ source file path
-> FilePath -- ^ base directory
-> String -- ^ module name
-> [String] -- ^ build flags
-> IO (Maybe ThingAtPoint)
getThingAtPointJSON line col fp base_dir modul options= do
mmf<-withJSONAST (\v->do
let f=overlap line (scionColToGhcCol col)
let mf=findInJSON f v
return $ findInJSONData mf
) fp base_dir modul options
return $ fromMaybe Nothing mmf
-- | get the "thing" at a particular point (line/column) in the source
-- this is using the saved JSON info if available
getLocalsJSON ::Int -- ^ start line
-> Int -- ^ start column
-> Int -- ^ end line
-> Int -- ^ end column
-> FilePath -- ^ source file path
-> FilePath -- ^ base directory
-> String -- ^ module name
-> [String] -- ^ build flags
-> IO [ThingAtPoint]
getLocalsJSON sline scol eline ecol fp base_dir modul options= do
mmf<-withJSONAST (\v->do
let cont=contains sline (scionColToGhcCol scol) eline (scionColToGhcCol ecol)
let isVar=isGHCType "Var"
let mf=findAllInJSON (\x->cont x && isVar x) v
return $ mapMaybe (findInJSONData . Just) mf
) fp base_dir modul options
return $ fromMaybe [] mmf
-- | evaluate an expression
eval :: String -- ^ the expression
-> FilePath -- ^ source file path
-> FilePath -- ^ base directory
-> String -- ^ module name
-> [String] -- ^ build flags
-> IO [EvalResult]
eval expression fp base_dir modul options= do
mf<-withASTNotes (\_ _->getEvalResults expression) id base_dir (SingleFile fp modul) options
return $ concat $ fst mf
-- | convert a GHC SrcSpan to a Span, ignoring the actual file info
ghcSpanToLocation ::GHC.SrcSpan
-> InFileSpan
ghcSpanToLocation sp
| GHC.isGoodSrcSpan sp =let
(stl,stc)=start sp
(enl,enc)=end sp
in mkFileSpan
stl
(ghcColToScionCol stc)
enl
(ghcColToScionCol enc)
| otherwise = mkFileSpan 0 0 0 0
-- | convert a GHC SrcSpan to a BWLocation
ghcSpanToBWLocation :: FilePath -- ^ Base directory
-> GHC.SrcSpan
-> BWLocation
ghcSpanToBWLocation baseDir sp
| GHC.isGoodSrcSpan sp =
let (stl,stc)=start sp
(enl,enc)=end sp
in BWLocation (makeRelative baseDir $ foldr f [] $ normalise $ unpackFS (sfile sp))
stl
(ghcColToScionCol stc)
enl
(ghcColToScionCol enc)
| otherwise = mkEmptySpan "" 1 1
where
f c (x:xs)
| c=='\\' && x=='\\'=x:xs -- WHY do we get two slashed after the drive sometimes?
| otherwise=c:x:xs
f c s=c:s
#if __GLASGOW_HASKELL__ < 702
sfile = GHC.srcSpanFile
#else
sfile (RealSrcSpan ss)= GHC.srcSpanFile ss
#endif
-- | convert a column info from GHC to our system (1 based)
ghcColToScionCol :: Int -> Int
#if __GLASGOW_HASKELL__ < 700
ghcColToScionCol c=c+1 -- GHC 6.x starts at 0 for columns
#else
ghcColToScionCol c=c -- GHC 7 starts at 1 for columns
#endif
-- | convert a column info from our system (1 based) to GHC
scionColToGhcCol :: Int -> Int
#if __GLASGOW_HASKELL__ < 700
scionColToGhcCol c=c-1 -- GHC 6.x starts at 0 for columns
#else
scionColToGhcCol c=c -- GHC 7 starts at 1 for columns
#endif
-- | Get a stream of tokens generated by the GHC lexer from the current document
ghctokensArbitrary :: FilePath -- ^ The file path to the document
-> String -- ^ The document's contents
-> [String] -- ^ The options
-> IO (Either BWNote [Located Token])
ghctokensArbitrary base_dir contents options= do
#if __GLASGOW_HASKELL__ < 702
sb <- stringToStringBuffer contents
#else
let sb=stringToStringBuffer contents
#endif
let lflags=map noLoc options
(_leftovers, _) <- parseStaticFlags lflags
runGhc (Just libdir) $ do
flg <- getSessionDynFlags
(flg', _, _) <- parseDynamicFlags flg _leftovers
#if __GLASGOW_HASKELL__ >= 700
let dflags1 = List.foldl' xopt_set flg' lexerFlags
#else
let dflags1 = List.foldl' dopt_set flg' lexerFlags
#endif
let prTS = lexTokenStreamH sb lexLoc dflags1
case prTS of
POk _ toks ->
-- GMU.liftIO $ print $ map (show . unLoc) toks
return $ Right $ filter ofInterest toks
PFailed loc msg -> return $ Left $ ghcErrMsgToNote dflags1 base_dir $
#if __GLASGOW_HASKELL__ < 706
mkPlainErrMsg loc msg
#else
mkPlainErrMsg dflags1 loc msg
#endif
-- | Get a stream of tokens generated by the GHC lexer from the current document
ghctokensArbitrary' :: FilePath -- ^ The file path to the document
-> String -- ^ The document's contents
-> Ghc (Either BWNote [Located Token])
ghctokensArbitrary' base_dir contents= do
#if __GLASGOW_HASKELL__ < 702
sb <- stringToStringBuffer contents
#else
let sb=stringToStringBuffer contents
#endif
flg' <- getSessionDynFlags
#if __GLASGOW_HASKELL__ >= 700
let dflags1 = List.foldl' xopt_set flg' lexerFlags
#else
let dflags1 = List.foldl' dopt_set flg' lexerFlags
#endif
let prTS = lexTokenStreamH sb lexLoc dflags1
case prTS of
POk _ toks ->
-- GMU.liftIO $ print $ map (show . unLoc) toks
return $ Right $ filter ofInterest toks
PFailed loc msg -> return $ Left $ ghcErrMsgToNote dflags1 base_dir $
#if __GLASGOW_HASKELL__ < 706
mkPlainErrMsg loc msg
#else
mkPlainErrMsg dflags1 loc msg
#endif
-- | like lexTokenStream, but keep Haddock flag
lexTokenStreamH :: StringBuffer -> RealSrcLoc -> DynFlags -> ParseResult [Located Token]
lexTokenStreamH buf loc dflags = unP go initState
#if __GLASGOW_HASKELL__ >= 707
where dflags' = gopt_set (gopt_set dflags Opt_KeepRawTokenStream) Opt_Haddock
#else
where dflags' = dopt_set (dopt_set dflags Opt_KeepRawTokenStream) Opt_Haddock
#endif
initState = mkPState dflags' buf loc
go = do
ltok <- lexer return
case ltok of
L _ ITeof -> return []
_ -> liftM (ltok:) go
-- | get lexer initial location
#if __GLASGOW_HASKELL__ < 702
lexLoc :: SrcLoc
lexLoc = mkSrcLoc (mkFastString "<interactive>") 1 (scionColToGhcCol 1)
#else
lexLoc :: RealSrcLoc
lexLoc = mkRealSrcLoc (mkFastString "<interactive>") 1 (scionColToGhcCol 1)
#endif
-- | get lexer flags
#if __GLASGOW_HASKELL__ >= 700
lexerFlags :: [ExtensionFlag]
#else
lexerFlags :: [DynFlag]
#endif
lexerFlags =
[ Opt_ForeignFunctionInterface
, Opt_Arrows
#if __GLASGOW_HASKELL__ < 702
, Opt_PArr
#else
, Opt_ParallelArrays
#endif
, Opt_TemplateHaskell
, Opt_QuasiQuotes
, Opt_ImplicitParams
, Opt_BangPatterns
, Opt_TypeFamilies
, Opt_MagicHash
, Opt_KindSignatures
, Opt_RecursiveDo
, Opt_UnicodeSyntax
, Opt_UnboxedTuples
, Opt_StandaloneDeriving
, Opt_TransformListComp
#if __GLASGOW_HASKELL__ < 702
, Opt_NewQualifiedOperators
#endif
#if GHC_VERSION > 611
, Opt_ExplicitForAll -- 6.12
, Opt_DoRec -- 6.12
#endif
]
-- | Filter tokens whose span appears legitimate (start line is less than end line, start column is
-- less than end column.)
ofInterest :: Located Token -> Bool
ofInterest (L loc _) =
let (sl,sc) = start loc
(el,ec) = end loc
in (sl < el) || (sc < ec)
-- | Convert a GHC token to an interactive token (abbreviated token type)
tokenToType :: Located Token -> TokenDef
tokenToType (L sp t) = TokenDef (tokenType t) (ghcSpanToLocation sp)
-- | Generate the interactive token list used by EclipseFP for syntax highlighting, in the IO monad
tokenTypesArbitrary :: FilePath -> String -> Bool -> [String] -> IO (Either BWNote [TokenDef])
tokenTypesArbitrary projectRoot contents literate options = generateTokens projectRoot contents literate options convertTokens id
where
convertTokens = map tokenToType
-- | Generate the interactive token list used by EclipseFP for syntax highlighting, when already in a GHC session
tokenTypesArbitrary' :: FilePath -> String -> Bool -> Ghc (Either BWNote [TokenDef])
tokenTypesArbitrary' projectRoot contents literate = generateTokens' projectRoot contents literate convertTokens id
where
convertTokens = map tokenToType
-- | Extract occurrences based on lexing
occurrences :: FilePath -- ^ Project root or base directory for absolute path conversion
-> String -- ^ Contents to be parsed
-> T.Text -- ^ Token value to find
-> Bool -- ^ Literate source flag (True = literate, False = ordinary)
-> [String] -- ^ Options
-> IO (Either BWNote [TokenDef])
occurrences projectRoot contents query literate options =
let
qualif = isJust $ T.find (=='.') query
-- Get the list of tokens matching the query for relevant token types
tokensMatching :: [TokenDef] -> [TokenDef]
tokensMatching = filter matchingVal
matchingVal :: TokenDef -> Bool
matchingVal (TokenDef v _)=query==v
mkToken (L sp t)=TokenDef (tokenValue qualif t) (ghcSpanToLocation sp)
in generateTokens projectRoot contents literate options (map mkToken) tokensMatching
-- | Extract occurrences based on lexing
occurrences' :: FilePath -- ^ Project root or base directory for absolute path conversion
-> String -- ^ Contents to be parsed
-> T.Text -- ^ Token value to find
-> Bool -- ^ Literate source flag (True = literate, False = ordinary)
-> Ghc (Either BWNote [TokenDef])
occurrences' projectRoot contents query literate =
let
qualif = isJust $ T.find (=='.') query
-- Get the list of tokens matching the query for relevant token types
tokensMatching :: [TokenDef] -> [TokenDef]
tokensMatching = filter matchingVal
matchingVal :: TokenDef -> Bool
matchingVal (TokenDef v _)=query==v
mkToken (L sp t)=TokenDef (tokenValue qualif t) (ghcSpanToLocation sp)
in generateTokens' projectRoot contents literate (map mkToken) tokensMatching
-- | Parse the current document, generating a TokenDef list, filtered by a function
generateTokens :: FilePath -- ^ The project's root directory
-> String -- ^ The current document contents, to be parsed
-> Bool -- ^ Literate Haskell flag
-> [String] -- ^ The options
-> ([Located Token] -> [TokenDef]) -- ^ Transform function from GHC tokens to TokenDefs
-> ([TokenDef] -> a) -- ^ The TokenDef filter function
-> IO (Either BWNote a)
generateTokens projectRoot contents literate options xform filterFunc =do
let (ppTs, ppC) = preprocessSource contents literate
-- putStrLn ppC
result<- ghctokensArbitrary projectRoot ppC options
case result of
Right toks ->do
let filterResult = filterFunc $ List.sortBy (comparing tdLoc) (ppTs ++ xform toks)
return $ Right filterResult
Left n -> return $ Left n
-- | Parse the current document, generating a TokenDef list, filtered by a function
generateTokens' :: FilePath -- ^ The project's root directory
-> String -- ^ The current document contents, to be parsed
-> Bool -- ^ Literate Haskell flag
-> ([Located Token] -> [TokenDef]) -- ^ Transform function from GHC tokens to TokenDefs
-> ([TokenDef] -> a) -- ^ The TokenDef filter function
-> Ghc (Either BWNote a)
generateTokens' projectRoot contents literate xform filterFunc =do
let (ppTs, ppC) = preprocessSource contents literate
-- GMU.liftIO $ putStrLn ppC
result<- ghctokensArbitrary' projectRoot ppC
case result of
Right toks ->do
let filterResult = filterFunc $ List.sortBy (comparing tdLoc) (ppTs ++ xform toks)
return $ Right filterResult
Left n -> return $ Left n
-- | Preprocess some source, returning the literate and Haskell source as tuple.
preprocessSource :: String -- ^ the source contents
-> Bool -- ^ is the source literate Haskell
-> ([TokenDef],String) -- ^ the preprocessor tokens and the final valid Haskell source
preprocessSource contents literate=
let
(ts1,s2)=if literate then ppSF contents ppSLit else ([],contents)
(ts2,s3)=ppSF s2 ppSCpp
in (ts1++ts2,s3)
where
ppSF contents2 p= let
linesWithCount=zip (lines contents2) [1..]
(ts,nc,_)= List.foldl' p ([],[],Start) linesWithCount
in (reverse ts, unlines $ reverse nc)
ppSCpp :: ([TokenDef],[String],PPBehavior) -> (String,Int) -> ([TokenDef],[String],PPBehavior)
ppSCpp (ts2,l2,f) (l,c)
| (Continue _)<-f = addPPToken "PP" (l,c) (ts2,l2,lineBehavior l f)
| (ContinuePragma f2) <-f= addPPToken "P" (l,c) (ts2,"":l2,pragmaBehavior l f2)
| ('#':_)<-l =addPPToken "PP" (l,c) (ts2,l2,lineBehavior l f)
| Just (l',s,e,f2)<-pragmaExtract l f=
(TokenDef "P" (mkFileSpan c s c e) : ts2 ,l':l2,f2)
-- "{-# " `List.isPrefixOf` l=addPPToken "P" (l,c) (ts2,"":l2,pragmaBehavior l f)
| (Indent n)<-f=(ts2,l:(replicate n (takeWhile (== ' ') l) ++ l2),Start)
| otherwise =(ts2,l:l2,Start)
ppSLit :: ([TokenDef],[String],PPBehavior) -> (String,Int) -> ([TokenDef],[String],PPBehavior)
ppSLit (ts2,l2,f) (l,c)
| "\\begin{code}" `List.isPrefixOf` l=addPPToken "DL" ("\\begin{code}",c) (ts2,"":l2,Continue 1)
| "\\end{code}" `List.isPrefixOf` l=addPPToken "DL" ("\\end{code}",c) (ts2,"":l2,Start)
| (Continue n)<-f = (ts2,l:l2,Continue (n+1))
| ('>':lCode)<-l=(ts2, (' ':lCode ):l2,f)
| otherwise =addPPToken "DL" (l,c) (ts2,"":l2,f)
addPPToken :: T.Text -> (String,Int) -> ([TokenDef],[String],PPBehavior) -> ([TokenDef],[String],PPBehavior)
addPPToken name (l,c) (ts2,l2,f) =(TokenDef name (mkFileSpan c 1 c (length l + 1)) : ts2 ,l2,f)
lineBehavior l f
| '\\' == last l = case f of
Continue n->Continue (n+1)
_ -> Continue 1
| otherwise = case f of
Continue n->Indent (n+1)
ContinuePragma p->p
Indent n->Indent (n+1)
_ -> Indent 1
pragmaBehavior l f
| "-}" `List.isInfixOf` l = f
| otherwise = ContinuePragma f
pragmaExtract :: String -> PPBehavior -> Maybe (String,Int,Int,PPBehavior)
pragmaExtract l f=
let
(spl1,spl2)=splitString "{-# " l
in if not $ null spl2
then
let
startIdx= length spl1
(spl3,spl4)=splitString "-}" spl2
in if not $ null spl4
then
let
endIdx= length spl3 + 2
len=endIdx
in Just (spl1++ replicate len ' ' ++ drop 2 spl4,startIdx+1,startIdx+len+1,f)
else Just (spl1,startIdx+1,length l+1,ContinuePragma f)
else Nothing
-- | preprocessor behavior data
data PPBehavior=Continue Int | Indent Int | Start | ContinuePragma PPBehavior
deriving Eq
-- | convert a GHC error message to our note type
ghcErrMsgToNote :: DynFlags -> FilePath -> ErrMsg -> BWNote
ghcErrMsgToNote df= ghcMsgToNote df BWError
-- | convert a GHC warning message to our note type
ghcWarnMsgToNote :: DynFlags -> FilePath -> WarnMsg -> BWNote
ghcWarnMsgToNote df= ghcMsgToNote df (if isWarnIsError df then BWError else BWWarning)
-- | convert a GHC message to our note type
-- Note that we do *not* include the extra info, since that information is
-- only useful in the case where we do not show the error location directly
-- in the source.
ghcMsgToNote :: DynFlags -> BWNoteStatus -> FilePath -> ErrMsg -> BWNote
ghcMsgToNote df note_kind base_dir msg =
BWNote { bwnLocation = ghcSpanToBWLocation base_dir loc
, bwnStatus = note_kind
, bwnTitle = removeBaseDir base_dir $ removeStatus note_kind $ show_msg (errMsgShortDoc msg)
}
where
#if __GLASGOW_HASKELL__ >= 707
loc | s <- errMsgSpan msg = s
#else
loc | (s:_) <- errMsgSpans msg = s
#endif
| otherwise = GHC.noSrcSpan
unqual = errMsgContext msg
show_msg = showSDUser unqual df
-- | remove the initial status text from a message
removeStatus :: BWNoteStatus -> String -> String
removeStatus BWWarning s
| "Warning:" `List.isPrefixOf` s = List.dropWhile isSpace $ drop 8 s
| otherwise = s
removeStatus BWError s
| "Error:" `List.isPrefixOf` s = List.dropWhile isSpace $ drop 6 s
| otherwise = s
#if CABAL_VERSION == 106
deriving instance Typeable StringBuffer
deriving instance Data StringBuffer
#endif
-- | make unqualified token
mkUnqualTokenValue :: FastString -- ^ the name
-> T.Text
mkUnqualTokenValue = T.pack . unpackFS
-- | make qualified token: join the qualifier and the name by a dot
mkQualifiedTokenValue :: FastString -- ^ the qualifier
-> FastString -- ^ the name
-> T.Text
mkQualifiedTokenValue q a = (T.pack . unpackFS . concatFS) [q, dotFS, a]
-- | make a text name from a token
mkTokenName :: Token -> T.Text
mkTokenName = T.pack . showConstr . toConstr
deriving instance Typeable Token
deriving instance Data Token
#if CABAL_VERSION == 106
deriving instance Typeable StringBuffer
deriving instance Data StringBuffer
#endif
-- | get token type from Token
tokenType :: Token -> T.Text
tokenType ITas = "K" -- Haskell keywords
tokenType ITcase = "K"
tokenType ITclass = "K"
tokenType ITdata = "K"
tokenType ITdefault = "K"
tokenType ITderiving = "K"
tokenType ITdo = "K"
tokenType ITelse = "K"
tokenType IThiding = "K"
tokenType ITif = "K"
tokenType ITimport = "K"
tokenType ITin = "K"
tokenType ITinfix = "K"
tokenType ITinfixl = "K"
tokenType ITinfixr = "K"
tokenType ITinstance = "K"
tokenType ITlet = "K"
tokenType ITmodule = "K"
tokenType ITnewtype = "K"
tokenType ITof = "K"
tokenType ITqualified = "K"
tokenType ITthen = "K"
tokenType ITtype = "K"
tokenType ITwhere = "K"
#if __GLASGOW_HASKELL__ < 707
tokenType ITscc = "K" -- ToDo: remove (we use {-# SCC "..." #-} now)
#endif
tokenType ITforall = "EK" -- GHC extension keywords
tokenType ITforeign = "EK"
tokenType ITexport= "EK"
tokenType ITlabel= "EK"
tokenType ITdynamic= "EK"
tokenType ITsafe= "EK"
#if __GLASGOW_HASKELL__ < 702
tokenType ITthreadsafe= "EK"
#endif
tokenType ITunsafe= "EK"
tokenType ITstdcallconv= "EK"
tokenType ITccallconv= "EK"
#if __GLASGOW_HASKELL__ >= 612
tokenType ITprimcallconv= "EK"
#endif
tokenType ITmdo= "EK"
tokenType ITfamily= "EK"
tokenType ITgroup= "EK"
tokenType ITby= "EK"
tokenType ITusing= "EK"
-- Pragmas
tokenType (ITinline_prag {})="P" -- True <=> INLINE, False <=> NOINLINE
#if __GLASGOW_HASKELL__ >= 612 && __GLASGOW_HASKELL__ < 700
tokenType (ITinline_conlike_prag {})="P" -- same
#endif
tokenType ITspec_prag="P" -- SPECIALISE
tokenType (ITspec_inline_prag {})="P" -- SPECIALISE INLINE (or NOINLINE)
tokenType ITsource_prag="P"
tokenType ITrules_prag="P"
tokenType ITwarning_prag="P"
tokenType ITdeprecated_prag="P"
tokenType ITline_prag="P"
tokenType ITscc_prag="P"
tokenType ITgenerated_prag="P"
tokenType ITcore_prag="P" -- hdaume: core annotations
tokenType ITunpack_prag="P"
#if __GLASGOW_HASKELL__ >= 612
tokenType ITann_prag="P"
#endif
tokenType ITclose_prag="P"
tokenType (IToptions_prag {})="P"
tokenType (ITinclude_prag {})="P"
tokenType ITlanguage_prag="P"
tokenType ITdotdot="S" -- reserved symbols
tokenType ITcolon="S"
tokenType ITdcolon="S"
tokenType ITequal="S"
tokenType ITlam="S"
tokenType ITvbar="S"
tokenType ITlarrow="S"
tokenType ITrarrow="S"
tokenType ITat="S"
tokenType ITtilde="S"
tokenType ITdarrow="S"
tokenType ITminus="S"
tokenType ITbang="S"
tokenType ITstar="S"
tokenType ITdot="S"
tokenType ITbiglam="ES" -- GHC-extension symbols
tokenType ITocurly="SS" -- special symbols
tokenType ITccurly="SS"
#if __GLASGOW_HASKELL__ < 706
tokenType ITocurlybar="SS" -- "{|", for type applications
tokenType ITccurlybar="SS" -- "|}", for type applications
#endif
tokenType ITvocurly="SS"
tokenType ITvccurly="SS"
tokenType ITobrack="SS"
tokenType ITopabrack="SS" -- [:, for parallel arrays with -XParr
tokenType ITcpabrack="SS" -- :], for parallel arrays with -XParr
tokenType ITcbrack="SS"
tokenType IToparen="SS"
tokenType ITcparen="SS"
tokenType IToubxparen="SS"
tokenType ITcubxparen="SS"
tokenType ITsemi="SS"
tokenType ITcomma="SS"
tokenType ITunderscore="SS"
tokenType ITbackquote="SS"
tokenType (ITvarid {})="IV" -- identifiers
tokenType (ITconid {})="IC"
tokenType (ITvarsym {})="VS"
tokenType (ITconsym {})="IC"
tokenType (ITqvarid {})="IV"
tokenType (ITqconid {})="IC"
tokenType (ITqvarsym {})="VS"
tokenType (ITqconsym {})="IC"
tokenType (ITprefixqvarsym {})="VS"
tokenType (ITprefixqconsym {})="IC"
tokenType (ITdupipvarid {})="EI" -- GHC extension: implicit param: ?x
tokenType (ITchar {})="LC"
tokenType (ITstring {})="LS"
tokenType (ITinteger {})="LI"
tokenType (ITrational {})="LR"
tokenType (ITprimchar {})="LC"
tokenType (ITprimstring {})="LS"
tokenType (ITprimint {})="LI"
tokenType (ITprimword {})="LW"
tokenType (ITprimfloat {})="LF"
tokenType (ITprimdouble {})="LD"
-- Template Haskell extension tokens
tokenType ITopenExpQuote="TH" -- [| or [e|
tokenType ITopenPatQuote="TH" -- [p|
tokenType ITopenDecQuote="TH" -- [d|
tokenType ITopenTypQuote="TH" -- [t|
tokenType ITcloseQuote="TH" --tokenType ]
tokenType (ITidEscape {})="TH" -- $x
tokenType ITparenEscape="TH" -- $(
#if __GLASGOW_HASKELL__ < 704
tokenType ITvarQuote="TH" -- '
#endif
tokenType ITtyQuote="TH" -- ''
tokenType (ITquasiQuote {})="TH" -- [:...|...|]
-- Arrow notation extension
tokenType ITproc="A"
tokenType ITrec="A"
tokenType IToparenbar="A" -- (|
tokenType ITcparenbar="A" --tokenType )
tokenType ITlarrowtail="A" -- -<
tokenType ITrarrowtail="A" -- >-
tokenType ITLarrowtail="A" -- -<<
tokenType ITRarrowtail="A" -- >>-
#if __GLASGOW_HASKELL__ <= 611
tokenType ITdotnet="SS" -- ??
tokenType (ITpragma _) = "SS" -- ??
#endif
tokenType (ITunknown {})="" -- Used when the lexer can't make sense of it
tokenType ITeof="" -- end of file token
-- Documentation annotations
tokenType (ITdocCommentNext {})="D" -- something beginning '-- |'
tokenType (ITdocCommentPrev {})="D" -- something beginning '-- ^'
tokenType (ITdocCommentNamed {})="D" -- something beginning '-- $'
tokenType (ITdocSection {})="D" -- a section heading
tokenType (ITdocOptions {})="D" -- doc options (prune, ignore-exports, etc)
tokenType (ITdocOptionsOld {})="D" -- doc options declared "-- # ..."-style
tokenType (ITlineComment {})="C" -- comment starting by "--"
tokenType (ITblockComment {})="C" -- comment in {- -}
-- 7.2 new token types
#if __GLASGOW_HASKELL__ >= 702
tokenType (ITinterruptible {})="EK"
tokenType (ITvect_prag {})="P"
tokenType (ITvect_scalar_prag {})="P"
tokenType (ITnovect_prag {})="P"
#endif
-- 7.4 new token types
#if __GLASGOW_HASKELL__ >= 704
tokenType ITcapiconv= "EK"
tokenType ITnounpack_prag= "P"
tokenType ITtildehsh= "S"
tokenType ITsimpleQuote="SS"
#endif
-- 7.6 new token types
#if __GLASGOW_HASKELL__ >= 706
tokenType ITctype= "P"
tokenType ITlcase= "S"
tokenType (ITqQuasiQuote {}) = "TH" -- [Qual.quoter| quote |]
#endif
-- 7.8 new token types
#if __GLASGOW_HASKELL__ >= 708
tokenType ITjavascriptcallconv = "EK" -- javascript
tokenType ITrole = "EK" -- role
tokenType ITpattern = "EK" -- pattern
tokenType ITminimal_prag = "EK" -- minimal
tokenType ITopenTExpQuote = "TH" -- [||
tokenType ITcloseTExpQuote = "TH" -- ||]
tokenType (ITidTyEscape {}) = "TH" -- $$x
tokenType ITparenTyEscape = "TH" -- $$(
#endif
-- | a dot as a FastString
dotFS :: FastString
dotFS = fsLit "."
-- | generate a token value
tokenValue :: Bool -> Token -> T.Text
tokenValue _ t | tokenType t `elem` ["K", "EK"] = T.drop 2 $ mkTokenName t
tokenValue _ (ITvarid a) = mkUnqualTokenValue a
tokenValue _ (ITconid a) = mkUnqualTokenValue a
tokenValue _ (ITvarsym a) = mkUnqualTokenValue a
tokenValue _ (ITconsym a) = mkUnqualTokenValue a
tokenValue False (ITqvarid (_,a)) = mkUnqualTokenValue a
tokenValue True (ITqvarid (q,a)) = mkQualifiedTokenValue q a
tokenValue False(ITqconid (_,a)) = mkUnqualTokenValue a
tokenValue True (ITqconid (q,a)) = mkQualifiedTokenValue q a
tokenValue False (ITqvarsym (_,a)) = mkUnqualTokenValue a
tokenValue True (ITqvarsym (q,a)) = mkQualifiedTokenValue q a
tokenValue False (ITqconsym (_,a)) = mkUnqualTokenValue a
tokenValue True (ITqconsym (q,a)) = mkQualifiedTokenValue q a
tokenValue False (ITprefixqvarsym (_,a)) = mkUnqualTokenValue a
tokenValue True (ITprefixqvarsym (q,a)) = mkQualifiedTokenValue q a
tokenValue False (ITprefixqconsym (_,a)) = mkUnqualTokenValue a
tokenValue True (ITprefixqconsym (q,a)) = mkQualifiedTokenValue q a
tokenValue _ _= ""
instance Monoid (Bag a) where
mempty = emptyBag
mappend = unionBags
mconcat = unionManyBags
-- | extract start line and column from SrcSpan
start :: SrcSpan -> (Int,Int)
-- | extract end line and column from SrcSpan
end :: SrcSpan -> (Int,Int)
#if __GLASGOW_HASKELL__ < 702
start ss= (srcSpanStartLine ss, srcSpanStartCol ss)
end ss= (srcSpanEndLine ss, srcSpanEndCol ss)
#else
start (RealSrcSpan ss)= (srcSpanStartLine ss, srcSpanStartCol ss)
start (UnhelpfulSpan _)=error "UnhelpfulSpan in cmpOverlap start"
end (RealSrcSpan ss)= (srcSpanEndLine ss, srcSpanEndCol ss)
end (UnhelpfulSpan _)=error "UnhelpfulSpan in cmpOverlap start"
#endif
-- | map of module aliases
type AliasMap=DM.Map ModuleName [ModuleName]
-- | get usages from GHC imports
ghcImportToUsage :: T.Text -> LImportDecl Name -> ([Usage],AliasMap) -> Ghc ([Usage],AliasMap)
ghcImportToUsage myPkg (L _ imp) (ls,moduMap)=(do
let L src modu=ideclName imp
pkg<-lookupModule modu (ideclPkgQual imp)
df<-getSessionDynFlags
let tmod=T.pack $ showSD True df $ ppr modu
#if __GLASGOW_HASKELL__ >= 710
tpkg=T.pack $ showSD True df $ ppr $ modulePackageKey pkg
#else
tpkg=T.pack $ showSD True df $ ppr $ modulePackageId pkg
#endif
nomain=if tpkg=="main" then myPkg else tpkg
subs=concatMap (ghcLIEToUsage df (Just nomain) tmod "import") $ maybe [] snd $ ideclHiding imp
moduMap2=maybe moduMap (\alias->let
mlmods=DM.lookup alias moduMap
newlmods=case mlmods of
Just lmods->modu:lmods
Nothing->[modu]
in DM.insert alias newlmods moduMap) $ ideclAs imp
usg =Usage (Just nomain) tmod "" "import" False (toJSON $ ghcSpanToLocation src) False
return (usg:subs++ls,moduMap2)
)
`gcatch` (\(se :: SourceError) -> do
GMU.liftIO $ print se
return ([],moduMap))
-- | get usages from GHC IE
ghcLIEToUsage :: DynFlags -> Maybe T.Text -> T.Text -> T.Text -> LIE Name -> [Usage]
ghcLIEToUsage df tpkg tmod tsection (L src (IEVar nm))=[ghcNameToUsage df tpkg tmod tsection nm src False]
ghcLIEToUsage df tpkg tmod tsection (L src (IEThingAbs nm))=[ghcNameToUsage df tpkg tmod tsection nm src True ]
ghcLIEToUsage df tpkg tmod tsection (L src (IEThingAll nm))=[ghcNameToUsage df tpkg tmod tsection nm src True]
ghcLIEToUsage df tpkg tmod tsection (L src (IEThingWith nm cons))=ghcNameToUsage df tpkg tmod tsection nm src True :
map (\ x -> ghcNameToUsage df tpkg tmod tsection x src False) cons
ghcLIEToUsage _ tpkg tmod tsection (L src (IEModuleContents _))= [Usage tpkg tmod "" tsection False (toJSON $ ghcSpanToLocation src) False]
ghcLIEToUsage _ _ _ _ _=[]
-- | get usage from GHC exports
ghcExportToUsage :: DynFlags -> T.Text -> T.Text ->AliasMap -> LIE Name -> Ghc [Usage]
ghcExportToUsage df myPkg myMod moduMap lie@(L _ name)=(do
ls<-case name of
(IEModuleContents modu)-> do
let realModus=fromMaybe [modu] (DM.lookup modu moduMap)
mapM (\modu2->do
pkg<-lookupModule modu2 Nothing
#if __GLASGOW_HASKELL__ >= 710
let tpkg=T.pack $ showSD True df $ ppr $ modulePackageKey pkg
#else
let tpkg=T.pack $ showSD True df $ ppr $ modulePackageId pkg
#endif
let tmod=T.pack $ showSD True df $ ppr modu2
return (tpkg,tmod)
) realModus
_ -> return [(myPkg,myMod)]
return $ concatMap (\(tpkg,tmod)->ghcLIEToUsage df (Just tpkg) tmod "export" lie) ls
)
`gcatch` (\(se :: SourceError) -> do
GMU.liftIO $ print se
return [])
-- | generate a usage for a name
ghcNameToUsage :: DynFlags -> Maybe T.Text -> T.Text -> T.Text -> Name -> SrcSpan -> Bool -> Usage
ghcNameToUsage df tpkg tmod tsection nm src typ=Usage tpkg tmod (T.pack $ showSD False df $ ppr nm) tsection typ (toJSON $ ghcSpanToLocation src) False
-- | map of imports
type ImportMap=DM.Map T.Text (LImportDecl Name,[T.Text])
-- | build an import map from all imports
ghcImportMap :: LImportDecl Name -> Ghc ImportMap
ghcImportMap l@(L _ imp)=(do
let L _ modu=ideclName imp
let moduS=T.pack $ moduleNameString modu
--GMU.liftIO $ putStrLn $ show moduS
let mm=DM.singleton moduS (l,[])
m<-lookupModule modu Nothing
mmi<-getModuleInfo m
df <- getSessionDynFlags
let maybeHiding=ideclHiding imp
let hidden=case maybeHiding of
Just(True,ns)->map (T.pack . showSD False df . ppr . unLoc) ns
_ ->[]
let fullM =case mmi of
Nothing -> mm
Just mi->let
exps=modInfoExports mi
-- extExps=filter (\x->(nameModule x) /= m) exps
in foldr insertImport mm exps
where insertImport :: Name -> ImportMap -> ImportMap
insertImport x mmx=
let
expM=T.pack $ moduleNameString $ moduleName $ nameModule x
nT=T.pack $ showSD False df $ ppr x
in if nT `elem` hidden
then mmx
else DM.insertWith (\(_,xs1) (_,xs2)->(l,xs1++xs2)) expM (l,[nT]) mmx
return $ if ideclImplicit imp
then DM.insert "" (l, concatMap snd $ DM.elems fullM) fullM
else fullM
)
`gcatch` (\(se :: SourceError) -> do
GMU.liftIO $ print se
return DM.empty)
--getGHCOutline :: ParsedSource
-- -> [OutlineDef]
--getGHCOutline (L src mod)=concatMap ldeclOutline (hsmodDecls mod)
-- where
-- ldeclOutline :: LHsDecl RdrName -> [OutlineDef]
-- ldeclOutline (L src1 (TyClD decl))=ltypeOutline decl
-- ldeclOutline _ = []
-- ltypeOutline :: TyClDecl RdrName -> [OutlineDef]
-- ltypeOutline (TyFamily{tcdLName})=[mkOutlineDef (nameDecl $ unLoc tcdLName) [Type,Family] (ghcSpanToLocation $ getLoc tcdLName)]
-- ltypeOutline (TyData{tcdLName,tcdCons})=[mkOutlineDef (nameDecl $ unLoc tcdLName) [Data] (ghcSpanToLocation $ getLoc tcdLName)]
-- ++ concatMap lconOutline tcdCons
-- lconOutline :: LConDecl RdrName -> [OutlineDef]
-- lconOutline (L src ConDecl{con_name,con_doc,con_details})=[(mkOutlineDef (nameDecl $ unLoc con_name) [Constructor] (ghcSpanToLocation $ getLoc con_name)){od_comment=commentDecl con_doc}]
-- ++ detailOutline con_details
-- detailOutline (RecCon fields)=concatMap lfieldOutline fields
-- detailOutline _=[]
-- lfieldOutline (ConDeclField{cd_fld_name,cd_fld_doc})=[(mkOutlineDef (nameDecl $ unLoc cd_fld_name) [Function] (ghcSpanToLocation $ getLoc cd_fld_name)){od_comment=commentDecl cd_fld_doc}]
-- nameDecl:: RdrName -> T.Text
-- nameDecl (Unqual occ)=T.pack $ showSDoc $ ppr occ
-- nameDecl (Qual _ occ)=T.pack $ showSDoc $ ppr occ
-- commentDecl :: Maybe LHsDocString -> Maybe T.Text
-- commentDecl (Just st)=Just $ T.pack $ showSDoc $ ppr st
-- commentDecl _=Nothing
-- ghcSpanToLocation
-- | module, function/type, constructors
type TypeMap=DM.Map T.Text (DM.Map T.Text (DS.Set T.Text))
-- | mapping to import declaration to actually needed names
type FinalImportValue=(LImportDecl Name,DM.Map T.Text (DS.Set T.Text))
-- | map from original text to needed names
type FinalImportMap=DM.Map T.Text FinalImportValue
-- | clean imports
ghcCleanImports :: FilePath -- ^ source path
-> FilePath -- ^ base directory
-> String -- ^ module name
-> [String] -- ^ build options
-> Bool -- ^ format?
-> IO (OpResult [ImportClean])
ghcCleanImports f base_dir modul options doFormat = do
(m,bwns)<-withASTNotes clean (base_dir </>) base_dir (SingleFile f modul) options
return (if null m then [] else head m,bwns)
where
-- | main clean method: get the usage, the existing imports, and retrieve only the needed names for each import
clean :: GHCApplyFunction [ImportClean]
clean _ tm=do
let (_,imps,_,_)=fromJust $ tm_renamed_source tm
df <- getSessionDynFlags
env<- getSession
let modu=T.pack $ showSD True df $ ppr $ moduleName $ ms_mod $ pm_mod_summary $ tm_parsed_module tm
(Array vs)<- GMU.liftIO $ generateGHCInfo df env tm
impMaps<-mapM ghcImportMap imps
-- let impMap=DM.unions impMaps
let implicit=DS.fromList $ concatMap (maybe [] snd . DM.lookup "") impMaps
let allImps=concatMap DM.assocs impMaps
-- GMU.liftIO $ putStrLn $ show $ map (\(n,(_,ns))->(n,ns)) allImps
-- GMU.liftIO $ print vs
let usgMap=V.foldr ghcValToUsgMap DM.empty vs
let usgMapWithoutMe=DM.delete modu usgMap
-- GMU.liftIO $ print usgMapWithoutMe
-- GMU.liftIO $ putStrLn $ show $ usgMapWithoutMe
--let ics=foldr (buildImportClean usgMapWithoutMe df) [] (DM.assocs impMap)
let ftm=foldr (buildImportCleanMap usgMapWithoutMe implicit) DM.empty allImps
let missingCleans=getRemovedImports allImps ftm
let formatF=if doFormat then formatImports else map (dumpImportMap df)
-- GMU.liftIO $ putStrLn $ show $ DM.keys ftm
let allCleans=formatF (DM.elems ftm) ++ missingCleans
return allCleans
-- | all used names by module
ghcValToUsgMap :: Value -> TypeMap -> TypeMap
ghcValToUsgMap (Object m) um |
Just (String n)<-HM.lookup "Name" m,
Just (String mo)<-HM.lookup "Module" m,
not $ T.null mo, -- ignore local objects
mst<-HM.lookup "Type" m,
Just (String ht)<-HM.lookup "HType" m
=let
mm=DM.lookup mo um
isType=ht=="t"
isConstructor=not isType && isUpper (T.head n) && isJust mst && Null /= fromJust mst
key=if isConstructor
then let
Just (String t)=mst
in fst $ T.breakOn " " $ T.strip $ snd $ T.breakOnEnd "->" t
else n
val=if isConstructor
then DS.singleton n
else DS.empty
in case mm of
Just usgM1->DM.insert mo (DM.insertWith DS.union key val usgM1) um
Nothing->DM.insert mo (DM.singleton key val) um
ghcValToUsgMap _ um=um
-- | reconcile the usage map and the import to generate the final import map: module -> names to import
buildImportCleanMap :: TypeMap -> DS.Set T.Text ->(T.Text,(LImportDecl Name,[T.Text])) -> FinalImportMap -> FinalImportMap
buildImportCleanMap usgMap implicit (cmod,(l@(L _ imp),ns)) tm |
Just namesMap<-DM.lookup cmod usgMap, -- used names for module
namesMapFiltered<-foldr (keepKeys namesMap) DM.empty ns, -- only names really exported by the import name
namesWithoutImplicit<-if ideclQualified imp
then namesMapFiltered
else DM.map (`DS.difference` implicit) $ foldr DM.delete namesMapFiltered $ DS.elems implicit,
not $ DM.null namesWithoutImplicit,
not $ ideclImplicit imp = let -- ignore implicit prelude
L _ modu=ideclName imp
moduS=T.pack $ moduleNameString modu
in DM.insertWith mergeTypeMap moduS (l,namesWithoutImplicit) tm
buildImportCleanMap _ _ _ tm = tm
-- | copy the key and value from one map to the other
keepKeys :: Ord k => DM.Map k v -> k -> DM.Map k v -> DM.Map k v
keepKeys m1 k m2=case DM.lookup k m1 of
Nothing -> m2
Just v1->DM.insert k v1 m2
-- | merge the map containing the set of names
mergeTypeMap :: FinalImportValue -> FinalImportValue -> FinalImportValue
mergeTypeMap (l1,m1) (_,m2)= (l1,DM.unionWith DS.union m1 m2)
-- | generate final import string from names map
dumpImportMap :: DynFlags -> FinalImportValue -> ImportClean
dumpImportMap df (L loc imp,ns)=let
txt= T.pack $ showSDDump df $ ppr (imp{ideclHiding=Nothing} :: ImportDecl Name) -- rely on GHC for the initial bit of the import, without the names
nameList= T.intercalate ", " $ List.sortBy (comparing T.toLower) $ map buildName $ DM.assocs ns -- build explicit import list
full=txt `mappend` " (" `mappend` nameList `mappend` ")"
in ImportClean (ghcSpanToLocation loc) full
pprName :: T.Text -> T.Text
pprName n | T.null n =n
| isAlpha $ T.head n=n
| otherwise=T.concat ["(",n,")"]
-- build the name with the constructors list if any
buildName :: (T.Text,DS.Set T.Text)->T.Text
buildName (n,cs)
| DS.null cs=pprName n
| otherwise =let
nameList= T.intercalate ", " $ List.sortBy (comparing T.toLower) $ map pprName $ DS.toList cs
in pprName n `mappend` " (" `mappend` nameList `mappend` ")"
getRemovedImports :: [(T.Text,(LImportDecl Name,[T.Text]))] -> FinalImportMap -> [ImportClean]
getRemovedImports allImps ftm= let
cleanedLines=DS.fromList $ map (\(L l _,_)->iflLine $ifsStart $ ghcSpanToLocation l) $ DM.elems ftm
missingImps=filter (\(_,(L l imp,_))->not $ ideclImplicit imp || DS.member (iflLine $ifsStart $ ghcSpanToLocation l) cleanedLines) allImps
in nubOrd $ map (\(_,(L l _,_))-> ImportClean (ghcSpanToLocation l) "") missingImps
getFormatInfo :: FinalImportValue -> (Int,Int,Int,Int,Int)->(Int,Int,Int,Int,Int)
getFormatInfo (L _ imp,_) (szSafe,szQualified,szPkg,szName,szAs)=let
szSafe2=if ideclSafe imp then 5 else szSafe
szQualified2=if ideclQualified imp then 10 else szQualified
szPkg2=maybe szPkg (\p->max szPkg (3 + lengthFS p)) $ ideclPkgQual imp
L _ mo=ideclName imp
szName2=maybe szName (\_->max szName (1 + lengthFS (moduleNameFS mo))) $ ideclAs imp
szAs2=maybe szAs (\m->max szAs (3 + lengthFS (moduleNameFS m))) $ ideclAs imp
in (szSafe2,szQualified2,szPkg2,szName2,szAs2)
formatImport :: (Int,Int,Int,Int,Int)-> FinalImportValue -> ImportClean
formatImport (szSafe,szQualified,szPkg,szName,szAs) (L loc imp,ns) =let
st="import "
saf=if ideclSafe imp then "safe " else T.justifyLeft szSafe ' ' ""
qual=if ideclQualified imp then "qualified " else T.justifyLeft szQualified ' ' ""
pkg=maybe (T.justifyLeft szPkg ' ' "") (\p->"\"" `mappend` T.pack (unpackFS p) `mappend` "\" ") $ ideclPkgQual imp
L _ mo=ideclName imp
nm=T.justifyLeft szName ' ' $ T.pack $ moduleNameString mo
ast=maybe (T.justifyLeft szAs ' ' "") (\m->"as " `mappend` T.pack (moduleNameString m)) $ ideclAs imp
nameList= T.intercalate ", " $ List.sortBy (comparing T.toLower) $ map buildName $ DM.assocs ns -- build explicit import list
full=st `mappend` saf `mappend` qual `mappend` pkg `mappend` nm `mappend` ast `mappend` " (" `mappend` nameList `mappend` ")"
in ImportClean (ghcSpanToLocation loc) full
formatImports :: [FinalImportValue] -> [ImportClean]
formatImports fivs = let
formatInfo=foldr getFormatInfo (0,0,0,0,0) fivs
in map (formatImport formatInfo) fivs
| JPMoresmau/BuildWrapper | src/Language/Haskell/BuildWrapper/GHC.hs | bsd-3-clause | 75,348 | 1,084 | 36 | 27,316 | 15,797 | 8,607 | 7,190 | 1,083 | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.