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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module WJR.Imports
( module Yesod
, Text
, module Data.Map
, module Control.Monad
, module Control.Applicative
, module Data.String
, module Data.Maybe
, module Data.Traversable
) where
import Yesod
import Data.Text (Text)
import Data.Map (Map,toList,fromList)
import Control.Monad (when)
import Control.Applicative ((<$>),(<*>))
import Data.Traversable (sequenceA)
import Data.String (fromString)
import Data.Maybe
| drpowell/Prokka-web | WJR/Imports.hs | gpl-3.0 | 453 | 0 | 5 | 86 | 132 | 85 | 47 | 17 | 0 |
{- |
Facilities for parsing power system data from text in the custom format
used for this program, i.e. kind of the reciprocal to `Text.Render`.
-}
module IO.Parse.Grid.Simple
(
-- * Grid parsing
parseGrid
-- * Line parsing
, parseLine
, parseLines
-- * Bus parsing
, parseBus
, parseBuses
) where
-- Local:
import IO.Parse.Util
import Data.Grid.Simple
-- Grid parsing
-- | Parse a `Grid`.
parseGrid :: Parser Grid
parseGrid = do
skipLine
name <- parseString <* skipLine
skipLines 2
base <- double <* skipLine
skipLines 3
bs <- parseBuses
skipLines 3
gs <- parseGens
skipLines 3
ls <- parseLines
return Grid
{ gridName = name
, gridMVAbase = base
, gridBuses = bs
, gridGens = gs
, gridLines = ls
}
-- Bus parsing.
-- | Parse a series of `Buses` from text.
parseBuses :: Parser Buses
parseBuses = many $ parseBus <* endOfLine
-- | Parse a single `Bus` from text.
parseBus :: Parser SBus
parseBus = do
name <- parseString
sep
bID <- decimal
sep
bPow <- complexDouble
sep
bAdm <- complexDouble
sep
v <- complexDouble
sep
vBase <- double
return SBus
{ sbusName=name
, sbusID=bID
, sbusPower=bPow
, sbusAdmittance=bAdm
, sbusVoltage=v
, sbusVoltageBase=vBase }
-- Generator parsing.
-- | Parse a series of `Gens` from text.
parseGens :: Parser Gens
parseGens = many $ parseGen <* skipLine
-- | Parse a `SGen` from text.
parseGen :: Parser SGen
parseGen = do
bID <- decimal
sep
pq <- complexDouble
sep
sMax <- complexDouble
sep
sMin <- complexDouble
sep
v <- double
return $ SGen bID pq sMax sMin v
-- Line parsing.
-- | Parse a series of `Line`s from text.
parseLines :: Parser Lines
parseLines = many $ parseLine <* endOfLine
-- | Parse a `Line` from text.
parseLine :: Parser SLine
parseLine = do
lID <- decimal
sep
lFrom <- decimal
sep
lTo <- decimal
sep
lImpedance <- complexDouble
sep
lSusceptance <- double
return $ SLine lID lFrom lTo lImpedance lSusceptance
| JohanPauli/Hunger | src/IO/Parse/Grid/Simple.hs | gpl-3.0 | 2,023 | 0 | 9 | 488 | 507 | 257 | 250 | 77 | 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.AdExchangeBuyer.PretargetingConfig.Update
-- 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)
--
-- Updates an existing pretargeting config.
--
-- /See:/ <https://developers.google.com/ad-exchange/buyer-rest Ad Exchange Buyer API Reference> for @adexchangebuyer.pretargetingConfig.update@.
module Network.Google.Resource.AdExchangeBuyer.PretargetingConfig.Update
(
-- * REST Resource
PretargetingConfigUpdateResource
-- * Creating a Request
, pretargetingConfigUpdate
, PretargetingConfigUpdate
-- * Request Lenses
, pcuPayload
, pcuAccountId
, pcuConfigId
) where
import Network.Google.AdExchangeBuyer.Types
import Network.Google.Prelude
-- | A resource alias for @adexchangebuyer.pretargetingConfig.update@ method which the
-- 'PretargetingConfigUpdate' request conforms to.
type PretargetingConfigUpdateResource =
"adexchangebuyer" :>
"v1.4" :>
"pretargetingconfigs" :>
Capture "accountId" (Textual Int64) :>
Capture "configId" (Textual Int64) :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] PretargetingConfig :>
Put '[JSON] PretargetingConfig
-- | Updates an existing pretargeting config.
--
-- /See:/ 'pretargetingConfigUpdate' smart constructor.
data PretargetingConfigUpdate =
PretargetingConfigUpdate'
{ _pcuPayload :: !PretargetingConfig
, _pcuAccountId :: !(Textual Int64)
, _pcuConfigId :: !(Textual Int64)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PretargetingConfigUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pcuPayload'
--
-- * 'pcuAccountId'
--
-- * 'pcuConfigId'
pretargetingConfigUpdate
:: PretargetingConfig -- ^ 'pcuPayload'
-> Int64 -- ^ 'pcuAccountId'
-> Int64 -- ^ 'pcuConfigId'
-> PretargetingConfigUpdate
pretargetingConfigUpdate pPcuPayload_ pPcuAccountId_ pPcuConfigId_ =
PretargetingConfigUpdate'
{ _pcuPayload = pPcuPayload_
, _pcuAccountId = _Coerce # pPcuAccountId_
, _pcuConfigId = _Coerce # pPcuConfigId_
}
-- | Multipart request metadata.
pcuPayload :: Lens' PretargetingConfigUpdate PretargetingConfig
pcuPayload
= lens _pcuPayload (\ s a -> s{_pcuPayload = a})
-- | The account id to update the pretargeting config for.
pcuAccountId :: Lens' PretargetingConfigUpdate Int64
pcuAccountId
= lens _pcuAccountId (\ s a -> s{_pcuAccountId = a})
. _Coerce
-- | The specific id of the configuration to update.
pcuConfigId :: Lens' PretargetingConfigUpdate Int64
pcuConfigId
= lens _pcuConfigId (\ s a -> s{_pcuConfigId = a}) .
_Coerce
instance GoogleRequest PretargetingConfigUpdate where
type Rs PretargetingConfigUpdate = PretargetingConfig
type Scopes PretargetingConfigUpdate =
'["https://www.googleapis.com/auth/adexchange.buyer"]
requestClient PretargetingConfigUpdate'{..}
= go _pcuAccountId _pcuConfigId (Just AltJSON)
_pcuPayload
adExchangeBuyerService
where go
= buildClient
(Proxy :: Proxy PretargetingConfigUpdateResource)
mempty
| brendanhay/gogol | gogol-adexchange-buyer/gen/Network/Google/Resource/AdExchangeBuyer/PretargetingConfig/Update.hs | mpl-2.0 | 3,960 | 0 | 14 | 841 | 497 | 293 | 204 | 76 | 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.ServiceManagement.Services.Undelete
-- 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)
--
-- Revives a previously deleted managed service. The method restores the
-- service using the configuration at the time the service was deleted. The
-- target service must exist and must have been deleted within the last 30
-- days. Operation
--
-- /See:/ <https://cloud.google.com/service-management/ Google Service Management API Reference> for @servicemanagement.services.undelete@.
module Network.Google.Resource.ServiceManagement.Services.Undelete
(
-- * REST Resource
ServicesUndeleteResource
-- * Creating a Request
, servicesUndelete
, ServicesUndelete
-- * Request Lenses
, suXgafv
, suUploadProtocol
, suPp
, suAccessToken
, suUploadType
, suBearerToken
, suServiceName
, suCallback
) where
import Network.Google.Prelude
import Network.Google.ServiceManagement.Types
-- | A resource alias for @servicemanagement.services.undelete@ method which the
-- 'ServicesUndelete' request conforms to.
type ServicesUndeleteResource =
"v1" :>
"services" :>
CaptureMode "serviceName" "undelete" 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 :> Post '[JSON] Operation
-- | Revives a previously deleted managed service. The method restores the
-- service using the configuration at the time the service was deleted. The
-- target service must exist and must have been deleted within the last 30
-- days. Operation
--
-- /See:/ 'servicesUndelete' smart constructor.
data ServicesUndelete = ServicesUndelete'
{ _suXgafv :: !(Maybe Xgafv)
, _suUploadProtocol :: !(Maybe Text)
, _suPp :: !Bool
, _suAccessToken :: !(Maybe Text)
, _suUploadType :: !(Maybe Text)
, _suBearerToken :: !(Maybe Text)
, _suServiceName :: !Text
, _suCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ServicesUndelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'suXgafv'
--
-- * 'suUploadProtocol'
--
-- * 'suPp'
--
-- * 'suAccessToken'
--
-- * 'suUploadType'
--
-- * 'suBearerToken'
--
-- * 'suServiceName'
--
-- * 'suCallback'
servicesUndelete
:: Text -- ^ 'suServiceName'
-> ServicesUndelete
servicesUndelete pSuServiceName_ =
ServicesUndelete'
{ _suXgafv = Nothing
, _suUploadProtocol = Nothing
, _suPp = True
, _suAccessToken = Nothing
, _suUploadType = Nothing
, _suBearerToken = Nothing
, _suServiceName = pSuServiceName_
, _suCallback = Nothing
}
-- | V1 error format.
suXgafv :: Lens' ServicesUndelete (Maybe Xgafv)
suXgafv = lens _suXgafv (\ s a -> s{_suXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
suUploadProtocol :: Lens' ServicesUndelete (Maybe Text)
suUploadProtocol
= lens _suUploadProtocol
(\ s a -> s{_suUploadProtocol = a})
-- | Pretty-print response.
suPp :: Lens' ServicesUndelete Bool
suPp = lens _suPp (\ s a -> s{_suPp = a})
-- | OAuth access token.
suAccessToken :: Lens' ServicesUndelete (Maybe Text)
suAccessToken
= lens _suAccessToken
(\ s a -> s{_suAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
suUploadType :: Lens' ServicesUndelete (Maybe Text)
suUploadType
= lens _suUploadType (\ s a -> s{_suUploadType = a})
-- | OAuth bearer token.
suBearerToken :: Lens' ServicesUndelete (Maybe Text)
suBearerToken
= lens _suBearerToken
(\ s a -> s{_suBearerToken = a})
-- | The name of the service. See the
-- [overview](\/service-management\/overview) for naming requirements. For
-- example: \`example.googleapis.com\`.
suServiceName :: Lens' ServicesUndelete Text
suServiceName
= lens _suServiceName
(\ s a -> s{_suServiceName = a})
-- | JSONP
suCallback :: Lens' ServicesUndelete (Maybe Text)
suCallback
= lens _suCallback (\ s a -> s{_suCallback = a})
instance GoogleRequest ServicesUndelete where
type Rs ServicesUndelete = Operation
type Scopes ServicesUndelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/service.management"]
requestClient ServicesUndelete'{..}
= go _suServiceName _suXgafv _suUploadProtocol
(Just _suPp)
_suAccessToken
_suUploadType
_suBearerToken
_suCallback
(Just AltJSON)
serviceManagementService
where go
= buildClient
(Proxy :: Proxy ServicesUndeleteResource)
mempty
| rueshyna/gogol | gogol-servicemanagement/gen/Network/Google/Resource/ServiceManagement/Services/Undelete.hs | mpl-2.0 | 5,781 | 0 | 18 | 1,389 | 865 | 505 | 360 | 122 | 1 |
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
import MoreThanSufficientlyLongModuleNameWithSome
(compact, fit, inA, items, layout, not, that, will)
import TestJustAbitToLongModuleNameLikeThisOneIs ()
import TestJustShortEnoughModuleNameLikeThisOne ()
| lspitzner/brittany | data/Test476.hs | agpl-3.0 | 321 | 0 | 5 | 29 | 43 | 28 | 15 | 4 | 0 |
{-# OPTIONS -fglasgow-exts #-}
module Plugin where
import API
import Data.Dynamic
my_fun = plugin { function = "plugin says \"hello\"" }
resource_dyn :: Dynamic
resource_dyn = toDyn my_fun
| stepcut/plugins | testsuite/dynload/simple/Plugin.hs | lgpl-2.1 | 193 | 0 | 6 | 32 | 39 | 24 | 15 | 7 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Kubernetes.V1.EndpointSubset where
import GHC.Generics
import Kubernetes.V1.EndpointAddress
import Kubernetes.V1.EndpointPort
import qualified Data.Aeson
-- | EndpointSubset is a group of addresses with a common set of ports. The expanded set of endpoints is the Cartesian product of Addresses x Ports. For example, given:\n {\n Addresses: [{\"ip\": \"10.10.1.1\"}, {\"ip\": \"10.10.2.2\"}],\n Ports: [{\"name\": \"a\", \"port\": 8675}, {\"name\": \"b\", \"port\": 309}]\n }\nThe resulting set of endpoints can be viewed as:\n a: [ 10.10.1.1:8675, 10.10.2.2:8675 ],\n b: [ 10.10.1.1:309, 10.10.2.2:309 ]
data EndpointSubset = EndpointSubset
{ addresses :: Maybe [EndpointAddress] -- ^ IP addresses which offer the related ports that are marked as ready. These endpoints should be considered safe for load balancers and clients to utilize.
, notReadyAddresses :: Maybe [EndpointAddress] -- ^ IP addresses which offer the related ports but are not currently marked as ready because they have not yet finished starting, have recently failed a readiness check, or have recently failed a liveness check.
, ports :: Maybe [EndpointPort] -- ^ Port numbers available on the related IP addresses.
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON EndpointSubset
instance Data.Aeson.ToJSON EndpointSubset
| minhdoboi/deprecated-openshift-haskell-api | kubernetes/lib/Kubernetes/V1/EndpointSubset.hs | apache-2.0 | 1,521 | 0 | 10 | 240 | 119 | 73 | 46 | 17 | 0 |
-- | The main Robot interface.
module Test.Robot
(
-- * Running your robot
Robot() -- hide implementation
, runRobot
-- * Key and button constants
, module Test.Robot.Types
-- * Doing things
, Pressable(press, release, hold)
, moveBy
, moveTo
, tap
-- * Miscellaneous
, sleep
, module Test.Robot.Connection
) where
import Control.Applicative
import Control.Concurrent (threadDelay)
import Control.Monad.Catch
import Control.Monad.IO.Class
import Test.Robot.Connection
import Test.Robot.Internal
import Test.Robot.Types
infixr 4 `hold` -- Allow e.g. xs ++ ys `hold` m
-- | Represents things that can be pressed: either a single 'Switch' or
-- a list of 'Switch'es.
class Pressable x where
-- | Press a key or button.
press :: x -> Robot ()
-- | Release a key or button.
release :: x -> Robot ()
-- | @hold x act@ holds down @x@ while executing @act@. It is
-- equivalent to:
--
-- @
-- press x >> act >> release x
-- @
--
-- except @hold@ ensures that the argument is released in the event
-- of an exception.
--
hold :: x -> Robot a -> Robot a
hold = bracket_ <$> press <*> release
instance Pressable Switch where
press = switch True
release = switch False
-- | Press items from left-to-right, but release from right-to-left.
--
-- This behavior ensures the following equivalence holds:
--
-- @
-- press xs >> act >> release xs
-- === xs \`hold\` act
-- === x1 \`hold\` x2 \`hold\` ... xn \`hold\` act
-- @
--
instance Pressable x => Pressable [x] where
press = mapM_ press
release = mapM_ release . reverse
hold = foldr (.) id . map hold
--hold [] = id
--hold (x:xs) = hold x . hold xs
-- | Move the pointer by an offset.
moveBy :: Int -> Int -> Robot ()
moveBy = motion True
-- | Move the pointer to a point on the screen.
moveTo :: Int -> Int -> Robot ()
moveTo = motion False
-- | Press the argument, then release it.
--
-- Note that the underlying events are fired very quickly; much faster
-- than some applications (such as Xmonad) can handle. If this becomes
-- an issue, you may introduce a delay using 'sleep':
--
-- @
-- slowTap x = x \`hold\` sleep 0.1
-- @
--
tap :: Pressable x => x -> Robot ()
tap = (`hold` return ())
-- | Do nothing for the specified number of seconds.
sleep :: Rational -> Robot ()
sleep = liftIO . threadDelay . round . (* 1000000)
| lfairy/robot | Test/Robot.hs | apache-2.0 | 2,461 | 0 | 9 | 620 | 427 | 259 | 168 | 43 | 1 |
{-# LANGUAGE OverloadedStrings, NoImplicitPrelude, FlexibleContexts
#-}
module Ethereum.Analyzer.EVM.CfgAugWithTopNPassSpec
( spec
) where
import Protolude hiding (show)
import Ckev.In.Text
import Data.Text as DT
import Ethereum.Analyzer.EVM
import Ethereum.Analyzer.TestData.Basic
import Test.Hspec
spec :: Spec
spec =
describe "doCfgAugWithTopNPass" $ do
it "works for hexstring1" $ do
let result =
unWordLabelMapM $ showText <$> doCfgAugWithTopNPass hexstring1
DT.length result `shouldBe` 4876
it "works for hexstring2" $ do
let result =
toS $
unWordLabelMapM
((toS . showText <$> doCfgAugWithTopNPass hexstring2) :: WordLabelMapM Text)
(result :: [Char]) `shouldContain` "OC: 9: JUMPI -> [L3,L5]"
| zchn/ethereum-analyzer | ethereum-analyzer/test/Ethereum/Analyzer/EVM/CfgAugWithTopNPassSpec.hs | apache-2.0 | 795 | 0 | 19 | 180 | 182 | 100 | 82 | 22 | 1 |
{-# LANGUAGE OverloadedStrings, NamedFieldPuns #-}
module FormEngine.FormElement.Rendering (
ElemAction
, ElemBehaviour(..)
, foldElements
, renderElement
) where
import Prelude
import Data.Monoid ((<>))
import Data.Foldable (foldlM)
import Data.Maybe (fromMaybe)
import Data.Char (chr)
--import Debug.Trace (traceShow)
--import Haste.DOM
import FormEngine.JQuery as JQ
import FormEngine.FormItem
import FormEngine.FormElement.FormElement as Element
import FormEngine.FormElement.Identifiers
import FormEngine.FormElement.Updating
import FormEngine.FormContext
import FormEngine.Functionality
import FormEngine.FormElement.AutoComplete (autoCompleteHandler)
foldElements :: [FormElement] -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
foldElements elems context behaviour jq = foldlM (\jq1 e -> renderElement e context behaviour jq1) jq elems
renderElement :: FormElement -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
renderElement element@SimpleGroupElem{} context behaviour jq = renderSimpleGroup element context behaviour jq
renderElement element@OptionalGroupElem{} context behaviour jq = renderOptionalGroup element context behaviour jq
renderElement element@MultipleGroupElem{} context behaviour jq = renderMultipleGroup element context behaviour jq
renderElement element@StringElem{} context behaviour jq = renderStringElement element context behaviour jq
renderElement element@TextElem{} context behaviour jq = renderTextElement element context behaviour jq
renderElement element@EmailElem{} context behaviour jq = renderEmailElement element context behaviour jq
renderElement element@NumberElem{} context behaviour jq = renderNumberElement element context behaviour jq
renderElement element@ChoiceElem{} context behaviour jq = renderChoiceElement element context behaviour jq
renderElement element@InfoElem{} context behaviour jq = renderInfoElement element context behaviour jq
renderElement element@ListElem{} context behaviour jq = renderListElement element context behaviour jq
renderElement element@SaveButtonElem{} context _ jq = renderSaveButtonElement element context jq
renderElement element@SubmitButtonElem{} context _ jq = renderSubmitButtonElement element context jq
renderElement _ _ _ jq = errorjq "renderElement did not unify" jq
setLongDescription :: FormElement -> IO ()
setLongDescription element = do
paragraphJq <- select $ "#" ++ descSubpaneParagraphId element
spanJq <- findSelector "span" paragraphJq
let maybeDesc = iLongDescription $ fiDescriptor $ formItem element
case maybeDesc of
Nothing -> return ()
Just desc -> do
_ <- setHtml desc spanJq
_ <- appearJq paragraphJq
return ()
return ()
unsetLongDescription :: FormElement -> IO ()
unsetLongDescription element = do
paragraphJq <- select $ "#" ++ descSubpaneParagraphId element
_ <- disappearJq paragraphJq
return ()
elementFocusHandler :: FormElement -> FormContext -> ElemBehaviour -> Handler
elementFocusHandler element context behaviour _ = do
inputFieldUpdate element context
applyRules element context
case focusAction behaviour of
Nothing -> return ()
Just action -> action element context
elementBlurHandler :: FormElement -> FormContext -> ElemBehaviour -> Handler
elementBlurHandler element context behaviour _ = do
inputFieldUpdate element context
applyRules element context
case blurAction behaviour of
Nothing -> return ()
Just action -> action element context
elementClickHandler :: FormElement -> FormContext -> ElemBehaviour -> Handler
elementClickHandler element context behaviour _ =
case clickAction behaviour of
Nothing -> return ()
Just action -> action element context
renderLabel :: FormElement -> JQuery -> IO JQuery
renderLabel element jq =
case Element.maybeLabel element of
Nothing -> return jq
Just label -> case Element.maybeLink element of
Nothing -> appendT "<label>" jq >>= setTextInside label
Just link -> appendT ("<label class=\"link\" onclick=\"" <> link <> "\">") jq
>>= setTextInside label
renderHeading :: Maybe String -> Int -> JQuery -> IO JQuery
renderHeading Nothing _ jq = return jq
renderHeading (Just label) lvl jq = appendT heading jq >>= setTextInside label
where
heading :: String
heading = "<h" <> show lvl <> ">"
renderShortDesc :: FormElement -> JQuery -> IO JQuery
renderShortDesc element jq = let maybeDesc = iShortDescription $ fiDescriptor $ formItem element in
case maybeDesc of
Nothing -> return jq
Just desc ->
appendT "<span class='short-desc'>" jq >>= setTextInside desc
renderInput :: IO JQuery -> FormElement -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
renderInput elemIOJq element context behaviour jq =
appendT "<table>" jq
>>= setMouseEnterHandler (\_ -> setLongDescription element)
>>= setMouseLeaveHandler (\_ -> unsetLongDescription element)
>>= inside
>>= appendT "<tbody>"
>>= inside
>>= appendT "<tr>"
>>= inside
>>= (case detailsFunc behaviour of
Nothing -> return
Just functionality -> renderQuestionDetails functionality)
>>= renderLabelCell
>>= renderElemCell
>>= renderFlagCell
>>= JQ.parent
>>= appendT "<tr>"
>>= inside
>>= appendT "<div></div>"
>>= setAttrInside "id" (autoCompleteBoxId element)
>>= addClassInside "autocomplete-suggestions"
>>= JQ.parent
>>= JQ.parent
>>= JQ.parent
>>= renderShortDesc element
where
renderQuestionDetails detFunc jq1 = appendT "<td>" jq1
>>= inside
>>= addClass "more-space functionality"
>>= appendT (funcImg detFunc)
>>= setClickHandler (\_ -> funcAction detFunc element context)
>>= JQ.parent
renderLabelCell jq1 = appendT "<td class='labeltd'>" jq1
>>= inside
>>= addClass "more-space"
>>= renderLabel element
>>= JQ.parent
renderElemCell jq1 = do
elemJq <- elemIOJq
appendT "<td>" jq1
>>= inside
>>= appendJq elemJq
>>= JQ.parent
renderFlagCell jq1 = appendT "<td>" jq1 >>= setAttrInside "id" (flagPlaceId element)
renderStringElement :: FormElement -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
renderStringElement element context behaviour jq =
let
elemIOJq = select "<input type='text'>"
>>= setAttr "name" (elementId element)
>>= setAttr "identity" (Element.identity element)
>>= setAttr "value" (seValue element)
>>= onMouseEnter (elementFocusHandler element context behaviour)
-- >>= onKeyup (elementFocusHandler element context behaviour)
>>= onKeyup (handlerCombinator [elementFocusHandler element context behaviour, autoCompleteHandler (chr 10) element context])
>>= onBlur (elementBlurHandler element context behaviour)
>>= onMouseLeave (elementBlurHandler element context behaviour)
>>= onClick (elementClickHandler element context behaviour)
in renderInput elemIOJq element context behaviour jq
renderTextElement :: FormElement -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
renderTextElement element context behaviour jq =
let
elemIOJq = select "<textarea>"
>>= setAttr "name" (elementId element)
>>= setAttr "identity" (Element.identity element)
>>= setHtml (teValue element)
>>= onMouseEnter (elementFocusHandler element context behaviour)
>>= onKeyup (handlerCombinator [elementFocusHandler element context behaviour, autoCompleteHandler (chr 10) element context])
>>= onBlur (elementBlurHandler element context behaviour)
>>= onMouseLeave (elementBlurHandler element context behaviour)
>>= onClick (elementClickHandler element context behaviour)
in renderInput elemIOJq element context behaviour jq
renderEmailElement :: FormElement -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
renderEmailElement element context behaviour jq =
let
elemIOJq = select "<input type='email'>"
>>= setAttr "name" (elementId element)
>>= setAttr "identity" (Element.identity element)
>>= setAttr "value" (eeValue element)
>>= onMouseEnter (elementFocusHandler element context behaviour)
>>= onKeyup (elementFocusHandler element context behaviour)
>>= onBlur (elementBlurHandler element context behaviour)
>>= onMouseLeave (elementBlurHandler element context behaviour)
>>= onClick (elementClickHandler element context behaviour)
in renderInput elemIOJq element context behaviour jq
renderNumberElement :: FormElement -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
renderNumberElement element context behaviour jq =
let
elemIOJq = select "<span></span>"
>>= appendT "<input type='number' step='0.1'>"
>>= setAttrInside "id" (elementId element)
>>= setAttrInside "name" (elementId element)
>>= setAttrInside "identity" (Element.identity element)
>>= setAttrInside "value" (fromMaybe "" $ show <$> neMaybeValue element)
>>= setMouseEnterHandler (elementFocusHandler element context behaviour)
>>= setKeyupHandler (elementFocusHandler element context behaviour)
>>= setBlurHandler (elementBlurHandler element context behaviour)
>>= setMouseLeaveHandler (elementBlurHandler element context behaviour)
>>= setChangeHandler (elementClickHandler element context behaviour)
>>= appendT " "
>>= case nfiUnit (formItem element) of
NoUnit -> return
SingleUnit u -> appendT u
MultipleUnit units -> renderUnits units
where
renderUnits :: [String] -> JQuery -> IO JQuery
renderUnits units jq1 = foldlM (flip renderUnit) jq1 units
where
renderUnit :: String -> JQuery -> IO JQuery
renderUnit unit jq2 =
appendT "<input type='radio'>" jq2
>>= setAttrInside "value" unit
>>= setAttrInside "name" (nfiUnitId $ nfi element)
>>= setMouseEnterHandler (elementFocusHandler element context behaviour)
>>= setClickHandler (elementFocusHandler element context behaviour)
>>= setMouseLeaveHandler (elementBlurHandler element context behaviour)
>>= case neMaybeUnitValue element of
Nothing -> return
Just selectedOption -> if selectedOption == unit then setAttrInside "checked" "checked" else return
>>= appendT "<label>" >>= setTextInside unit
>>= appendT " "
in renderInput elemIOJq element context behaviour jq
renderListElement :: FormElement -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
renderListElement element context behaviour jq =
let
selectIOJq = select "<select>"
>>= setAttr "name" (elementId element)
>>= setAttr "identity" (Element.identity element)
>>= onBlur (elementFocusHandler element context behaviour)
>>= onChange (elementFocusHandler element context behaviour)
>>= onMouseLeave (elementBlurHandler element context behaviour)
>>= onClick (elementClickHandler element context behaviour)
>>= renderOptions
in
renderInput selectIOJq element context behaviour jq
where
renderOptions :: JQuery -> IO JQuery
renderOptions jq1 = foldlM (flip renderOption) jq1 (lfiAvailableOptions (formItem element))
where
renderOption :: (String, String) -> JQuery -> IO JQuery
renderOption (listVal, label) jq2 =
appendT "<option>" jq2
>>= setAttrInside "value" listVal
>>= setTextInside label
>>= case leMaybeValue element of
Nothing -> return
Just selectedOption -> if listVal == selectedOption then setAttrInside "selected" "selected" else return
choiceSwitchHandler :: FormElement -> OptionElement -> Handler
choiceSwitchHandler element optionElem _ = do
allPanes <- mapM selectOptionSection detailOptionElems
mapM_ disappearJq allPanes
case optionElem of
SimpleOptionElem {} ->
return ()
DetailedOptionElem {} -> do
_ <- selectOptionSection optionElem >>= appearJq
return ()
where
selectOptionSection :: OptionElement -> IO JQuery
selectOptionSection oe = select $ "#" <> optionSectionId element oe
detailOptionElems = Prelude.filter justDetailed (cheOptions element)
where
justDetailed :: OptionElement -> Bool
justDetailed SimpleOptionElem{} = False
justDetailed DetailedOptionElem{} = True
choiceValidateHandler :: FormElement -> FormContext -> Handler
choiceValidateHandler element context _ = do
isSelected <- isRadioSelected $ radioName element
updateValidityFlag element context isSelected
-- Now a hack, needs to get the validity from the instances
renderRadio :: FormElement -> OptionElement -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
renderRadio element optionElem context behaviour jq =
--dumptIO (optionElemValue optionElem)
-- dumptIO (choiceIisSelected choiceI)
appendT "<input type='radio'>" jq
>>= setAttrInside "id" (radioId element optionElem)
>>= setAttrInside "name" (radioName element)
>>= setAttrInside "identity" (Element.identity element)
>>= setAttrInside "value" (optionElemValue optionElem)
>>= (if optionElemIsSelected optionElem then setAttrInside "checked" "checked" else return)
>>= setClickHandler (handlerCombinator
[ choiceSwitchHandler element optionElem
, choiceValidateHandler element context
, elementClickHandler element context behaviour
])
>>= setMouseLeaveHandler (choiceValidateHandler element context)
>>= appendT "<label>"
>>= setTextInside (optionElemValue optionElem)
>>= appendT appendix
where
appendix :: String
appendix = case optionElem of
SimpleOptionElem {} -> ""
DetailedOptionElem {} -> "▾"
renderChoiceElement :: FormElement -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
renderChoiceElement element context behaviour jq =
let elemIOJq = select "<div></div>" >>= renderButtons (cheOptions element)
in
renderInput elemIOJq element context behaviour jq
>>= renderPanes (cheOptions element)
where
renderButtons :: [OptionElement] -> JQuery -> IO JQuery
renderButtons optionElems jq1 = foldlM (flip renderButton) jq1 optionElems
where
renderButton :: OptionElement -> JQuery -> IO JQuery
renderButton optionElem jq2 =
renderRadio element optionElem context behaviour jq2
>>= (if optionElem == Prelude.last (cheOptions element) then return else appendT "<br>")
renderPanes :: [OptionElement] -> JQuery -> IO JQuery
renderPanes optionElems jq1 = foldlM (flip renderPane) jq1 optionElems
where
renderPane :: OptionElement -> JQuery -> IO JQuery
renderPane SimpleOptionElem{} jq2 = return jq2
renderPane optionElem@DetailedOptionElem{ dcheElements } jq2 =
appendT "<div>" jq2
>>= setAttrInside "id" (optionSectionId element optionElem) >>= inside
>>= disappearJq
>>= foldElements dcheElements context behaviour
>>= JQ.parent
renderInfoElement :: FormElement -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
renderInfoElement element _ _ jq =
appendT "<table>" jq
>>= setMouseEnterHandler (\_ -> setLongDescription element)
>>= setMouseLeaveHandler (\_ -> unsetLongDescription element)
>>= inside
>>= appendT "<tbody>"
>>= inside
>>= appendT "<tr>"
>>= inside
>>= appendT "<td class='more-space intro' colspan='2'>"
>>= setTextInside (ifiText $ formItem element)
>>= JQ.parent
>>= JQ.parent
>>= JQ.parent
>>= renderShortDesc element
renderSimpleGroup :: FormElement -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
renderSimpleGroup element context behaviour jq = let lvl = Element.level element in
--dumptIO $ fromMaybe "" (Element.maybeLabel element)
appendT "<div class='simple-group'>" jq
>>= setAttrInside "level" (show lvl)
>>= (if lvl > 1 then addClassInside "framed" else return)
>>= inside
>>= renderHeading (Element.maybeLabel element) lvl
>>= renderShortDesc element
>>= foldElements (sgeElements element) context behaviour
>>= JQ.parent
renderOptionalGroup :: FormElement -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
renderOptionalGroup element context behaviour jq = let lvl = Element.level element in
--dumptIO $ fromMaybe "" (Element.maybeLabel element)
appendT "<div class='optional-group'>" jq
>>= setAttrInside "level" (show lvl)
>>= setMouseEnterHandler (\_ -> setLongDescription element)
>>= setMouseLeaveHandler (\_ -> unsetLongDescription element)
>>= inside
>>= renderCheckbox
>>= appendT (if not $ null (ogeElements element) then "▾" else "")
>>= renderShortDesc element
>>= renderOgContents
>>= JQ.parent
where
renderCheckbox :: JQuery -> IO JQuery
renderCheckbox jq1 =
appendT "<input type='checkbox'>" jq1
>>= setAttrInside "name" (elementId element)
>>= (if ogeChecked element then setAttrInside "checked" "checked" else return)
>>= setClickHandler (handlerCombinator [handler, elementClickHandler element context behaviour])
>>= renderLabel element
where
handler ev = do
sectionJq <- select $ "#" <> checkboxId element
checkBox <- target ev
checked <- isChecked checkBox
_ <- if checked then
appearJq sectionJq
else
disappearJq sectionJq
return ()
renderOgContents :: JQuery -> IO JQuery
renderOgContents jq1 =
case ogeElements element of
[] -> return jq1
_ ->
appendT "<div class='optional-section'>" jq1 >>= setAttrInside "id" (checkboxId element)
>>= inside
>>= foldElements (ogeElements element) context behaviour
>>= JQ.parent
renderMultipleGroup :: FormElement -> FormContext -> ElemBehaviour -> JQuery -> IO JQuery
renderMultipleGroup element context behaviour jq = let lvl = Element.level element in
appendT "<div class='multiple-group'>" jq
>>= addClassInside "framed"
>>= setAttrInside "level" (show lvl)
>>= inside
>>= renderHeading (Element.maybeLabel element) lvl
>>= renderShortDesc element
>>= renderMgGroups (mgeGroups element)
>>= renderAddButton
>>= JQ.parent
where
renderMgGroups :: [ElemGroup] -> JQuery -> IO JQuery
renderMgGroups groups jq1 = foldlM (flip renderMgGroup) jq1 groups
renderMgGroup :: ElemGroup -> JQuery -> IO JQuery
renderMgGroup group jq2 =
--dumptIO $ show $ getGroupNo $ elementId $ head $ egElements group
--dumptIO $ show $ head $ egElements group
appendT "<table>" jq2 >>= inside -- MG item holder
>>= appendT "<tbody>" >>= inside
>>= appendT "<tr>" >>= inside
>>= appendT "<td>" >>= inside
>>= appendT "<div class='multiple-section'>"
>>= inside
>>= foldElements (egElements group) context behaviour
>>= JQ.parent
>>= JQ.parent
>>= (if egNumber group > 0 then renderRemoveButton else return)
>>= JQ.parent
>>= JQ.parent
>>= JQ.parent
where
renderRemoveButton :: JQuery -> IO JQuery
renderRemoveButton jq3 =
appendT "<td style='vertical-align: middle;'>" jq3 >>= inside
>>= appendT (removeImg context)
>>= setClickHandler removingHandler
>>= JQ.parent
where
removingHandler :: Handler
removingHandler ev = do
minusButtonJq <- target ev
tableJq <- JQ.parent minusButtonJq >>= JQ.parent >>= JQ.parent >>= JQ.parent -- img -> td -> tr -> tbody -> table
_ <- removeJq tableJq
return ()
renderAddButton :: JQuery -> IO JQuery
renderAddButton jq2 =
appendT (addImg context) jq2
>>= setAttrInside "count" "1" -- must be refactored after real adding of groups
>>= setClickHandler addingHandler
where
addingHandler :: Handler
addingHandler ev = do
plusButtonJq <- target ev
countStr <- getAttr "count" plusButtonJq
let countNum = read (show countStr) :: Int
_ <- setAttr "count" (show $ countNum + 1) plusButtonJq
let newGroup = ElemGroup { egElements = map (setGroupOfElem $ Just newGroup) $ egElements $ Prelude.last $ mgeGroups element, egNumber = countNum }
tableJq <- prev plusButtonJq
_ <- renderMgGroup newGroup tableJq
mapM_ (\e -> selectByName (elementId e) >>= mouseleave) $ egElements newGroup
return ()
renderSubmitButtonElement :: FormElement -> FormContext -> JQuery -> IO JQuery
renderSubmitButtonElement element _ jq =
appendT "<table style='margin-top: 10px'>" jq >>= inside
>>= appendT "<tbody>" >>= inside
>>= appendT "<tr>" >>= inside
>>= appendT "<td class='labeltd more-space' style='text-align: center'>" >>= inside
>>= appendT "<input type='button' class='submit'>"
-- >>= setClickHandler submitHandler
>>= setAttrInside "value" (fromMaybe "Submit" (show <$> Element.maybeLabel element))
>>= JQ.parent
>>= JQ.parent
>>= JQ.parent
>>= JQ.parent
>>= renderShortDesc element
renderSaveButtonElement :: FormElement -> FormContext -> JQuery -> IO JQuery
renderSaveButtonElement element _ jq =
appendT "<table style='margin-top: 10px'>" jq >>= inside
>>= appendT "<tbody>" >>= inside
>>= appendT "<tr>" >>= inside
>>= appendT "<td class='labeltd more-space' style='text-align: center'>" >>= inside
>>= appendT "<input type='submit'>"
>>= setAttrInside "value" (fromMaybe "Submit" (show <$> Element.maybeLabel element))
>>= JQ.parent
>>= JQ.parent
>>= JQ.parent
>>= JQ.parent
>>= renderShortDesc element
| DataStewardshipPortal/ds-form-engine | FormElement/Rendering.hs | apache-2.0 | 21,774 | 0 | 29 | 4,579 | 5,714 | 2,751 | 2,963 | 435 | 5 |
{-# LANGUAGE NoMonomorphismRestriction #-}
module Tests.OpsTest where
import Ops
import Lambda
import Prelude ( ($), Int, (==), return, sequence, (>>=), and, (.), IO, Bool )
import qualified Control.Monad
test1 :: (LOps l) => l Int
test1 = app (lam $ \x -> lit 3 + x) (lit 2)
test2 :: (LOps l) => l Int
test2 = app (lam $ \x -> lit 3 * x) (lit 2)
test3 :: (LOps l) => l Int
test3 = app (lam $ \x -> lit 2 * x + lit 1) (lit 5 - lit 2)
test1ast :: IO Bool
test1ast = do
t <- ast test1
return $ t "" == "(λa.3+a) 2"
test1eval :: IO Bool
test1eval = return $ eval test1 == 5
test2ast :: IO Bool
test2ast = do
t <- ast test2
return $ t "" == "(λa.3*a) 2"
test2eval :: IO Bool
test2eval = return $ eval test2 == 6
test3ast :: IO Bool
test3ast = do
t <- ast test3
return $ t "" == "(λa.2*a+1) (5-2)"
test3eval :: IO Bool
test3eval = return $ eval test3 == 7
tests :: [IO Bool]
tests = [
test1ast
, test1eval
]
runTests :: IO Bool
runTests = Control.Monad.liftM and $ sequence tests
| agobi/sizechecking | Tests/OpsTest.hs | bsd-2-clause | 1,031 | 0 | 11 | 259 | 463 | 244 | 219 | 36 | 1 |
module HaskHOL.Lib.IndTypes.Pre2 where
import HaskHOL.Core hiding (typeOf, lefts)
import HaskHOL.Core.Kernel (typeOf)
import qualified HaskHOL.Core.State as S (mkType)
import HaskHOL.Deductive
import HaskHOL.Lib.Pair
import HaskHOL.Lib.Recursion
import HaskHOL.Lib.Nums
import HaskHOL.Lib.CalcNum
import HaskHOL.Lib.WF
import HaskHOL.Lib.IndTypesPre
import qualified HaskHOL.Lib.IndTypes.Pre as Pre
defineTypeRaw :: IndTypesPreCtxt thry
=> [(HOLType, [(Text, [HOLType])])]
-> HOL Theory thry (HOLThm, HOLThm)
defineTypeRaw def =
do (ith, rth) <- Pre.defineTypeRaw def
rth' <- generalizeRecursionTheorem rth
return (ith, rth')
generalizeRecursionTheorem :: BoolCtxt thry => HOLThm -> HOL cls thry HOLThm
generalizeRecursionTheorem thm =
let (_, ebod) = stripForall $ concl thm
(evs, bod) = stripExists ebod
n = length evs in
if n == 1 then return thm
else let tys = map (\ i -> mkVarType $ "Z" `append` textShow i)
[0..(n-1)] in
do sty <- mkSum tys
inls <- mkInls sty
outls <- mkOutls sty
zty <- typeOf `fmap`
(rand . snd . stripForall . head $ conjuncts bod)
ith <- primINST_TYPE [(zty, sty)] thm
let (_, ebod') = stripForall $ concl ith
(evs', bod') = stripExists ebod'
fns' <- map2M mkNewfun evs' outls
fnalist <- zip evs' `fmap` mapM (rator <=< lhs . concl) fns'
let inlalist = zip evs' inls
outlalist = zip evs' outls
defs <- mapM (hackClause outlalist inlalist) $ conjuncts bod'
jth <- ruleBETA $ ruleSPECL (map fst defs) ith
bth <- primASSUME . snd . stripExists $ concl jth
cth <- foldr1M ruleCONJ =<< mapM (finishClause outlalist) =<<
ruleCONJUNCTS bth
dth <- ruleELIM_OUTCOMBS cth
eth <- ruleGEN_REWRITE convONCE_DEPTH (map ruleSYM fns') dth
fth <- foldrM ruleSIMPLE_EXISTS eth (map snd fnalist)
let dtms = map (head . hyp) fns'
gth <- foldrM (\ e th -> do (l, r) <- destEq e
th' <- ruleDISCH e th
th'' <- primINST [(l, r)] th'
ruleMP th'' $ primREFL r) fth dtms
hth <- rulePROVE_HYP jth $
foldrM ruleSIMPLE_CHOOSE gth evs'
xvs <- mapM (fmap (fst . stripComb) .
(rand . snd . stripForall)) .
conjuncts $ concl eth
ruleGENL xvs hth
where ruleELIM_OUTCOMBS :: BoolCtxt thry => HOLThm -> HOL cls thry HOLThm
ruleELIM_OUTCOMBS =
ruleGEN_REWRITE convTOP_DEPTH
[getRecursiveDefinition "OUTL", getRecursiveDefinition "OUTR"]
mkSum :: [HOLType] -> HOL cls thry HOLType
mkSum tys =
let k = length tys in
if k == 1 then return $! head tys
else do (tys1, tys2) <- trySplitAt (k `div` 2) tys
tys1' <- mkSum tys1
tys2' <- mkSum tys2
mkType "sum" [tys1', tys2']
mkInls :: HOLType -> HOL cls thry [HOLTerm]
mkInls typ =
do bods <- mkInlsRec typ
mapM (\ t -> mkAbs (try' $ findTerm isVar t) t) bods
where mkInlsRec :: HOLType -> HOL cls thry [HOLTerm]
mkInlsRec ty@TyVar{} = sequence [mkVar "x" ty]
mkInlsRec ty =
do (_, [ty1, ty2]) <- destType ty
inls1 <- mkInlsRec ty1
inls2 <- mkInlsRec ty2
inl <- mkConst "INL" [(tyA, ty1), (tyB, ty2)]
inr <- mkConst "INR" [(tyA, ty1), (tyB, ty2)]
insl1' <- mapM (mkComb inl) inls1
insl2' <- mapM (mkComb inr) inls2
return $! insl1' ++ insl2'
mkOutls :: HOLType -> HOL cls thry [HOLTerm]
mkOutls typ =
let x = mkVar "x" typ in
do inls <- mkOutlsRec x typ
mapM (mkAbs x) inls
where mkOutlsRec :: HOLTermRep tm cls thry
=> tm -> HOLType -> HOL cls thry [HOLTerm]
mkOutlsRec sof TyVar{} =
do tm <- toHTm sof
return [tm]
mkOutlsRec sof ty =
do (_, [ty1, ty2]) <- destType ty
outl <- mkConst "OUTL" [(tyA, ty1), (tyB, ty2)]
outr <- mkConst "OUTR" [(tyA, ty1), (tyB, ty2)]
outl' <- mkOutlsRec (mkComb outl sof) ty1
outr' <- mkOutlsRec (mkComb outr sof) ty2
return $! outl' ++ outr'
mkNewfun :: HOLTerm -> HOLTerm -> HOL cls thry HOLThm
mkNewfun fn outl =
do (s, ty) <- destVar fn
dty <- (head . snd) `fmap` destType ty
let x = mkVar "x" dty
(y, bod) <- destAbs outl
fnx <- mkComb fn x
r <- mkAbs x =<< varSubst [(y, fnx)] bod
let l = mkVar s $ typeOf r
etm <- mkEq l r
ruleRIGHT_BETAS [x] $ primASSUME etm
hackClause :: HOLTermEnv -> HOLTermEnv -> HOLTerm
-> HOL cls thry (HOLTerm, HOLTerm)
hackClause outlalist inlalist tm =
let (_, bod) = stripForall tm in
do (l, r) <- destEq bod
let (fn, args) = stripComb r
pargs <- mapM (\ a ->
do g <- genVar $ typeOf a
if isVar a
then return (g, g)
else do outl <- flip assoc outlalist =<<
rator a
outl' <- mkComb outl g
return (outl', g)) args
let (args', args'') = unzip pargs
inl <- flip assoc inlalist =<< rator l
rty <- (head . snd) `fmap` (destType $ typeOf inl)
nty <- foldrM (mkFunTy . typeOf) rty args'
(fname, _) <- destVar fn
let fn' = mkVar fname nty
r' <- listMkAbs args'' =<< mkComb inl =<< listMkComb fn' args'
return (r', fn)
finishClause :: BoolCtxt thry => HOLTermEnv -> HOLThm
-> HOL cls thry HOLThm
finishClause outlalist t =
let (avs, bod) = stripForall $ concl t in
do outl <- flip assoc outlalist =<< rator (lHand bod)
th' <- ruleSPECL avs t
ruleGENL avs . ruleBETA $ ruleAP_TERM outl th'
proveConstructorsInjective :: PairCtxt thry => HOLThm
-> HOL cls thry HOLThm
proveConstructorsInjective ax =
let cls = conjuncts . snd . stripExists . snd . stripForall $ concl ax in
do pats <- mapM (rand <=< lHand . snd . stripForall) cls
foldr1M ruleCONJ =<< mapFilterM proveDistinctness pats
where ruleDEPAIR :: PairCtxt thry => HOLThm -> HOL cls thry HOLThm
ruleDEPAIR = ruleGEN_REWRITE convTOP_SWEEP [thmPAIR_EQ]
proveDistinctness :: PairCtxt thry
=> HOLTerm
-> HOL cls thry HOLThm
proveDistinctness pat =
let (f, args) = stripComb pat in
do rt <- foldr1M mkPair args
ty <- mkFunTy (typeOf pat) $ typeOf rt
fn <- genVar ty
dtm <- mkEq (mkComb fn pat) rt
eth <- proveRecursiveFunctionsExist ax =<<
listMkForall args dtm
let args' = variants args args
atm <- mkEq pat =<< listMkComb f args'
ath <- primASSUME atm
bth <- ruleAP_TERM fn ath
cth1 <- ruleSPECL args $ primASSUME =<<
snd `fmap` (destExists $ concl eth)
cth2 <- primINST (zip args args') cth1
pth <- primTRANS (primTRANS (ruleSYM cth1) bth) cth2
qth <- ruleDEPAIR pth
let qtm = concl qth
qths <- ruleCONJUNCTS $ primASSUME qtm
fth <- primREFL f
rth <- foldlM primMK_COMB fth qths
tth <- ruleIMP_ANTISYM (ruleDISCH atm qth) $ ruleDISCH qtm rth
uth <- ruleGENL args $ ruleGENL args' tth
rulePROVE_HYP eth $ ruleSIMPLE_CHOOSE fn uth
proveDistinct_pth :: ClassicCtxt thry => HOL cls thry HOLThm
proveDistinct_pth = cacheProof "proveDistinct_pth" ctxtClassic $
ruleTAUT [txt| a ==> F <=> ~a |]
proveConstructorsDistinct :: WFCtxt thry => HOLThm -> HOL cls thry HOLThm
proveConstructorsDistinct ax =
let cls = conjuncts . snd . stripExists . snd . stripForall $ concl ax in
do lefts <- mapM (destComb <=< lHand . snd . stripForall) cls
let fns = foldr (insert . fst) [] lefts
pats = map (\ f -> map snd (filter (\ (x,_) -> x == f) lefts)) fns
foldr1M ruleCONJ =<<
(foldr1 (++)) `fmap` (mapFilterM proveDistinct pats)
where allopairs :: Monad m => (a -> a -> m a) -> [a] -> [a] -> m [a]
allopairs _ [] _ = return []
allopairs f (l:ls) (_:ms) =
do xs <- mapM (f l) ms
ys <- allopairs f ls ms
return $! xs ++ ys
allopairs _ _ _ = return []
ruleNEGATE :: (ClassicCtxt thry, HOLThmRep thm cls thry)
=> thm -> HOL cls thry HOLThm
ruleNEGATE = ruleGEN_ALL . ruleCONV (convREWR proveDistinct_pth)
ruleREWRITE' :: (BoolCtxt thry, HOLThmRep thm cls thry)
=> HOLTerm -> thm -> HOL cls thry HOLThm
ruleREWRITE' bod th =
do ths <- ruleCONJUNCTS $ primASSUME bod
ruleGEN_REWRITE convONCE_DEPTH ths th
proveDistinct :: WFCtxt thry => [HOLTerm] -> HOL cls thry [HOLThm]
proveDistinct pat =
do tyNum <- S.mkType "num" ([]::[HOLType])
nms <- mapM mkNumeral ([0..(length pat -1)] :: [Int])
fn <- genVar =<< mkType "fun" [typeOf $ head pat, tyNum]
ls <- mapM (mkComb fn) pat
defs <- map2M (\ l r -> do l' <- frees `fmap` rand l
listMkForall l' =<< mkEq l r) ls nms
eth <- proveRecursiveFunctionsExist ax =<< listMkConj defs
(ev, bod) <- destExists $ concl eth
pat' <-mapM (\ t -> let (f, args) = if isNumeral t
then (t, [])
else stripComb t in
listMkComb f $ variants args args) pat
pairs <- allopairs mkEq pat pat'
nths <- mapM (ruleREWRITE' bod . ruleAP_TERM fn . primASSUME)
pairs
fths <- map2M (\ t th -> ruleNEGATE . ruleDISCH t $
ruleCONV convNUM_EQ th) pairs nths
ruleCONJUNCTS . rulePROVE_HYP eth .
ruleSIMPLE_CHOOSE ev $ foldr1M ruleCONJ fths
| ecaustin/haskhol-math | src/HaskHOL/Lib/IndTypes/Pre2.hs | bsd-2-clause | 11,566 | 0 | 22 | 4,921 | 3,731 | 1,815 | 1,916 | -1 | -1 |
{-# LANGUAGE ForeignFunctionInterface #-}
module Grenade.Layers.Internal.Pooling (
poolForward
, poolBackward
) where
import qualified Data.Vector.Storable as U ( unsafeToForeignPtr0, unsafeFromForeignPtr0 )
import Foreign ( mallocForeignPtrArray, withForeignPtr )
import Foreign.Ptr ( Ptr )
import Numeric.LinearAlgebra ( Matrix , flatten )
import qualified Numeric.LinearAlgebra.Devel as U
import System.IO.Unsafe ( unsafePerformIO )
poolForward :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Matrix Double -> Matrix Double
poolForward channels height width kernelRows kernelColumns strideRows strideColumns dataIm =
let vec = flatten dataIm
rowOut = (height - kernelRows) `div` strideRows + 1
colOut = (width - kernelColumns) `div` strideColumns + 1
numberOfPatches = rowOut * colOut
in unsafePerformIO $ do
outPtr <- mallocForeignPtrArray (numberOfPatches * channels)
let (inPtr, _) = U.unsafeToForeignPtr0 vec
withForeignPtr inPtr $ \inPtr' ->
withForeignPtr outPtr $ \outPtr' ->
pool_forwards_cpu inPtr' channels height width kernelRows kernelColumns strideRows strideColumns outPtr'
let matVec = U.unsafeFromForeignPtr0 outPtr (numberOfPatches * channels)
return $ U.matrixFromVector U.RowMajor (rowOut * channels) colOut matVec
foreign import ccall unsafe
pool_forwards_cpu
:: Ptr Double -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Ptr Double -> IO ()
poolBackward :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Matrix Double -> Matrix Double -> Matrix Double
poolBackward channels height width kernelRows kernelColumns strideRows strideColumns dataIm dataGrad =
let vecIm = flatten dataIm
vecGrad = flatten dataGrad
in unsafePerformIO $ do
outPtr <- mallocForeignPtrArray (height * width * channels)
let (imPtr, _) = U.unsafeToForeignPtr0 vecIm
let (gradPtr, _) = U.unsafeToForeignPtr0 vecGrad
withForeignPtr imPtr $ \imPtr' ->
withForeignPtr gradPtr $ \gradPtr' ->
withForeignPtr outPtr $ \outPtr' ->
pool_backwards_cpu imPtr' gradPtr' channels height width kernelRows kernelColumns strideRows strideColumns outPtr'
let matVec = U.unsafeFromForeignPtr0 outPtr (height * width * channels)
return $ U.matrixFromVector U.RowMajor (height * channels) width matVec
foreign import ccall unsafe
pool_backwards_cpu
:: Ptr Double -> Ptr Double -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Ptr Double -> IO ()
| HuwCampbell/grenade | src/Grenade/Layers/Internal/Pooling.hs | bsd-2-clause | 2,565 | 0 | 17 | 563 | 760 | 388 | 372 | 44 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Language.Drasil.Chunk.DefinedQuantity (DefinedQuantityDict, dqd, dqdNoUnit, dqd',
dqdQd, dqdWr) where
import Language.Drasil.Classes.Core (HasUID(uid), HasSymbol(symbol))
import Language.Drasil.Classes (NamedIdea(term), Idea(getA), Concept,
Definition(defn), ConceptDomain(cdom), HasSpace(typ), IsUnit, Quantity)
import Language.Drasil.Chunk.Concept (ConceptChunk, cw)
import Language.Drasil.Chunk.UnitDefn (UnitDefn, unitWrapper,
MayHaveUnit(getUnit))
import Language.Drasil.Space (Space)
import Language.Drasil.Stages (Stage)
import Language.Drasil.Symbol (Symbol)
import Control.Lens ((^.), makeLenses, view)
-- | DefinedQuantity = Concept + Quantity
data DefinedQuantityDict = DQD { _con :: ConceptChunk
, _symb :: Stage -> Symbol
, _spa :: Space
, _unit' :: Maybe UnitDefn
}
makeLenses ''DefinedQuantityDict
instance HasUID DefinedQuantityDict where uid = con . uid
instance Eq DefinedQuantityDict where a == b = (a ^. uid) == (b ^. uid)
instance NamedIdea DefinedQuantityDict where term = con . term
instance Idea DefinedQuantityDict where getA = getA . view con
instance Definition DefinedQuantityDict where defn = con . defn
instance ConceptDomain DefinedQuantityDict where cdom = cdom . view con
instance HasSpace DefinedQuantityDict where typ = spa
instance HasSymbol DefinedQuantityDict where symbol = view symb
instance Quantity DefinedQuantityDict where
instance MayHaveUnit DefinedQuantityDict where getUnit = view unit'
-- For when the symbol is constant through stages
dqd :: (IsUnit u) => ConceptChunk -> Symbol -> Space -> u -> DefinedQuantityDict
dqd c s sp = DQD c (const s) sp . Just . unitWrapper
dqdNoUnit :: ConceptChunk -> Symbol -> Space -> DefinedQuantityDict
dqdNoUnit c s sp = DQD c (const s) sp Nothing
-- For when the symbol changes depending on the stage
dqd' :: ConceptChunk -> (Stage -> Symbol) -> Space -> Maybe UnitDefn -> DefinedQuantityDict
dqd' = DQD
-- When the input already has all the necessary information. A 'projection' operator
dqdWr :: (Quantity c, Concept c, MayHaveUnit c) => c -> DefinedQuantityDict
dqdWr c = DQD (cw c) (symbol c) (c ^. typ) (getUnit c)
-- When we want to merge a quantity and a concept. This is suspicious.
dqdQd :: (Quantity c, MayHaveUnit c) => c -> ConceptChunk -> DefinedQuantityDict
dqdQd c cc = DQD cc (symbol c) (c ^. typ) (getUnit c)
| JacquesCarette/literate-scientific-software | code/drasil-lang/Language/Drasil/Chunk/DefinedQuantity.hs | bsd-2-clause | 2,546 | 0 | 9 | 527 | 707 | 399 | 308 | 38 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module Game.Types where
import Data.Matrix
import GHC.Generics
import Data.Aeson
import Data.Aeson.TH
import Data.Functor
data Move = Move {
player :: String,
outerPos :: Int,
innerPos :: Int
} deriving (Generic, Show, Read, Eq)
data Square = X | O | Empty | Both deriving (Generic, Show, Read, Eq)
data Game = Game {
playerX :: String,
playerO :: String,
lastMove :: Move,
board :: [[Square]],
metaBoard :: [Square],
moves :: Int,
gameWon :: Square
} deriving (Generic, Show, Eq)
newGame:: String -> String -> Game
newGame playerX playerO = Game playerX playerO (Move "None" 0 0) (map (\_ -> (map (const Empty) [1..9])) [1..9]) (map (const Empty) [1..9]) 0 Empty
instance ToJSON Move
instance FromJSON Move
instance ToJSON Square
instance FromJSON Square
instance ToJSON Game
instance FromJSON Game
| octopuscabbage/UltimateTicTacToeServer | src/Game/Types.hs | bsd-3-clause | 890 | 0 | 13 | 162 | 339 | 190 | 149 | 31 | 1 |
-- | Conduit of keys pressed by xinput
module where
| chrisdone/xinput-conduit | src/.hs | bsd-3-clause | 54 | 1 | 4 | 12 | 7 | 3 | 4 | -1 | -1 |
{-# OPTIONS -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.C.String
-- Copyright : (c) The FFI task force 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : ffi@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Utilities for primitive marshaling
--
-----------------------------------------------------------------------------
module Foreign.C.String ( -- representation of strings in C
CString, -- = Ptr CChar
CStringLen, -- = (CString, Int)
-- conversion of C strings into Haskell strings
--
peekCString, -- :: CString -> IO String
peekCStringLen, -- :: CStringLen -> IO String
-- conversion of Haskell strings into C strings
--
newCString, -- :: String -> IO CString
newCStringLen, -- :: String -> IO CStringLen
-- conversion of Haskell strings into C strings using temporary storage
--
withCString, -- :: String -> (CString -> IO a) -> IO a
withCStringLen, -- :: String -> (CStringLen -> IO a) -> IO a
-- conversion between Haskell and C characters *ignoring* the encoding
--
castCharToCChar, -- :: Char -> CChar
castCCharToChar, -- :: CChar -> Char
) where
import Foreign.Marshal.Array
import Foreign.C.Types
import Foreign.Ptr
import Foreign.Storable
import Data.Word
import Data.Char ( chr, ord )
-----------------------------------------------------------------------------
-- Strings
-- representation of strings in C
-- ------------------------------
type CString = Ptr CChar -- conventional NUL terminates strings
type CStringLen = (CString, Int) -- strings with explicit length
-- exported functions
-- ------------------
--
-- * the following routines apply the default conversion when converting the
-- C-land character encoding into the Haskell-land character encoding
--
-- ** NOTE: The current implementation doesn't handle conversions yet! **
--
-- * the routines using an explicit length tolerate NUL characters in the
-- middle of a string
--
-- marshal a NUL terminated C string into a Haskell string
--
peekCString :: CString -> IO String
peekCString cp = do cs <- peekArray0 nUL cp; return (cCharsToChars cs)
-- marshal a C string with explicit length into a Haskell string
--
peekCStringLen :: CStringLen -> IO String
peekCStringLen (cp, len) = do cs <- peekArray len cp; return (cCharsToChars cs)
-- marshal a Haskell string into a NUL terminated C strings
--
-- * the Haskell string may *not* contain any NUL characters
--
-- * new storage is allocated for the C string and must be explicitly freed
--
newCString :: String -> IO CString
newCString = newArray0 nUL . charsToCChars
-- marshal a Haskell string into a C string (ie, character array) with
-- explicit length information
--
-- * new storage is allocated for the C string and must be explicitly freed
--
newCStringLen :: String -> IO CStringLen
newCStringLen str = do a <- newArray (charsToCChars str)
return (pairLength str a)
-- marshal a Haskell string into a NUL terminated C strings using temporary
-- storage
--
-- * the Haskell string may *not* contain any NUL characters
--
-- * see the lifetime constraints of `MarshalAlloc.alloca'
--
withCString :: String -> (CString -> IO a) -> IO a
withCString = withArray0 nUL . charsToCChars
-- marshal a Haskell string into a NUL terminated C strings using temporary
-- storage
--
-- * the Haskell string may *not* contain any NUL characters
--
-- * see the lifetime constraints of `MarshalAlloc.alloca'
--
withCStringLen :: String -> (CStringLen -> IO a) -> IO a
withCStringLen str act = withArray (charsToCChars str) $ act . pairLength str
-- auxilliary definitions
-- ----------------------
-- C's end of string character
--
nUL :: CChar
nUL = 0
-- pair a C string with the length of the given Haskell string
--
pairLength :: String -> CString -> CStringLen
pairLength = flip (,) . length
-- cast [CChar] to [Char]
--
cCharsToChars :: [CChar] -> [Char]
cCharsToChars xs = map castCCharToChar xs
-- cast [Char] to [CChar]
--
charsToCChars :: [Char] -> [CChar]
charsToCChars xs = map castCharToCChar xs
castCCharToChar :: CChar -> Char
castCCharToChar ch = chr (fromIntegral (fromIntegral ch :: Word8))
castCharToCChar :: Char -> CChar
castCharToCChar ch = fromIntegral (ord ch)
| OS2World/DEV-UTIL-HUGS | libraries/Foreign/C/String.hs | bsd-3-clause | 4,462 | 0 | 11 | 876 | 608 | 363 | 245 | 45 | 1 |
{-# LANGUAGE LambdaCase, PatternGuards, ViewPatterns #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Elab.Term where
import Idris.AbsSyntax
import Idris.AbsSyntaxTree
import Idris.DSL
import Idris.Delaborate
import Idris.Error
import Idris.ProofSearch
import Idris.Output (pshow)
import Idris.Core.CaseTree (SC, SC'(STerm), findCalls, findUsedArgs)
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.Unify
import Idris.Core.ProofTerm (getProofTerm)
import Idris.Core.Typecheck (check, recheck, isType)
import Idris.Coverage (buildSCG, checkDeclTotality, genClauses, recoverableCoverage, validCoverageCase)
import Idris.ErrReverse (errReverse)
import Idris.ElabQuasiquote (extractUnquotes)
import Idris.Elab.Utils
import Idris.Reflection
import qualified Util.Pretty as U
import Control.Applicative ((<$>))
import Control.Monad
import Control.Monad.State.Strict
import Data.List
import qualified Data.Map as M
import Data.Maybe (mapMaybe, fromMaybe, catMaybes)
import qualified Data.Set as S
import qualified Data.Text as T
import Debug.Trace
data ElabMode = ETyDecl | ELHS | ERHS
deriving Eq
data ElabResult =
ElabResult { resultTerm :: Term -- ^ The term resulting from elaboration
, resultMetavars :: [(Name, (Int, Maybe Name, Type))]
-- ^ Information about new metavariables
, resultCaseDecls :: [PDecl]
-- ^ Deferred declarations as the meaning of case blocks
, resultContext :: Context
-- ^ The potentially extended context from new definitions
, resultTyDecls :: [RDeclInstructions]
-- ^ Meta-info about the new type declarations
, resultHighlighting :: [(FC, OutputAnnotation)]
}
-- Using the elaborator, convert a term in raw syntax to a fully
-- elaborated, typechecked term.
--
-- If building a pattern match, we convert undeclared variables from
-- holes to pattern bindings.
-- Also find deferred names in the term and their types
build :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm ->
ElabD ElabResult
build ist info emode opts fn tm
= do elab ist info emode opts fn tm
let tmIn = tm
let inf = case lookupCtxt fn (idris_tyinfodata ist) of
[TIPartial] -> True
_ -> False
when (not pattern) $ solveAutos ist fn True
hs <- get_holes
ivs <- get_instances
ptm <- get_term
-- Resolve remaining type classes. Two passes - first to get the
-- default Num instances, second to clean up the rest
when (not pattern) $
mapM_ (\n -> when (n `elem` hs) $
do focus n
g <- goal
try (resolveTC True False 10 g fn ist)
(movelast n)) ivs
ivs <- get_instances
hs <- get_holes
when (not pattern) $
mapM_ (\n -> when (n `elem` hs) $
do focus n
g <- goal
ptm <- get_term
resolveTC True True 10 g fn ist) ivs
tm <- get_term
ctxt <- get_context
probs <- get_probs
u <- getUnifyLog
hs <- get_holes
when (not pattern) $
traceWhen u ("Remaining holes:\n" ++ show hs ++ "\n" ++
"Remaining problems:\n" ++ qshow probs) $
do unify_all; matchProblems True; unifyProblems
probs <- get_probs
case probs of
[] -> return ()
((_,_,_,_,e,_,_):es) -> traceWhen u ("Final problems:\n" ++ qshow probs ++ "\nin\n" ++ show tm) $
if inf then return ()
else lift (Error e)
when tydecl (do mkPat
update_term liftPats
update_term orderPats)
EState is _ impls highlights <- getAux
tt <- get_term
ctxt <- get_context
let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) []
log <- getLog
if log /= ""
then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights)
else return (ElabResult tm ds (map snd is) ctxt impls highlights)
where pattern = emode == ELHS
tydecl = emode == ETyDecl
mkPat = do hs <- get_holes
tm <- get_term
case hs of
(h: hs) -> do patvar h; mkPat
[] -> return ()
-- Build a term autogenerated as a typeclass method definition
-- (Separate, so we don't go overboard resolving things that we don't
-- know about yet on the LHS of a pattern def)
buildTC :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm ->
ElabD ElabResult
buildTC ist info emode opts fn tm
= do -- set name supply to begin after highest index in tm
let ns = allNamesIn tm
let tmIn = tm
let inf = case lookupCtxt fn (idris_tyinfodata ist) of
[TIPartial] -> True
_ -> False
initNextNameFrom ns
elab ist info emode opts fn tm
probs <- get_probs
tm <- get_term
case probs of
[] -> return ()
((_,_,_,_,e,_,_):es) -> if inf then return ()
else lift (Error e)
dots <- get_dotterm
-- 'dots' are the PHidden things which have not been solved by
-- unification
when (not (null dots)) $
lift (Error (CantMatch (getInferTerm tm)))
EState is _ impls highlights <- getAux
tt <- get_term
ctxt <- get_context
let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) []
log <- getLog
if (log /= "")
then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights)
else return (ElabResult tm ds (map snd is) ctxt impls highlights)
where pattern = emode == ELHS
-- return whether arguments of the given constructor name can be
-- matched on. If they're polymorphic, no, unless the type has beed made
-- concrete by the time we get around to elaborating the argument.
getUnmatchable :: Context -> Name -> [Bool]
getUnmatchable ctxt n | isDConName n ctxt && n /= inferCon
= case lookupTyExact n ctxt of
Nothing -> []
Just ty -> checkArgs [] [] ty
where checkArgs :: [Name] -> [[Name]] -> Type -> [Bool]
checkArgs env ns (Bind n (Pi _ t _) sc)
= let env' = case t of
TType _ -> n : env
_ -> env in
checkArgs env' (intersect env (refsIn t) : ns)
(instantiate (P Bound n t) sc)
checkArgs env ns t
= map (not . null) (reverse ns)
getUnmatchable ctxt n = []
data ElabCtxt = ElabCtxt { e_inarg :: Bool,
e_isfn :: Bool, -- ^ Function part of application
e_guarded :: Bool,
e_intype :: Bool,
e_qq :: Bool,
e_nomatching :: Bool -- ^ can't pattern match
}
initElabCtxt = ElabCtxt False False False False False False
goal_polymorphic :: ElabD Bool
goal_polymorphic =
do ty <- goal
case ty of
P _ n _ -> do env <- get_env
case lookup n env of
Nothing -> return False
_ -> return True
_ -> return False
-- | Returns the set of declarations we need to add to complete the
-- definition (most likely case blocks to elaborate) as well as
-- declarations resulting from user tactic scripts (%runElab)
elab :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm ->
ElabD ()
elab ist info emode opts fn tm
= do let loglvl = opt_logLevel (idris_options ist)
when (loglvl > 5) $ unifyLog True
compute -- expand type synonyms, etc
let fc = maybe "(unknown)"
elabE initElabCtxt (elabFC info) tm -- (in argument, guarded, in type, in qquote)
est <- getAux
sequence_ (get_delayed_elab est)
end_unify
ptm <- get_term
when pattern -- convert remaining holes to pattern vars
(do update_term orderPats
unify_all
matchProblems False -- only the ones we matched earlier
unifyProblems
mkPat)
where
pattern = emode == ELHS
bindfree = emode == ETyDecl || emode == ELHS
get_delayed_elab est =
let ds = delayed_elab est in
map snd $ sortBy (\(p1, _) (p2, _) -> compare p1 p2) ds
tcgen = Dictionary `elem` opts
reflection = Reflection `elem` opts
isph arg = case getTm arg of
Placeholder -> (True, priority arg)
tm -> (False, priority arg)
toElab ina arg = case getTm arg of
Placeholder -> Nothing
v -> Just (priority arg, elabE ina (elabFC info) v)
toElab' ina arg = case getTm arg of
Placeholder -> Nothing
v -> Just (elabE ina (elabFC info) v)
mkPat = do hs <- get_holes
tm <- get_term
case hs of
(h: hs) -> do patvar h; mkPat
[] -> return ()
-- | elabE elaborates an expression, possibly wrapping implicit coercions
-- and forces/delays. If you make a recursive call in elab', it is
-- normally correct to call elabE - the ones that don't are desugarings
-- typically
elabE :: ElabCtxt -> Maybe FC -> PTerm -> ElabD ()
elabE ina fc' t =
do solved <- get_recents
as <- get_autos
hs <- get_holes
-- If any of the autos use variables which have recently been solved,
-- have another go at solving them now.
mapM_ (\(a, ns) -> if any (\n -> n `elem` solved) ns && head hs /= a
then solveAuto ist fn False a
else return ()) as
itm <- if not pattern then insertImpLam ina t else return t
ct <- insertCoerce ina itm
t' <- insertLazy ct
g <- goal
tm <- get_term
ps <- get_probs
hs <- get_holes
--trace ("Elaborating " ++ show t' ++ " in " ++ show g
-- ++ "\n" ++ show tm
-- ++ "\nholes " ++ show hs
-- ++ "\nproblems " ++ show ps
-- ++ "\n-----------\n") $
--trace ("ELAB " ++ show t') $
let fc = fileFC "Force"
env <- get_env
handleError (forceErr t' env)
(elab' ina fc' t')
(elab' ina fc' (PApp fc (PRef fc (sUN "Force"))
[pimp (sUN "t") Placeholder True,
pimp (sUN "a") Placeholder True,
pexp ct]))
forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _)
| (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t),
ht == txt "Lazy'" = notDelay orig
forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _)
| (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t'),
ht == txt "Lazy'" = notDelay orig
forceErr orig env (InfiniteUnify _ t _)
| (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t),
ht == txt "Lazy'" = notDelay orig
forceErr orig env (Elaborating _ _ t) = forceErr orig env t
forceErr orig env (ElaboratingArg _ _ _ t) = forceErr orig env t
forceErr orig env (At _ t) = forceErr orig env t
forceErr orig env t = False
notDelay t@(PApp _ (PRef _ (UN l)) _) | l == txt "Delay" = False
notDelay _ = True
local f = do e <- get_env
return (f `elem` map fst e)
-- | Is a constant a type?
constType :: Const -> Bool
constType (AType _) = True
constType StrType = True
constType VoidType = True
constType _ = False
-- "guarded" means immediately under a constructor, to help find patvars
elab' :: ElabCtxt -- ^ (in an argument, guarded, in a type, in a quasiquote)
-> Maybe FC -- ^ The closest FC in the syntax tree, if applicable
-> PTerm -- ^ The term to elaborate
-> ElabD ()
elab' ina fc (PNoImplicits t) = elab' ina fc t -- skip elabE step
elab' ina fc (PType fc') =
do apply RType []
solve
highlightSource fc' (AnnType "Type" "The type of types")
elab' ina fc (PUniverse u) = do apply (RUType u) []; solve
-- elab' (_,_,inty) (PConstant c)
-- | constType c && pattern && not reflection && not inty
-- = lift $ tfail (Msg "Typecase is not allowed")
elab' ina fc tm@(PConstant fc' c)
| pattern && not reflection && not (e_qq ina) && not (e_intype ina)
&& isTypeConst c
= lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
| pattern && not reflection && not (e_qq ina) && e_nomatching ina
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| otherwise = do apply (RConstant c) []
solve
highlightSource fc' (AnnConst c)
elab' ina fc (PQuote r) = do fill r; solve
elab' ina _ (PTrue fc _) =
do hnf_compute
g <- goal
case g of
TType _ -> elab' ina (Just fc) (PRef fc unitTy)
UType _ -> elab' ina (Just fc) (PRef fc unitTy)
_ -> elab' ina (Just fc) (PRef fc unitCon)
elab' ina fc (PResolveTC (FC "HACK" _ _)) -- for chasing parent classes
= do g <- goal; resolveTC False False 5 g fn ist
elab' ina fc (PResolveTC fc')
= do c <- getNameFrom (sMN 0 "class")
instanceArg c
-- Elaborate the equality type first homogeneously, then
-- heterogeneously as a fallback
elab' ina _ (PApp fc (PRef _ n) args)
| n == eqTy, [Placeholder, Placeholder, l, r] <- map getTm args
= try (do tyn <- getNameFrom (sMN 0 "aqty")
claim tyn RType
movelast tyn
elab' ina (Just fc) (PApp fc (PRef fc eqTy)
[pimp (sUN "A") (PRef NoFC tyn) True,
pimp (sUN "B") (PRef NoFC tyn) False,
pexp l, pexp r]))
(do atyn <- getNameFrom (sMN 0 "aqty")
btyn <- getNameFrom (sMN 0 "bqty")
claim atyn RType
movelast atyn
claim btyn RType
movelast btyn
elab' ina (Just fc) (PApp fc (PRef fc eqTy)
[pimp (sUN "A") (PRef NoFC atyn) True,
pimp (sUN "B") (PRef NoFC btyn) False,
pexp l, pexp r]))
elab' ina _ (PPair fc _ l r)
= do hnf_compute
g <- goal
let (tc, _) = unApply g
case g of
TType _ -> elab' ina (Just fc) (PApp fc (PRef fc pairTy)
[pexp l,pexp r])
UType _ -> elab' ina (Just fc) (PApp fc (PRef fc upairTy)
[pexp l,pexp r])
_ -> case tc of
P _ n _ | n == upairTy
-> elab' ina (Just fc) (PApp fc (PRef fc upairCon)
[pimp (sUN "A") Placeholder False,
pimp (sUN "B") Placeholder False,
pexp l, pexp r])
_ -> elab' ina (Just fc) (PApp fc (PRef fc pairCon)
[pimp (sUN "A") Placeholder False,
pimp (sUN "B") Placeholder False,
pexp l, pexp r])
-- _ -> try' (elab' ina (Just fc) (PApp fc (PRef fc pairCon)
-- [pimp (sUN "A") Placeholder False,
-- pimp (sUN "B") Placeholder False,
-- pexp l, pexp r]))
-- (elab' ina (Just fc) (PApp fc (PRef fc upairCon)
-- [pimp (sUN "A") Placeholder False,
-- pimp (sUN "B") Placeholder False,
-- pexp l, pexp r]))
-- True
elab' ina _ (PDPair fc p l@(PRef _ n) t r)
= case t of
Placeholder ->
do hnf_compute
g <- goal
case g of
TType _ -> asType
_ -> asValue
_ -> asType
where asType = elab' ina (Just fc) (PApp fc (PRef fc sigmaTy)
[pexp t,
-- TODO: save the FC from the dependent pair
-- syntax and put it on this lambda for interactive
-- semantic highlighting support. NoFC for now.
pexp (PLam fc n NoFC Placeholder r)])
asValue = elab' ina (Just fc) (PApp fc (PRef fc sigmaCon)
[pimp (sMN 0 "a") t False,
pimp (sMN 0 "P") Placeholder True,
pexp l, pexp r])
elab' ina _ (PDPair fc p l t r) = elab' ina (Just fc) (PApp fc (PRef fc sigmaCon)
[pimp (sMN 0 "a") t False,
pimp (sMN 0 "P") Placeholder True,
pexp l, pexp r])
elab' ina fc (PAlternative (ExactlyOne delayok) as)
= do hnf_compute
ty <- goal
ctxt <- get_context
let (tc, _) = unApply ty
env <- get_env
let as' = pruneByType (map fst env) tc ctxt as
-- trace (-- show tc ++ " " ++ show as ++ "\n ==> " ++
-- show (length as') ++ "\n" ++
-- showSep ", " (map showTmImpls as') ++ "\nEND") $
(h : hs) <- get_holes
case as' of
[x] -> elab' ina fc x
-- If there's options, try now, and if that fails, postpone
-- to later.
_ -> handleError isAmbiguous
(tryAll (zip (map (elab' ina fc) as')
(map showHd as')))
(do movelast h
delayElab 5 $ do
focus h
tryAll (zip (map (elab' ina fc) as')
(map showHd as')))
where showHd (PApp _ (PRef _ n) _) = n
showHd (PRef _ n) = n
showHd (PApp _ h _) = showHd h
showHd x = NErased -- We probably should do something better than this here
isAmbiguous (CantResolveAlts _) = delayok
isAmbiguous (Elaborating _ _ e) = isAmbiguous e
isAmbiguous (ElaboratingArg _ _ _ e) = isAmbiguous e
isAmbiguous (At _ e) = isAmbiguous e
isAmbiguous _ = False
elab' ina fc (PAlternative FirstSuccess as)
= trySeq as
where -- if none work, take the error from the first
trySeq (x : xs) = let e1 = elab' ina fc x in
try' e1 (trySeq' e1 xs) True
trySeq [] = fail "Nothing to try in sequence"
trySeq' deferr [] = proofFail deferr
trySeq' deferr (x : xs)
= try' (do elab' ina fc x
solveAutos ist fn False) (trySeq' deferr xs) True
elab' ina _ (PPatvar fc n) | bindfree
= do patvar n
update_term liftPats
highlightSource fc (AnnBoundName n False)
-- elab' (_, _, inty) (PRef fc f)
-- | isTConName f (tt_ctxt ist) && pattern && not reflection && not inty
-- = lift $ tfail (Msg "Typecase is not allowed")
elab' ec _ tm@(PRef fc n)
| pattern && not reflection && not (e_qq ec) && not (e_intype ec)
&& isTConName n (tt_ctxt ist)
= lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
| pattern && not reflection && not (e_qq ec) && e_nomatching ec
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| (pattern || (bindfree && bindable n)) && not (inparamBlock n) && not (e_qq ec)
= do let ina = e_inarg ec
guarded = e_guarded ec
inty = e_intype ec
ctxt <- get_context
let defined = case lookupTy n ctxt of
[] -> False
_ -> True
-- this is to stop us resolve type classes recursively
-- trace (show (n, guarded)) $
if (tcname n && ina)
then erun fc $
do patvar n
update_term liftPats
highlightSource fc (AnnBoundName n False)
else if (defined && not guarded)
then do apply (Var n) []
annot <- findHighlight n
solve
highlightSource fc annot
else try (do apply (Var n) []
annot <- findHighlight n
solve
highlightSource fc annot)
(do patvar n
update_term liftPats
highlightSource fc (AnnBoundName n False))
where inparamBlock n = case lookupCtxtName n (inblock info) of
[] -> False
_ -> True
bindable (NS _ _) = False
bindable (UN xs) = True
bindable n = implicitable n
elab' ina _ f@(PInferRef fc n) = elab' ina (Just fc) (PApp NoFC f [])
elab' ina fc' tm@(PRef fc n)
| pattern && not reflection && not (e_qq ina) && not (e_intype ina)
&& isTConName n (tt_ctxt ist)
= lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
| pattern && not reflection && not (e_qq ina) && e_nomatching ina
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| otherwise =
do fty <- get_type (Var n) -- check for implicits
ctxt <- get_context
env <- get_env
let a' = insertScopedImps fc (normalise ctxt env fty) []
if null a'
then erun fc $
do apply (Var n) []
hl <- findHighlight n
solve
highlightSource fc hl
else elab' ina fc' (PApp fc tm [])
elab' ina _ (PLam _ _ _ _ PImpossible) = lift . tfail . Msg $ "Only pattern-matching lambdas can be impossible"
elab' ina _ (PLam fc n nfc Placeholder sc)
= do -- if n is a type constructor name, this makes no sense...
ctxt <- get_context
when (isTConName n ctxt) $
lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here")
checkPiGoal n
attack; intro (Just n);
-- trace ("------ intro " ++ show n ++ " ---- \n" ++ show ptm)
elabE (ina { e_inarg = True } ) (Just fc) sc; solve
highlightSource nfc (AnnBoundName n False)
elab' ec _ (PLam fc n nfc ty sc)
= do tyn <- getNameFrom (sMN 0 "lamty")
-- if n is a type constructor name, this makes no sense...
ctxt <- get_context
when (isTConName n ctxt) $
lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here")
checkPiGoal n
claim tyn RType
explicit tyn
attack
ptm <- get_term
hs <- get_holes
introTy (Var tyn) (Just n)
focus tyn
elabE (ec { e_inarg = True, e_intype = True }) (Just fc) ty
elabE (ec { e_inarg = True }) (Just fc) sc
solve
highlightSource nfc (AnnBoundName n False)
elab' ina fc (PPi p n nfc Placeholder sc)
= do attack; arg n (is_scoped p) (sMN 0 "ty")
elabE (ina { e_inarg = True, e_intype = True }) fc sc
solve
highlightSource nfc (AnnBoundName n False)
elab' ina fc (PPi p n nfc ty sc)
= do attack; tyn <- getNameFrom (sMN 0 "ty")
claim tyn RType
n' <- case n of
MN _ _ -> unique_hole n
_ -> return n
forall n' (is_scoped p) (Var tyn)
focus tyn
let ec' = ina { e_inarg = True, e_intype = True }
elabE ec' fc ty
elabE ec' fc sc
solve
highlightSource nfc (AnnBoundName n False)
elab' ina _ (PLet fc n nfc ty val sc)
= do attack
ivs <- get_instances
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
explicit valn
letbind n (Var tyn) (Var valn)
case ty of
Placeholder -> return ()
_ -> do focus tyn
explicit tyn
elabE (ina { e_inarg = True, e_intype = True })
(Just fc) ty
focus valn
elabE (ina { e_inarg = True, e_intype = True })
(Just fc) val
ivs' <- get_instances
env <- get_env
elabE (ina { e_inarg = True }) (Just fc) sc
when (not pattern) $
mapM_ (\n -> do focus n
g <- goal
hs <- get_holes
if all (\n -> n == tyn || not (n `elem` hs)) (freeNames g)
then try (resolveTC True False 10 g fn ist)
(movelast n)
else movelast n)
(ivs' \\ ivs)
-- HACK: If the name leaks into its type, it may leak out of
-- scope outside, so substitute in the outer scope.
expandLet n (case lookup n env of
Just (Let t v) -> v
other -> error ("Value not a let binding: " ++ show other))
solve
highlightSource nfc (AnnBoundName n False)
elab' ina _ (PGoal fc r n sc) = do
rty <- goal
attack
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letbind n (Var tyn) (Var valn)
focus valn
elabE (ina { e_inarg = True, e_intype = True }) (Just fc) (PApp fc r [pexp (delab ist rty)])
env <- get_env
computeLet n
elabE (ina { e_inarg = True }) (Just fc) sc
solve
-- elab' ina fc (PLet n Placeholder
-- (PApp fc r [pexp (delab ist rty)]) sc)
elab' ina _ tm@(PApp fc (PInferRef _ f) args) = do
rty <- goal
ds <- get_deferred
ctxt <- get_context
-- make a function type a -> b -> c -> ... -> rty for the
-- new function name
env <- get_env
argTys <- claimArgTys env args
fn <- getNameFrom (sMN 0 "inf_fn")
let fty = fnTy argTys rty
-- trace (show (ptm, map fst argTys)) $ focus fn
-- build and defer the function application
attack; deferType (mkN f) fty (map fst argTys); solve
-- elaborate the arguments, to unify their types. They all have to
-- be explicit.
mapM_ elabIArg (zip argTys args)
where claimArgTys env [] = return []
claimArgTys env (arg : xs) | Just n <- localVar env (getTm arg)
= do nty <- get_type (Var n)
ans <- claimArgTys env xs
return ((n, (False, forget nty)) : ans)
claimArgTys env (_ : xs)
= do an <- getNameFrom (sMN 0 "inf_argTy")
aval <- getNameFrom (sMN 0 "inf_arg")
claim an RType
claim aval (Var an)
ans <- claimArgTys env xs
return ((aval, (True, (Var an))) : ans)
fnTy [] ret = forget ret
fnTy ((x, (_, xt)) : xs) ret = RBind x (Pi Nothing xt RType) (fnTy xs ret)
localVar env (PRef _ x)
= case lookup x env of
Just _ -> Just x
_ -> Nothing
localVar env _ = Nothing
elabIArg ((n, (True, ty)), def) =
do focus n; elabE ina (Just fc) (getTm def)
elabIArg _ = return () -- already done, just a name
mkN n@(NS _ _) = n
mkN n@(SN _) = n
mkN n = case namespace info of
Just xs@(_:_) -> sNS n xs
_ -> n
elab' ina _ (PMatchApp fc fn)
= do (fn', imps) <- case lookupCtxtName fn (idris_implicits ist) of
[(n, args)] -> return (n, map (const True) args)
_ -> lift $ tfail (NoSuchVariable fn)
ns <- match_apply (Var fn') (map (\x -> (x,0)) imps)
solve
-- if f is local, just do a simple_app
-- FIXME: Anyone feel like refactoring this mess? - EB
elab' ina topfc tm@(PApp fc (PRef ffc f) args_in)
| pattern && not reflection && not (e_qq ina) && e_nomatching ina
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| otherwise = implicitApp $
do env <- get_env
ty <- goal
fty <- get_type (Var f)
ctxt <- get_context
annot <- findHighlight f
mapM_ checkKnownImplicit args_in
let args = insertScopedImps fc (normalise ctxt env fty) args_in
let unmatchableArgs = if pattern
then getUnmatchable (tt_ctxt ist) f
else []
-- trace ("BEFORE " ++ show f ++ ": " ++ show ty) $
when (pattern && not reflection && not (e_qq ina) && not (e_intype ina)
&& isTConName f (tt_ctxt ist)) $
lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
-- trace (show (f, args_in, args)) $
if (f `elem` map fst env && length args == 1 && length args_in == 1)
then -- simple app, as below
do simple_app False
(elabE (ina { e_isfn = True }) (Just fc) (PRef ffc f))
(elabE (ina { e_inarg = True }) (Just fc) (getTm (head args)))
(show tm)
solve
highlightSource ffc annot
return []
else
do ivs <- get_instances
ps <- get_probs
-- HACK: we shouldn't resolve type classes if we're defining an instance
-- function or default definition.
let isinf = f == inferCon || tcname f
-- if f is a type class, we need to know its arguments so that
-- we can unify with them
case lookupCtxt f (idris_classes ist) of
[] -> return ()
_ -> do mapM_ setInjective (map getTm args)
-- maybe more things are solvable now
unifyProblems
let guarded = isConName f ctxt
-- trace ("args is " ++ show args) $ return ()
ns <- apply (Var f) (map isph args)
-- trace ("ns is " ++ show ns) $ return ()
-- mark any type class arguments as injective
mapM_ checkIfInjective (map snd ns)
unifyProblems -- try again with the new information,
-- to help with disambiguation
ulog <- getUnifyLog
annot <- findHighlight f
highlightSource ffc annot
elabArgs ist (ina { e_inarg = e_inarg ina || not isinf })
[] fc False f
(zip ns (unmatchableArgs ++ repeat False))
(f == sUN "Force")
(map (\x -> getTm x) args) -- TODO: remove this False arg
imp <- if (e_isfn ina) then
do guess <- get_guess
env <- get_env
case safeForgetEnv (map fst env) guess of
Nothing ->
return []
Just rguess -> do
gty <- get_type rguess
let ty_n = normalise ctxt env gty
return $ getReqImps ty_n
else return []
-- Now we find out how many implicits we needed at the
-- end of the application by looking at the goal again
-- - Have another go, but this time add the
-- implicits (can't think of a better way than this...)
case imp of
rs@(_:_) | not pattern -> return rs -- quit, try again
_ -> do solve
hs <- get_holes
ivs' <- get_instances
-- Attempt to resolve any type classes which have 'complete' types,
-- i.e. no holes in them
when (not pattern || (e_inarg ina && not tcgen &&
not (e_guarded ina))) $
mapM_ (\n -> do focus n
g <- goal
env <- get_env
hs <- get_holes
if all (\n -> not (n `elem` hs)) (freeNames g)
then try (resolveTC False False 10 g fn ist)
(movelast n)
else movelast n)
(ivs' \\ ivs)
return []
where
-- Run the elaborator, which returns how many implicit
-- args were needed, then run it again with those args. We need
-- this because we have to elaborate the whole application to
-- find out whether any computations have caused more implicits
-- to be needed.
implicitApp :: ElabD [ImplicitInfo] -> ElabD ()
implicitApp elab
| pattern = do elab; return ()
| otherwise
= do s <- get
imps <- elab
case imps of
[] -> return ()
es -> do put s
elab' ina topfc (PAppImpl tm es)
checkKnownImplicit imp
| UnknownImp `elem` argopts imp
= lift $ tfail $ UnknownImplicit (pname imp) f
checkKnownImplicit _ = return ()
getReqImps (Bind x (Pi (Just i) ty _) sc)
= i : getReqImps sc
getReqImps _ = []
checkIfInjective n = do
env <- get_env
case lookup n env of
Nothing -> return ()
Just b ->
case unApply (binderTy b) of
(P _ c _, args) ->
case lookupCtxtExact c (idris_classes ist) of
Nothing -> return ()
Just ci -> -- type class, set as injective
do mapM_ setinjArg (getDets 0 (class_determiners ci) args)
-- maybe we can solve more things now...
ulog <- getUnifyLog
probs <- get_probs
traceWhen ulog ("Injective now " ++ show args ++ "\n" ++ qshow probs) $
unifyProblems
probs <- get_probs
traceWhen ulog (qshow probs) $ return ()
_ -> return ()
setinjArg (P _ n _) = setinj n
setinjArg _ = return ()
getDets i ds [] = []
getDets i ds (a : as) | i `elem` ds = a : getDets (i + 1) ds as
| otherwise = getDets (i + 1) ds as
tacTm (PTactics _) = True
tacTm (PProof _) = True
tacTm _ = False
setInjective (PRef _ n) = setinj n
setInjective (PApp _ (PRef _ n) _) = setinj n
setInjective _ = return ()
elab' ina _ tm@(PApp fc f [arg]) =
erun fc $
do simple_app (not $ headRef f)
(elabE (ina { e_isfn = True }) (Just fc) f)
(elabE (ina { e_inarg = True }) (Just fc) (getTm arg))
(show tm)
solve
where headRef (PRef _ _) = True
headRef (PApp _ f _) = headRef f
headRef (PAlternative _ as) = all headRef as
headRef _ = False
elab' ina fc (PAppImpl f es) = do appImpl (reverse es) -- not that we look...
solve
where appImpl [] = elab' (ina { e_isfn = False }) fc f -- e_isfn not set, so no recursive expansion of implicits
appImpl (e : es) = simple_app False
(appImpl es)
(elab' ina fc Placeholder)
(show f)
elab' ina fc Placeholder
= do (h : hs) <- get_holes
movelast h
elab' ina fc (PMetavar nfc n) =
do ptm <- get_term
-- When building the metavar application, leave out the unique
-- names which have been used elsewhere in the term, since we
-- won't be able to use them in the resulting application.
let unique_used = getUniqueUsed (tt_ctxt ist) ptm
let n' = mkN n
attack
defer unique_used n'
solve
highlightSource nfc (AnnName n' (Just MetavarOutput) Nothing Nothing)
where mkN n@(NS _ _) = n
mkN n = case namespace info of
Just xs@(_:_) -> sNS n xs
_ -> n
elab' ina fc (PProof ts) = do compute; mapM_ (runTac True ist (elabFC info) fn) ts
elab' ina fc (PTactics ts)
| not pattern = do mapM_ (runTac False ist fc fn) ts
| otherwise = elab' ina fc Placeholder
elab' ina fc (PElabError e) = lift $ tfail e
elab' ina _ (PRewrite fc r sc newg)
= do attack
tyn <- getNameFrom (sMN 0 "rty")
claim tyn RType
valn <- getNameFrom (sMN 0 "rval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "_rewrite_rule")
letbind letn (Var tyn) (Var valn)
focus valn
elab' ina (Just fc) r
compute
g <- goal
rewrite (Var letn)
g' <- goal
when (g == g') $ lift $ tfail (NoRewriting g)
case newg of
Nothing -> elab' ina (Just fc) sc
Just t -> doEquiv t sc
solve
where doEquiv t sc =
do attack
tyn <- getNameFrom (sMN 0 "ety")
claim tyn RType
valn <- getNameFrom (sMN 0 "eqval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "equiv_val")
letbind letn (Var tyn) (Var valn)
focus tyn
elab' ina (Just fc) t
focus valn
elab' ina (Just fc) sc
elab' ina (Just fc) (PRef fc letn)
solve
elab' ina _ c@(PCase fc scr opts)
= do attack
tyn <- getNameFrom (sMN 0 "scty")
claim tyn RType
valn <- getNameFrom (sMN 0 "scval")
scvn <- getNameFrom (sMN 0 "scvar")
claim valn (Var tyn)
letbind scvn (Var tyn) (Var valn)
focus valn
elabE (ina { e_inarg = True }) (Just fc) scr
-- Solve any remaining implicits - we need to solve as many
-- as possible before making the 'case' type
unifyProblems
matchProblems True
args <- get_env
envU <- mapM (getKind args) args
let namesUsedInRHS = nub $ scvn : concatMap (\(_,rhs) -> allNamesIn rhs) opts
-- Drop the unique arguments used in the term already
-- and in the scrutinee (since it's
-- not valid to use them again anyway)
--
-- Also drop unique arguments which don't appear explicitly
-- in either case branch so they don't count as used
-- unnecessarily (can only do this for unique things, since we
-- assume they don't appear implicitly in types)
ptm <- get_term
let inOpts = (filter (/= scvn) (map fst args)) \\ (concatMap (\x -> allNamesIn (snd x)) opts)
let argsDropped = filter (isUnique envU)
(nub $ allNamesIn scr ++ inApp ptm ++
inOpts)
let args' = filter (\(n, _) -> n `notElem` argsDropped) args
cname <- unique_hole' True (mkCaseName fn)
let cname' = mkN cname
-- elab' ina fc (PMetavar cname')
attack; defer argsDropped cname'; solve
-- if the scrutinee is one of the 'args' in env, we should
-- inspect it directly, rather than adding it as a new argument
let newdef = PClauses fc [] cname'
(caseBlock fc cname'
(map (isScr scr) (reverse args')) opts)
-- elaborate case
updateAux (\e -> e { case_decls = (cname', newdef) : case_decls e } )
-- if we haven't got the type yet, hopefully we'll get it later!
movelast tyn
solve
where mkCaseName (NS n ns) = NS (mkCaseName n) ns
mkCaseName n = SN (CaseN n)
-- mkCaseName (UN x) = UN (x ++ "_case")
-- mkCaseName (MN i x) = MN i (x ++ "_case")
mkN n@(NS _ _) = n
mkN n = case namespace info of
Just xs@(_:_) -> sNS n xs
_ -> n
inApp (P _ n _) = [n]
inApp (App _ f a) = inApp f ++ inApp a
inApp (Bind n (Let _ v) sc) = inApp v ++ inApp sc
inApp (Bind n (Guess _ v) sc) = inApp v ++ inApp sc
inApp (Bind n b sc) = inApp sc
inApp _ = []
isUnique envk n = case lookup n envk of
Just u -> u
_ -> False
getKind env (n, _)
= case lookup n env of
Nothing -> return (n, False) -- can't happen, actually...
Just b ->
do ty <- get_type (forget (binderTy b))
case ty of
UType UniqueType -> return (n, True)
UType AllTypes -> return (n, True)
_ -> return (n, False)
tcName tm | (P _ n _, _) <- unApply tm
= case lookupCtxt n (idris_classes ist) of
[_] -> True
_ -> False
tcName _ = False
usedIn ns (n, b)
= n `elem` ns
|| any (\x -> x `elem` ns) (allTTNames (binderTy b))
elab' ina fc (PUnifyLog t) = do unifyLog True
elab' ina fc t
unifyLog False
elab' ina fc (PQuasiquote t goalt)
= do -- First extract the unquoted subterms, replacing them with fresh
-- names in the quasiquoted term. Claim their reflections to be
-- an inferred type (to support polytypic quasiquotes).
finalTy <- goal
(t, unq) <- extractUnquotes 0 t
let unquoteNames = map fst unq
mapM_ (\uqn -> claim uqn (forget finalTy)) unquoteNames
-- Save the old state - we need a fresh proof state to avoid
-- capturing lexically available variables in the quoted term.
ctxt <- get_context
datatypes <- get_datatypes
saveState
updatePS (const .
newProof (sMN 0 "q") ctxt datatypes $
P Ref (reflm "TT") Erased)
-- Re-add the unquotes, letting Idris infer the (fictional)
-- types. Here, they represent the real type rather than the type
-- of their reflection.
mapM_ (\n -> do ty <- getNameFrom (sMN 0 "unqTy")
claim ty RType
movelast ty
claim n (Var ty)
movelast n)
unquoteNames
-- Determine whether there's an explicit goal type, and act accordingly
-- Establish holes for the type and value of the term to be
-- quasiquoted
qTy <- getNameFrom (sMN 0 "qquoteTy")
claim qTy RType
movelast qTy
qTm <- getNameFrom (sMN 0 "qquoteTm")
claim qTm (Var qTy)
-- Let-bind the result of elaborating the contained term, so that
-- the hole doesn't disappear
nTm <- getNameFrom (sMN 0 "quotedTerm")
letbind nTm (Var qTy) (Var qTm)
-- Fill out the goal type, if relevant
case goalt of
Nothing -> return ()
Just gTy -> do focus qTy
elabE (ina { e_qq = True }) fc gTy
-- Elaborate the quasiquoted term into the hole
focus qTm
elabE (ina { e_qq = True }) fc t
end_unify
-- We now have an elaborated term. Reflect it and solve the
-- original goal in the original proof state, preserving highlighting
env <- get_env
EState _ _ _ hs <- getAux
loadState
updateAux (\aux -> aux { highlighting = hs })
let quoted = fmap (explicitNames . binderVal) $ lookup nTm env
isRaw = case unApply (normaliseAll ctxt env finalTy) of
(P _ n _, []) | n == reflm "Raw" -> True
_ -> False
case quoted of
Just q -> do ctxt <- get_context
(q', _, _) <- lift $ recheck ctxt [(uq, Lam Erased) | uq <- unquoteNames] (forget q) q
if pattern
then if isRaw
then reflectRawQuotePattern unquoteNames (forget q')
else reflectTTQuotePattern unquoteNames q'
else do if isRaw
then -- we forget q' instead of using q to ensure rechecking
fill $ reflectRawQuote unquoteNames (forget q')
else fill $ reflectTTQuote unquoteNames q'
solve
Nothing -> lift . tfail . Msg $ "Broken elaboration of quasiquote"
-- Finally fill in the terms or patterns from the unquotes. This
-- happens last so that their holes still exist while elaborating
-- the main quotation.
mapM_ elabUnquote unq
where elabUnquote (n, tm)
= do focus n
elabE (ina { e_qq = False }) fc tm
elab' ina fc (PUnquote t) = fail "Found unquote outside of quasiquote"
elab' ina fc (PQuoteName n) =
do ctxt <- get_context
env <- get_env
case lookup n env of
Just _ -> do fill $ reflectName n ; solve
Nothing ->
case lookupNameDef n ctxt of
[(n', _)] -> do fill $ reflectName n'
solve
[] -> lift . tfail . NoSuchVariable $ n
more -> lift . tfail . CantResolveAlts $ map fst more
elab' ina fc (PAs _ n t) = lift . tfail . Msg $ "@-pattern not allowed here"
elab' ina fc (PHidden t)
| reflection = elab' ina fc t
| otherwise
= do (h : hs) <- get_holes
-- Dotting a hole means that either the hole or any outer
-- hole (a hole outside any occurrence of it)
-- must be solvable by unification as well as being filled
-- in directly.
-- Delay dotted things to the end, then when we elaborate them
-- we can check the result against what was inferred
movelast h
delayElab 10 $ do focus h
dotterm
elab' ina fc t
elab' ina fc (PRunElab fc' tm) =
do attack
n <- getNameFrom (sMN 0 "tacticScript")
n' <- getNameFrom (sMN 0 "tacticExpr")
let scriptTy = RApp (Var (sNS (sUN "Elab")
["Elab", "Reflection", "Language"]))
(Var unitTy)
claim n scriptTy
movelast n
letbind n' scriptTy (Var n)
focus n
elab' ina (Just fc') tm
env <- get_env
runTactical ist (maybe fc' id fc) env (P Bound n' Erased)
solve
elab' ina fc x = fail $ "Unelaboratable syntactic form " ++ showTmImpls x
-- delay elaboration of 't', with priority 'pri' until after everything
-- else is done.
-- The delayed things with lower numbered priority will be elaborated
-- first. (In practice, this means delayed alternatives, then PHidden
-- things.)
delayElab pri t
= updateAux (\e -> e { delayed_elab = delayed_elab e ++ [(pri, t)] })
isScr :: PTerm -> (Name, Binder Term) -> (Name, (Bool, Binder Term))
isScr (PRef _ n) (n', b) = (n', (n == n', b))
isScr _ (n', b) = (n', (False, b))
caseBlock :: FC -> Name ->
[(Name, (Bool, Binder Term))] -> [(PTerm, PTerm)] -> [PClause]
caseBlock fc n env opts
= let args' = findScr env
args = map mkarg (map getNmScr args') in
map (mkClause args) opts
where -- Find the variable we want as the scrutinee and mark it as
-- 'True'. If the scrutinee is in the environment, match on that
-- otherwise match on the new argument we're adding.
findScr ((n, (True, t)) : xs)
= (n, (True, t)) : scrName n xs
findScr [(n, (_, t))] = [(n, (True, t))]
findScr (x : xs) = x : findScr xs
-- [] can't happen since scrutinee is in the environment!
findScr [] = error "The impossible happened - the scrutinee was not in the environment"
-- To make sure top level pattern name remains in scope, put
-- it at the end of the environment
scrName n [] = []
scrName n [(_, t)] = [(n, t)]
scrName n (x : xs) = x : scrName n xs
getNmScr (n, (s, _)) = (n, s)
mkarg (n, s) = (PRef fc n, s)
-- may be shadowed names in the new pattern - so replace the
-- old ones with an _
mkClause args (l, r)
= let args' = map (shadowed (allNamesIn l)) args
lhs = PApp (getFC fc l) (PRef (getFC fc l) n)
(map (mkLHSarg l) args') in
PClause (getFC fc l) n lhs [] r []
mkLHSarg l (tm, True) = pexp l
mkLHSarg l (tm, False) = pexp tm
shadowed new (PRef _ n, s) | n `elem` new = (Placeholder, s)
shadowed new t = t
getFC d (PApp fc _ _) = fc
getFC d (PRef fc _) = fc
getFC d (PAlternative _ (x:_)) = getFC d x
getFC d x = d
insertLazy :: PTerm -> ElabD PTerm
insertLazy t@(PApp _ (PRef _ (UN l)) _) | l == txt "Delay" = return t
insertLazy t@(PApp _ (PRef _ (UN l)) _) | l == txt "Force" = return t
insertLazy (PCoerced t) = return t
insertLazy t =
do ty <- goal
env <- get_env
let (tyh, _) = unApply (normalise (tt_ctxt ist) env ty)
let tries = if pattern then [t, mkDelay env t] else [mkDelay env t, t]
case tyh of
P _ (UN l) _ | l == txt "Lazy'"
-> return (PAlternative FirstSuccess tries)
_ -> return t
where
mkDelay env (PAlternative b xs) = PAlternative b (map (mkDelay env) xs)
mkDelay env t
= let fc = fileFC "Delay" in
addImplBound ist (map fst env) (PApp fc (PRef fc (sUN "Delay"))
[pexp t])
-- Don't put implicit coercions around applications which are marked
-- as '%noImplicit', or around case blocks, otherwise we get exponential
-- blowup especially where there are errors deep in large expressions.
notImplicitable (PApp _ f _) = notImplicitable f
-- TMP HACK no coercing on bind (make this configurable)
notImplicitable (PRef _ n)
| [opts] <- lookupCtxt n (idris_flags ist)
= NoImplicit `elem` opts
notImplicitable (PAlternative (ExactlyOne _) as) = any notImplicitable as
-- case is tricky enough without implicit coercions! If they are needed,
-- they can go in the branches separately.
notImplicitable (PCase _ _ _) = True
notImplicitable _ = False
insertScopedImps fc (Bind n (Pi im@(Just i) _ _) sc) xs
| tcinstance i
= pimp n (PResolveTC fc) True : insertScopedImps fc sc xs
| otherwise
= pimp n Placeholder True : insertScopedImps fc sc xs
insertScopedImps fc (Bind n (Pi _ _ _) sc) (x : xs)
= x : insertScopedImps fc sc xs
insertScopedImps _ _ xs = xs
insertImpLam ina t =
do ty <- goal
env <- get_env
let ty' = normalise (tt_ctxt ist) env ty
addLam ty' t
where
-- just one level at a time
addLam (Bind n (Pi (Just _) _ _) sc) t =
do impn <- unique_hole n -- (sMN 0 "scoped_imp")
if e_isfn ina -- apply to an implicit immediately
then return (PApp emptyFC
(PLam emptyFC impn NoFC Placeholder t)
[pexp Placeholder])
else return (PLam emptyFC impn NoFC Placeholder t)
addLam _ t = return t
insertCoerce ina t@(PCase _ _ _) = return t
insertCoerce ina t | notImplicitable t = return t
insertCoerce ina t =
do ty <- goal
-- Check for possible coercions to get to the goal
-- and add them as 'alternatives'
env <- get_env
let ty' = normalise (tt_ctxt ist) env ty
let cs = getCoercionsTo ist ty'
let t' = case (t, cs) of
(PCoerced tm, _) -> tm
(_, []) -> t
(_, cs) -> PAlternative FirstSuccess [t ,
PAlternative (ExactlyOne False)
(map (mkCoerce env t) cs)]
return t'
where
mkCoerce env t n = let fc = maybe (fileFC "Coercion") id (highestFC t) in
addImplBound ist (map fst env)
(PApp fc (PRef fc n) [pexp (PCoerced t)])
-- | Elaborate the arguments to a function
elabArgs :: IState -- ^ The current Idris state
-> ElabCtxt -- ^ (in an argument, guarded, in a type, in a qquote)
-> [Bool]
-> FC -- ^ Source location
-> Bool
-> Name -- ^ Name of the function being applied
-> [((Name, Name), Bool)] -- ^ (Argument Name, Hole Name, unmatchable)
-> Bool -- ^ under a 'force'
-> [PTerm] -- ^ argument
-> ElabD ()
elabArgs ist ina failed fc retry f [] force _ = return ()
elabArgs ist ina failed fc r f (((argName, holeName), unm):ns) force (t : args)
= do hs <- get_holes
if holeName `elem` hs then
do focus holeName
case t of
Placeholder -> do movelast holeName
elabArgs ist ina failed fc r f ns force args
_ -> elabArg t
else elabArgs ist ina failed fc r f ns force args
where elabArg t =
do -- solveAutos ist fn False
now_elaborating fc f argName
wrapErr f argName $ do
hs <- get_holes
tm <- get_term
-- No coercing under an explicit Force (or it can Force/Delay
-- recursively!)
let elab = if force then elab' else elabE
failed' <- -- trace (show (n, t, hs, tm)) $
-- traceWhen (not (null cs)) (show ty ++ "\n" ++ showImp True t) $
do focus holeName;
g <- goal
-- Can't pattern match on polymorphic goals
poly <- goal_polymorphic
ulog <- getUnifyLog
traceWhen ulog ("Elaborating argument " ++ show (argName, holeName, g)) $
elab (ina { e_nomatching = unm && poly }) (Just fc) t
return failed
done_elaborating_arg f argName
elabArgs ist ina failed fc r f ns force args
wrapErr f argName action =
do elabState <- get
while <- elaborating_app
let while' = map (\(x, y, z)-> (y, z)) while
(result, newState) <- case runStateT action elabState of
OK (res, newState) -> return (res, newState)
Error e -> do done_elaborating_arg f argName
lift (tfail (elaboratingArgErr while' e))
put newState
return result
elabArgs _ _ _ _ _ _ (((arg, hole), _) : _) _ [] =
fail $ "Can't elaborate these args: " ++ show arg ++ " " ++ show hole
-- For every alternative, look at the function at the head. Automatically resolve
-- any nested alternatives where that function is also at the head
pruneAlt :: [PTerm] -> [PTerm]
pruneAlt xs = map prune xs
where
prune (PApp fc1 (PRef fc2 f) as)
= PApp fc1 (PRef fc2 f) (fmap (fmap (choose f)) as)
prune t = t
choose f (PAlternative a as)
= let as' = fmap (choose f) as
fs = filter (headIs f) as' in
case fs of
[a] -> a
_ -> PAlternative a as'
choose f (PApp fc f' as) = PApp fc (choose f f') (fmap (fmap (choose f)) as)
choose f t = t
headIs f (PApp _ (PRef _ f') _) = f == f'
headIs f (PApp _ f' _) = headIs f f'
headIs f _ = True -- keep if it's not an application
-- Rule out alternatives that don't return the same type as the head of the goal
-- (If there are none left as a result, do nothing)
pruneByType :: [Name] -> Term -> -- head of the goal
Context -> [PTerm] -> [PTerm]
-- if an alternative has a locally bound name at the head, take it
pruneByType env t c as
| Just a <- locallyBound as = [a]
where
locallyBound [] = Nothing
locallyBound (t:ts)
| Just n <- getName t,
n `elem` env = Just t
| otherwise = locallyBound ts
getName (PRef _ n) = Just n
getName (PApp _ f _) = getName f
getName (PHidden t) = getName t
getName _ = Nothing
pruneByType env (P _ n _) ctxt as
-- if the goal type is polymorphic, keep e
| Nothing <- lookupTyExact n ctxt = as
| otherwise
= let asV = filter (headIs True n) as
as' = filter (headIs False n) as in
case as' of
[] -> case asV of
[] -> as
_ -> asV
_ -> as'
where
headIs var f (PRef _ f') = typeHead var f f'
headIs var f (PApp _ (PRef _ f') _) = typeHead var f f'
headIs var f (PApp _ f' _) = headIs var f f'
headIs var f (PPi _ _ _ _ sc) = headIs var f sc
headIs var f (PHidden t) = headIs var f t
headIs var f t = True -- keep if it's not an application
typeHead var f f'
= -- trace ("Trying " ++ show f' ++ " for " ++ show n) $
case lookupTyExact f' ctxt of
Just ty -> case unApply (getRetTy ty) of
(P _ ctyn _, _) | isConName ctyn ctxt -> ctyn == f
_ -> let ty' = normalise ctxt [] ty in
case unApply (getRetTy ty') of
(P _ ftyn _, _) -> ftyn == f
(V _, _) -> var -- keep, variable
_ -> False
_ -> False
pruneByType _ t _ as = as
-- | Use the local elab context to work out the highlighting for a name
findHighlight :: Name -> ElabD OutputAnnotation
findHighlight n = do ctxt <- get_context
env <- get_env
case lookup n env of
Just _ -> return $ AnnBoundName n False
Nothing -> case lookupTyExact n ctxt of
Just _ -> return $ AnnName n Nothing Nothing Nothing
Nothing -> lift . tfail . InternalMsg $
"Can't find name" ++ show n
-- | Find the names of instances that have been designeated for
-- searching (i.e. non-named instances or instances from Elab scripts)
findInstances :: IState -> Term -> [Name]
findInstances ist t
| (P _ n _, _) <- unApply (getRetTy t)
= case lookupCtxt n (idris_classes ist) of
[CI _ _ _ _ _ ins _] ->
[n | (n, True) <- ins, accessible n]
_ -> []
| otherwise = []
where accessible n = case lookupDefAccExact n False (tt_ctxt ist) of
Just (_, Hidden) -> False
_ -> True
-- Try again to solve auto implicits
solveAuto :: IState -> Name -> Bool -> Name -> ElabD ()
solveAuto ist fn ambigok n
= do hs <- get_holes
tm <- get_term
when (n `elem` hs) $ do
focus n
g <- goal
isg <- is_guess -- if it's a guess, we're working on it recursively, so stop
when (not isg) $
proofSearch' ist True ambigok 100 True Nothing fn []
solveAutos :: IState -> Name -> Bool -> ElabD ()
solveAutos ist fn ambigok
= do autos <- get_autos
mapM_ (solveAuto ist fn ambigok) (map fst autos)
trivial' ist
= trivial (elab ist toplevel ERHS [] (sMN 0 "tac")) ist
trivialHoles' h ist
= trivialHoles h (elab ist toplevel ERHS [] (sMN 0 "tac")) ist
proofSearch' ist rec ambigok depth prv top n hints
= do unifyProblems
proofSearch rec prv ambigok (not prv) depth
(elab ist toplevel ERHS [] (sMN 0 "tac")) top n hints ist
-- | Resolve type classes. This will only pick up 'normal' instances, never
-- named instances (which is enforced by 'findInstances').
resolveTC :: Bool -- ^ using default Int
-> Bool -- ^ allow metavariables in the goal
-> Int -- ^ depth
-> Term -- ^ top level goal, for error messages
-> Name -- ^ top level function name, to prevent loops
-> IState -> ElabD ()
resolveTC def mvok depth top fn ist
= do hs <- get_holes
resTC' [] def hs depth top fn ist
resTC' tcs def topholes 0 topg fn ist = fail $ "Can't resolve type class"
resTC' tcs def topholes 1 topg fn ist = try' (trivial' ist) (resolveTC def False 0 topg fn ist) True
resTC' tcs defaultOn topholes depth topg fn ist
= do compute
g <- goal
-- Resolution can proceed only if there is something concrete in the
-- determining argument positions. Keep track of the holes in the
-- non-determining position, because it's okay for 'trivial' to solve
-- those holes and no others.
let (argsok, okholePos) = case tcArgsOK g topholes of
Nothing -> (False, [])
Just hs -> (True, hs)
if not argsok -- && not mvok)
then lift $ tfail $ CantResolve True topg
else do
ptm <- get_term
ulog <- getUnifyLog
hs <- get_holes
env <- get_env
t <- goal
let (tc, ttypes) = unApply (getRetTy t)
let okholes = case tc of
P _ n _ -> zip (repeat n) okholePos
_ -> []
traceWhen ulog ("Resolving class " ++ show g ++ "\nin" ++ show env ++ "\n" ++ show okholes) $
try' (trivialHoles' okholes ist)
(do addDefault t tc ttypes
let stk = map fst (filter snd $ elab_stack ist)
let insts = findInstances ist t
blunderbuss t depth stk (stk ++ insts)) True
where
-- returns Just hs if okay, where hs are holes which are okay in the
-- goal, or Nothing if not okay to proceed
tcArgsOK ty hs | (P _ nc _, as) <- unApply (getRetTy ty), nc == numclass && defaultOn
= Just []
tcArgsOK ty hs -- if any determining arguments are metavariables, postpone
= let (f, as) = unApply (getRetTy ty) in
case f of
P _ cn _ -> case lookupCtxtExact cn (idris_classes ist) of
Just ci -> tcDetArgsOK 0 (class_determiners ci) hs as
Nothing -> if any (isMeta hs) as
then Nothing
else Just []
_ -> if any (isMeta hs) as
then Nothing
else Just []
-- return the list of argument positions which can safely be a hole
-- or Nothing if one of the determining arguments is a hole
tcDetArgsOK i ds hs (x : xs)
| i `elem` ds = if isMeta hs x
then Nothing
else tcDetArgsOK (i + 1) ds hs xs
| otherwise = do rs <- tcDetArgsOK (i + 1) ds hs xs
case x of
P _ n _ -> Just (i : rs)
_ -> Just rs
tcDetArgsOK _ _ _ [] = Just []
isMeta :: [Name] -> Term -> Bool
isMeta ns (P _ n _) = n `elem` ns
isMeta _ _ = False
notHole hs (P _ n _, c)
| (P _ cn _, _) <- unApply (getRetTy c),
n `elem` hs && isConName cn (tt_ctxt ist) = False
| Constant _ <- c = not (n `elem` hs)
notHole _ _ = True
-- HACK! Rather than giving a special name, better to have some kind
-- of flag in ClassInfo structure
chaser (UN nm)
| ('@':'@':_) <- str nm = True -- old way
chaser (SN (ParentN _ _)) = True
chaser (NS n _) = chaser n
chaser _ = False
numclass = sNS (sUN "Num") ["Classes","Prelude"]
addDefault t num@(P _ nc _) [P Bound a _] | nc == numclass && defaultOn
= do focus a
fill (RConstant (AType (ATInt ITBig))) -- default Integer
solve
addDefault t f as
| all boundVar as = return () -- True -- fail $ "Can't resolve " ++ show t
addDefault t f a = return () -- trace (show t) $ return ()
boundVar (P Bound _ _) = True
boundVar _ = False
blunderbuss t d stk [] = do -- c <- get_env
-- ps <- get_probs
lift $ tfail $ CantResolve False topg
blunderbuss t d stk (n:ns)
| n /= fn -- && (n `elem` stk)
= tryCatch (resolve n d)
(\e -> case e of
CantResolve True _ -> lift $ tfail e
_ -> blunderbuss t d stk ns)
| otherwise = blunderbuss t d stk ns
introImps = do g <- goal
case g of
(Bind _ (Pi _ _ _) sc) -> do attack; intro Nothing
num <- introImps
return (num + 1)
_ -> return 0
solven 0 = return ()
solven n = do solve; solven (n - 1)
resolve n depth
| depth == 0 = fail $ "Can't resolve type class"
| otherwise
= do lams <- introImps
t <- goal
let (tc, ttypes) = trace (show t) $ unApply (getRetTy t)
-- if (all boundVar ttypes) then resolveTC (depth - 1) fn insts ist
-- else do
-- if there's a hole in the goal, don't even try
let imps = case lookupCtxtName n (idris_implicits ist) of
[] -> []
[args] -> map isImp (snd args) -- won't be overloaded!
xs -> error "The impossible happened - overloading is not expected here!"
ps <- get_probs
tm <- get_term
args <- map snd <$> try' (apply (Var n) imps)
(match_apply (Var n) imps) True
solven lams -- close any implicit lambdas we introduced
ps' <- get_probs
when (length ps < length ps' || unrecoverable ps') $
fail "Can't apply type class"
-- traceWhen (all boundVar ttypes) ("Progress: " ++ show t ++ " with " ++ show n) $
mapM_ (\ (_,n) -> do focus n
t' <- goal
let (tc', ttype) = unApply (getRetTy t')
let got = fst (unApply (getRetTy t))
let depth' = if tc' `elem` tcs
then depth - 1 else depth
resTC' (got : tcs) defaultOn topholes depth' topg fn ist)
(filter (\ (x, y) -> not x) (zip (map fst imps) args))
-- if there's any arguments left, we've failed to resolve
hs <- get_holes
ulog <- getUnifyLog
solve
traceWhen ulog ("Got " ++ show n) $ return ()
where isImp (PImp p _ _ _ _) = (True, p)
isImp arg = (False, priority arg)
collectDeferred :: Maybe Name -> [Name] -> Context ->
Term -> State [(Name, (Int, Maybe Name, Type))] Term
collectDeferred top casenames ctxt (Bind n (GHole i t) app) =
do ds <- get
t' <- collectDeferred top casenames ctxt t
when (not (n `elem` map fst ds)) $ put (ds ++ [(n, (i, top, tidyArg [] t'))])
collectDeferred top casenames ctxt app
where
-- Evaluate the top level functions in arguments, if possible, and if it's
-- not a name we're immediately going to define in a case block, so that
-- any immediate specialisation of the function applied to constructors
-- can be done
tidyArg env (Bind n b@(Pi im t k) sc)
= Bind n (Pi im (tidy ctxt env t) k)
(tidyArg ((n, b) : env) sc)
tidyArg env t = t
tidy ctxt env t | (f, args) <- unApply t,
P _ specn _ <- getFn f,
n `notElem` casenames
= fst $ specialise ctxt env [(specn, 99999)] t
tidy ctxt env t@(Bind n (Let _ _) sct)
| (f, args) <- unApply sct,
P _ specn _ <- getFn f,
n `notElem` casenames
= fst $ specialise ctxt env [(specn, 99999)] t
tidy ctxt env t = t
getFn (Bind n (Lam _) t) = getFn t
getFn t | (f, a) <- unApply t = f
collectDeferred top ns ctxt (Bind n b t)
= do b' <- cdb b
t' <- collectDeferred top ns ctxt t
return (Bind n b' t')
where
cdb (Let t v) = liftM2 Let (collectDeferred top ns ctxt t) (collectDeferred top ns ctxt v)
cdb (Guess t v) = liftM2 Guess (collectDeferred top ns ctxt t) (collectDeferred top ns ctxt v)
cdb b = do ty' <- collectDeferred top ns ctxt (binderTy b)
return (b { binderTy = ty' })
collectDeferred top ns ctxt (App s f a) = liftM2 (App s) (collectDeferred top ns ctxt f)
(collectDeferred top ns ctxt a)
collectDeferred top ns ctxt t = return t
case_ :: Bool -> Bool -> IState -> Name -> PTerm -> ElabD ()
case_ ind autoSolve ist fn tm = do
attack
tyn <- getNameFrom (sMN 0 "ity")
claim tyn RType
valn <- getNameFrom (sMN 0 "ival")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "irule")
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
env <- get_env
let (Just binding) = lookup letn env
let val = binderVal binding
if ind then induction (forget val)
else casetac (forget val)
when autoSolve solveAll
runTactical :: IState -> FC -> Env -> Term -> ElabD ()
runTactical ist fc env tm = do tm' <- eval tm
runTacTm tm'
return ()
where
eval tm = do ctxt <- get_context
return $ normaliseAll ctxt env (finalise tm)
returnUnit = return $ P (DCon 0 0 False) unitCon (P (TCon 0 0) unitTy Erased)
patvars :: [Name] -> Term -> ([Name], Term)
patvars ns (Bind n (PVar t) sc) = patvars (n : ns) (instantiate (P Bound n t) sc)
patvars ns tm = (ns, tm)
pullVars :: (Term, Term) -> ([Name], Term, Term)
pullVars (lhs, rhs) = (fst (patvars [] lhs), snd (patvars [] lhs), snd (patvars [] rhs)) -- TODO alpha-convert rhs
defineFunction :: RFunDefn -> ElabD ()
defineFunction (RDefineFun n clauses) =
do ctxt <- get_context
ty <- maybe (fail "no type decl") return $ lookupTyExact n ctxt
let info = CaseInfo True True False -- TODO document and figure out
clauses' <- forM clauses (\case
RMkFunClause lhs rhs ->
do lhs' <- fmap fst . lift $ check ctxt [] lhs
rhs' <- fmap fst . lift $ check ctxt [] rhs
return $ Right (lhs', rhs')
RMkImpossibleClause lhs ->
do lhs' <- fmap fst . lift $ check ctxt [] lhs
return $ Left lhs')
let clauses'' = map (\case Right c -> pullVars c
Left lhs -> let (ns, lhs') = patvars [] lhs'
in (ns, lhs', Impossible))
clauses'
set_context $
addCasedef n (const [])
info False (STerm Erased)
True False -- TODO what are these?
(map snd $ getArgTys ty) [] -- TODO inaccessible types
clauses'
clauses''
clauses''
clauses''
clauses''
ty
ctxt
updateAux $ \e -> e { new_tyDecls = RClausesInstrs n clauses'' : new_tyDecls e}
return ()
-- | Do a step in the reflected elaborator monad. The input is the
-- step, the output is the (reflected) term returned.
runTacTm :: Term -> ElabD Term
runTacTm (unApply -> tac@(P _ n _, args))
| n == tacN "prim__Solve", [] <- args
= do solve
returnUnit
| n == tacN "prim__Goal", [] <- args
= do (h:_) <- get_holes
t <- goal
fmap fst . get_type_val $
rawPair (Var (reflm "TTName"), Var (reflm "TT"))
(reflectName h, reflect t)
| n == tacN "prim__Holes", [] <- args
= do hs <- get_holes
fmap fst . get_type_val $
mkList (Var $ reflm "TTName") (map reflectName hs)
| n == tacN "prim__Guess", [] <- args
= do ok <- is_guess
if ok
then do guess <- fmap forget get_guess
fmap fst . get_type_val $
RApp (RApp (Var (sNS (sUN "Just") ["Maybe", "Prelude"]))
(Var (reflm "TT")))
guess
else fmap fst . get_type_val $
RApp (Var (sNS (sUN "Nothing") ["Maybe", "Prelude"]))
(Var (reflm "TT"))
| n == tacN "prim__LookupTy", [n] <- args
= do n' <- reifyTTName n
ctxt <- get_context
let getNameTypeAndType = \case Function ty _ -> (Ref, ty)
TyDecl nt ty -> (nt, ty)
Operator ty _ _ -> (Ref, ty)
CaseOp _ ty _ _ _ _ -> (Ref, ty)
-- Idris tuples nest to the right
reflectTriple (x, y, z) =
raw_apply (Var pairCon) [ Var (reflm "TTName")
, raw_apply (Var pairTy) [Var (reflm "NameType"), Var (reflm "TT")]
, x
, raw_apply (Var pairCon) [ Var (reflm "NameType"), Var (reflm "TT")
, y, z]]
let defs = [ reflectTriple (reflectName n, reflectNameType nt, reflect ty)
| (n, def) <- lookupNameDef n' ctxt
, let (nt, ty) = getNameTypeAndType def ]
fmap fst . get_type_val $
rawList (raw_apply (Var pairTy) [ Var (reflm "TTName")
, raw_apply (Var pairTy) [ Var (reflm "NameType")
, Var (reflm "TT")]])
defs
| n == tacN "prim__LookupDatatype", [name] <- args
= do n' <- reifyTTName name
datatypes <- get_datatypes
ctxt <- get_context
fmap fst . get_type_val $
rawList (Var (tacN "Datatype"))
(map reflectDatatype (buildDatatypes ctxt datatypes n'))
| n == tacN "prim__SourceLocation", [] <- args
= fmap fst . get_type_val $
reflectFC fc
| n == tacN "prim__Env", [] <- args
= do env <- get_env
fmap fst . get_type_val $ reflectEnv env
| n == tacN "prim__Fail", [_a, errs] <- args
= do errs' <- eval errs
parts <- reifyReportParts errs'
lift . tfail $ ReflectionError [parts] (Msg "")
| n == tacN "prim__PureElab", [_a, tm] <- args
= return tm
| n == tacN "prim__BindElab", [_a, _b, first, andThen] <- args
= do first' <- eval first
res <- eval =<< runTacTm first'
next <- eval (App Complete andThen res)
runTacTm next
| n == tacN "prim__Try", [_a, first, alt] <- args
= do first' <- eval first
alt' <- eval alt
try' (runTacTm first') (runTacTm alt') True
| n == tacN "prim__Fill", [raw] <- args
= do raw' <- reifyRaw =<< eval raw
fill raw'
returnUnit
| n == tacN "prim__Apply", [raw] <- args
= do raw' <- reifyRaw =<< eval raw
apply raw' []
returnUnit
| n == tacN "prim__Gensym", [hint] <- args
= do hintStr <- eval hint
case hintStr of
Constant (Str h) -> do
n <- getNameFrom (sMN 0 h)
fmap fst $ get_type_val (reflectName n)
_ -> fail "no hint"
| n == tacN "prim__Claim", [n, ty] <- args
= do n' <- reifyTTName n
ty' <- reifyRaw ty
claim n' ty'
returnUnit
| n == tacN "prim__Forget", [tt] <- args
= do tt' <- reifyTT tt
fmap fst . get_type_val . reflectRaw $ forget tt'
| n == tacN "prim__Attack", [] <- args
= do attack
returnUnit
| n == tacN "prim__Rewrite", [rule] <- args
= do r <- reifyRaw rule
rewrite r
returnUnit
| n == tacN "prim__Focus", [what] <- args
= do n' <- reifyTTName what
focus n'
returnUnit
| n == tacN "prim__Unfocus", [what] <- args
= do n' <- reifyTTName what
movelast n'
returnUnit
| n == tacN "prim__Intro", [mn] <- args
= do n <- case fromTTMaybe mn of
Nothing -> return Nothing
Just name -> fmap Just $ reifyTTName name
intro n
returnUnit
| n == tacN "prim__Forall", [n, ty] <- args
= do n' <- reifyTTName n
ty' <- reifyRaw ty
forall n' Nothing ty'
returnUnit
| n == tacN "prim__PatVar", [n] <- args
= do n' <- reifyTTName n
patvar n'
returnUnit
| n == tacN "prim__PatBind", [n] <- args
= do n' <- reifyTTName n
patbind n'
returnUnit
| n == tacN "prim__Compute", [] <- args
= do compute ; returnUnit
| n == tacN "prim__DeclareType", [decl] <- args
= do (RDeclare n args res) <- reifyTyDecl decl
ctxt <- get_context
let mkPi arg res = RBind (argName arg)
(Pi Nothing (argTy arg) (RUType AllTypes))
res
rty = foldr mkPi res args
(checked, ty') <- lift $ check ctxt [] rty
case normaliseAll ctxt [] (finalise ty') of
UType _ -> return ()
TType _ -> return ()
ty'' -> lift . tfail . InternalMsg $
show checked ++ " is not a type: it's " ++ show ty''
case lookupDefExact n ctxt of
Just _ -> lift . tfail . InternalMsg $
show n ++ " is already defined."
Nothing -> return ()
let decl = TyDecl Ref checked
ctxt' = addCtxtDef n decl ctxt
set_context ctxt'
updateAux $ \e -> e { new_tyDecls = (RTyDeclInstrs n fc (map rArgToPArg args) checked) :
new_tyDecls e }
aux <- getAux
returnUnit
| n == tacN "prim__DefineFunction", [decl] <- args
= do defn <- reifyFunDefn decl
defineFunction defn
returnUnit
| n == tacN "prim__AddInstance", [cls, inst] <- args
= do className <- reifyTTName cls
instName <- reifyTTName inst
updateAux $ \e -> e { new_tyDecls = RAddInstance className instName :
new_tyDecls e}
returnUnit
| n == tacN "prim__ResolveTC", [fn] <- args
= do g <- goal
fn <- reifyTTName fn
resolveTC False True 100 g fn ist
returnUnit
| n == tacN "prim__RecursiveElab", [goal, script] <- args
= do goal' <- reifyRaw goal
ctxt <- get_context
script <- eval script
(goalTT, goalTy) <- lift $ check ctxt [] goal'
lift $ isType ctxt [] goalTy
recH <- getNameFrom (sMN 0 "recElabHole")
aux <- getAux
datatypes <- get_datatypes
env <- get_env
(_, ES (p, aux') _ _) <-
lift $ runElab aux (runTactical ist fc [] script)
(newProof recH ctxt datatypes goalTT)
let tm_out = getProofTerm (pterm p)
updateAux $ const aux'
env' <- get_env
(tm, ty, _) <- lift $ recheck ctxt env (forget tm_out) tm_out
let (tm', ty') = (reflect tm, reflect ty)
fmap fst . get_type_val $
rawPair (Var $ reflm "TT", Var $ reflm "TT")
(tm', ty')
| n == tacN "prim__Debug", [ty, msg] <- args
= do let msg' = fromTTMaybe msg
case msg' of
Nothing -> debugElaborator Nothing
Just (Constant (Str m)) -> debugElaborator (Just m)
Just x -> lift . tfail . InternalMsg $ "Can't reify message for debugging: " ++ show x
runTacTm x = lift . tfail $ ElabScriptStuck x
-- Running tactics directly
-- if a tactic adds unification problems, return an error
runTac :: Bool -> IState -> Maybe FC -> Name -> PTactic -> ElabD ()
runTac autoSolve ist perhapsFC fn tac
= do env <- get_env
g <- goal
let tac' = fmap (addImplBound ist (map fst env)) tac
if autoSolve
then runT tac'
else no_errors (runT tac')
(Just (CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env)))
where
runT (Intro []) = do g <- goal
attack; intro (bname g)
where
bname (Bind n _ _) = Just n
bname _ = Nothing
runT (Intro xs) = mapM_ (\x -> do attack; intro (Just x)) xs
runT Intros = do g <- goal
attack;
intro (bname g)
try' (runT Intros)
(return ()) True
where
bname (Bind n _ _) = Just n
bname _ = Nothing
runT (Exact tm) = do elab ist toplevel ERHS [] (sMN 0 "tac") tm
when autoSolve solveAll
runT (MatchRefine fn)
= do fnimps <-
case lookupCtxtName fn (idris_implicits ist) of
[] -> do a <- envArgs fn
return [(fn, a)]
ns -> return (map (\ (n, a) -> (n, map (const True) a)) ns)
let tacs = map (\ (fn', imps) ->
(match_apply (Var fn') (map (\x -> (x, 0)) imps),
fn')) fnimps
tryAll tacs
when autoSolve solveAll
where envArgs n = do e <- get_env
case lookup n e of
Just t -> return $ map (const False)
(getArgTys (binderTy t))
_ -> return []
runT (Refine fn [])
= do fnimps <-
case lookupCtxtName fn (idris_implicits ist) of
[] -> do a <- envArgs fn
return [(fn, a)]
ns -> return (map (\ (n, a) -> (n, map isImp a)) ns)
let tacs = map (\ (fn', imps) ->
(apply (Var fn') (map (\x -> (x, 0)) imps),
fn')) fnimps
tryAll tacs
when autoSolve solveAll
where isImp (PImp _ _ _ _ _) = True
isImp _ = False
envArgs n = do e <- get_env
case lookup n e of
Just t -> return $ map (const False)
(getArgTys (binderTy t))
_ -> return []
runT (Refine fn imps) = do ns <- apply (Var fn) (map (\x -> (x,0)) imps)
when autoSolve solveAll
runT DoUnify = do unify_all
when autoSolve solveAll
runT (Claim n tm) = do tmHole <- getNameFrom (sMN 0 "newGoal")
claim tmHole RType
claim n (Var tmHole)
focus tmHole
elab ist toplevel ERHS [] (sMN 0 "tac") tm
focus n
runT (Equiv tm) -- let bind tm, then
= do attack
tyn <- getNameFrom (sMN 0 "ety")
claim tyn RType
valn <- getNameFrom (sMN 0 "eqval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "equiv_val")
letbind letn (Var tyn) (Var valn)
focus tyn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
focus valn
when autoSolve solveAll
runT (Rewrite tm) -- to elaborate tm, let bind it, then rewrite by that
= do attack; -- (h:_) <- get_holes
tyn <- getNameFrom (sMN 0 "rty")
-- start_unify h
claim tyn RType
valn <- getNameFrom (sMN 0 "rval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "rewrite_rule")
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
rewrite (Var letn)
when autoSolve solveAll
runT (Induction tm) -- let bind tm, similar to the others
= case_ True autoSolve ist fn tm
runT (CaseTac tm)
= case_ False autoSolve ist fn tm
runT (LetTac n tm)
= do attack
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- unique_hole n
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
when autoSolve solveAll
runT (LetTacTy n ty tm)
= do attack
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- unique_hole n
letbind letn (Var tyn) (Var valn)
focus tyn
elab ist toplevel ERHS [] (sMN 0 "tac") ty
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
when autoSolve solveAll
runT Compute = compute
runT Trivial = do trivial' ist; when autoSolve solveAll
runT TCInstance = runT (Exact (PResolveTC emptyFC))
runT (ProofSearch rec prover depth top hints)
= do proofSearch' ist rec False depth prover top fn hints
when autoSolve solveAll
runT (Focus n) = focus n
runT Unfocus = do hs <- get_holes
case hs of
[] -> return ()
(h : _) -> movelast h
runT Solve = solve
runT (Try l r) = do try' (runT l) (runT r) True
runT (TSeq l r) = do runT l; runT r
runT (ApplyTactic tm) = do tenv <- get_env -- store the environment
tgoal <- goal -- store the goal
attack -- let f : List (TTName, Binder TT) -> TT -> Tactic = tm in ...
script <- getNameFrom (sMN 0 "script")
claim script scriptTy
scriptvar <- getNameFrom (sMN 0 "scriptvar" )
letbind scriptvar scriptTy (Var script)
focus script
elab ist toplevel ERHS [] (sMN 0 "tac") tm
(script', _) <- get_type_val (Var scriptvar)
-- now that we have the script apply
-- it to the reflected goal and context
restac <- getNameFrom (sMN 0 "restac")
claim restac tacticTy
focus restac
fill (raw_apply (forget script')
[reflectEnv tenv, reflect tgoal])
restac' <- get_guess
solve
-- normalise the result in order to
-- reify it
ctxt <- get_context
env <- get_env
let tactic = normalise ctxt env restac'
runReflected tactic
where tacticTy = Var (reflm "Tactic")
listTy = Var (sNS (sUN "List") ["List", "Prelude"])
scriptTy = (RBind (sMN 0 "__pi_arg")
(Pi Nothing (RApp listTy envTupleType) RType)
(RBind (sMN 1 "__pi_arg")
(Pi Nothing (Var $ reflm "TT") RType) tacticTy))
runT (ByReflection tm) -- run the reflection function 'tm' on the
-- goal, then apply the resulting reflected Tactic
= do tgoal <- goal
attack
script <- getNameFrom (sMN 0 "script")
claim script scriptTy
scriptvar <- getNameFrom (sMN 0 "scriptvar" )
letbind scriptvar scriptTy (Var script)
focus script
ptm <- get_term
elab ist toplevel ERHS [] (sMN 0 "tac")
(PApp emptyFC tm [pexp (delabTy' ist [] tgoal True True)])
(script', _) <- get_type_val (Var scriptvar)
-- now that we have the script apply
-- it to the reflected goal
restac <- getNameFrom (sMN 0 "restac")
claim restac tacticTy
focus restac
fill (forget script')
restac' <- get_guess
solve
-- normalise the result in order to
-- reify it
ctxt <- get_context
env <- get_env
let tactic = normalise ctxt env restac'
runReflected tactic
where tacticTy = Var (reflm "Tactic")
scriptTy = tacticTy
runT (Reflect v) = do attack -- let x = reflect v in ...
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "letvar")
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") v
(value, _) <- get_type_val (Var letn)
ctxt <- get_context
env <- get_env
let value' = hnf ctxt env value
runTac autoSolve ist perhapsFC fn (Exact $ PQuote (reflect value'))
runT (Fill v) = do attack -- let x = fill x in ...
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "letvar")
letbind letn (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") v
(value, _) <- get_type_val (Var letn)
ctxt <- get_context
env <- get_env
let value' = normalise ctxt env value
rawValue <- reifyRaw value'
runTac autoSolve ist perhapsFC fn (Exact $ PQuote rawValue)
runT (GoalType n tac) = do g <- goal
case unApply g of
(P _ n' _, _) ->
if nsroot n' == sUN n
then runT tac
else fail "Wrong goal type"
_ -> fail "Wrong goal type"
runT ProofState = do g <- goal
return ()
runT Skip = return ()
runT (TFail err) = lift . tfail $ ReflectionError [err] (Msg "")
runT SourceFC =
case perhapsFC of
Nothing -> lift . tfail $ Msg "There is no source location available."
Just fc ->
do fill $ reflectFC fc
solve
runT Qed = lift . tfail $ Msg "The qed command is only valid in the interactive prover"
runT x = fail $ "Not implemented " ++ show x
runReflected t = do t' <- reify ist t
runTac autoSolve ist perhapsFC fn t'
elaboratingArgErr :: [(Name, Name)] -> Err -> Err
elaboratingArgErr [] err = err
elaboratingArgErr ((f,x):during) err = fromMaybe err (rewrite err)
where rewrite (ElaboratingArg _ _ _ _) = Nothing
rewrite (ProofSearchFail e) = fmap ProofSearchFail (rewrite e)
rewrite (At fc e) = fmap (At fc) (rewrite e)
rewrite err = Just (ElaboratingArg f x during err)
withErrorReflection :: Idris a -> Idris a
withErrorReflection x = idrisCatch x (\ e -> handle e >>= ierror)
where handle :: Err -> Idris Err
handle e@(ReflectionError _ _) = do logLvl 3 "Skipping reflection of error reflection result"
return e -- Don't do meta-reflection of errors
handle e@(ReflectionFailed _ _) = do logLvl 3 "Skipping reflection of reflection failure"
return e
-- At and Elaborating are just plumbing - error reflection shouldn't rewrite them
handle e@(At fc err) = do logLvl 3 "Reflecting body of At"
err' <- handle err
return (At fc err')
handle e@(Elaborating what n err) = do logLvl 3 "Reflecting body of Elaborating"
err' <- handle err
return (Elaborating what n err')
handle e@(ElaboratingArg f a prev err) = do logLvl 3 "Reflecting body of ElaboratingArg"
hs <- getFnHandlers f a
err' <- if null hs
then handle err
else applyHandlers err hs
return (ElaboratingArg f a prev err')
-- ProofSearchFail is an internal detail - so don't expose it
handle (ProofSearchFail e) = handle e
-- TODO: argument-specific error handlers go here for ElaboratingArg
handle e = do ist <- getIState
logLvl 2 "Starting error reflection"
let handlers = idris_errorhandlers ist
applyHandlers e handlers
getFnHandlers :: Name -> Name -> Idris [Name]
getFnHandlers f arg = do ist <- getIState
let funHandlers = maybe M.empty id .
lookupCtxtExact f .
idris_function_errorhandlers $ ist
return . maybe [] S.toList . M.lookup arg $ funHandlers
applyHandlers e handlers =
do ist <- getIState
let err = fmap (errReverse ist) e
logLvl 3 $ "Using reflection handlers " ++
concat (intersperse ", " (map show handlers))
let reports = map (\n -> RApp (Var n) (reflectErr err)) handlers
-- Typecheck error handlers - if this fails, then something else was wrong earlier!
handlers <- case mapM (check (tt_ctxt ist) []) reports of
Error e -> ierror $ ReflectionFailed "Type error while constructing reflected error" e
OK hs -> return hs
-- Normalize error handler terms to produce the new messages
ctxt <- getContext
let results = map (normalise ctxt []) (map fst handlers)
logLvl 3 $ "New error message info: " ++ concat (intersperse " and " (map show results))
-- For each handler term output, either discard it if it is Nothing or reify it the Haskell equivalent
let errorpartsTT = mapMaybe unList (mapMaybe fromTTMaybe results)
errorparts <- case mapM (mapM reifyReportPart) errorpartsTT of
Left err -> ierror err
Right ok -> return ok
return $ case errorparts of
[] -> e
parts -> ReflectionError errorparts e
solveAll = try (do solve; solveAll) (return ())
-- | Do the left-over work after creating declarations in reflected
-- elaborator scripts
processTacticDecls :: ElabInfo -> [RDeclInstructions] -> Idris ()
processTacticDecls info steps =
-- The order of steps is important: type declarations might
-- establish metavars that later function bodies resolve.
forM_ (reverse steps) $ \case
RTyDeclInstrs n fc impls ty ->
do logLvl 3 $ "Declaration from tactics: " ++ show n ++ " : " ++ show ty
logLvl 3 $ " It has impls " ++ show impls
updateIState $ \i -> i { idris_implicits =
addDef n impls (idris_implicits i) }
addIBC (IBCImp n)
ds <- checkDef fc (\_ e -> e) [(n, (-1, Nothing, ty))]
addIBC (IBCDef n)
ctxt <- getContext
case lookupDef n ctxt of
(TyDecl _ _ : _) ->
-- If the function isn't defined at the end of the elab script,
-- then it must be added as a metavariable. This needs guarding
-- to prevent overwriting case defs with a metavar, if the case
-- defs come after the type decl in the same script!
let ds' = map (\(n, (i, top, t)) -> (n, (i, top, t, True))) ds
in addDeferred ds'
_ -> return ()
RAddInstance className instName ->
do -- The type class resolution machinery relies on a special
logLvl 2 $ "Adding elab script instance " ++ show instName ++
" for " ++ show className
addInstance False True className instName
addIBC (IBCInstance False True className instName)
RClausesInstrs n cs ->
do logLvl 3 $ "Pattern-matching definition from tactics: " ++ show n
solveDeferred n
let lhss = map (\(_, lhs, _) -> lhs) cs
let fc = fileFC "elab_reflected"
pmissing <-
do ist <- getIState
possible <- genClauses fc n lhss
(map (\lhs ->
delab' ist lhs True True) lhss)
missing <- filterM (checkPossible n) possible
return (filter (noMatch ist lhss) missing)
let tot = if null pmissing
then Unchecked -- still need to check recursive calls
else Partial NotCovering -- missing cases implies not total
setTotality n tot
updateIState $ \i -> i { idris_patdefs =
addDef n (cs, pmissing) $ idris_patdefs i }
addIBC (IBCDef n)
ctxt <- getContext
case lookupDefExact n ctxt of
Just (CaseOp _ _ _ _ _ cd) ->
-- Here, we populate the call graph with a list of things
-- we refer to, so that if they aren't total, the whole
-- thing won't be.
let (scargs, sc) = cases_compiletime cd
(scargs', sc') = cases_runtime cd
calls = findCalls sc' scargs
used = findUsedArgs sc' scargs'
cg = CGInfo scargs' calls [] used []
in do logLvl 2 $ "Called names in reflected elab: " ++ show cg
addToCG n cg
addToCalledG n (nub (map fst calls))
addIBC $ IBCCG n
Just _ -> return () -- TODO throw internal error
Nothing -> return ()
-- checkDeclTotality requires that the call graph be present
-- before calling it.
-- TODO: reduce code duplication with Idris.Elab.Clause
buildSCG (fc, n)
-- Actually run the totality checker. In the main clause
-- elaborator, this is deferred until after. Here, we run it
-- now to get totality information as early as possible.
tot' <- checkDeclTotality (fc, n)
setTotality n tot'
when (tot' /= Unchecked) $ addIBC (IBCTotal n tot')
where
-- TODO: see if the code duplication with Idris.Elab.Clause can be
-- reduced or eliminated.
checkPossible :: Name -> PTerm -> Idris Bool
checkPossible fname lhs_in =
do ctxt <- getContext
ist <- getIState
let lhs = addImplPat ist lhs_in
let fc = fileFC "elab_reflected_totality"
let tcgen = False -- TODO: later we may support dictionary generation
case elaborate ctxt (idris_datatypes ist) (sMN 0 "refPatLHS") infP initEState
(erun fc (buildTC ist info ELHS [] fname (infTerm lhs))) of
OK (ElabResult lhs' _ _ _ _ _, _) ->
do -- not recursively calling here, because we don't
-- want to run infinitely many times
let lhs_tm = orderPats (getInferTerm lhs')
case recheck ctxt [] (forget lhs_tm) lhs_tm of
OK _ -> return True
err -> return False
-- if it's a recoverable error, the case may become possible
Error err -> if tcgen then return (recoverableCoverage ctxt err)
else return (validCoverageCase ctxt err ||
recoverableCoverage ctxt err)
-- TODO: Attempt to reduce/eliminate code duplication with Idris.Elab.Clause
noMatch i cs tm = all (\x -> case matchClause i (delab' i x True True) tm of
Right _ -> False
Left _ -> True) cs
| BartAdv/Idris-dev | src/Idris/Elab/Term.hs | bsd-3-clause | 109,952 | 965 | 16 | 48,965 | 12,431 | 9,686 | 2,745 | 1,955 | 183 |
{-# LANGUAGE DeriveDataTypeable #-}
module Control.Pipe.Coroutine (
Coroutine,
resume,
suspend,
coroutine,
step,
terminate
) where
import Control.Monad
import Control.Pipe
import Control.Pipe.Exception
import qualified Control.Exception as E
import Data.Typeable
import Prelude hiding (catch)
data Coroutine a b m r = Coroutine
{ resume :: Pipe a b m r
, finalizer :: [m ()]
}
suspend :: Monad m
=> Pipe a b m r
-> Pipe a x m (Either r (b, Coroutine a b m r))
suspend (Pure r w) = Pure (Left r) w
suspend (Throw e w) = Throw e w
suspend (Yield x p w) = return (Right (x, Coroutine p w))
suspend (M s m h) = M s (liftM suspend m) (suspend . h)
suspend (Await k h) = Await (suspend . k) (suspend . h)
coroutine :: Monad m
=> Pipe a b m r
-> Coroutine a b m r
coroutine p = Coroutine p []
step :: Monad m
=> Coroutine a b m r
-> Pipe a x m (Either r (b, Coroutine a b m r))
step = suspend . resume
terminate :: Monad m
=> Coroutine a b m r
-> Pipe a b m ()
terminate p = mapM_ masked (finalizer p)
| pcapriotti/pipes-extra | Control/Pipe/Coroutine.hs | bsd-3-clause | 1,087 | 0 | 11 | 297 | 496 | 259 | 237 | 37 | 1 |
{-# LANGUAGE RankNTypes, ScopedTypeVariables, GADTs #-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- | @operational@-style programs for 'MonadPlus'. See the
-- documentation for "Control.Applicative.Operational" and
-- "Control.Monad.Operational" for guidance on how to use this module.
module Control.MonadPlus.Operational
( module Control.Operational.Class
, ProgramP(..)
, interpretP
, fromProgramP
, ProgramViewP(..)
, view
) where
import Control.Applicative
import Control.Monad
import Control.MonadPlus.Free
import Control.Operational.Class
import Data.Functor.Coyoneda
newtype ProgramP instr a =
ProgramP { -- | Interpret the program as a free 'MonadPlus'.
toFree :: Free (Coyoneda instr) a
} deriving (Functor, Applicative, Alternative, Monad, MonadPlus)
instance Operational instr (ProgramP instr) where
singleton = ProgramP . liftF . liftCoyoneda
interpretP :: forall m instr a. (Functor m, MonadPlus m) =>
(forall x. instr x -> m x)
-> ProgramP instr a
-> m a
interpretP evalI = retract . hoistFree evalF . toFree
where evalF :: forall x. Coyoneda instr x -> m x
evalF (Coyoneda f i) = fmap f (evalI i)
fromProgramP
:: (Operational instr m, Functor m, MonadPlus m) => ProgramP instr a -> m a
fromProgramP = interpretP singleton
data ProgramViewP instr a where
Return :: a -> ProgramViewP instr a
(:>>=) :: instr a -> (a -> ProgramP instr b) -> ProgramViewP instr b
MPlus :: [ProgramViewP instr a] -> ProgramViewP instr a
view :: ProgramP instr a -> ProgramViewP instr a
view = eval . toFree
where eval (Pure a) = Return a
eval (Free (Coyoneda f i)) = i :>>= (ProgramP . f)
eval (Plus mas) = MPlus $ map eval mas
| sacundim/free-operational | Control/MonadPlus/Operational.hs | bsd-3-clause | 1,859 | 0 | 11 | 433 | 511 | 277 | 234 | 40 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module RunstaskellSpec where
import Control.Exception
import System.Exit
import System.FilePath
import System.IO
import System.IO.Silently
import System.IO.Temp
import Test.Hspec
import BootstrapSpec
import PackageSets
import Path
import Runstaskell
import Sandboxes
spec :: Spec
spec = do
describe "getPackageNameSetFromProgramPath" $ do
it "parses runstaskell-test" $ do
getPackageNameSetFromProgName (Path "runstaskell-test")
`shouldBe` "test"
it "parses runstaskell-1.11" $ do
getPackageNameSetFromProgName (Path "runstaskell-1.11")
`shouldBe` "1.11"
it "returns the default for runstaskell" $ do
getPackageNameSetFromProgName (Path "runstaskell")
`shouldBe` latest
it "returns the default for foo" $ do
getPackageNameSetFromProgName (Path "foo")
`shouldBe` latest
describe "runScript" $ do
let stdoutCode = unlines $
"import System.Exit" :
"import System.IO" :
"main = do" :
" hPutStrLn stdout $ \"this goes to stdout\"" :
[]
stderrCode = unlines $
"import System.Exit" :
"import System.IO" :
"main = do" :
" hPutStrLn stderr $ \"this goes to stderr\"" :
" exitWith $ ExitFailure 23" :
[]
argsCode = unlines $
"import System.Environment" :
"main = getArgs >>= print" :
[]
it "inherits stdout/stderr and exitcode from running the script" $ do
withBootstrappedScript stdoutCode $ \executable sandboxes scriptPath -> do
output <- hCapture_ [stdout] $
runScript executable sandboxes scriptPath []
output `shouldBe` "this goes to stdout\n"
it "inherits stderr and exitcode from running the script" $ do
withBootstrappedScript stderrCode $ \executable sandboxes scriptPath -> do
output <- hCapture_ [stderr] $
runScript executable sandboxes scriptPath []
`catch` \e -> e `shouldBe` ExitFailure 23
output `shouldBe` "this goes to stderr\n"
it "passes arguments to the running script" $ do
withBootstrappedScript argsCode $ \executable sandboxes scriptPath -> do
let args = ["arg1", "arg2"]
output <- hCapture_ [stdout] $
runScript executable sandboxes scriptPath args
output `shouldBe` (show args ++ "\n")
withBootstrappedScript :: String
-> (Path ProgName -> Path Sandboxes -> Path Script -> IO ())
-> IO ()
withBootstrappedScript code action =
withBootstrapped "test" $ \ binPath dataPath ->
withSystemTempFile "Code.hs" $ \ scriptPath handle -> do
hPutStr handle code
hClose handle
action
(Path $ toPath binPath </> "runstaskell-test")
(getSandboxes dataPath)
(Path scriptPath)
| soenkehahn/runstaskell | test/RunstaskellSpec.hs | bsd-3-clause | 3,049 | 0 | 21 | 930 | 657 | 325 | 332 | 77 | 1 |
module Day23 (part1,part2,test1,part1Solution, part2Solution) where
import Control.Applicative
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Sequence (Seq)
import qualified Data.Sequence as S
import Text.Trifecta
type Register = Char
data Instruction = CpyI Integer Register
| CpyR Register Register
| Inc Register
| Dec Register
| JnzR Register Integer
| JnzR' Integer Register
| JnzR'' Register Register
| JnzI Integer Integer
| Tgl Register
| Skip Instruction
deriving (Eq, Ord, Show)
type CurrentPosition = Int
data ProgramState = ProgramState CurrentPosition (Seq Instruction) (Map Register Integer)
deriving (Eq, Ord, Show)
startState :: Map Register Integer -> [Instruction] -> ProgramState
startState m is = ProgramState 0 (S.fromList is) m
instructionParser :: Parser Instruction
instructionParser = try cpyIParser <|> try cpyRParser <|> try incParser <|> try decParser <|> try jnzRParser <|> try jnzR'Parser <|> try tglParser <|> jnzIParser
where
cpyIParser = string "cpy " *> (CpyI <$> integer <*> letter)
cpyRParser = string "cpy " *> (CpyR <$> letter <*> (space *> letter))
incParser = string "inc " *> (Inc <$> letter)
decParser = string "dec " *> (Dec <$> letter)
jnzRParser = string "jnz " *> (JnzR <$> letter <*> (space *> integer ))
jnzR'Parser = string "jnz " *> (JnzR' <$> integer <*> letter)
jnzIParser = string "jnz " *> (JnzI <$> integer <*> integer)
tglParser = string "tgl " *> (Tgl <$> letter)
fromSuccess :: Result x -> x
fromSuccess (Success x) = x
fromSuccess (Failure x) = error (show x)
parseInput :: String -> [Instruction]
parseInput = fromSuccess . parseString (some (instructionParser <* skipOptional windowsNewLine)) mempty
where windowsNewLine = const () <$ skipOptional newline <*> skipOptional (char '\r')
doNextInstruction :: ProgramState -> ProgramState
doNextInstruction ps@(ProgramState i instructions rMap)
| endOfInstruction ps = ps
| otherwise = ProgramState (newI currInstruction) (newInstructions currInstruction) (newMap currInstruction)
where
currInstruction = S.index instructions i
newI (JnzR' x r)
| x > 0 = i + fromIntegral (currVal r)
| otherwise = i+1
newI (JnzR'' r1 r2)
| currVal r1 > 0 = i + fromIntegral (currVal r2)
| otherwise = i+1
newI (JnzR r x)
| currVal r > 0 = i + fromIntegral x
| otherwise = i+1
newI (JnzI x y)
| x > 0 = i + fromIntegral y
| otherwise = i+1
newI _ = i+1
currVal r = M.findWithDefault 0 r rMap
newInstructions (Tgl r) = S.adjust tglInstruction instructionToTgl instructions
where
instructionToTgl = i + fromIntegral (currVal r)
newInstructions _ = instructions
newMap (CpyI x r) = M.insert r x rMap
newMap (CpyR x y) = M.insert y (currVal x) rMap
newMap (Inc r) = M.insert r (currVal r + 1) rMap
newMap (Dec r) = M.insert r (currVal r - 1) rMap
newMap _ = rMap
tglInstruction :: Instruction -> Instruction
tglInstruction (CpyI t1 t2) = JnzR' t1 t2
tglInstruction (CpyR t1 t2) = JnzR'' t1 t2
tglInstruction (Inc t) = Dec t
tglInstruction (Dec t) = Inc t
tglInstruction i@(JnzR _ _) = Skip i
tglInstruction (JnzR' t1 t2) = CpyI t1 t2
tglInstruction (JnzR'' t1 t2) = CpyR t1 t2
tglInstruction i@(JnzI _ _) = Skip i
tglInstruction (Tgl t) = Inc t
tglInstruction (Skip i) = case n of
(Skip ins) -> Skip ins
_ -> n
where n = tglInstruction i
endOfInstruction :: ProgramState -> Bool
endOfInstruction (ProgramState i instructions _) = i >= S.length instructions
getRegister :: Register -> ProgramState -> Integer
getRegister r (ProgramState _ _ rMap) = M.findWithDefault 0 r rMap
part1 :: Map Register Integer -> Char -> String -> Integer
part1 m c = getRegister c . last . takeWhile (not . endOfInstruction) . iterate doNextInstruction . startState m . parseInput
part1Solution :: IO Integer
part1Solution = part1 (M.fromList [('a',7)]) 'a' <$> readFile "./data/Day23.txt"
part2 :: Map Register Integer -> Char -> String -> Integer
part2 = part1
part2Solution :: IO Integer
part2Solution = part2 (M.fromList [('a',12)]) 'a' <$> readFile "./data/Day23.txt"
test1 :: String
test1 = "cpy 2 a\ntgl a\ntgl a\ntgl a\ncpy 1 a\ndec a\ndec a"
| z0isch/aoc2016 | src/Day23.hs | bsd-3-clause | 4,599 | 0 | 12 | 1,208 | 1,629 | 821 | 808 | 95 | 10 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE PatternSynonyms #-}
module Pt.StateMachine where
import Ptui.Types
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Lazy.UTF8 as U
import Data.Char (isDigit)
import Data.List (foldl',uncons)
import Data.Maybe (mapMaybe,fromMaybe)
import Text.Read (readMaybe)
data CX = C0 | C1 deriving Show
data Q_ = Q0
| QSS2
| QSS3
| QESC
| QESCSP
| QCSI
| QDCS
| QOSC
| QOSC2
| QSGR0
| QSGR38
| QSGR38c
| QSGR38r
| QSGR38g
| QSGR38b
| QSGR48
| QSGR48c
| QSGR48r
| QSGR48g
| QSGR48b
deriving Show
pattern b :> bs <- (B.uncons -> Just (b,bs))
pattern Empty <- (B.uncons -> Nothing)
runFSM :: B.ByteString -> [Command]
runFSM = transduce Q0 C0 ("","",[])
runFSMC1 :: B.ByteString -> [Command]
runFSMC1 = transduce Q0 C1 ("","",[])
transduce :: Q_ -> CX -> (String,String,[String]) -> B.ByteString -> [Command]
transduce _ _ _ Empty = []
transduce Q0 cs t ('\x1b':>bs) = transduce QESC cs t bs
transduce Q0 cs t ('\x07':>bs) = BEL : transduce Q0 cs t bs
transduce Q0 cs t ('\x08':>bs) = BS : transduce Q0 cs t bs
transduce Q0 cs t ('\x09':>bs) = HT : transduce Q0 cs t bs
transduce Q0 cs t ('\x0a':>bs) = LF : transduce Q0 cs t bs
transduce Q0 cs t ('\x0b':>bs) = VT : transduce Q0 cs t bs
transduce Q0 cs t ('\x0c':>bs) = FF : transduce Q0 cs t bs
transduce Q0 cs t ('\x0d':>bs) = CR : transduce Q0 cs t bs
transduce Q0 C1 t ('\x84':>bs) = IND : transduce Q0 C1 t bs
transduce Q0 C1 t ('\x85':>bs) = NEL : transduce Q0 C1 t bs
transduce Q0 C1 t ('\x88':>bs) = HTS : transduce Q0 C1 t bs
transduce Q0 C1 t ('\x8d':>bs) = RI : transduce Q0 C1 t bs
transduce Q0 C1 t ('\x8e':>bs) = transduce QSS2 C1 t bs
transduce Q0 C1 t ('\x8f':>bs) = transduce QSS3 C1 t bs
transduce Q0 C1 t ('\x9b':>bs) = transduce QCSI C1 t bs
transduce Q0 cs t bs = maybe [] (\(b,bs') -> Output b : transduce Q0 cs t bs') (U.uncons bs)
transduce QSS2 cs t (b:>bs) = SS2 b : transduce Q0 cs t bs
transduce QSS3 cs t (b:>bs) = SS3 b : transduce Q0 cs t bs
transduce QESC cs t ('D':>bs) = IND : transduce Q0 cs t bs
transduce QESC cs t ('E':>bs) = NEL : transduce Q0 cs t bs
transduce QESC cs t ('H':>bs) = HTS : transduce Q0 cs t bs
transduce QESC cs t ('M':>bs) = RI : transduce Q0 cs t bs
transduce QESC cs t ('N':>bs) = transduce QSS2 cs t bs
transduce QESC cs t ('O':>bs) = transduce QSS3 cs t bs
transduce QESC cs _ ('[':>bs) = transduce QCSI cs ("","",[]) bs
transduce QESC cs _ ('(':>bs) = transduce QDCS cs ("(","",[]) bs
transduce QESC cs _ (']':>bs) = transduce QOSC cs ("","",[]) bs
transduce QESC cs t (' ':>bs) = transduce QESCSP cs t bs
transduce QOSC cs t@(p,x,xs) (';':>bs) = transduce QOSC2 cs (p,"",xs++[x]) bs
transduce QOSC cs t@(p,x,xs) (b:>bs) | isDigit b = transduce QOSC cs (p,x++[b],xs) bs
| otherwise = transduce Q0 cs t bs
transduce QOSC2 cs t@(p,x,xs) ('\a':>bs) = makeOSC (xs++[x]) : transduce Q0 cs t bs
transduce QOSC2 C1 t@(p,x,xs) ('\x9c':>bs) = makeOSC (xs++[x]) : transduce Q0 C1 t bs
transduce QOSC2 cs t@(p,x,xs) bs = maybe [] (\(b,bs') -> transduce QOSC2 cs (p,x++[b],xs) bs') (U.uncons bs)
transduce QDCS cs t@(p,x,xs) ('0':>bs) = makeCharsetDesignation p Special : transduce Q0 cs t bs
transduce QDCS cs t@(p,x,xs) ('A':>bs) = makeCharsetDesignation p UK : transduce Q0 cs t bs
transduce QDCS cs t@(p,x,xs) ('B':>bs) = makeCharsetDesignation p USASCII : transduce Q0 cs t bs
transduce QESCSP _ t ('F':>bs) = transduce Q0 C0 t bs
transduce QESCSP _ t ('G':>bs) = transduce Q0 C1 t bs
transduce QCSI cs t@(p,x,xs) ('A':>bs) = CUU (fromMaybe 1 $ readMaybe x) : transduce Q0 cs t bs
transduce QCSI cs t@(p,x,xs) ('B':>bs) = CUD (fromMaybe 1 $ readMaybe x) : transduce Q0 cs t bs
transduce QCSI cs t@(p,x,xs) ('C':>bs) = CUF (fromMaybe 1 $ readMaybe x) : transduce Q0 cs t bs
transduce QCSI cs t@(p,x,xs) ('D':>bs) = CUB (fromMaybe 1 $ readMaybe x) : transduce Q0 cs t bs
transduce QCSI cs t@(p,x,xs) ('E':>bs) = CNL (fromMaybe 1 $ readMaybe x) : transduce Q0 cs t bs
transduce QCSI cs t@(p,x,xs) ('F':>bs) = CPL (fromMaybe 1 $ readMaybe x) : transduce Q0 cs t bs
transduce QCSI cs t@(p,x,xs) ('G':>bs) = CHA (fromMaybe 1 $ readMaybe x) : transduce Q0 cs t bs
transduce QCSI cs t@(p,x,xs) ('H':>bs) = makeCUP (xs++[x]) : transduce Q0 cs t bs
transduce QCSI cs t@(p,x,xs) ('I':>bs) = CHT (fromMaybe 1 $ readMaybe x) : transduce Q0 cs t bs
transduce QCSI cs t@(p,x,xs) ('m':>bs) = makeSGR (xs++[x]) : transduce Q0 cs t bs
transduce QCSI cs t@(p,x,xs) (';':>bs) = transduce QCSI cs (p,"",xs++[x]) bs
transduce QCSI cs t@(p,x,xs) (b:>bs) | isDigit b = transduce QCSI cs (p,x++[b],xs) bs
| otherwise = transduce Q0 cs t bs
transduce _ cs t (b:>bs) = transduce Q0 cs t bs
makeCUP :: [String] -> Command
makeCUP [] = CUP 1 1
makeCUP [r] = CUP (fromMaybe 1 $ readMaybe r) 1
makeCUP (r:c:_) = CUP (fromMaybe 1 $ readMaybe r) (fromMaybe 1 $ readMaybe c)
makeOSC :: [String] -> Command
makeOSC [] = Noop
makeOSC [_] = Noop
makeOSC ("0":t:_) = SetIconTitle t
makeOSC _ = Noop
makeCharsetDesignation :: String -> CharacterSet -> Command
makeCharsetDesignation g cs = case g of
"(" -> SetCharset G0 cs
")" -> SetCharset G1 cs
"*" -> SetCharset G2 cs
"+" -> SetCharset G3 cs
"-" -> SetCharset G1 cs
"." -> SetCharset G2 cs
"/" -> SetCharset G3 cs
_ -> Noop
makeSGR :: [String] -> Command
makeSGR = SGR . transduceSGR QSGR0 [] . mapMaybe (readMaybe :: String -> Maybe Int)
where transduceSGR _ _ [] = []
transduceSGR QSGR0 l (0:xs) = Reset : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (1:xs) = Bold True : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (2:xs) = Faint : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (3:xs) = Italic True : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (4:xs) = Underscore True : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (5:xs) = Blink True : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (7:xs) = Reverse True : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (8:xs) = Invisible True : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (9:xs) = Strikethrough True : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (21:xs) = DoubleUnderline : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (22:xs) = Bold False : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (23:xs) = Italic False : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (24:xs) = Underscore False : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (25:xs) = Blink False : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (27:xs) = Reverse False : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (28:xs) = Invisible False : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (29:xs) = Strikethrough False : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (30:xs) = Foreground (Color256 0) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (31:xs) = Foreground (Color256 1) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (32:xs) = Foreground (Color256 2) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (33:xs) = Foreground (Color256 3) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (34:xs) = Foreground (Color256 4) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (35:xs) = Foreground (Color256 5) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (36:xs) = Foreground (Color256 6) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (37:xs) = Foreground (Color256 7) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (38:xs) = transduceSGR QSGR38 l xs
transduceSGR QSGR0 l (39:xs) = Foreground Default : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (40:xs) = Background (Color256 0) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (41:xs) = Background (Color256 1) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (42:xs) = Background (Color256 2) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (43:xs) = Background (Color256 3) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (44:xs) = Background (Color256 4) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (45:xs) = Background (Color256 5) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (46:xs) = Background (Color256 6) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (47:xs) = Background (Color256 7) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (48:xs) = transduceSGR QSGR48 l xs
transduceSGR QSGR0 l (49:xs) = Background Default : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (90:xs) = Foreground (Color256 0) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (91:xs) = Foreground (Color256 1) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (92:xs) = Foreground (Color256 2) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (93:xs) = Foreground (Color256 3) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (94:xs) = Foreground (Color256 4) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (95:xs) = Foreground (Color256 5) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (96:xs) = Foreground (Color256 6) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (97:xs) = Foreground (Color256 7) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (100:xs) = Background (Color256 0) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (101:xs) = Background (Color256 1) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (102:xs) = Background (Color256 2) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (103:xs) = Background (Color256 3) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (104:xs) = Background (Color256 4) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (105:xs) = Background (Color256 5) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (106:xs) = Background (Color256 6) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (107:xs) = Background (Color256 7) : transduceSGR QSGR0 l xs
transduceSGR QSGR0 l (_:xs) = transduceSGR QSGR0 l xs
transduceSGR QSGR38 l (5:xs) = transduceSGR QSGR38c l xs
transduceSGR QSGR38 l (2:xs) = transduceSGR QSGR38r l xs
transduceSGR QSGR38c l (x:xs) = Foreground (Color256 x) : transduceSGR QSGR0 l xs
transduceSGR QSGR38r _ (r:xs) = transduceSGR QSGR38g [r] xs
transduceSGR QSGR38g [r] (g:xs) = transduceSGR QSGR38b [r,g] xs
transduceSGR QSGR38b [r,g] (b:xs) = Foreground (Truecolor r g b) : transduceSGR QSGR0 [] xs
transduceSGR QSGR48 l (5:xs) = transduceSGR QSGR48c l xs
transduceSGR QSGR48 l (2:xs) = transduceSGR QSGR48r l xs
transduceSGR QSGR48c l (x:xs) = Background (Color256 x) : transduceSGR QSGR0 l xs
transduceSGR QSGR48r _ (r:xs) = transduceSGR QSGR48g [r] xs
transduceSGR QSGR48g [r] (g:xs) = transduceSGR QSGR48b [r,g] xs
transduceSGR QSGR48b [r,g] (b:xs) = Background (Truecolor r g b) : transduceSGR QSGR0 [] xs
transduceSGR _ _ (_:xs) = transduceSGR QSGR0 [] xs
| mrak/ptui | src/Pt/StateMachine.hs | bsd-3-clause | 11,621 | 0 | 11 | 3,056 | 5,385 | 2,749 | 2,636 | 183 | 68 |
{-# LANGUAGE OverloadedStrings #-}
module ETA.CodeGen.Foreign where
import ETA.Main.DynFlags
import ETA.Types.Type
import ETA.Types.TyCon
import ETA.StgSyn.StgSyn
import ETA.Prelude.ForeignCall
import ETA.Utils.FastString
import ETA.Utils.Util
import ETA.Util
import ETA.CodeGen.ArgRep
import ETA.CodeGen.Env
import ETA.CodeGen.Monad
import ETA.CodeGen.Name
import ETA.CodeGen.Layout
import ETA.CodeGen.Rts
import ETA.CodeGen.Types
import ETA.Debug
import ETA.Util
import Codec.JVM
import Data.Monoid ((<>))
import Data.List (stripPrefix)
import Data.Maybe (catMaybes, fromJust, isJust, maybe)
import Data.Foldable (fold)
import Control.Monad (when)
import qualified Data.Text as T
cgForeignCall :: ForeignCall -> [StgArg] -> Type -> CodeGen ()
cgForeignCall (CCall (CCallSpec target cconv safety)) args resType
| StaticTarget label _ _ <- target = do
let (hasObj, isStatic, callTarget) = deserializeTarget (unpackFS label)
shuffledArgs = if hasObj then last args : init args else args
dflags <- getDynFlags
argFtCodes <- getNonVoidArgFtCodes shuffledArgs
let (argFts, callArgs') = unzip argFtCodes
callArgs = if hasObj && isStatic then drop 1 callArgs' else callArgs'
mbObj = if hasObj then Just (expectHead "cgForiegnCall: empty callArgs'"
callArgs') else Nothing
mbObjFt = safeHead argFts
sequel <- getSequel
case sequel of
AssignTo targetLocs ->
emitForeignCall safety mbObj targetLocs (callTarget mbObjFt) callArgs
_ -> do
resLocs <- newUnboxedTupleLocs resType
emitForeignCall safety mbObj resLocs (callTarget mbObjFt) callArgs
emitReturn resLocs
deserializeTarget :: String -> (Bool, Bool, Maybe FieldType -> [Code] -> Code)
deserializeTarget label = (hasObj, isStatic, callTarget)
where (hasObj':isStatic':callTargetSpec:_) = split '|' label
hasObj = read hasObj'
isStatic = read isStatic'
(tag:restSpec) = split ',' callTargetSpec
callTarget = case read tag of
0 -> genNewTarget restSpec
1 -> genFieldTarget restSpec
2 -> genMethodTarget restSpec
_ -> error $ "deserializeTarget: deserialization failed: " ++ label
genNewTarget [clsName', methodDesc'] =
\_ args -> new clsFt
<> dup clsFt
<> fold args
<> invokespecial (mkMethodRef clsName "<init>" argFts void)
where clsName = read clsName'
clsFt = obj clsName
(argFts, _) = expectJust ("deserializeTarget: bad method desc: " ++ label)
$ decodeMethodDesc (read methodDesc')
genFieldTarget [clsName', fieldName', fieldDesc', instr'] =
\_ args -> fold args
<> instr (mkFieldRef clsName fieldName fieldFt)
where (getInstr, putInstr) = if isStatic
then (getstatic, putstatic)
else (getfield, putfield)
clsName = read clsName'
fieldName = read fieldName'
fieldFt = expectJust ("deserializeTarget: bad field desc: " ++ label)
$ decodeFieldDesc (read fieldDesc')
instr = case read instr' of
0 -> putInstr
1 -> getInstr
_ -> error $ "deserializeTarget: bad instr: " ++ label
genMethodTarget [isInterface', hasSubclass', clsName', methodName', methodDesc'] =
\mbObjFt args -> fold args
<> instr (mkMethodRef (clsName mbObjFt) methodName argFts resFt)
where clsName mbObjFt =
if hasSubclass && not isInterface
then maybe (error "deserializeTarget: no subclass field type.")
getFtClass mbObjFt
else read clsName'
methodName = read methodName'
isInterface = read isInterface'
hasSubclass = read hasSubclass'
(argFts, resFt) = expectJust ("deserializeTarget: bad method desc: " ++ label)
$ decodeMethodDesc (read methodDesc')
instr = if isInterface
then invokeinterface
else if isStatic
then invokestatic
else invokevirtual
emitForeignCall :: Safety -> Maybe Code -> [CgLoc] -> ([Code] -> Code) -> [Code] -> CodeGen ()
emitForeignCall safety mbObj results target args =
wrapSafety $ do
maybe (emit callCode) (flip emitAssign callCode) resLoc
maybe (return ()) (flip emitAssign (fromJust mbObj)) objLoc
where wrapSafety code = do
whenSafe $ emit $ suspendThreadMethod (playInterruptible safety)
code
whenSafe $ emit resumeThreadMethod
where whenSafe = when (playSafe safety)
callCode = target args
(resLoc, objLoc) =
if isJust mbObj then
case results of
[a] -> (Nothing, Just a)
[a,b] -> (Just b, Just a)
else
(case results of
[] -> Nothing
[a] -> Just a,
Nothing)
| alexander-at-github/eta | compiler/ETA/CodeGen/Foreign.hs | bsd-3-clause | 5,276 | 0 | 15 | 1,721 | 1,381 | 726 | 655 | 118 | 10 |
module Main where
import Command
main :: IO ()
main = execCommand
| ku00/meow | app/Main.hs | bsd-3-clause | 68 | 0 | 6 | 14 | 22 | 13 | 9 | 4 | 1 |
module Language.Modelica.Test.Expression (test) where
import qualified Language.Modelica.Parser.Expression as Expr
import Language.Modelica.Test.Utility (testFunc)
test :: IO [Bool]
test = do
res1 <- mapM (testFunc Expr.expression) $
"true <= (false * (5.0^(, , ))^(, \"bla\", 2.0))" :
"3.0 : 7.0 + 8.0 : 9.0" :
"(3.0 : 7.0) + 8.0 : 9.0" :
"3.0 : 7.0 + (8.0 : 9.0)" :
"(3.0 : 7.0) + (8.0 : 9.0)" :
"3.0 : (7.0 + 8.0) : 9.0" :
"(3.0 : 7.0 + 8.0) : 9.0" :
"3.0 : (7.0 + 8.0 : 9.0)" :
"(3.0 : 7.0 + 8.0 : 9.0)" :
"(3.0) : (7.0) + (8.0 : 9.0)" :
"[true, .bla[x]; false]" :
"()" :
"{x, y}" :
"{x = 9.0, y = 9.0}" :
"f(9.0)" :
"f(9.0, g(), x)" :
"if true then x else y" :
"if true then x elseif false then z else y" :
"if true then x elseif false then z elseif x < y then 7.0 else y" :
"x.y" :
"x .y" :
"x. y" :
"x . y" :
"3 + 4" :
"3 .+ 4" :
"x + y" :
"x .+ y" :
"points[m:end] + (x1-x0)" :
"end" : []
res2 <- mapM (testFunc Expr.function_arguments) $
"x, y for x in 9.0" :
"function x()" :
"function x(), function y()" :
"x, function y()" :
"function x() for bla in 1, blub in true" :
"x, y = 7" :
"function x.y(), 9+4, x = 8" :
"function x.y(), 9+4 for x in 8" :
"x, y, a for y, x in (-9.0 + (-a)), a" :
"x, y" :
"true, \"BlaBlub\", level = Error.level" :
"engineFile = \"maps/engine/base.txt\"" :
"bla = \"äüöß\"" :
"x = 9.0, y = 9.0" :
"x = function b()" :
"x = function b(), y = 7" : []
res3 <- mapM (testFunc Expr.for_indices) $
"bla in 3.0, blub, x in (3.0, 3.0, (, , ), , )" : []
res4 <- mapM (testFunc Expr.output_expression_list) $
"(, (, , , ), )" :
",,," :
"x,,x,," : []
res5 <- mapM (testFunc Expr.named_arguments) $
"bla = blub" :
"x = y, y = z" :
"x = y, y = z, z = x" : []
res7 <- mapM (testFunc Expr.expression) $
"not 5" :
"not true :5" :
"true : 6 :3" :
"true or (6 : 3 and 7)" :
"(.bla[x.x,:], x.y,,).^ 4.e-3 " :
"(b0[1:n] - b0[na]/a[na]*a[1:n])*x + b0[na]/a[na]*u" : []
res8 <- mapM (testFunc Expr.function_argument) $
"function b.x()" :
"function b(x = -0)" :
"x + y" : []
res9 <- mapM (testFunc Expr.expression_list) $
"(, ( ,,), 3 , 3.0 )" :
"a, b" : []
res10 <- mapM (testFunc Expr.array_subscripts) $
"[ 3^2, true : false : 3, 4, : , :,:, 3:3 ] " : []
res11 <- mapM (testFunc Expr.component_reference) $
".bla.dfs[3,: ,:].ads[ :,3 : true].x" : []
res12 <- mapM (testFunc Expr.named_arguments) $
"bla = blub, x = .x[(,,)]" :
"y = function f(x =9)" :
"y = function .f(x= function g.x(a=7, b=-4.0)), z = -1.0" : []
res13 <- mapM (testFunc Expr.name) $
"bla" :
".a.b.c" : []
res14 <- mapM (testFunc Expr.primary) $
"3" :
"\"bla\"" :
"\"äöüß\"" :
"false" :
"true" :
"der(1)" :
"f(3)" :
"points[m:end]" :
"cat(1, {0}, points[m:end] .+ (x1-x0), {1})" :
[]
return $ concat [res1, res2, res3, res4, res5, res7, res8, res9, res10, res11, res12, res13, res14]
| xie-dongping/modelicaparser | test/Language/Modelica/Test/Expression.hs | bsd-3-clause | 3,163 | 0 | 41 | 954 | 728 | 365 | 363 | 99 | 1 |
-- | Periodic background activities that Kademlia must perform
module Network.DHT.Kademlia.Workers (
module Network.DHT.Kademlia.Workers.Interactive
, module Network.DHT.Kademlia.Workers.Persistence
, module Network.DHT.Kademlia.Workers.Reapers
) where
import Network.DHT.Kademlia.Workers.Interactive
import Network.DHT.Kademlia.Workers.Persistence
import Network.DHT.Kademlia.Workers.Reapers
| phylake/kademlia | Network/DHT/Kademlia/Workers.hs | bsd-3-clause | 396 | 0 | 5 | 31 | 62 | 47 | 15 | 7 | 0 |
{-# LANGUAGE GeneralizedNewtypeDeriving, CPP, TypeSynonymInstances, FlexibleInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Perfs
-- Copyright : (c)2011, Texas Instruments France
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : c-favergeon-borgialli@ti.com
-- Stability : provisional
-- Portability : portable
--
-- Functions for helping write and display performance tests
--
-----------------------------------------------------------------------------
module Perfs(
-- * Benchmark environment
Bench(..)
, Samples(..)
, Sample(..)
, classifySample
, newSample
, recordSample
, getBenchResults
, io
, simpleCurve
, graph
, Byte(..)
, AsByte(..)
) where
import qualified Data.Map as M
import Data.Monoid
import Control.Monad.Trans.Writer.Strict
import Benchmark
import TestTools
import Control.Monad(when)
import Control.Monad.IO.Class
import System.FilePath
import System.IO
import System.Cmd(system)
import Data.Int
type Sample = (Int,Double)
type Samples = [(String,Sample)]
type Bench a = WriterT Samples IO a
newtype Byte = Byte Int deriving(Eq,Num,Ord, Integral, Real, Enum)
instance Show Byte where
show (Byte s) = show s
class AsByte a where
toBytes :: a -> Byte
instance AsByte (CLInt s) where
toBytes _ = Byte 4
instance AsByte Int32 where
toBytes _ = Byte 4
instance AsByte (CLFloat s) where
toBytes _ = Byte 4
instance AsByte Float where
toBytes _ = Byte 4
instance AsByte [Float] where
toBytes l = toBytes (undefined :: Float) * fromIntegral (length l)
instance AsByte [Int32] where
toBytes l = toBytes (undefined :: Int32) * fromIntegral (length l)
instance AsByte Float4 where
toBytes _ = Byte 16
instance AsByte [Float4] where
toBytes l = toBytes (undefined :: Float4) * fromIntegral (length l)
instance AsByte (CLIntArray s) where
toBytes (CLIntArray l) = toBytes (undefined :: Int32) * fromIntegral (length l)
toBytes (CLConstIntArray l _) = toBytes (undefined :: Int32) * fromIntegral l
instance AsByte (CLFloatArray s) where
toBytes (CLFloatArray l) = toBytes (undefined :: Float) * fromIntegral (length l)
toBytes (CLConstFloatArray l _) = toBytes (undefined :: Float) * fromIntegral l
instance AsByte (CLFloat4Array s) where
toBytes (CLFloat4Array l) = toBytes (undefined :: Float4) * fromIntegral (length l)
toBytes (CLConstFloat4Array l _) = toBytes (undefined :: Float4) * fromIntegral l
newSample :: Sample -> Bench()
newSample s = tell [("",s)]
-- | Create a text file for R post processing
withR name = withFile (makeValid ("R" </> name)) WriteMode
-- | Create a R data file and process it using the simple.r script
-- to generate a y=f(x) curve for several clock values
simpleCurve :: (Num a , Num b)
=> String -- ^ Name
-> String -- ^ y
-> String -- ^ x
-> (Clocks -> IO [(a,b)])
-> IO ()
simpleCurve name x y a = do
withR (name <.> "dat") $ \h -> do
hPutStrLn h $ y ++ "," ++ x ++ ",cpu,mem,gpu"
forAllClocks (\_ c -> a c >>= writeResult h c)
system("./simple.r " ++ name)
return()
where
writeResult h c l = do
let Clocks cpu mem gpu = c
clockString = "," ++ show cpu ++ "," ++ show mem ++ "," ++ show gpu
writeSample (xa,ya) = hPutStrLn h $ show ya ++ "," ++ show xa ++ clockString
mapM_ writeSample l
-- | Create a R data file and process it using the graph.r script
graph :: String -- ^ Name
-> (Clocks -> IO [(Byte,TimingResult)])
-> IO ()
graph name a = do
withR (name <.> "dat") $ \h -> do
hPutStrLn h "b,nb,c,w,e,r,cpu,mem,gpu"
forAllClocks (\_ c -> a c >>= writeResult h c)
system("./graph.r " ++ name)
return()
where
writeResult h c l = do
let Clocks cpu mem gpu = c
clockString = "," ++ show cpu ++ "," ++ show mem ++ "," ++ show gpu
writeSample (bytes,(c,w,e,r)) = do
let clBandwidth = fromIntegral bytes / e * 1e-6
s = show clBandwidth ++ "," ++ show bytes ++ "," ++ show c ++ "," ++ show w ++ ","
++ show e ++ "," ++ show r ++ clockString
hPutStrLn h s
mapM_ writeSample l
-- | Classify a sample
classifySample :: String -> Bool -> Bench Sample -> Bench Sample
classifySample curve cond b = do
s <- b
when (cond) $ do
recordSample curve s
return s
-- | Record a new sample with classification
recordSample :: String -> Sample -> Bench ()
recordSample curve s = tell [(curve,s)]
getBenchResults :: Bench () -> IO Samples
getBenchResults b = execWriterT b
#ifdef OMAP4
-- | Generate different benchmark for different clock values
forAllClocks :: MonadIO m => (String -> Clocks -> m ()) -> m ()
forAllClocks b = do
io $ putStrLn " CPU 1GHz, L3 200MHz, DDR 400MHz, GPU 307MHz"
b "CPU 1GHz, L3 200MHz, DDR 400MHz, GPU 307MHz" defaultClocks
io $ putStrLn " CPU 800MHz"
b "CPU 800MHz, L3 200MHz, DDR 400MHz, GPU 307MHz" (defaultClocks {cpuClock = CPU_800MHz})
io $ putStrLn " L3 100MHz, DDR 200MHz"
b "CPU 1GHz, L3 100MHz, DDR 200MHz, GPU 307MHz" (defaultClocks {memClock = MEM_200MHz})
io $ putStrLn " GPU 192MHz"
b "CPU 1GHz, L3 200MHz, DDR 400 MHz, GPU 192MHz" (defaultClocks {gpuClock = GPU_192MHz})
io $ putStrLn " CPU 800MHz, L3 100MHz, DDR 200 MHz, GPU 192MHz"
b "CPU 800MHz, L3 100MHz, DDR 200 MHz, GPU 192MHz" (defaultClocks {cpuClock = CPU_800MHz, memClock = MEM_200MHz, gpuClock = GPU_192MHz})
#else
-- | Generate different benchmark for different clock values
forAllClocks :: (String -> Clocks -> Bench()) -> Bench ()
forAllClocks b = b "Standard clocks" defaultClocks
#endif
| ChristopheF/OpenCLTestFramework | Client/Perfs.hs | bsd-3-clause | 5,643 | 0 | 28 | 1,224 | 1,742 | 896 | 846 | 108 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Chess.Search.SearchResult
( SearchResult(..)
, (<@>)
, (<++>)
, first
, second
, eval
, moves
) where
import Control.Lens
import Control.Monad
import Data.Maybe
import qualified Chess.Move as M
-- | Represents the result of a Search
data SearchResult = SearchResult
{ _moves :: ! [ M.Move ]
, _eval :: ! Int
}
$(makeLenses ''SearchResult)
-- | modifies eval in a SearchResult, in a monadic computation
(<@>) :: (Monad m) => (Int -> Int) -> m (Maybe SearchResult) -> m (Maybe SearchResult)
f <@> m = liftM ((_Just . eval) %~ f) m
-- | Prepends a Move to a SearchResult
(<++>) :: Monad m => M.Move -> m (Maybe SearchResult) -> m (Maybe SearchResult)
x <++> m = liftM (_Just . moves %~ (x:)) m
-- | The first Move of a SearchResult
first :: SearchResult -> Maybe M.Move
first = listToMaybe . view moves
-- | The second Move of a SearchResult
second :: SearchResult -> Maybe M.Move
second sr = case sr^.moves of
_:m:_ -> Just m
_ -> Nothing
| phaul/chess | Chess/Search/SearchResult.hs | bsd-3-clause | 1,147 | 4 | 10 | 348 | 340 | 188 | 152 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-missing-import-lists #-}
{-# OPTIONS_GHC -fno-warn-implicit-prelude #-}
module Paths_HaskellEngine (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
#if defined(VERSION_base)
#if MIN_VERSION_base(4,0,0)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#else
catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a
#endif
#else
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#endif
catchIO = Exception.catch
version :: Version
version = Version [0,1,0,0] []
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/Users/user/Desktop/HaskellEngine/.cabal-sandbox/bin"
libdir = "/Users/user/Desktop/HaskellEngine/.cabal-sandbox/lib/x86_64-osx-ghc-8.0.1/HaskellEngine-0.1.0.0"
datadir = "/Users/user/Desktop/HaskellEngine/.cabal-sandbox/share/x86_64-osx-ghc-8.0.1/HaskellEngine-0.1.0.0"
libexecdir = "/Users/user/Desktop/HaskellEngine/.cabal-sandbox/libexec"
sysconfdir = "/Users/user/Desktop/HaskellEngine/.cabal-sandbox/etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "HaskellEngine_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "HaskellEngine_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "HaskellEngine_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "HaskellEngine_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "HaskellEngine_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| MyForteIsTimeTravel/HaskellEngine | dist/build/autogen/Paths_HaskellEngine.hs | bsd-3-clause | 1,816 | 0 | 10 | 223 | 371 | 215 | 156 | 31 | 1 |
myNot True = False
myNot False = True
sumList (x:xs) = x + sumList xs
sumList [] = 0
| NeonGraal/rwh-stack | ch03/add.hs | bsd-3-clause | 90 | 3 | 6 | 24 | 59 | 24 | 35 | 4 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module KMC.Util.Bits ( DoubleBits(combine, split), packCombine, unpackSplit ) where
import Data.Bits (shift, (.|.), (.&.), complement, finiteBitSize, clearBit, Bits(bit), FiniteBits)
import Data.Word (Word8, Word16, Word32, Word64)
-- | Pack two 8-bit words in a 16-bit word, two 16-bit words in a 32-bit word,
-- etc. Split a 16-bit word into two 8-bit words, etc.
class (FiniteBits b, Enum b, FiniteBits (Twice b), Enum (Twice b)) => DoubleBits b where
type Twice b :: *
combine :: (b, b) -> Twice b
combine (w1, w2) = (castWord w1 `shift` (finiteBitSize w1)) .|. (castWord w2)
-- The actual split implementation requires a zero element of the correct
-- type, so the type checker knows which instance to pick.
split' :: b -> Twice b -> (b, b)
split' z w = ( castWord $ (w .&. hi) `shift` (negate (finiteBitSize w `div` 2))
, castWord $ w .&. lo
)
where
hi = combine (complement z, z)
lo = combine (z, complement z)
split :: (Twice b) -> (b, b)
-- The implementation is just split' but with a type-annotated zero element
-- given to make the type checker happy. It complains about Twice being
-- non-injective, so we help it with type annotations in the instances.
zeroBits :: (Bits a) => a
zeroBits = clearBit (bit 0) 0
instance DoubleBits Word8 where
type Twice Word8 = Word16
split = split' (zeroBits :: Word8)
instance DoubleBits Word16 where
type Twice Word16 = Word32
split = split' (zeroBits :: Word16)
instance DoubleBits Word32 where
type Twice Word32 = Word64
split = split' (zeroBits :: Word32)
packCombine :: (DoubleBits b) => b -> [b] -> [Twice b]
packCombine _ [] = []
packCombine end (w1:w2:ws) = combine (w1, w2) : packCombine end ws
packCombine end [w1] = [combine (w1, end)]
unpackSplit :: (DoubleBits b) => [Twice b] -> [b]
unpackSplit = concatMap ((\(x,y) -> [x,y]) . split)
castWord :: (Enum a, Enum b) => a -> b
castWord = toEnum . fromEnum
| diku-kmc/repg | src/KMC/Util/Bits.hs | mit | 2,101 | 0 | 13 | 507 | 671 | 382 | 289 | 37 | 1 |
module Main where
import Web.GitHub.CLI.Options
import Web.GitHub.CLI.Actions
import Options.Applicative
import Network.Octohat.Types (OrganizationName(..), TeamName(..))
import qualified Data.Text as T (pack)
accessBotCLI :: TeamOptions -> IO ()
accessBotCLI (TeamOptions (ListTeams nameOfOrg)) =
findTeamsInOrganization (OrganizationName $ T.pack nameOfOrg)
accessBotCLI (TeamOptions (ListMembers nameOfOrg nameOfTeam)) =
findMembersInTeam (OrganizationName $ T.pack nameOfOrg) (TeamName $ T.pack nameOfTeam)
accessBotCLI (TeamOptions (AddToTeam nameOfOrg nameOfTeam nameOfUser)) =
addUserToTeamInOrganization nameOfUser
(OrganizationName $ T.pack nameOfOrg)
(TeamName $ T.pack nameOfTeam)
accessBotCLI (TeamOptions (DeleteFromTeam nameOfOrg nameOfTeam nameOfUser)) =
deleteUserFromTeamInOrganization nameOfUser
(OrganizationName $ T.pack nameOfOrg)
(TeamName $ T.pack nameOfTeam)
main :: IO ()
main = execParser argumentsParser >>= accessBotCLI
argumentsParser :: ParserInfo TeamOptions
argumentsParser = info (helper <*> teamOptions)
(fullDesc
<> progDesc "GitHub client to manage teams. Please specify your token as GITHUB_TOKEN"
<> header "Some options"
)
| stackbuilders/octohat | src-demo/Web/GitHub/CLI/Main.hs | mit | 1,385 | 0 | 9 | 346 | 332 | 175 | 157 | 26 | 1 |
import Universum
import Test.Hspec (hspec)
import Spec (spec)
main :: IO ()
main =
hspec spec
| input-output-hk/pos-haskell-prototype | util/test/test.hs | mit | 131 | 0 | 7 | 53 | 45 | 23 | 22 | 6 | 1 |
{-# LANGUAGE CPP #-}
{-|
-}
module Hledger.UI.UIOptions
where
import Data.Default (def)
import Data.List (intercalate)
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import Lens.Micro (set)
import System.Environment (getArgs)
import Hledger.Cli hiding (packageversion, progname, prognameandversion)
import Hledger.UI.Theme (themes, themeNames)
-- cf Hledger.Cli.Version
packageversion :: PackageVersion
packageversion =
#ifdef VERSION
VERSION
#else
""
#endif
progname :: ProgramName
progname = "hledger-ui"
prognameandversion :: VersionString
prognameandversion = versionString progname packageversion
uiflags = [
-- flagNone ["debug-ui"] (setboolopt "rules-file") "run with no terminal output, showing console"
flagNone ["watch","w"] (setboolopt "watch") "watch for data and date changes and reload automatically"
,flagReq ["theme"] (\s opts -> Right $ setopt "theme" s opts) "THEME" ("use this custom display theme ("++intercalate ", " themeNames++")")
,flagReq ["register"] (\s opts -> Right $ setopt "register" s opts) "ACCTREGEX" "start in the (first) matched account's register"
,flagNone ["change"] (setboolopt "change")
"show period balances (changes) at startup instead of historical balances"
-- ,flagNone ["cumulative"] (setboolopt "cumulative")
-- "show balance change accumulated across periods (in multicolumn reports)"
-- ,flagNone ["historical","H"] (setboolopt "historical")
-- "show historical ending balance in each period (includes postings before report start date)\n "
]
++ flattreeflags False
-- ,flagNone ["present"] (setboolopt "present") "exclude transactions dated later than today (default)"
-- ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "with --flat, omit this many leading account name components"
-- ,flagReq ["format"] (\s opts -> Right $ setopt "format" s opts) "FORMATSTR" "use this custom line format"
-- ,flagNone ["no-elide"] (setboolopt "no-elide") "don't compress empty parent accounts on one line"
--uimode :: Mode RawOpts
uimode = (mode "hledger-ui" (setopt "command" "ui" def)
"browse accounts, postings and entries in a full-window curses interface"
(argsFlag "[PATTERNS]") []){
modeGroupFlags = Group {
groupUnnamed = uiflags
,groupHidden = hiddenflags
++ [flagNone ["future"] (setboolopt "forecast") "compatibility alias, use --forecast instead"]
,groupNamed = [(generalflagsgroup1)]
}
,modeHelpSuffix=[
-- "Reads your ~/.hledger.journal file, or another specified by $LEDGER_FILE or -f, and starts the full-window curses ui."
]
}
-- hledger-ui options, used in hledger-ui and above
data UIOpts = UIOpts
{ uoWatch :: Bool
, uoTheme :: Maybe String
, uoRegister :: Maybe String
, uoCliOpts :: CliOpts
} deriving (Show)
defuiopts = UIOpts
{ uoWatch = False
, uoTheme = Nothing
, uoRegister = Nothing
, uoCliOpts = defcliopts
}
-- | Process a RawOpts into a UIOpts.
-- This will return a usage error if provided an invalid theme.
rawOptsToUIOpts :: RawOpts -> IO UIOpts
rawOptsToUIOpts rawopts = do
cliopts <- set balanceaccum accum <$> rawOptsToCliOpts rawopts
return defuiopts {
uoWatch = boolopt "watch" rawopts
,uoTheme = checkTheme <$> maybestringopt "theme" rawopts
,uoRegister = maybestringopt "register" rawopts
,uoCliOpts = cliopts
}
where
-- show historical balance by default (unlike hledger)
accum = fromMaybe Historical $ balanceAccumulationOverride rawopts
checkTheme t = if t `M.member` themes then t else usageError $ "invalid theme name: " ++ t
-- XXX some refactoring seems due
getHledgerUIOpts :: IO UIOpts
--getHledgerUIOpts = processArgs uimode >>= return >>= rawOptsToUIOpts
getHledgerUIOpts = do
args <- getArgs >>= expandArgsAt
let args' = replaceNumericFlags args
let cmdargopts = either usageError id $ process uimode args'
rawOptsToUIOpts cmdargopts
instance HasCliOpts UIOpts where
cliOpts f uiopts = (\x -> uiopts{uoCliOpts=x}) <$> f (uoCliOpts uiopts)
instance HasInputOpts UIOpts where
inputOpts = cliOpts.inputOpts
instance HasBalancingOpts UIOpts where
balancingOpts = cliOpts.balancingOpts
instance HasReportSpec UIOpts where
reportSpec = cliOpts.reportSpec
instance HasReportOptsNoUpdate UIOpts where
reportOptsNoUpdate = cliOpts.reportOptsNoUpdate
instance HasReportOpts UIOpts where
reportOpts = cliOpts.reportOpts
| adept/hledger | hledger-ui/Hledger/UI/UIOptions.hs | gpl-3.0 | 4,721 | 0 | 13 | 1,057 | 800 | 448 | 352 | 72 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Stack.Options
(BuildCommand(..)
,GlobalOptsContext(..)
,benchOptsParser
,buildOptsParser
,cleanOptsParser
,configCmdSetParser
,configOptsParser
,dockerOptsParser
,dockerCleanupOptsParser
,dotOptsParser
,execOptsParser
,evalOptsParser
,globalOptsParser
,initOptsParser
,newOptsParser
,nixOptsParser
,logLevelOptsParser
,ghciOptsParser
,solverOptsParser
,testOptsParser
,hpcReportOptsParser
,pvpBoundsOption
,globalOptsFromMonoid
,splitObjsWarning
) where
import Control.Monad.Logger (LogLevel (..))
import Data.Char (isSpace, toLower, toUpper)
import Data.List (intercalate)
import Data.List.Split (splitOn)
import qualified Data.Map as Map
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Monoid.Extra
import qualified Data.Set as Set
import qualified Data.Text as T
import Data.Text.Read (decimal)
import Distribution.Version (anyVersion)
import Options.Applicative
import Options.Applicative.Args
import Options.Applicative.Builder.Extra
import Options.Applicative.Types (fromM, oneM, readerAsk)
import Path
import Stack.Build (splitObjsWarning)
import Stack.Clean (CleanOpts (..))
import Stack.Config (packagesParser)
import Stack.ConfigCmd
import Stack.Constants
import Stack.Coverage (HpcReportOpts (..))
import Stack.Docker
import qualified Stack.Docker as Docker
import Stack.Dot
import Stack.Ghci (GhciOpts (..))
import Stack.Init
import Stack.New
import Stack.Nix
import Stack.Types
import Stack.Types.TemplateName
-- | Allows adjust global options depending on their context
-- Note: This was being used to remove ambibuity between the local and global
-- implementation of stack init --resolver option. Now that stack init has no
-- local --resolver this is not being used anymore but the code is kept for any
-- similar future use cases.
data GlobalOptsContext
= OuterGlobalOpts -- ^ Global options before subcommand name
| OtherCmdGlobalOpts -- ^ Global options following any other subcommand
| BuildCmdGlobalOpts
deriving (Show, Eq)
-- | Parser for bench arguments.
-- FIXME hiding options
benchOptsParser :: Bool -> Parser BenchmarkOptsMonoid
benchOptsParser hide0 = BenchmarkOptsMonoid
<$> optionalFirst (strOption (long "benchmark-arguments" <>
metavar "BENCH_ARGS" <>
help ("Forward BENCH_ARGS to the benchmark suite. " <>
"Supports templates from `cabal bench`") <>
hide))
<*> optionalFirst (switch (long "no-run-benchmarks" <>
help "Disable running of benchmarks. (Benchmarks will still be built.)" <>
hide))
where hide = hideMods hide0
-- | Parser for CLI-only build arguments
buildOptsParser :: BuildCommand
-> Parser BuildOptsCLI
buildOptsParser cmd =
BuildOptsCLI <$>
many
(textArgument
(metavar "TARGET" <>
help "If none specified, use all packages")) <*>
switch
(long "dry-run" <>
help "Don't build anything, just prepare to") <*>
((\x y z ->
concat [x, y, z]) <$>
flag
[]
["-Wall", "-Werror"]
(long "pedantic" <>
help "Turn on -Wall and -Werror") <*>
flag
[]
["-O0"]
(long "fast" <>
help "Turn off optimizations (-O0)") <*>
many
(textOption
(long "ghc-options" <>
metavar "OPTION" <>
help "Additional options passed to GHC"))) <*>
(Map.unionsWith Map.union <$>
many
(option
readFlag
(long "flag" <>
metavar "PACKAGE:[-]FLAG" <>
help
("Override flags set in stack.yaml " <>
"(applies to local packages and extra-deps)")))) <*>
(flag'
BSOnlyDependencies
(long "dependencies-only" <>
help "A synonym for --only-dependencies") <|>
flag'
BSOnlySnapshot
(long "only-snapshot" <>
help
"Only build packages for the snapshot database, not the local database") <|>
flag'
BSOnlyDependencies
(long "only-dependencies" <>
help
"Only build packages that are dependencies of targets on the command line") <|>
pure BSAll) <*>
(flag'
FileWatch
(long "file-watch" <>
help
"Watch for changes in local files and automatically rebuild. Ignores files in VCS boring/ignore file") <|>
flag'
FileWatchPoll
(long "file-watch-poll" <>
help
"Like --file-watch, but polling the filesystem instead of using events") <|>
pure NoFileWatch) <*>
many (cmdOption
(long "exec" <>
metavar "CMD [ARGS]" <>
help "Command and arguments to run after a successful build")) <*>
switch
(long "only-configure" <>
help
"Only perform the configure step, not any builds. Intended for tool usage, may break when used on multiple packages at once!") <*>
pure cmd
-- | Parser for package:[-]flag
readFlag :: ReadM (Map (Maybe PackageName) (Map FlagName Bool))
readFlag = do
s <- readerAsk
case break (== ':') s of
(pn, ':':mflag) -> do
pn' <-
case parsePackageNameFromString pn of
Nothing
| pn == "*" -> return Nothing
| otherwise -> readerError $ "Invalid package name: " ++ pn
Just x -> return $ Just x
let (b, flagS) =
case mflag of
'-':x -> (False, x)
_ -> (True, mflag)
flagN <-
case parseFlagNameFromString flagS of
Nothing -> readerError $ "Invalid flag name: " ++ flagS
Just x -> return x
return $ Map.singleton pn' $ Map.singleton flagN b
_ -> readerError "Must have a colon"
-- | Command-line parser for the clean command.
cleanOptsParser :: Parser CleanOpts
cleanOptsParser = CleanShallow <$> packages <|> doFullClean
where
packages =
many
(packageNameArgument
(metavar "PACKAGE" <>
help "If none specified, clean all local packages"))
doFullClean =
flag'
CleanFull
(long "full" <>
help "Delete all work directories (.stack-work by default) in the project")
-- | Command-line arguments parser for configuration.
configOptsParser :: GlobalOptsContext -> Parser ConfigMonoid
configOptsParser hide0 =
(\stackRoot workDir buildOpts dockerOpts nixOpts systemGHC installGHC arch os ghcVariant jobs includes libs skipGHCCheck skipMsys localBin modifyCodePage allowDifferentUser -> mempty
{ configMonoidStackRoot = stackRoot
, configMonoidWorkDir = workDir
, configMonoidBuildOpts = buildOpts
, configMonoidDockerOpts = dockerOpts
, configMonoidNixOpts = nixOpts
, configMonoidSystemGHC = systemGHC
, configMonoidInstallGHC = installGHC
, configMonoidSkipGHCCheck = skipGHCCheck
, configMonoidArch = arch
, configMonoidOS = os
, configMonoidGHCVariant = ghcVariant
, configMonoidJobs = jobs
, configMonoidExtraIncludeDirs = includes
, configMonoidExtraLibDirs = libs
, configMonoidSkipMsys = skipMsys
, configMonoidLocalBinPath = localBin
, configMonoidModifyCodePage = modifyCodePage
, configMonoidAllowDifferentUser = allowDifferentUser
})
<$> optionalFirst (option readAbsDir
( long stackRootOptionName
<> metavar (map toUpper stackRootOptionName)
<> help ("Absolute path to the global stack root directory " ++
"(Overrides any STACK_ROOT environment variable)")
<> hide
))
<*> optionalFirst (strOption
( long "work-dir"
<> metavar "WORK-DIR"
<> help "Override work directory (default: .stack-work)"
<> hide
))
<*> buildOptsMonoidParser (hide0 /= BuildCmdGlobalOpts)
<*> dockerOptsParser True
<*> nixOptsParser True
<*> firstBoolFlags
"system-ghc"
"using the system installed GHC (on the PATH) if available and a matching version"
hide
<*> firstBoolFlags
"install-ghc"
"downloading and installing GHC if necessary (can be done manually with stack setup)"
hide
<*> optionalFirst (strOption
( long "arch"
<> metavar "ARCH"
<> help "System architecture, e.g. i386, x86_64"
<> hide
))
<*> optionalFirst (strOption
( long "os"
<> metavar "OS"
<> help "Operating system, e.g. linux, windows"
<> hide
))
<*> optionalFirst (ghcVariantParser (hide0 /= OuterGlobalOpts))
<*> optionalFirst (option auto
( long "jobs"
<> short 'j'
<> metavar "JOBS"
<> help "Number of concurrent jobs to run"
<> hide
))
<*> fmap Set.fromList (many (textOption
( long "extra-include-dirs"
<> metavar "DIR"
<> help "Extra directories to check for C header files"
<> hide
)))
<*> fmap Set.fromList (many (textOption
( long "extra-lib-dirs"
<> metavar "DIR"
<> help "Extra directories to check for libraries"
<> hide
)))
<*> firstBoolFlags
"skip-ghc-check"
"skipping the GHC version and architecture check"
hide
<*> firstBoolFlags
"skip-msys"
"skipping the local MSYS installation (Windows only)"
hide
<*> optionalFirst (strOption
( long "local-bin-path"
<> metavar "DIR"
<> help "Install binaries to DIR"
<> hide
))
<*> firstBoolFlags
"modify-code-page"
"setting the codepage to support UTF-8 (Windows only)"
hide
<*> firstBoolFlags
"allow-different-user"
("permission for users other than the owner of the stack root " ++
"directory to use a stack installation (POSIX only)")
hide
where hide = hideMods (hide0 /= OuterGlobalOpts)
readAbsDir :: ReadM (Path Abs Dir)
readAbsDir = do
s <- readerAsk
case parseAbsDir s of
Just p -> return p
Nothing ->
readerError
("Failed to parse absolute path to directory: '" ++ s ++ "'")
buildOptsMonoidParser :: Bool -> Parser BuildOptsMonoid
buildOptsMonoidParser hide0 =
transform <$> trace <*> profile <*> options
where
hide =
hideMods hide0
transform tracing profiling =
enable
where
enable opts
| tracing || profiling =
opts
{ buildMonoidLibProfile = First (Just True)
, buildMonoidExeProfile = First (Just True)
, buildMonoidBenchmarkOpts = bopts
{ beoMonoidAdditionalArgs = First (getFirst (beoMonoidAdditionalArgs bopts) <>
Just (" " <> unwords additionalArgs))
}
, buildMonoidTestOpts = topts
{ toMonoidAdditionalArgs = (toMonoidAdditionalArgs topts) <>
additionalArgs
}
}
| otherwise =
opts
where
bopts =
buildMonoidBenchmarkOpts opts
topts =
buildMonoidTestOpts opts
additionalArgs =
"+RTS" : catMaybes [trac, prof, Just "-RTS"]
trac =
if tracing
then Just "-xc"
else Nothing
prof =
if profiling
then Just "-p"
else Nothing
profile =
flag
False
True
(long "profile" <>
help
"Enable profiling in libraries, executables, etc. \
\for all expressions and generate a profiling report\
\ in exec or benchmarks" <>
hide)
trace =
flag
False
True
(long "trace" <>
help
"Enable profiling in libraries, executables, etc. \
\for all expressions and generate a backtrace on \
\exception" <>
hide)
options =
BuildOptsMonoid <$> libProfiling <*> exeProfiling <*> haddock <*> openHaddocks <*>
haddockDeps <*> copyBins <*> preFetch <*> keepGoing <*> forceDirty <*>
tests <*> testOptsParser hide0 <*> benches <*> benchOptsParser hide0 <*> reconfigure <*>
cabalVerbose <*> splitObjs
libProfiling =
firstBoolFlags
"library-profiling"
"library profiling for TARGETs and all its dependencies"
hide
exeProfiling =
firstBoolFlags
"executable-profiling"
"executable profiling for TARGETs and all its dependencies"
hide
haddock =
firstBoolFlags
"haddock"
"generating Haddocks the package(s) in this directory/configuration"
hide
openHaddocks =
firstBoolFlags
"open"
"opening the local Haddock documentation in the browser"
hide
haddockDeps =
firstBoolFlags "haddock-deps" "building Haddocks for dependencies" hide
copyBins =
firstBoolFlags
"copy-bins"
"copying binaries to the local-bin-path (see 'stack path')"
hide
keepGoing =
firstBoolFlags
"keep-going"
"continue running after a step fails (default: false for build, true for test/bench)"
hide
preFetch =
firstBoolFlags
"prefetch"
"Fetch packages necessary for the build immediately, useful with --dry-run"
hide
forceDirty =
firstBoolFlags
"force-dirty"
"Force treating all local packages as having dirty files (useful for cases where stack can't detect a file change"
hide
tests =
firstBoolFlags
"test"
"testing the package(s) in this directory/configuration"
hide
benches =
firstBoolFlags
"bench"
"benchmarking the package(s) in this directory/configuration"
hide
reconfigure =
firstBoolFlags
"reconfigure"
"Perform the configure step even if unnecessary. Useful in some corner cases with custom Setup.hs files"
hide
cabalVerbose =
firstBoolFlags
"cabal-verbose"
"Ask Cabal to be verbose in its output"
hide
splitObjs =
firstBoolFlags
"split-objs"
("Enable split-objs, to reduce output size (at the cost of build time). " ++ splitObjsWarning)
hide
nixOptsParser :: Bool -> Parser NixOptsMonoid
nixOptsParser hide0 = overrideActivation <$>
(NixOptsMonoid
<$> pure (Any False)
<*> firstBoolFlags nixCmdName
"use of a Nix-shell"
hide
<*> firstBoolFlags "nix-pure"
"use of a pure Nix-shell"
hide
<*> optionalFirst
(textArgsOption
(long "nix-packages" <>
metavar "NAMES" <>
help "List of packages that should be available in the nix-shell (space separated)" <>
hide))
<*> optionalFirst
(option
str
(long "nix-shell-file" <>
metavar "FILEPATH" <>
help "Nix file to be used to launch a nix-shell (for regular Nix users)" <>
hide))
<*> optionalFirst
(textArgsOption
(long "nix-shell-options" <>
metavar "OPTIONS" <>
help "Additional options passed to nix-shell" <>
hide))
<*> optionalFirst
(textArgsOption
(long "nix-path" <>
metavar "PATH_OPTIONS" <>
help "Additional options to override NIX_PATH parts (notably 'nixpkgs')" <>
hide))
)
where
hide = hideMods hide0
overrideActivation m =
if m /= mempty then m { nixMonoidEnable = (First . Just . fromFirst True) (nixMonoidEnable m) }
else m
textArgsOption = fmap (map T.pack) . argsOption
-- | Options parser configuration for Docker.
dockerOptsParser :: Bool -> Parser DockerOptsMonoid
dockerOptsParser hide0 =
DockerOptsMonoid
<$> pure (Any False)
<*> firstBoolFlags dockerCmdName
"using a Docker container"
hide
<*> fmap First
((Just . DockerMonoidRepo) <$> option str (long (dockerOptName dockerRepoArgName) <>
hide <>
metavar "NAME" <>
help "Docker repository name") <|>
(Just . DockerMonoidImage) <$> option str (long (dockerOptName dockerImageArgName) <>
hide <>
metavar "IMAGE" <>
help "Exact Docker image ID (overrides docker-repo)") <|>
pure Nothing)
<*> firstBoolFlags (dockerOptName dockerRegistryLoginArgName)
"registry requires login"
hide
<*> firstStrOption (long (dockerOptName dockerRegistryUsernameArgName) <>
hide <>
metavar "USERNAME" <>
help "Docker registry username")
<*> firstStrOption (long (dockerOptName dockerRegistryPasswordArgName) <>
hide <>
metavar "PASSWORD" <>
help "Docker registry password")
<*> firstBoolFlags (dockerOptName dockerAutoPullArgName)
"automatic pulling latest version of image"
hide
<*> firstBoolFlags (dockerOptName dockerDetachArgName)
"running a detached Docker container"
hide
<*> firstBoolFlags (dockerOptName dockerPersistArgName)
"not deleting container after it exits"
hide
<*> firstStrOption (long (dockerOptName dockerContainerNameArgName) <>
hide <>
metavar "NAME" <>
help "Docker container name")
<*> argsOption (long (dockerOptName dockerRunArgsArgName) <>
hide <>
value [] <>
metavar "'ARG1 [ARG2 ...]'" <>
help "Additional options to pass to 'docker run'")
<*> many (option auto (long (dockerOptName dockerMountArgName) <>
hide <>
metavar "(PATH | HOST-PATH:CONTAINER-PATH)" <>
help ("Mount volumes from host in container " ++
"(may specify multiple times)")))
<*> many (option str (long (dockerOptName dockerEnvArgName) <>
hide <>
metavar "NAME=VALUE" <>
help ("Set environment variable in container " ++
"(may specify multiple times)")))
<*> firstStrOption (long (dockerOptName dockerDatabasePathArgName) <>
hide <>
metavar "PATH" <>
help "Location of image usage tracking database")
<*> firstStrOption
(long(dockerOptName dockerStackExeArgName) <>
hide <>
metavar (intercalate "|"
[ dockerStackExeDownloadVal
, dockerStackExeHostVal
, dockerStackExeImageVal
, "PATH" ]) <>
help (concat [ "Location of "
, stackProgName
, " executable used in container" ]))
<*> firstBoolFlags (dockerOptName dockerSetUserArgName)
"setting user in container to match host"
hide
<*> pure (IntersectingVersionRange anyVersion)
where
dockerOptName optName = dockerCmdName ++ "-" ++ T.unpack optName
firstStrOption = optionalFirst . option str
hide = hideMods hide0
-- | Parser for docker cleanup arguments.
dockerCleanupOptsParser :: Parser Docker.CleanupOpts
dockerCleanupOptsParser =
Docker.CleanupOpts <$>
(flag' Docker.CleanupInteractive
(short 'i' <>
long "interactive" <>
help "Show cleanup plan in editor and allow changes (default)") <|>
flag' Docker.CleanupImmediate
(short 'y' <>
long "immediate" <>
help "Immediately execute cleanup plan") <|>
flag' Docker.CleanupDryRun
(short 'n' <>
long "dry-run" <>
help "Display cleanup plan but do not execute") <|>
pure Docker.CleanupInteractive) <*>
opt (Just 14) "known-images" "LAST-USED" <*>
opt Nothing "unknown-images" "CREATED" <*>
opt (Just 0) "dangling-images" "CREATED" <*>
opt Nothing "stopped-containers" "CREATED" <*>
opt Nothing "running-containers" "CREATED"
where opt def' name mv =
fmap Just
(option auto
(long name <>
metavar (mv ++ "-DAYS-AGO") <>
help ("Remove " ++
toDescr name ++
" " ++
map toLower (toDescr mv) ++
" N days ago" ++
case def' of
Just n -> " (default " ++ show n ++ ")"
Nothing -> ""))) <|>
flag' Nothing
(long ("no-" ++ name) <>
help ("Do not remove " ++
toDescr name ++
case def' of
Just _ -> ""
Nothing -> " (default)")) <|>
pure def'
toDescr = map (\c -> if c == '-' then ' ' else c)
-- | Parser for arguments to `stack dot`
dotOptsParser :: Parser DotOpts
dotOptsParser = DotOpts
<$> includeExternal
<*> includeBase
<*> depthLimit
<*> fmap (maybe Set.empty Set.fromList . fmap splitNames) prunedPkgs
where includeExternal = boolFlags False
"external"
"inclusion of external dependencies"
idm
includeBase = boolFlags True
"include-base"
"inclusion of dependencies on base"
idm
depthLimit =
optional (option auto
(long "depth" <>
metavar "DEPTH" <>
help ("Limit the depth of dependency resolution " <>
"(Default: No limit)")))
prunedPkgs = optional (strOption
(long "prune" <>
metavar "PACKAGES" <>
help ("Prune each package name " <>
"from the comma separated list " <>
"of package names PACKAGES")))
splitNames :: String -> [String]
splitNames = map (takeWhile (not . isSpace) . dropWhile isSpace) . splitOn ","
ghciOptsParser :: Parser GhciOpts
ghciOptsParser = GhciOpts
<$> switch (long "no-build" <> help "Don't build before launching GHCi")
<*> fmap concat (many (argsOption (long "ghci-options" <>
metavar "OPTION" <>
help "Additional options passed to GHCi")))
<*> optional
(strOption (long "with-ghc" <>
metavar "GHC" <>
help "Use this GHC to run GHCi"))
<*> (not <$> boolFlags True "load" "load modules on start-up" idm)
<*> packagesParser
<*> optional
(textOption
(long "main-is" <>
metavar "TARGET" <>
help "Specify which target should contain the main \
\module to load, such as for an executable for \
\test suite or benchmark."))
<*> switch (long "load-local-deps" <> help "Load all local dependencies of your targets")
<*> switch (long "skip-intermediate-deps" <> help "Skip loading intermediate target dependencies")
<*> boolFlags True "package-hiding" "package hiding" idm
<*> buildOptsParser Build
-- | Parser for exec command
execOptsParser :: Maybe SpecialExecCmd -> Parser ExecOpts
execOptsParser mcmd =
ExecOpts
<$> maybe eoCmdParser pure mcmd
<*> eoArgsParser
<*> execOptsExtraParser
where
eoCmdParser = ExecCmd <$> strArgument (metavar "CMD")
eoArgsParser = many (strArgument (metavar "-- ARGS (e.g. stack ghc -- X.hs -o x)"))
evalOptsParser :: String -- ^ metavar
-> Parser EvalOpts
evalOptsParser meta =
EvalOpts
<$> eoArgsParser
<*> execOptsExtraParser
where
eoArgsParser :: Parser String
eoArgsParser = strArgument (metavar meta)
-- | Parser for extra options to exec command
execOptsExtraParser :: Parser ExecOptsExtra
execOptsExtraParser = eoPlainParser <|>
ExecOptsEmbellished
<$> eoEnvSettingsParser
<*> eoPackagesParser
where
eoEnvSettingsParser :: Parser EnvSettings
eoEnvSettingsParser = EnvSettings
<$> pure True
<*> boolFlags True
"ghc-package-path"
"setting the GHC_PACKAGE_PATH variable for the subprocess"
idm
<*> boolFlags True
"stack-exe"
"setting the STACK_EXE environment variable to the path for the stack executable"
idm
<*> pure False
eoPackagesParser :: Parser [String]
eoPackagesParser = many (strOption (long "package" <> help "Additional packages that must be installed"))
eoPlainParser :: Parser ExecOptsExtra
eoPlainParser = flag' ExecOptsPlain
(long "plain" <>
help "Use an unmodified environment (only useful with Docker)")
-- | Parser for global command-line options.
globalOptsParser :: GlobalOptsContext -> Maybe LogLevel -> Parser GlobalOptsMonoid
globalOptsParser kind defLogLevel =
GlobalOptsMonoid <$>
optionalFirst (strOption (long Docker.reExecArgName <> hidden <> internal)) <*>
optionalFirst (option auto (long dockerEntrypointArgName <> hidden <> internal)) <*>
(First <$> logLevelOptsParser hide0 defLogLevel) <*>
configOptsParser kind <*>
optionalFirst (abstractResolverOptsParser hide0) <*>
optionalFirst (compilerOptsParser hide0) <*>
firstBoolFlags
"terminal"
"overriding terminal detection in the case of running in a false terminal"
hide <*>
optionalFirst
(strOption
(long "stack-yaml" <>
metavar "STACK-YAML" <>
help ("Override project stack.yaml file " <>
"(overrides any STACK_YAML environment variable)") <>
hide))
where
hide = hideMods hide0
hide0 = kind /= OuterGlobalOpts
-- | Create GlobalOpts from GlobalOptsMonoid.
globalOptsFromMonoid :: Bool -> GlobalOptsMonoid -> GlobalOpts
globalOptsFromMonoid defaultTerminal GlobalOptsMonoid{..} = GlobalOpts
{ globalReExecVersion = getFirst globalMonoidReExecVersion
, globalDockerEntrypoint = getFirst globalMonoidDockerEntrypoint
, globalLogLevel = fromFirst defaultLogLevel globalMonoidLogLevel
, globalConfigMonoid = globalMonoidConfigMonoid
, globalResolver = getFirst globalMonoidResolver
, globalCompiler = getFirst globalMonoidCompiler
, globalTerminal = fromFirst defaultTerminal globalMonoidTerminal
, globalStackYaml = getFirst globalMonoidStackYaml }
initOptsParser :: Parser InitOpts
initOptsParser =
InitOpts <$> searchDirs
<*> solver <*> omitPackages
<*> overwrite <*> fmap not ignoreSubDirs
where
searchDirs =
many (textArgument
(metavar "DIRS" <>
help "Directories to include, default is current directory."))
ignoreSubDirs = switch (long "ignore-subdirs" <>
help "Do not search for .cabal files in sub directories")
overwrite = switch (long "force" <>
help "Force overwriting an existing stack.yaml")
omitPackages = switch (long "omit-packages" <>
help "Exclude conflicting or incompatible user packages")
solver = switch (long "solver" <>
help "Use a dependency solver to determine extra dependencies")
-- | Parser for a logging level.
logLevelOptsParser :: Bool -> Maybe LogLevel -> Parser (Maybe LogLevel)
logLevelOptsParser hide defLogLevel =
fmap (Just . parse)
(strOption (long "verbosity" <>
metavar "VERBOSITY" <>
help "Verbosity: silent, error, warn, info, debug" <>
hideMods hide)) <|>
flag' (Just verboseLevel)
(short 'v' <> long "verbose" <>
help ("Enable verbose mode: verbosity level \"" <> showLevel verboseLevel <> "\"") <>
hideMods hide) <|>
flag' (Just silentLevel)
(long "silent" <>
help ("Enable silent mode: verbosity level \"" <> showLevel silentLevel <> "\"") <>
hideMods hide) <|>
pure defLogLevel
where verboseLevel = LevelDebug
silentLevel = LevelOther "silent"
showLevel l =
case l of
LevelDebug -> "debug"
LevelInfo -> "info"
LevelWarn -> "warn"
LevelError -> "error"
LevelOther x -> T.unpack x
parse s =
case s of
"debug" -> LevelDebug
"info" -> LevelInfo
"warn" -> LevelWarn
"error" -> LevelError
_ -> LevelOther (T.pack s)
-- | Parser for the resolver
abstractResolverOptsParser :: Bool -> Parser AbstractResolver
abstractResolverOptsParser hide =
option readAbstractResolver
(long "resolver" <>
metavar "RESOLVER" <>
help "Override resolver in project file" <>
hideMods hide)
readAbstractResolver :: ReadM AbstractResolver
readAbstractResolver = do
s <- readerAsk
case s of
"global" -> return ARGlobal
"nightly" -> return ARLatestNightly
"lts" -> return ARLatestLTS
'l':'t':'s':'-':x | Right (x', "") <- decimal $ T.pack x ->
return $ ARLatestLTSMajor x'
_ ->
case parseResolverText $ T.pack s of
Left e -> readerError $ show e
Right x -> return $ ARResolver x
compilerOptsParser :: Bool -> Parser CompilerVersion
compilerOptsParser hide =
option readCompilerVersion
(long "compiler" <>
metavar "COMPILER" <>
help "Use the specified compiler" <>
hideMods hide)
readCompilerVersion :: ReadM CompilerVersion
readCompilerVersion = do
s <- readerAsk
case parseCompilerVersion (T.pack s) of
Nothing -> readerError $ "Failed to parse compiler: " ++ s
Just x -> return x
-- | GHC variant parser
ghcVariantParser :: Bool -> Parser GHCVariant
ghcVariantParser hide =
option
readGHCVariant
(long "ghc-variant" <> metavar "VARIANT" <>
help
"Specialized GHC variant, e.g. integersimple (implies --no-system-ghc)" <>
hideMods hide
)
where
readGHCVariant = do
s <- readerAsk
case parseGHCVariant s of
Left e -> readerError (show e)
Right v -> return v
-- | Parser for @solverCmd@
solverOptsParser :: Parser Bool
solverOptsParser = boolFlags False
"update-config"
"Automatically update stack.yaml with the solver's recommendations"
idm
-- | Parser for test arguments.
-- FIXME hide args
testOptsParser :: Bool -> Parser TestOptsMonoid
testOptsParser hide0 =
TestOptsMonoid
<$> firstBoolFlags
"rerun-tests"
"running already successful tests"
hide
<*> fmap
(fromMaybe [])
(optional
(argsOption
(long "test-arguments" <>
metavar "TEST_ARGS" <>
help "Arguments passed in to the test suite program" <>
hide)))
<*> optionalFirst
(switch
(long "coverage" <>
help "Generate a code coverage report" <>
hide))
<*> optionalFirst
(switch
(long "no-run-tests" <>
help "Disable running of tests. (Tests will still be built.)" <>
hide))
where hide = hideMods hide0
-- | Parser for @stack new@.
newOptsParser :: Parser (NewOpts,InitOpts)
newOptsParser = (,) <$> newOpts <*> initOptsParser
where
newOpts =
NewOpts <$>
packageNameArgument
(metavar "PACKAGE_NAME" <> help "A valid package name.") <*>
switch
(long "bare" <>
help "Do not create a subdirectory for the project") <*>
optional (templateNameArgument
(metavar "TEMPLATE_NAME" <>
help "Name of a template or a local template in a file or a URL.\
\ For example: foo or foo.hsfiles or ~/foo or\
\ https://example.com/foo.hsfiles")) <*>
fmap
M.fromList
(many
(templateParamArgument
(short 'p' <> long "param" <> metavar "KEY:VALUE" <>
help
"Parameter for the template in the format key:value")))
-- | Parser for @stack hpc report@.
hpcReportOptsParser :: Parser HpcReportOpts
hpcReportOptsParser = HpcReportOpts
<$> many (textArgument $ metavar "TARGET_OR_TIX")
<*> switch (long "all" <> help "Use results from all packages and components")
<*> optional (strOption (long "destdir" <> help "Output directy for HTML report"))
pvpBoundsOption :: Parser PvpBounds
pvpBoundsOption =
option
readPvpBounds
(long "pvp-bounds" <> metavar "PVP-BOUNDS" <>
help
"How PVP version bounds should be added to .cabal file: none, lower, upper, both")
where
readPvpBounds = do
s <- readerAsk
case parsePvpBounds $ T.pack s of
Left e ->
readerError e
Right v ->
return v
configCmdSetParser :: Parser ConfigCmdSet
configCmdSetParser =
fromM
(do field <-
oneM
(strArgument
(metavar "FIELD VALUE"))
oneM (fieldToValParser field))
where
fieldToValParser :: String -> Parser ConfigCmdSet
fieldToValParser s =
case s of
"resolver" ->
ConfigCmdSetResolver <$>
argument
readAbstractResolver
idm
_ ->
error "parse stack config set field: only set resolver is implemented"
-- | If argument is True, hides the option from usage and help
hideMods :: Bool -> Mod f a
hideMods hide = if hide then internal <> hidden else idm
| phadej/stack | src/Stack/Options.hs | bsd-3-clause | 37,388 | 0 | 33 | 14,151 | 6,527 | 3,247 | 3,280 | 872 | 9 |
-- Par monad and thread representation; types
--
-- Visibility: HpH.Internal.{IVar,Sparkpool,Threadpool,Scheduler}
-- Author: Patrick Maier <P.Maier@hw.ac.uk>
-- Created: 28 Sep 2011
--
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE TemplateHaskell #-} -- req'd for mkClosure, etc
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
-----------------------------------------------------------------------------
module Control.Parallel.HdpH.Internal.Type.Par
( -- * Par monad, threads and sparks
ParM(..),
Thread(..),
CurrentLocation(..),
Task,SupervisedSpark(..),
SupervisedTaskState(..),Scheduling(..),
taskSupervised,declareStatic
) where
import Prelude
import Control.Parallel.HdpH.Internal.Location (NodeId)
import Control.Parallel.HdpH.Internal.Type.GRef (TaskRef)
import Data.Monoid (mconcat)
import Control.Parallel.HdpH.Closure
(Closure,ToClosure(..),StaticDecl,StaticToClosure,
declare,staticToClosure,here)
import Data.Binary (Binary,put,get)
declareStatic :: StaticDecl
declareStatic = mconcat
[declare (staticToClosure :: forall a . StaticToClosure (SupervisedSpark a))]
-----------------------------------------------------------------------------
-- Par monad, based on ideas from
-- [1] Claessen "A Poor Man's Concurrency Monad", JFP 9(3), 1999.
-- [2] Marlow et al. "A monad for deterministic parallelism". Haskell 2011.
-- 'ParM m' is a continuation monad, specialised to the return type 'Thread m';
-- 'm' abstracts a monad encapsulating the underlying state.
newtype ParM m a = Par { unPar :: (a -> Thread m) -> Thread m }
-- A thread is determined by its actions, as described in this data type.
-- In [2] this type is called 'Trace'.
newtype Thread m = Atom (m (Maybe (Thread m))) -- atomic action (in monad 'm')
-- result is next action, maybe
data SupervisedSpark m = SupervisedSpark
{
clo :: Closure (ParM m ())
, remoteRef :: TaskRef
, thisReplica :: Int
}
instance Binary (SupervisedSpark m) where
put (SupervisedSpark closure ref thisSeq) =
Data.Binary.put closure >>
Data.Binary.put ref >>
Data.Binary.put thisSeq
get = do
closure <- Data.Binary.get
ref <- Data.Binary.get
thisSeq <- Data.Binary.get
return $ SupervisedSpark closure ref thisSeq
type Task m = Either (Closure (SupervisedSpark m)) (Closure (ParM m ()))
taskSupervised :: Task m -> Bool
taskSupervised (Left _) = True
taskSupervised (Right _) = False
-- |Local representation of a spark for the supervisor
data SupervisedTaskState m = SupervisedTaskState
{
-- | The copy of the task that will need rescheduled,
-- in the case when it has not been evaluated.
task :: Closure (ParM m ())
-- | Used by the spark supervisor. Used to decide
-- whether to put the spark copy in the local
-- sparkpool or threadpool.
, scheduling :: Scheduling
-- | sequence number of most recent copy of the task.
, newestReplica :: Int
-- | book keeping for most recent task copy.
, location :: CurrentLocation
}
-- | Book keeping of a task. A task is either
-- known to be on a node, or in transition between
-- two nodes over the wire.
data CurrentLocation =
OnNode NodeId
| InTransition
{ movingFrom :: NodeId
, movingTo :: NodeId }
-- | The task was originally created as a spark
-- or as an eagerly scheduled thread
data Scheduling = Sparked | Pushed deriving (Eq)
instance ToClosure (SupervisedSpark m) where locToClosure = $(here)
| robstewart57/hdph-rs | src/Control/Parallel/HdpH/Internal/Type/Par.hs | bsd-3-clause | 3,793 | 0 | 12 | 829 | 632 | 384 | 248 | 59 | 1 |
{-# LANGUAGE TypeOperators, TypeSynonymInstances #-}
{-# LANGUAGE GADTs, KindSignatures #-}
{-# OPTIONS_GHC -Wall #-}
-- {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP
-- {-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP
----------------------------------------------------------------------
-- |
-- Module : Circat.LinearMap
-- Copyright : (c) 2014 Tabula, Inc.
--
-- Maintainer : conal@tabula.com
-- Stability : experimental
--
-- Linear maps as GADT
----------------------------------------------------------------------
module Circat.LinearMap where
-- TODO: explicit exports
import Circat.Misc ((:*))
import Data.AdditiveGroup (AdditiveGroup(..))
infixr 1 :-*
data (:-*) :: * -> * -> * where
Scale :: Num a => a -> (a :-* a)
(:&&&) :: (a :-* c) -> (a :-* d) -> (a :-* c :* d)
(:|||) :: AdditiveGroup c =>
(a :-* c) -> (b :-* c) -> (a :* b :-* c)
-- infixl 9 @$
-- Scale s @$ x = s * x
-- (f :&&& g) @$ a = (f @$ a, g @$ a)
-- (f :||| g) @$ (a,b) = f @$ a ^+^ f @$ b
-- mu = (@$) -- for prefix
mu :: (u :-* v) -> u -> v
mu (Scale s) x = s * x
mu (f :&&& g) a = (mu f a, mu g a)
mu (f :||| g) (a,b) = mu f a ^+^ mu g b
{- Note the homomorphisms:
> mu (f :&&& g) = mu f &&& mu g
> mu (f :||| g) = mu f ||| mu g
if the RHSs are interpreted in **Vect**.
To do: make a clear notational distinction between the representation and the model of linear maps.
-}
class HasZero z where zeroL :: a :-* z
instance (HasZero u, HasZero v) => HasZero (u :* v) where
zeroL = (zeroL,zeroL)
-- instance AdditiveGroup v => AdditiveGroup (u :-* v) where
-- zeroV =
-- infixr 9 @.
-- (@.) :: (b :-* c) -> (a :- b) -> (a :-* c)
-- Specification: mu (g @. f) == mu g . mu f
| capn-freako/circat | src/Circat/LinearMap.hs | bsd-3-clause | 1,746 | 0 | 10 | 416 | 359 | 212 | 147 | 19 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE RecordWildCards #-}
import Control.Monad (unless)
import Data.Monoid
import Data.Version (showVersion)
import Options.Applicative
import System.Environment (getEnvironment)
import System.Exit (ExitCode (ExitSuccess), exitWith)
import System.FilePath (splitSearchPath)
import System.Process (rawSystem)
import AddHandler (addHandler)
import Devel (DevelOpts (..), devel, DevelTermOpt(..))
import Keter (keter)
import Options (injectDefaults)
import qualified Paths_yesod_bin
import Scaffolding.Scaffolder (scaffold, backendOptions)
import HsFile (mkHsFile)
#ifndef WINDOWS
import Build (touch)
touch' :: IO ()
touch' = touch
windowsWarning :: String
windowsWarning = ""
#else
touch' :: IO ()
touch' = return ()
windowsWarning :: String
windowsWarning = " (does not work on Windows)"
#endif
data CabalPgm = Cabal | CabalDev deriving (Show, Eq)
data Options = Options
{ optCabalPgm :: CabalPgm
, optVerbose :: Bool
, optCommand :: Command
}
deriving (Show, Eq)
data Command = Init { _initBare :: Bool, _initName :: Maybe String, _initDatabase :: Maybe String }
| HsFiles
| Configure
| Build { buildExtraArgs :: [String] }
| Touch
| Devel { _develDisableApi :: Bool
, _develSuccessHook :: Maybe String
, _develFailHook :: Maybe String
, _develRescan :: Int
, _develBuildDir :: Maybe String
, develIgnore :: [String]
, develExtraArgs :: [String]
, _develPort :: Int
, _develTlsPort :: Int
, _proxyTimeout :: Int
, _noReverseProxy :: Bool
, _interruptOnly :: Bool
}
| Test
| AddHandler
{ addHandlerRoute :: Maybe String
, addHandlerPattern :: Maybe String
, addHandlerMethods :: [String]
}
| Keter
{ _keterNoRebuild :: Bool
, _keterNoCopyTo :: Bool
}
| Version
deriving (Show, Eq)
cabalCommand :: Options -> String
cabalCommand mopt
| optCabalPgm mopt == CabalDev = "cabal-dev"
| otherwise = "cabal"
main :: IO ()
main = do
o <- execParser =<< injectDefaults "yesod"
[ ("yesod.devel.extracabalarg" , \o args -> o { optCommand =
case optCommand o of
d@Devel{} -> d { develExtraArgs = args }
c -> c
})
, ("yesod.devel.ignore" , \o args -> o { optCommand =
case optCommand o of
d@Devel{} -> d { develIgnore = args }
c -> c
})
, ("yesod.build.extracabalarg" , \o args -> o { optCommand =
case optCommand o of
b@Build{} -> b { buildExtraArgs = args }
c -> c
})
] optParser'
let cabal = rawSystem' (cabalCommand o)
case optCommand o of
Init{..} -> scaffold _initBare _initName _initDatabase
HsFiles -> mkHsFile
Configure -> cabal ["configure"]
Build es -> touch' >> cabal ("build":es)
Touch -> touch'
Keter{..} -> keter (cabalCommand o) _keterNoRebuild _keterNoCopyTo
Version -> putStrLn ("yesod-bin version: " ++ showVersion Paths_yesod_bin.version)
AddHandler{..} -> addHandler addHandlerRoute addHandlerPattern addHandlerMethods
Test -> cabalTest cabal
Devel{..} ->do
(configOpts, menv) <- handleGhcPackagePath
let develOpts = DevelOpts
{ isCabalDev = optCabalPgm o == CabalDev
, forceCabal = _develDisableApi
, verbose = optVerbose o
, eventTimeout = _develRescan
, successHook = _develSuccessHook
, failHook = _develFailHook
, buildDir = _develBuildDir
, develPort = _develPort
, develTlsPort = _develTlsPort
, proxyTimeout = _proxyTimeout
, useReverseProxy = not _noReverseProxy
, terminateWith = if _interruptOnly then TerminateOnlyInterrupt else TerminateOnEnter
, develConfigOpts = configOpts
, develEnv = menv
}
devel develOpts develExtraArgs
where
cabalTest cabal = do touch'
_ <- cabal ["configure", "--enable-tests", "-flibrary-only"]
_ <- cabal ["build"]
cabal ["test"]
handleGhcPackagePath :: IO ([String], Maybe [(String, String)])
handleGhcPackagePath = do
env <- getEnvironment
case lookup "GHC_PACKAGE_PATH" env of
Nothing -> return ([], Nothing)
Just gpp -> do
let opts = "--package-db=clear"
: "--package-db=global"
: map ("--package-db=" ++)
(drop 1 $ reverse $ splitSearchPath gpp)
return (opts, Just $ filter (\(x, _) -> x /= "GHC_PACKAGE_PATH") env)
optParser' :: ParserInfo Options
optParser' = info (helper <*> optParser) ( fullDesc <> header "Yesod Web Framework command line utility" )
optParser :: Parser Options
optParser = Options
<$> flag Cabal CabalDev ( long "dev" <> short 'd' <> help "use cabal-dev" )
<*> switch ( long "verbose" <> short 'v' <> help "More verbose output" )
<*> subparser ( command "init" (info initOptions
(progDesc "Scaffold a new site"))
<> command "hsfiles" (info (pure HsFiles)
(progDesc "Create a hsfiles file for the current folder"))
<> command "configure" (info (pure Configure)
(progDesc "Configure a project for building"))
<> command "build" (info (Build <$> extraCabalArgs)
(progDesc $ "Build project (performs TH dependency analysis)" ++ windowsWarning))
<> command "touch" (info (pure Touch)
(progDesc $ "Touch any files with altered TH dependencies but do not build" ++ windowsWarning))
<> command "devel" (info develOptions
(progDesc "Run project with the devel server"))
<> command "test" (info (pure Test)
(progDesc "Build and run the integration tests"))
<> command "add-handler" (info addHandlerOptions
(progDesc ("Add a new handler and module to the project."
++ " Interactively asks for input if you do not specify arguments.")))
<> command "keter" (info keterOptions
(progDesc "Build a keter bundle"))
<> command "version" (info (pure Version)
(progDesc "Print the version of Yesod"))
)
initOptions :: Parser Command
initOptions = Init
<$> switch (long "bare" <> help "Create files in current folder")
<*> optStr (long "name" <> short 'n' <> metavar "APP_NAME"
<> help "Set the application name")
<*> optStr (long "database" <> short 'd' <> metavar "DATABASE"
<> help ("Preconfigure for selected database (options: " ++ backendOptions ++ ")"))
keterOptions :: Parser Command
keterOptions = Keter
<$> switch ( long "nobuild" <> short 'n' <> help "Skip rebuilding" )
<*> switch ( long "nocopyto" <> help "Ignore copy-to directive in keter config file" )
defaultRescan :: Int
defaultRescan = 10
develOptions :: Parser Command
develOptions = Devel <$> switch ( long "disable-api" <> short 'd'
<> help "Disable fast GHC API rebuilding")
<*> optStr ( long "success-hook" <> short 's' <> metavar "COMMAND"
<> help "Run COMMAND after rebuild succeeds")
<*> optStr ( long "failure-hook" <> short 'f' <> metavar "COMMAND"
<> help "Run COMMAND when rebuild fails")
<*> option auto ( long "event-timeout" <> short 't' <> value defaultRescan <> metavar "N"
<> help ("Force rescan of files every N seconds (default "
++ show defaultRescan
++ ", use -1 to rely on FSNotify alone)") )
<*> optStr ( long "builddir" <> short 'b'
<> help "Set custom cabal build directory, default `dist'")
<*> many ( strOption ( long "ignore" <> short 'i' <> metavar "DIR"
<> help "ignore file changes in DIR" )
)
<*> extraCabalArgs
<*> option auto ( long "port" <> short 'p' <> value 3000 <> metavar "N"
<> help "Devel server listening port" )
<*> option auto ( long "tls-port" <> short 'q' <> value 3443 <> metavar "N"
<> help "Devel server listening port (tls)" )
<*> option auto ( long "proxy-timeout" <> short 'x' <> value 0 <> metavar "N"
<> help "Devel server timeout before returning 'not ready' message (in seconds, 0 for none)" )
<*> switch ( long "disable-reverse-proxy" <> short 'n'
<> help "Disable reverse proxy" )
<*> switch ( long "interrupt-only" <> short 'c'
<> help "Disable exiting when enter is pressed")
extraCabalArgs :: Parser [String]
extraCabalArgs = many (strOption ( long "extra-cabal-arg" <> short 'e' <> metavar "ARG"
<> help "pass extra argument ARG to cabal")
)
addHandlerOptions :: Parser Command
addHandlerOptions = AddHandler
<$> optStr ( long "route" <> short 'r' <> metavar "ROUTE"
<> help "Name of route (without trailing R). Required.")
<*> optStr ( long "pattern" <> short 'p' <> metavar "PATTERN"
<> help "Route pattern (ex: /entry/#EntryId). Defaults to \"\".")
<*> many (strOption ( long "method" <> short 'm' <> metavar "METHOD"
<> help "Takes one method. Use this multiple times to add multiple methods. Defaults to none.")
)
-- | Optional @String@ argument
optStr :: Mod OptionFields (Maybe String) -> Parser (Maybe String)
optStr m = option (Just <$> str) $ value Nothing <> m
-- | Like @rawSystem@, but exits if it receives a non-success result.
rawSystem' :: String -> [String] -> IO ()
rawSystem' x y = do
res <- rawSystem x y
unless (res == ExitSuccess) $ exitWith res
| frontrowed/yesod | yesod-bin/main.hs | mit | 11,794 | 145 | 21 | 4,793 | 2,448 | 1,276 | 1,172 | 202 | 14 |
module Object.Check where
-- $Id$
import Object.Data
import Object.Infer
import Autolib.Reporter.Type
import Autolib.ToDoc
import Autolib.Size
import Autolib.TES.Term
import Autolib.TES.Position
import Autolib.TES.Identifier
import Data.Typeable
import Inter.Types
import qualified Challenger as C
data TypeCheck = TypeCheck deriving ( Eq, Ord, Show, Read, Typeable )
instance C.Partial TypeCheck TI Exp where
describe p i = vcat
[ text "Gesucht ist ein Ausdruck vom Typ" <+> toDoc (target i)
, text "in der Signatur"
, nest 4 $ toDoc (signature i)
]
initial p i = read "f(a,g(b))"
total p i b = do
inform $ vcat
[ text "Die Baumstruktur dieses Ausdrucks ist"
, nest 4 $ draw b
]
t <- infer (signature i) b
assert ( t == target i )
$ text "ist das der geforderte Typ?"
instance C.Measure TypeCheck TI Exp where
measure p i b = fromIntegral $ size b
make :: Make
make = direct TypeCheck $
TI { target = read "boolean"
, signature = read "int a; boolean eq (int a, int b);"
}
| Erdwolf/autotool-bonn | src/Object/Check.hs | gpl-2.0 | 1,096 | 4 | 12 | 291 | 337 | 175 | 162 | -1 | -1 |
athing = and [a, b]
| mpickering/hlint-refactor | tests/examples/AndList.hs | bsd-3-clause | 20 | 0 | 6 | 5 | 15 | 8 | 7 | 1 | 1 |
-- A Pandoc filter to turn `ref:xxx` into <span class="ref">xxx</span
-- Used to create references for HTML processed with refbull
-- Matti Pastell 2011 <matti.pastell@helsinki.fi>
-- Requires Pandoc 1.8
import Text.Pandoc
import Text.Pandoc.Shared
main = interact $ jsonFilter $ bottomUp refs
refs :: Inline -> Inline
refs (Code attr code)
| (take 4 code) == "ref:" = RawInline "html" ("<span class=\"ref\">" ++ (drop 4 code) ++ "</span>")
| otherwise = Code attr code
refs x = x
| danielchatfield/tails | wiki/src/promote/slides/Tails-SIT_conference-201206/pandoc-filters/refbull_filter.hs | gpl-3.0 | 497 | 2 | 11 | 93 | 126 | 63 | 63 | 8 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-|
This is a small module that contains a single enumeration type.
Note that we can't include this in "Database.Tables" because of
a restriction on Template Haskell.
-}
module Database.DataType where
import Database.Persist.TH
data ShapeType = BoolNode | Node | Hybrid | Region
deriving (Show, Read, Eq)
derivePersistField "ShapeType"
| cchens/courseography | hs/Database/DataType.hs | gpl-3.0 | 373 | 0 | 6 | 57 | 51 | 30 | 21 | 6 | 0 |
<?xml version='1.0' encoding='ISO-8859-1' ?>
<!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">
<!-- title -->
<title>Spring Rich Simple Sample Help</title>
<!-- maps -->
<maps>
<homeID>Overview</homeID>
<mapref location="simple.jhm" />
</maps>
<!-- views -->
<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>
| lievendoclo/Valkyrie-RCP | valkyrie-rcp-samples/valkyrie-rcp-simple-sample/src/main/resources/help/simple.hs | apache-2.0 | 756 | 56 | 42 | 140 | 275 | 140 | 135 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses #-}
import Data.Coerce (Coercible)
instance Coercible () ()
main = return ()
| ezyang/ghc | testsuite/tests/typecheck/should_fail/TcCoercibleFail2.hs | bsd-3-clause | 115 | 0 | 6 | 18 | 35 | 18 | 17 | 4 | 1 |
module Main (main) where
import Data.Bits
{-
Do some bitwise operations on some large numbers.
These number are designed so that they are likely to exercise all the
interesting split-up cases for implementations that implement Integer
as some sort of sequence of roughly word-sized values. They are
essentially random apart from that.
-}
px, py, nx, ny :: Integer
px = 0x03A4B5C281F6E9D7029C3FE81D6A4B75
nx = -0x03A4B5C281F6E9D7029C3FE81D6A4B75
py = 0x069AF53C4D1BE728
ny = -0x069AF53C4D1BE728
-- \.. 64 bits ../\.. 64 bits ../
{-
px = 0 0000001110100100101101011100001010000001111101101110100111010111 0000001010011100001111111110100000011101011010100100101101110101
py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000011010011010111101010011110001001101000110111110011100101000
px and py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000001010011000001101010010100000001101000010100100001100100000
px = 0 0000001110100100101101011100001010000001111101101110100111010111 0000001010011100001111111110100000011101011010100100101101110101
ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111100101100101000010101100001110110010111001000001100011011000
px and ny = 0 0000001110100100101101011100001010000001111101101110100111010111 0000000000000100000010101100000000010000011000000000100001010000
nx = 1 1111110001011011010010100011110101111110000010010001011000101000 1111110101100011110000000001011111100010100101011011010010001011
py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000011010011010111101010011110001001101000110111110011100101000
nx and py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000010000000010110000000001010001000000000100011010010000001000
nx = 1 1111110001011011010010100011110101111110000010010001011000101000 1111110101100011110000000001011111100010100101011011010010001011
ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111100101100101000010101100001110110010111001000001100011011000
nx and ny = 1 1111110001011011010010100011110101111110000010010001011000101000 1111100101100001000000000000001110100010100001000001000010001000
= neg 0 0000001110100100101101011100001010000001111101101110100111010111 0000011010011110111111111111110001011101011110111110111101111000
px = 0 0000001110100100101101011100001010000001111101101110100111010111 0000001010011100001111111110100000011101011010100100101101110101
py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000011010011010111101010011110001001101000110111110011100101000
px or py = 0 0000001110100100101101011100001010000001111101101110100111010111 0000011010011110111111111111110001011101011110111110111101111101
px = 0 0000001110100100101101011100001010000001111101101110100111010111 0000001010011100001111111110100000011101011010100100101101110101
ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111100101100101000010101100001110110010111001000001100011011000
px or ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111101111111101001111111110101110111111111011100101101111111101
= neg 0 0000000000000000000000000000000000000000000000000000000000000000 0000010000000010110000000001010001000000000100011010010000000011
nx = 1 1111110001011011010010100011110101111110000010010001011000101000 1111110101100011110000000001011111100010100101011011010010001011
py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000011010011010111101010011110001001101000110111110011100101000
nx or py = 1 1111110001011011010010100011110101111110000010010001011000101000 1111111111111011111101010011111111101111100111111111011110101011
= neg 0 0000001110100100101101011100001010000001111101101110100111010111 0000000000000100000010101100000000010000011000000000100001010101
nx = 1 1111110001011011010010100011110101111110000010010001011000101000 1111110101100011110000000001011111100010100101011011010010001011
ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111100101100101000010101100001110110010111001000001100011011000
nx or ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111110101100111110010101101011111110010111101011011110011011011
= neg 0 0000000000000000000000000000000000000000000000000000000000000000 0000001010011000001101010010100000001101000010100100001100100101
px = 0 0000001110100100101101011100001010000001111101101110100111010111 0000001010011100001111111110100000011101011010100100101101110101
py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000011010011010111101010011110001001101000110111110011100101000
px xor py = 0 0000001110100100101101011100001010000001111101101110100111010111 0000010000000110110010101101010001010000011100011010110001011101
px = 0 0000001110100100101101011100001010000001111101101110100111010111 0000001010011100001111111110100000011101011010100100101101110101
ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111100101100101000010101100001110110010111001000001100011011000
px xor ny = 1 1111110001011011010010100011110101111110000010010001011000101000 1111101111111001001101010010101110101111100011100101001110101101
= neg 0 0000001110100100101101011100001010000001111101101110100111010111 0000010000000110110010101101010001010000011100011010110001010011
nx = 1 1111110001011011010010100011110101111110000010010001011000101000 1111110101100011110000000001011111100010100101011011010010001011
py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000011010011010111101010011110001001101000110111110011100101000
nx xor py = 1 1111110001011011010010100011110101111110000010010001011000101000 1111101111111001001101010010101110101111100011100101001110100011
= neg 0 0000001110100100101101011100001010000001111101101110100111010111 0000010000000110110010101101010001010000011100011010110001011101
nx = 1 1111110001011011010010100011110101111110000010010001011000101000 1111110101100011110000000001011111100010100101011011010010001011
ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111100101100101000010101100001110110010111001000001100011011000
nx xor ny = 0 0000001110100100101101011100001010000001111101101110100111010111 0000010000000110110010101101010001010000011100011010110001010011
-}
px_and_py :: Integer
px_and_py = 0x29835280D0A4320
px_and_ny :: Integer
px_and_ny = 0x3A4B5C281F6E9D700040AC010600850
nx_and_py :: Integer
nx_and_py = 0x402C0144011A408
nx_and_ny :: Integer
nx_and_ny = -0x3A4B5C281F6E9D7069EFFFC5D7BEF78
px_or_py :: Integer
px_or_py = 0x3A4B5C281F6E9D7069EFFFC5D7BEF7D
px_or_ny :: Integer
px_or_ny = -0x402C0144011A403
nx_or_py :: Integer
nx_or_py = -0x3A4B5C281F6E9D700040AC010600855
nx_or_ny :: Integer
nx_or_ny = -0x29835280D0A4325
px_xor_py :: Integer
px_xor_py = 0x3A4B5C281F6E9D70406CAD45071AC5D
px_xor_ny :: Integer
px_xor_ny = -0x3A4B5C281F6E9D70406CAD45071AC53
nx_xor_py :: Integer
nx_xor_py = -0x3A4B5C281F6E9D70406CAD45071AC5D
nx_xor_ny :: Integer
nx_xor_ny = 0x3A4B5C281F6E9D70406CAD45071AC53
main :: IO ()
main = do putStrLn "Start"
test "px and py" px_and_py (px .&. py)
test "px and ny" px_and_ny (px .&. ny)
test "nx and py" nx_and_py (nx .&. py)
test "nx and ny" nx_and_ny (nx .&. ny)
test "px or py" px_or_py (px .|. py)
test "px or ny" px_or_ny (px .|. ny)
test "nx or py" nx_or_py (nx .|. py)
test "nx or ny" nx_or_ny (nx .|. ny)
test "px xor py" px_xor_py (px `xor` py)
test "px xor ny" px_xor_ny (px `xor` ny)
test "nx xor py" nx_xor_py (nx `xor` py)
test "nx xor ny" nx_xor_ny (nx `xor` ny)
putStrLn "End"
test :: String -> Integer -> Integer -> IO ()
test what want got
| want == got = return ()
| otherwise = print (what, want, got)
| urbanslug/ghc | testsuite/tests/lib/integer/integerBits.hs | bsd-3-clause | 8,148 | 0 | 9 | 905 | 493 | 263 | 230 | 50 | 1 |
-- #hide, prune, ignore-exports
module A where
| siddhanathan/ghc | testsuite/tests/haddock/should_compile_noflag_haddock/haddockC017.hs | bsd-3-clause | 47 | 0 | 2 | 7 | 5 | 4 | 1 | 1 | 0 |
{-# LANGUAGE CPP,
TupleSections, LambdaCase, RecordWildCards,
OverloadedLists, OverloadedStrings,
FlexibleContexts, RankNTypes, ScopedTypeVariables,
ViewPatterns, MultiWayIf #-}
#include "ghc-compat.h"
module HsToCoq.ConvertHaskell.Expr (
convertTypedModuleBinding,
convertMethodBinding,
convertTypedModuleBindings,
hsBindName,
) where
import Prelude hiding (Num())
import Control.Lens
import Control.Arrow ((&&&))
import Data.Bifunctor
import Data.Foldable
import HsToCoq.Util.Foldable
import Data.Functor (($>))
import Data.Traversable
import Data.Bitraversable
import HsToCoq.Util.Function
import Data.Maybe
import Data.Either
import Data.List (sortOn)
import HsToCoq.Util.List hiding (unsnoc)
import Data.List.NonEmpty (nonEmpty, NonEmpty(..))
import qualified Data.List.NonEmpty as NEL
import qualified HsToCoq.Util.List as NEL ((|>))
import Data.Text (Text)
import qualified Data.Text as T
import Control.Monad.Trans.Maybe
import Control.Monad.Except
import Control.Monad.Writer
import HsToCoq.Util.Containers
import Data.Set (Set)
import Data.Map.Strict (Map)
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import GHC hiding (Name, HsChar, HsString, AsPat)
import qualified GHC
import Bag
import BasicTypes
import HsToCoq.Util.GHC.FastString
import RdrName
import HsToCoq.Util.GHC.Exception
import qualified Outputable as GHC
import HsToCoq.Util.GHC
import HsToCoq.Util.GHC.Name hiding (Name)
import HsToCoq.Util.GHC.HsExpr
import HsToCoq.Util.GHC.HsTypes (selectorFieldOcc_, fieldOcc)
#if __GLASGOW_HASKELL__ >= 806
import HsToCoq.Util.GHC.HsTypes (noExtCon)
#endif
import HsToCoq.Coq.Gallina as Coq
import HsToCoq.Coq.Gallina.Util
import HsToCoq.Coq.Gallina.UseTypeInBinders
import HsToCoq.Coq.Subst
import HsToCoq.Coq.Gallina.Rewrite as Coq
import HsToCoq.Coq.FreeVars
import HsToCoq.Util.FVs (ErrOrVars(..))
import HsToCoq.Coq.Pretty
import HsToCoq.ConvertHaskell.Parameters.Edits
import HsToCoq.ConvertHaskell.TypeInfo
import HsToCoq.ConvertHaskell.Monad
import HsToCoq.ConvertHaskell.Variables
import HsToCoq.ConvertHaskell.Definitions
import HsToCoq.ConvertHaskell.Literals
import HsToCoq.ConvertHaskell.Type
import HsToCoq.ConvertHaskell.Pattern
import HsToCoq.ConvertHaskell.Sigs
import HsToCoq.ConvertHaskell.Axiomatize
--------------------------------------------------------------------------------
rewriteExpr :: ConversionMonad r m => Term -> m Term
rewriteExpr tm = do
rws <- view (edits.rewrites)
return $ Coq.rewrite rws tm
-- Module-local
il_integer :: IntegralLit -> Integer
il_integer IL{..} = (if il_neg then negate else id) il_value
-- Module-local
convert_int_literal :: LocalConvMonad r m => String -> Integer -> m Term
convert_int_literal what = either convUnsupported (pure . Num)
. convertInteger (what ++ " literals")
convertExpr :: LocalConvMonad r m => HsExpr GhcRn -> m Term
convertExpr hsExpr = convertExpr_ hsExpr >>= rewriteExpr
convertExpr_ :: forall r m. LocalConvMonad r m => HsExpr GhcRn -> m Term
convertExpr_ (HsVar NOEXTP (L _ x)) =
Qualid <$> var ExprNS x
convertExpr_ (HsUnboundVar NOEXTP x) =
Var <$> freeVar (unboundVarOcc x)
convertExpr_ (HsRecFld NOEXTP fld) =
Qualid <$> recordField fld
convertExpr_ HsOverLabel{} =
convUnsupported "overloaded labels"
convertExpr_ (HsIPVar NOEXTP _) =
convUnsupported "implicit parameters"
convertExpr_ (HsOverLit NOEXTP OverLit{..}) =
case ol_val of
HsIntegral intl -> App1 "GHC.Num.fromInteger" <$> convert_int_literal "integer" (il_integer intl)
HsFractional fr -> convertFractional fr
HsIsString _src str -> pure $ convertFastString str
convertExpr_ (HsLit NOEXTP lit) =
case lit of
GHC.HsChar _ c -> pure $ HsChar c
HsCharPrim _ _ -> convUnsupported "`Char#' literals"
GHC.HsString _ fs -> pure $ convertFastString fs
HsStringPrim _ _ -> convUnsupported "`Addr#' literals"
HsInt _ intl -> convert_int_literal "`Int'" (il_integer intl)
HsIntPrim _ int -> convert_int_literal "`IntPrim'" int
HsWordPrim _ _ -> convUnsupported "`Word#' literals"
HsInt64Prim _ _ -> convUnsupported "`Int64#' literals"
HsWord64Prim _ _ -> convUnsupported "`Word64#' literals"
HsInteger _ int _ty -> convert_int_literal "`Integer'" int
HsRat _ _ _ -> convUnsupported "`Rational' literals"
HsFloatPrim _ _ -> convUnsupported "`Float#' literals"
HsDoublePrim _ _ -> convUnsupported "`Double#' literals"
#if __GLASGOW_HASKELL__ >= 806
XLit v -> noExtCon v
#endif
convertExpr_ (HsLam NOEXTP mg) =
uncurry Fun <$> convertFunction [] mg -- We don't skip any equations in an ordinary lambda
convertExpr_ (HsLamCase NOEXTP mg) = do
skipPats <- views (edits.skippedCasePatterns) (S.map pure)
uncurry Fun <$> convertFunction skipPats mg
convertExpr_ (HsApp NOEXTP e1 e2) =
App1 <$> convertLExpr e1 <*> convertLExpr e2
#if __GLASGOW_HASKELL__ >= 808
convertExpr_ (HsAppType NOEXTP e1 _) =
#elif __GLASGOW_HASKELL__ == 806
convertExpr_ (HsAppType _ e1) =
#else
convertExpr_ (HsAppType e1 _) =
#endif
convertLExpr e1
-- convUnsupported "type applications"
-- SCW: just ignore them for now, and let the user figure it out.
#if __GLASGOW_HASKELL__ >= 806
convertExpr_ (OpApp _fixity el eop er) =
#else
convertExpr_ (OpApp el eop _fixity er) =
#endif
case eop of
L _ (HsVar NOEXTP (L _ hsOp)) -> do
op <- var ExprNS hsOp
op' <- rewriteExpr $ Qualid op
l <- convertLExpr el
r <- convertLExpr er
pure $ App2 op' l r
_ ->
convUnsupported "non-variable infix operators"
convertExpr_ (NegApp NOEXTP e1 _) =
App1 <$> (pure "GHC.Num.negate" >>= rewriteExpr) <*> convertLExpr e1
convertExpr_ (HsPar NOEXTP e) =
Parens <$> convertLExpr e
convertExpr_ (SectionL NOEXTP l opE) =
convert_section (Just l) opE Nothing
convertExpr_ (SectionR NOEXTP opE r) =
convert_section Nothing opE (Just r)
-- TODO: Mark converted unboxed tuples specially?
convertExpr_ (ExplicitTuple NOEXTP exprs _boxity) = do
-- TODO A tuple constructor in the Gallina grammar?
(tuple, args) <- runWriterT
. fmap (foldl1 . App2 $ "pair")
. for exprs $ unLoc <&> \case
Present NOEXTP e -> lift $ convertLExpr e
Missing PlaceHolder ->
do arg <- lift (genqid "arg")
Qualid arg <$ tell [arg]
#if __GLASGOW_HASKELL__ >= 806
XTupArg v -> noExtCon v
#endif
pure $ maybe id Fun (nonEmpty $ map (mkBinder Coq.Explicit . Ident) args) tuple
convertExpr_ (HsCase NOEXTP e mg) = do
scrut <- convertLExpr e
skipPats <- views (edits.skippedCasePatterns) (S.map pure)
bindIn "scrut" scrut $ \scrut -> convertMatchGroup skipPats [scrut] mg
convertExpr_ (HsIf NOEXTP overloaded c t f) =
if maybe True isNoSyntaxExpr overloaded
then ifThenElse <*> pure SymmetricIf <*> convertLExpr c <*> convertLExpr t <*> convertLExpr f
else convUnsupported "overloaded if-then-else"
convertExpr_ (HsMultiIf PlaceHolder lgrhsList) =
convertLGRHSList [] lgrhsList patternFailure
convertExpr_ (HsLet NOEXTP (L _ binds) body) =
convertLocalBinds binds $ convertLExpr body
#if __GLASGOW_HASKELL__ >= 806
convertExpr_ (HsDo _ sty (L _ stmts)) =
#else
convertExpr_ (HsDo sty (L _ stmts) PlaceHolder) =
#endif
case sty of
ListComp -> convertListComprehension stmts
DoExpr -> convertDoBlock stmts
MonadComp -> convUnsupported "monad comprehensions"
MDoExpr -> convUnsupported "`mdo' expressions"
ArrowExpr -> convUnsupported "arrow expressions"
GhciStmtCtxt -> convUnsupported "GHCi statement expressions"
PatGuard _ -> convUnsupported "pattern guard expressions"
ParStmtCtxt _ -> convUnsupported "parallel statement expressions"
TransStmtCtxt _ -> convUnsupported "transform statement expressions"
#if __GLASGOW_HASKELL__ < 806
PArrComp -> convUnsupported "parallel array comprehensions"
#endif
convertExpr_ (ExplicitList PlaceHolder overloaded exprs) =
if maybe True isNoSyntaxExpr overloaded
then foldr (App2 "cons") "nil" <$> traverse convertLExpr exprs
else convUnsupported "overloaded lists"
-- TODO: Unify with the `RecCon` case in `ConPatIn` for `convertPat` (in
-- `HsToCoq.ConvertHaskell.Pattern`)
#if __GLASGOW_HASKELL__ >= 806
convertExpr_ (RecordCon _ (L _ hsCon) HsRecFields{..}) = do
#else
convertExpr_ (RecordCon (L _ hsCon) PlaceHolder conExpr HsRecFields{..}) = do
unless (isNoPostTcExpr conExpr) $
convUnsupported "unexpected post-typechecker record constructor"
#endif
let recConUnsupported what = do
hsConStr <- ghcPpr hsCon
convUnsupported $ "creating a record with the " ++ what
++ " constructor `" ++ T.unpack hsConStr ++ "'"
con <- var ExprNS hsCon
lookupConstructorFields con >>= \case
Just (RecordFields conFields) -> do
let defaultVal field | isJust rec_dotdot = Qualid field
| otherwise = missingValue
vals <- fmap M.fromList . for rec_flds $
\(L _ (HsRecField (L _ occ) hsVal pun)) -> do
field <- var ExprNS (selectorFieldOcc_ occ)
val <- if pun
then pure $ Qualid field
else convertLExpr hsVal
pure (field, val)
pure . appList (Qualid con)
$ map (\field -> PosArg $ M.findWithDefault (defaultVal field) field vals) conFields
Just (NonRecordFields count)
| null rec_flds && isNothing rec_dotdot ->
pure . appList (Qualid con) $ replicate count (PosArg missingValue)
| otherwise ->
recConUnsupported "non-record"
Nothing -> recConUnsupported "unknown"
#if __GLASGOW_HASKELL__ >= 806
convertExpr_ (RecordUpd _ recVal fields) = do
#else
convertExpr_ (RecordUpd recVal fields PlaceHolder PlaceHolder PlaceHolder PlaceHolder) = do
#endif
updates <- fmap M.fromList . for fields $ \(L _ HsRecField{..}) -> do
field <- recordField $ unLoc hsRecFieldLbl
pure (field, if hsRecPun then Nothing else Just hsRecFieldArg)
let updFields = M.keys updates
prettyUpdFields what =
let quote f = "`" ++ T.unpack (qualidToIdent f) ++ "'"
in explainStrItems quote "no" "," "and" what (what ++ "s") updFields
recType <- S.minView . S.fromList <$> traverse (\field -> lookupRecordFieldType field) updFields >>= \case
Just (Just recType, []) -> pure recType
Just (Nothing, []) -> convUnsupported $ "invalid record update with " ++ prettyUpdFields "non-record-field"
_ -> convUnsupported $ "invalid mixed-data-type record updates with " ++ prettyUpdFields "the given field"
ctors :: [Qualid] <- maybe (convUnsupported "invalid unknown record type") pure =<< lookupConstructors recType
let loc :: e -> Located e
loc = mkGeneralLocated "generated"
toLPat_ :: Pat GhcRn -> LPat GhcRn
toLPat_ = toLPat "generated"
toHs = freshInternalName . T.unpack
let partialUpdateError :: Qualid -> m (Match GhcRn (Located (HsExpr GhcRn)))
partialUpdateError con = do
hsCon <- toHs (qualidToIdent con)
hsError <- toHs "GHC.Err.error"
pure $ GHC.Match
{ m_ctxt = LambdaExpr
, m_pats = [ toLPat_ . ConPatIn (loc hsCon)
. RecCon $ HsRecFields { rec_flds = []
, rec_dotdot = Nothing } ]
, m_grhss = GRHSs { grhssGRHSs = [ loc . GRHS NOEXT [] . loc $
HsApp NOEXT
(loc . HsVar NOEXT . loc $ hsError)
(loc . HsLit NOEXT . GHC.HsString (SourceText "") $ fsLit "Partial record update") ]
, grhssLocalBinds = loc (EmptyLocalBinds NOEXT)
#if __GLASGOW_HASKELL__ >= 806
, grhssExt = NOEXT
#endif
}
#if __GLASGOW_HASKELL__ >= 806
, m_ext = NOEXT
#endif
}
matches <- for ctors $ \con ->
lookupConstructorFields con >>= \case
Just (RecordFields fields) | all (`elem` fields) $ M.keysSet updates -> do
let addFieldOcc :: HsRecField' GHC.Name arg -> HsRecField GhcRn arg
addFieldOcc field@HsRecField{hsRecFieldLbl = L s lbl} =
let rdrLbl = mkOrig <$> nameModule <*> nameOccName $ lbl
l = L s (fieldOcc (L s rdrLbl) lbl)
in field{ hsRecFieldLbl = l }
useFields fields = HsRecFields { rec_flds = map (fmap addFieldOcc) fields
, rec_dotdot = Nothing }
(fieldPats, fieldVals) <- fmap (bimap useFields useFields . unzip) . for fields $ \field -> do
fieldVar <- gensym (qualidBase field)
hsField <- toHs (qualidToIdent field)
hsFieldVar <- toHs fieldVar
let mkField arg = loc $ HsRecField { hsRecFieldLbl = loc hsField
, hsRecFieldArg = arg
, hsRecPun = False }
pure ( mkField . toLPat_ . GHC.VarPat NOEXT . loc $ hsFieldVar
, mkField . fromMaybe (loc . HsVar NOEXT $ loc hsField) -- NOT `fieldVar` – this was punned
$ M.findWithDefault (Just . loc . HsVar NOEXT $ loc hsFieldVar) field updates )
hsCon <- toHs (qualidToIdent con)
#if __GLASGOW_HASKELL__ >= 806
let r = RecordCon NOEXT (loc hsCon) fieldVals
#else
let r = RecordCon (loc hsCon) PlaceHolder noPostTcExpr fieldVals
#endif
pure GHC.Match { m_ctxt = LambdaExpr
, m_pats = [ toLPat_ . ConPatIn (loc hsCon) $ RecCon fieldPats ]
, m_grhss = GRHSs { grhssGRHSs = [ loc . GRHS NOEXT [] . loc $ r ]
, grhssLocalBinds = loc (EmptyLocalBinds NOEXT)
#if __GLASGOW_HASKELL__ >= 806
, grhssExt = NOEXT
#endif
}
#if __GLASGOW_HASKELL__ >= 806
, m_ext = NOEXT
#endif
}
Just _ ->
partialUpdateError con
Nothing ->
convUnsupported "invalid unknown constructor in record update"
#if __GLASGOW_HASKELL__ >= 806
convertExpr . HsCase NOEXT recVal $
MG { mg_alts = loc $ map loc matches
, mg_ext = NOEXT
, mg_origin = Generated }
#else
convertExpr . HsCase recVal $
MG { mg_alts = loc $ map loc matches
, mg_arg_tys = []
, mg_res_ty = PlaceHolder
, mg_origin = Generated }
#endif
#if __GLASGOW_HASKELL__ >= 808
convertExpr_ (ExprWithTySig NOEXTP e sigWcTy) =
#elif __GLASGOW_HASKELL__ == 806
convertExpr_ (ExprWithTySig sigWcTy e) =
#else
convertExpr_ (ExprWithTySig e sigWcTy) =
#endif
HasType <$> convertLExpr e <*> convertLHsSigWcType PreserveUnusedTyVars sigWcTy
convertExpr_ (ArithSeq _postTc _overloadedLists info) =
-- TODO: Special-case infinite lists?
-- TODO: `enumFrom{,Then}{,To}` is really…?
-- TODO: Add Coq syntax sugar? Something like
--
-- Notation "[ :: from '..' ]" := (enumFrom from).
-- Notation "[ :: from , next '..' ]" := (enumFromThen from next).
-- Notation "[ :: from '..' to ]" := (enumFromTo from to).
-- Notation "[ :: from , next '..' to ]" := (enumFromThenTo from next to).
--
-- Only `'..'` doesn't work for some reason.
case info of
From low -> App1 "GHC.Enum.enumFrom" <$> convertLExpr low
FromThen low next -> App2 "GHC.Enum.enumFromThen" <$> convertLExpr low <*> convertLExpr next
FromTo low high -> App2 "GHC.Enum.enumFromTo" <$> convertLExpr low <*> convertLExpr high
FromThenTo low next high -> App3 "GHC.Enum.enumFromThenTo" <$> convertLExpr low <*> convertLExpr next <*> convertLExpr high
convertExpr_ (HsSCC NOEXTP _ _ e) =
convertLExpr e
convertExpr_ (HsCoreAnn NOEXTP _ _ e) =
convertLExpr e
convertExpr_ (HsBracket{}) =
convUnsupported "Template Haskell brackets"
convertExpr_ (HsRnBracketOut{}) =
convUnsupported "`HsRnBracketOut' constructor"
convertExpr_ (HsTcBracketOut{}) =
convUnsupported "`HsTcBracketOut' constructor"
convertExpr_ (HsSpliceE{}) =
convUnsupported "Quasiquoters and Template Haskell splices"
convertExpr_ (HsProc{}) =
convUnsupported "`proc' expressions"
convertExpr_ HsStatic{} =
convUnsupported "static pointers"
convertExpr_ (HsTick NOEXTP _ e) =
convertLExpr e
convertExpr_ (HsBinTick NOEXTP _ _ e) =
convertLExpr e
convertExpr_ (HsTickPragma NOEXTP _ _ _ e) =
convertLExpr e
convertExpr_ (HsWrap{}) =
convUnsupported "`HsWrap' constructor"
convertExpr_ (HsConLikeOut{}) =
convUnsupported "`HsConLikeOut' constructor"
convertExpr_ (ExplicitSum{}) =
convUnsupported "`ExplicitSum' constructor"
#if __GLASGOW_HASKELL__ >= 806
convertExpr_ (HsOverLit _ (XOverLit v)) = noExtCon v
convertExpr_ (XExpr v) = noExtCon v
#else
convertExpr_ (HsAppTypeOut _ _) =
convUnsupported "`HsAppTypeOut' constructor"
convertExpr_ (ExprWithTySigOut e sigWcTy) =
HasType <$> convertLExpr e <*> convertLHsSigWcType PreserveUnusedTyVars sigWcTy
convertExpr_ (ExplicitPArr _ _) =
convUnsupported "explicit parallel arrays"
convertExpr_ (PArrSeq _ _) =
convUnsupported "parallel array arithmetic sequences"
#endif
#if __GLASGOW_HASKELL__ < 810
convertExpr_ HsArrApp{} =
convUnsupported "arrow application command"
convertExpr_ HsArrForm{} =
convUnsupported "arrow command formation"
convertExpr_ EWildPat{} =
convUnsupported "wildcard pattern in expression"
convertExpr_ EAsPat{} =
convUnsupported "as-pattern in expression"
convertExpr_ EViewPat{} =
convUnsupported "view-pattern in expression"
convertExpr_ ELazyPat{} =
convUnsupported "lazy pattern in expression"
#endif
--------------------------------------------------------------------------------
-- Module-local
convert_section :: LocalConvMonad r m => Maybe (LHsExpr GhcRn) -> LHsExpr GhcRn -> Maybe (LHsExpr GhcRn) -> m Term
convert_section ml opE mr = do
let -- We need this type signature, and I think it's because @let@ isn't being
-- generalized.
hs :: ConversionMonad r m => Qualid -> m (HsExpr GhcRn)
hs = fmap (HsVar NOEXT . mkGeneralLocated "generated") . freshInternalName . T.unpack . qualidToIdent
coq = mkBinder Coq.Explicit . Ident
arg <- Bare <$> gensym "arg"
let orArg = maybe (fmap noLoc $ hs arg) pure
l <- orArg ml
r <- orArg mr
#if __GLASGOW_HASKELL__ >= 806
Fun [coq arg] <$> convertExpr (OpApp defaultFixity l opE r)
#else
-- TODO RENAMER look up fixity?
Fun [coq arg] <$> convertExpr (OpApp l opE defaultFixity r)
#endif
--------------------------------------------------------------------------------
convertLExpr :: LocalConvMonad r m => LHsExpr GhcRn -> m Term
convertLExpr = convertExpr . unLoc
--------------------------------------------------------------------------------
convertFunction :: LocalConvMonad r m
=> Set (NonEmpty NormalizedPattern)
-> MatchGroup GhcRn (LHsExpr GhcRn)
-> m (Binders, Term)
convertFunction _ mg | Just alt <- isTrivialMatch mg = convTrivialMatch alt
convertFunction skipEqns mg = do
let n_args = matchGroupArity mg
args <- replicateM n_args (genqid "arg") >>= maybe err pure . nonEmpty
let argBinders = (mkBinder Coq.Explicit . Ident) <$> args
match <- convertMatchGroup skipEqns (Qualid <$> args) mg
pure (argBinders, match)
where
err = convUnsupported "convertFunction: Empty argument list"
isTrivialMatch :: MatchGroup GhcRn (LHsExpr GhcRn) -> Maybe (Match GhcRn (LHsExpr GhcRn))
isTrivialMatch (MG { mg_alts = L _ [L _ alt] }) = trivMatch alt where
trivMatch :: Match GhcRn (LHsExpr GhcRn) -> Maybe (Match GhcRn (LHsExpr GhcRn))
trivMatch alt = if all trivLPat (m_pats alt) then Just alt else Nothing
trivPat :: Pat GhcRn -> Bool
trivPat (GHC.WildPat _) = False
trivPat (GHC.VarPat NOEXTP _) = True
trivPat (GHC.BangPat NOEXTP p) = trivLPat p
trivPat (GHC.LazyPat NOEXTP p) = trivLPat p
trivPat (GHC.ParPat NOEXTP p) = trivLPat p
trivPat _ = False
trivLPat = trivPat . unLPat
isTrivialMatch _ = Nothing
-- TODO: Unify with `isTrivialMatch` to return a `Maybe (Binders, Term)`
convTrivialMatch :: LocalConvMonad r m =>
Match GhcRn (LHsExpr GhcRn) -> m (Binders, Term)
convTrivialMatch alt = do
(MultPattern pats, _, rhs) <- convertMatch alt
<&> maybe (error "internal error: convTrivialMatch: not a trivial match!") id
names <- mapM patToName pats
let argBinders = (mkBinder Explicit) <$> names
body <- rhs patternFailure
return (argBinders, body)
patToName :: LocalConvMonad r m => Pattern -> m Name
patToName UnderscorePat = pure UnderscoreName
patToName (QualidPat qid) = pure $ Ident qid
patToName _ = convUnsupported "patToArg: not a trivial pat"
--------------------------------------------------------------------------------
isTrueLExpr :: GhcMonad m => LHsExpr GhcRn -> m Bool
isTrueLExpr (L _ (HsVar NOEXTP x)) = ((||) <$> (== "otherwise") <*> (== "True")) <$> ghcPpr x
isTrueLExpr (L _ (HsTick NOEXTP _ e)) = isTrueLExpr e
isTrueLExpr (L _ (HsBinTick NOEXTP _ _ e)) = isTrueLExpr e
isTrueLExpr (L _ (HsPar NOEXTP e)) = isTrueLExpr e
isTrueLExpr _ = pure False
--------------------------------------------------------------------------------
-- TODO: Unify `buildTrivial` and `buildNontrivial`?
convertPatternBinding :: LocalConvMonad r m
=> LPat GhcRn -> LHsExpr GhcRn
-> (Term -> (Term -> Term) -> m a)
-> (Term -> Qualid -> (Term -> Term -> Term) -> m a)
-> (Qualid -> m a)
-> Term
-> m a
convertPatternBinding hsPat hsExp buildTrivial buildNontrivial buildSkipped fallback =
runPatternT (convertLPat hsPat) >>= \case
Left skipped -> buildSkipped skipped
Right (pat, guards) -> do
exp <- convertLExpr hsExp
ib <- ifThenElse
refutability pat >>= \case
Trivial tpat | null guards ->
buildTrivial exp $ Fun [mkBinder Coq.Explicit $ maybe UnderscoreName Ident tpat]
nontrivial -> do
cont <- genqid "cont"
arg <- genqid "arg"
-- TODO: Use SSReflect's `let:` in the `SoleConstructor` case?
-- (Involves adding a constructor to `Term`.)
let fallbackMatches
| SoleConstructor <- nontrivial = []
| otherwise = [ Equation [MultPattern [UnderscorePat]] fallback ]
guarded tm | null guards = tm
| otherwise = ib LinearIf (foldr1 (App2 "andb") guards) tm fallback
buildNontrivial exp cont $ \body rest ->
Let cont [mkBinder Coq.Explicit $ Ident arg] Nothing
(Coq.Match [MatchItem (Qualid arg) Nothing Nothing] Nothing $
Equation [MultPattern [pat]] (guarded rest) : fallbackMatches)
body
convertDoBlock :: LocalConvMonad r m => [ExprLStmt GhcRn] -> m Term
convertDoBlock allStmts = do
case fmap unLoc <$> unsnoc allStmts of
Just (stmts, lastStmt -> Just e) -> foldMap (Endo . toExpr . unLoc) stmts `appEndo` convertLExpr e
Just _ -> convUnsupported "invalid malformed `do' block"
Nothing -> convUnsupported "invalid empty `do' block"
where
#if __GLASGOW_HASKELL__ >= 806
lastStmt (BodyStmt _ e _ _) = Just e
#else
lastStmt (BodyStmt e _ _ _) = Just e
#endif
lastStmt (LastStmt NOEXTP e _ _) = Just e
lastStmt _ = Nothing
toExpr x rest = toExpr_ x rest >>= rewriteExpr
#if __GLASGOW_HASKELL__ >= 806
toExpr_ (BodyStmt _ e _bind _guard) rest =
#else
toExpr_ (BodyStmt e _bind _guard _PlaceHolder) rest =
#endif
monThen <$> convertLExpr e <*> rest
#if __GLASGOW_HASKELL__ >= 806
toExpr_ (BindStmt _ pat exp _bind _fail) rest =
#else
toExpr_ (BindStmt pat exp _bind _fail PlaceHolder) rest =
#endif
convertPatternBinding
pat exp
(\exp' fun -> monBind exp' . fun <$> rest)
(\exp' cont letCont -> letCont (monBind exp' (Qualid cont)) <$> rest)
(\skipped -> convUnsupported $
"binding against the skipped constructor `" ++ showP skipped ++ "' in `do' notation")
(missingValue `App1` HsString "Partial pattern match in `do' notation")
toExpr_ (LetStmt NOEXTP (L _ binds)) rest =
convertLocalBinds binds rest
toExpr_ (RecStmt{}) _ =
convUnsupported "`rec' statements in `do` blocks"
toExpr_ _ _ =
convUnsupported "impossibly fancy `do' block statements"
monBind e1 e2 = mkInfix e1 "GHC.Base.>>=" e2
monThen e1 e2 = mkInfix e1 "GHC.Base.>>" e2
convertListComprehension :: LocalConvMonad r m => [ExprLStmt GhcRn] -> m Term
convertListComprehension allStmts = case fmap unLoc <$> unsnoc allStmts of
Just (stmts, LastStmt NOEXTP e _applicativeDoInfo _returnInfo) ->
foldMap (Endo . toExpr . unLoc) stmts `appEndo`
(App2 (Var "cons") <$> convertLExpr e <*> pure (Var "nil"))
Just _ ->
convUnsupported "invalid malformed list comprehensions"
Nothing ->
convUnsupported "invalid empty list comprehension"
where
#if __GLASGOW_HASKELL__ >= 806
toExpr (BodyStmt _ e _bind _guard) rest =
#else
toExpr (BodyStmt e _bind _guard _PlaceHolder) rest =
#endif
isTrueLExpr e >>= \case
True -> rest
False -> ifThenElse <*> pure LinearIf
<*> convertLExpr e
<*> rest
<*> pure (Var "nil")
-- TODO: `concatMap` is really…?
#if __GLASGOW_HASKELL__ >= 806
toExpr (BindStmt _ pat exp _bind _fail) rest =
#else
toExpr (BindStmt pat exp _bind _fail PlaceHolder) rest =
#endif
convertPatternBinding
pat exp
(\exp' fun -> App2 concatMapT <$> (fun <$> rest) <*> pure exp')
(\exp' cont letCont -> letCont (App2 concatMapT (Qualid cont) exp') <$> rest)
(\skipped -> pure $ App1 (Qualid "GHC.Skip.nil_skipped") (String $ textP skipped))
(Var "nil")
-- `GHC.Skip.nil_skipped` always returns `[]`, but it has a note about
-- what constructor was skipped.
toExpr (LetStmt NOEXTP (L _ binds)) rest =
convertLocalBinds binds rest
toExpr _ _ =
convUnsupported "impossibly fancy list comprehension conditions"
concatMapT :: Term
concatMapT = "Coq.Lists.List.flat_map"
--------------------------------------------------------------------------------
-- Could this pattern be considered a 'catch all' or exhaustive pattern?
isWildCoq :: Pattern -> Bool
isWildCoq UnderscorePat = True
isWildCoq (QualidPat _) = True
isWildCoq (AsPat p _) = isWildCoq p
isWildCoq (ArgsPat qid nep) = qid == (Bare "pair") && all isWildCoq nep
isWildCoq _ = False
{-
= ArgsPat Qualid (NE.NonEmpty Pattern)
| ExplicitArgsPat Qualid (NE.NonEmpty Pattern)
| InfixPat Pattern Op Pattern
| AsPat Pattern Ident
| InScopePat Pattern Ident
| QualidPat Qualid
| UnderscorePat
| NumPat HsToCoq.Coq.Gallina.Num
| StringPat T.Text
| OrPats (NE.NonEmpty OrPattern)
-}
-- This function, used by both convertMatchGroup for the various matches,
-- as well as in convertMatch for the various guarded RHS, implements
-- fall-though semantics, by binding each item to a jump point and passing
-- the right failure jump target to the prevoius item.
chainFallThroughs :: LocalConvMonad r m =>
[Term -> m Term] -> -- The matches, in syntax order
Term -> -- The final failure value
m Term
chainFallThroughs cases failure = go (reverse cases) failure where
go (m:ls) next_case = do
this_match <- m next_case
bindIn "j" this_match $ \failure -> go ls failure
go [] failure = pure failure
-- A match group contains multiple alternatives, and each can have guards, and
-- there is fall-through semantics. But often we know that if one pattern fall-through,
-- then the next pattern will not match. In that case, we want to bind them in the same
-- match-with clause, in the hope of obtaining a full pattern match
--
-- The plan is:
-- * Convert each alternative individually into a pair of a pattern and a RHS.
-- The RHS is a (shallow) function that takes the fall-through target.
-- This is done by convertMatch
-- * Group patterns that are mutually exclusive, and put them in match-with clauses.
-- Add a catch-all case if that group is not complete already.
-- * Chain these groups.
convertMatchGroup :: LocalConvMonad r m
=> Set (NonEmpty NormalizedPattern)
-> NonEmpty Term
-> MatchGroup GhcRn (LHsExpr GhcRn)
-> m Term
convertMatchGroup skipEqns args (MG { mg_alts = L _ alts }) = do
allConvAlts <- traverse (convertMatch . unLoc) alts
let convAlts = [alt | Just alt@(MultPattern pats, _, _) <- allConvAlts
, (normalizePattern <$> pats) `notElem` skipEqns ]
-- TODO: Group
convGroups <- groupMatches convAlts
let scrut = args <&> \arg -> MatchItem arg Nothing Nothing
let matches = buildMatch scrut <$> convGroups
chainFallThroughs matches patternFailure
#if __GLASGOW_HASKELL__ >= 806
convertMatchGroup _ _ (XMatchGroup v) = noExtCon v
#endif
data HasGuard = HasGuard | HasNoGuard deriving (Eq, Ord, Enum, Bounded, Show, Read)
groupMatches :: forall r m a. ConversionMonad r m =>
[(MultPattern, HasGuard, a)] -> m [[(MultPattern, a)]]
groupMatches pats = map (map snd) . go <$> mapM summarize pats
where
-- Gather some summary information on the alternatives
-- - do they have guards
-- - what is their PatternSummary
summarize :: (MultPattern, HasGuard, a) -> m ([PatternSummary], HasGuard, (MultPattern, a))
summarize (mp,hg,x) = do
s <- multPatternSummary mp
return (s,hg,(mp,x))
go :: forall x. [([PatternSummary], HasGuard, x)] -> [[([PatternSummary], x)]]
go [] = pure []
go ((ps,hg,x):xs) = case go xs of
-- Append to a group if it has no guard
(g:gs) | HasNoGuard <- hg -> ((ps,x):g) : gs
-- Append to a group, if mutually exclusive with all members
| all (mutExcls ps . fst) g -> ((ps,x):g) : gs
-- Otherwise, start a new group
gs -> ((ps,x):[]) : gs
convertMatch :: LocalConvMonad r m =>
Match GhcRn (LHsExpr GhcRn) -> -- the match
m (Maybe (MultPattern, HasGuard, Term -> m Term)) -- the pattern, hasGuards, the right-hand side
convertMatch GHC.Match{..} =
(runPatternT $ maybe (convUnsupported "no-pattern case arms") pure . nonEmpty
=<< traverse convertLPat m_pats) <&> \case
Left _skipped -> Nothing
Right (pats, guards) ->
let extraGuards = map BoolGuard guards
rhs = convertGRHSs extraGuards m_grhss
hg | null extraGuards = hasGuards m_grhss
| otherwise = HasGuard
in Just (MultPattern pats, hg, rhs)
#if __GLASGOW_HASKELL__ >= 806
convertMatch (XMatch v) = noExtCon v
#endif
buildMatch :: ConversionMonad r m =>
NonEmpty MatchItem -> [(MultPattern, Term -> m Term)] -> Term -> m Term
-- This short-cuts wildcard matches (avoid introducing a match-with alltogether)
buildMatch _ [(pats,mkRhs)] failure
| isUnderscoreMultPattern pats = mkRhs failure
buildMatch scruts eqns failure = do
-- Pass the failure
eqns' <- forM eqns $ \(pat,mkRhs) -> (pat,) <$> mkRhs failure
is_complete <- isCompleteMultiPattern (map fst eqns')
pure $ Coq.Match scruts Nothing $
[ Equation [pats] rhs | (pats, rhs) <- eqns' ] ++
[ Equation [MultPattern (UnderscorePat <$ scruts)] failure | not is_complete ]
-- Only add a catch-all clause if the the patterns can fail
--------------------------------------------------------------------------------
hasGuards :: GRHSs b e -> HasGuard
hasGuards (GRHSs NOEXTP [ L _ (GRHS NOEXTP [] _) ] _) = HasNoGuard
hasGuards _ = HasGuard
convertGRHS :: LocalConvMonad r m
=> [ConvertedGuard m]
-> GRHS GhcRn (LHsExpr GhcRn)
-> ExceptT Qualid m (Term -> m Term)
convertGRHS extraGuards (GRHS NOEXTP gs rhs) = do
convGuards <- (extraGuards ++) <$> convertGuard gs
rhs <- convertLExpr rhs
pure $ \failure -> guardTerm convGuards rhs failure
#if __GLASGOW_HASKELL__ >= 806
convertGRHS _ (XGRHS v) = noExtCon v
#endif
convertLGRHSList :: LocalConvMonad r m
=> [ConvertedGuard m]
-> [LGRHS GhcRn (LHsExpr GhcRn)]
-> Term
-> m Term
convertLGRHSList extraGuards lgrhs failure = do
let rhss = unLoc <$> lgrhs
convRhss <- rights <$> traverse (runExceptT . convertGRHS extraGuards) rhss
chainFallThroughs convRhss failure
convertGRHSs :: LocalConvMonad r m
=> [ConvertedGuard m]
-> GRHSs GhcRn (LHsExpr GhcRn)
-> Term
-> m Term
convertGRHSs extraGuards GRHSs{..} failure =
convertLocalBinds (unLoc grhssLocalBinds) $
convertLGRHSList extraGuards grhssGRHSs failure
#if __GLASGOW_HASKELL__ >= 806
convertGRHSs _ (XGRHSs v) _ = noExtCon v
#endif
--------------------------------------------------------------------------------
data ConvertedGuard m = OtherwiseGuard
| BoolGuard Term
| PatternGuard Pattern Term
| LetGuard (m Term -> m Term)
convertGuard :: LocalConvMonad r m => [GuardLStmt GhcRn] -> ExceptT Qualid m [ConvertedGuard m]
convertGuard [] = pure []
convertGuard gs = collapseGuards <$> traverse (toCond . unLoc) gs where
#if __GLASGOW_HASKELL__ >= 806
toCond (BodyStmt _ e _bind _guard) =
#else
toCond (BodyStmt e _bind _guard _PlaceHolder) =
#endif
isTrueLExpr e >>= \case
True -> pure [OtherwiseGuard]
False -> (:[]) . BoolGuard <$> convertLExpr e
toCond (LetStmt NOEXTP (L _ binds)) =
pure . (:[]) . LetGuard $ convertLocalBinds binds
#if __GLASGOW_HASKELL__ >= 806
toCond (BindStmt _ pat exp _bind _fail) = do
#else
toCond (BindStmt pat exp _bind _fail PlaceHolder) = do
#endif
(pat', guards) <- runWriterT (convertLPat pat)
exp' <- convertLExpr exp
pure $ PatternGuard pat' exp' : map BoolGuard guards
toCond _ =
convUnsupported "impossibly fancy guards"
-- We optimize the code a bit, and combine
-- successive boolean guards with andb
collapseGuards = foldr addGuard [] . concat
-- TODO: Add multi-pattern-guard case
addGuard g [] =
[g]
addGuard (BoolGuard cond') (BoolGuard cond : gs) =
BoolGuard (App2 (Var "andb") cond' cond) : gs
addGuard g' (g:gs) =
g':g:gs
-- Returns a function waiting for the "else case"
guardTerm :: LocalConvMonad r m =>
[ConvertedGuard m] ->
Term -> -- The guarded expression
Term -> -- the failure expression
m Term
guardTerm gs rhs failure = go gs where
go [] =
pure rhs
go (OtherwiseGuard : gs) =
go gs
-- A little innocent but useful hack: Detect the pattern
-- | foo `seq` False = …
-- And hard-code that it fails
go (BoolGuard (App2 "GHC.Prim.seq" _ p) : gs) = go (BoolGuard p : gs)
go (BoolGuard "false" : _) = pure failure
go (BoolGuard cond : gs) =
ifThenElse <*> pure LinearIf <*> pure cond <*> go gs <*> pure failure
-- if the pattern is exhaustive, don't include an otherwise case
go (PatternGuard pat exp : gs) | isWildCoq pat = do
guarded' <- go gs
pure $ Coq.Match [MatchItem exp Nothing Nothing] Nothing
[ Equation [MultPattern [pat]] guarded' ]
go (PatternGuard pat exp : gs) = do
guarded' <- go gs
pure $ Coq.Match [MatchItem exp Nothing Nothing] Nothing
[ Equation [MultPattern [pat]] guarded'
, Equation [MultPattern [UnderscorePat]] failure ]
go (LetGuard bind : gs) =
bind $ go gs
--------------------------------------------------------------------------------
-- Does not detect recursion/introduce `fix`
convertTypedBinding :: LocalConvMonad r m => Maybe Term -> HsBind GhcRn -> m (Maybe ConvertedBinding)
convertTypedBinding _convHsTy VarBind{} = convUnsupported "[internal] `VarBind'"
convertTypedBinding _convHsTy AbsBinds{} = convUnsupported "[internal?] `AbsBinds'"
convertTypedBinding _convHsTy PatSynBind{} = convUnsupported "pattern synonym bindings"
#if __GLASGOW_HASKELL__ >= 806
convertTypedBinding _ (XHsBindsLR v) = noExtCon v
#endif
convertTypedBinding _convHsTy PatBind{..} = do -- TODO use `_convHsTy`?
-- TODO: Respect `skipped'?
-- TODO: what if we need to rename this definition? (i.e. for a class member)
ax <- view currentModuleAxiomatized
if ax
then
liftIO $ Nothing <$ putStrLn "skipping a pattern binding in an axiomatized module" -- TODO: FIX HACK
-- convUnsupported "pattern bindings in axiomatized modules"
else
runPatternT (convertLPat pat_lhs) >>= \case
Left _skipped -> pure Nothing
Right (pat, guards) -> Just . ConvertedPatternBinding pat <$> convertGRHSs (map BoolGuard guards) pat_rhs patternFailure
convertTypedBinding convHsTy FunBind{..} = do
name <- var ExprNS (unLoc fun_id)
-- Skip it? Axiomatize it?
definitionTask name >>= \case
SkipIt ->
pure . Just $ SkippedBinding name
RedefineIt def ->
pure . Just $ RedefinedBinding name def
AxiomatizeIt axMode ->
let missingType = case axMode of
SpecificAxiomatize -> convUnsupported "axiomatizing definitions without type signatures"
GeneralAxiomatize -> pure bottomType
in Just . ConvertedAxiomBinding name <$> maybe missingType pure convHsTy
TranslateIt -> do
let (tvs, coqTy) =
-- The @forall@ed arguments need to be brought into scope
let peelForall (Forall tvs body) = first (NEL.toList tvs ++) $ peelForall body
peelForall ty = ([], ty)
in maybe ([], Nothing) (second Just . peelForall) convHsTy
-- in maybe ([], Nothing) (second Just . peelForall) (Just $ Qualid $ Bare "test")
let tryCollapseLet defn = do
view (edits.collapsedLets.contains name) >>= \case
True -> collapseLet name defn
& maybe (convUnsupported "collapsing non-`let x=… in x` lets") pure
False -> pure defn
defn <-
tryCollapseLet =<<
if all (null . m_pats . unLoc) . unLoc $ mg_alts fun_matches
then case unLoc $ mg_alts fun_matches of
[L _ (GHC.Match NOEXTP _ [] grhss)] -> convertGRHSs [] grhss patternFailure
_ -> convUnsupported "malformed multi-match variable definitions"
else do
skipEqns <- view $ edits.skippedEquations.at name.non mempty
uncurry Fun <$> convertFunction skipEqns fun_matches
addScope <- maybe id (flip InScope) <$> view (edits.additionalScopes.at (SPValue, name))
pure . Just . ConvertedDefinitionBinding $ ConvertedDefinition name tvs coqTy (addScope defn)
collapseLet :: Qualid -> Term -> Maybe Term
collapseLet outer (Let x args _oty defn (Qualid x')) | x == x' =
Just . maybeFun args $ case defn of
Fix (FixOne (FixBody f args' _mord _oty body)) -> Fun args' $ subst1 f (Qualid outer) body
_ -> defn
collapseLet _ _ =
Nothing
wfFix :: ConversionMonad r m => TerminationArgument -> FixBody -> m Term
wfFix Deferred (FixBody ident argBinders Nothing Nothing rhs)
= pure $ App1 (Qualid deferredFixN) $ Fun (mkBinder Explicit (Ident ident) NEL.<| argBinders ) rhs
where
deferredFixN = qualidMapBase (<> T.pack (show (NEL.length argBinders)))
"GHC.DeferredFix.deferredFix"
wfFix (WellFoundedTA order) (FixBody ident argBinders Nothing Nothing rhs)
= do (rel, measure) <- case order of
MeasureOrder_ measure Nothing -> pure ("Coq.Init.Peano.lt", measure)
MeasureOrder_ measure (Just rel) -> pure (rel, measure)
WFOrder_ rel arg -> pure (rel, Qualid arg)
pure . appList (Qualid wfFixN) $ map PosArg
[ rel
, Fun argBinders measure
, Underscore
, Fun (argBinders NEL.|> mkBinder Explicit (Ident ident)) rhs
]
where
wfFixN = qualidMapBase (<> T.pack (show (NEL.length argBinders)))
"GHC.Wf.wfFix"
wfFix Corecursive fb = pure . Cofix $ FixOne fb
wfFix StructOrderTA{} (FixBody ident _ _ _ _) = convUnsupportedIn
"well-founded recursion does not include structural recursion"
"fixpoint" (showP ident)
wfFix _ fb = convUnsupportedIn "well-founded recursion cannot handle annotations or types"
"fixpoint"
(showP $ fb^.fixBodyName)
--------------------------------------------------------------------------------
-- find the first name in a pattern binding
patBindName :: ConversionMonad r m => Pat GhcRn -> m Qualid
patBindName p = case p of
WildPat _ -> convUnsupported' ("no name in binding pattern")
GHC.VarPat NOEXTP (L _ hsName) -> var ExprNS hsName
LazyPat NOEXTP p -> lpatBindName p
GHC.AsPat NOEXTP (L _ hsName) _ -> var ExprNS hsName
ParPat NOEXTP p -> lpatBindName p
BangPat NOEXTP p -> lpatBindName p
#if __GLASGOW_HASKELL__ >= 806
ListPat _ (p:_) -> lpatBindName p
TuplePat _ (p:_) _ -> lpatBindName p
#else
ListPat (p:_) _ _ -> lpatBindName p
TuplePat (p:_) _ _ -> lpatBindName p
#endif
_ -> convUnsupported' ("Cannot find name in pattern: " ++ GHC.showSDocUnsafe (GHC.ppr p))
lpatBindName :: ConversionMonad r m => LPat GhcRn -> m Qualid
lpatBindName = patBindName . unLPat
unLPat :: LPat GhcRn -> Pat GhcRn
toLPat :: String -> Pat GhcRn -> LPat GhcRn
#if __GLASGOW_HASKELL__ == 808
unLPat = id
toLPat _ = id
#else
unLPat = unLoc
toLPat = mkGeneralLocated
#endif
hsBindName :: ConversionMonad r m => HsBind GhcRn -> m Qualid
hsBindName defn = case defn of
FunBind{fun_id = L _ hsName} -> var ExprNS hsName
PatBind{pat_lhs = p} -> lpatBindName p
_ -> convUnsupported' ( "non-function top level bindings: " ++ GHC.showSDocUnsafe (GHC.ppr defn))
-- | Warn and immediately return 'Nothing' for unsupported top-level bindings.
withHsBindName
:: ConversionMonad r m => HsBind GhcRn -> (Qualid -> m (Maybe a)) -> m (Maybe a)
withHsBindName b continue = case b of
FunBind{fun_id = L _ hsName} -> var ExprNS hsName >>= continue
PatBind{pat_lhs = p} ->
warnConvUnsupported' (getLoc p) "top-level pattern binding" $> Nothing
PatSynBind NOEXTP PSB{psb_id = i} ->
warnConvUnsupported' (getLoc i) "pattern synonym" $> Nothing
VarBind{} -> convUnsupported' "[internal] `VarBind' can't be a top-level binding"
AbsBinds{} -> convUnsupported' "[internal] `AbsBinds' can't be a top-level binding"
#if __GLASGOW_HASKELL__ >= 806
PatSynBind NOEXTP (XPatSynBind v) -> noExtCon v
XHsBindsLR v -> noExtCon v
#endif
-- This is where we switch from the global monad to the local monad
convertTypedModuleBinding :: ConversionMonad r m => Maybe Term -> HsBind GhcRn -> m (Maybe ConvertedBinding)
convertTypedModuleBinding ty defn =
withHsBindName defn $ \name ->
withCurrentDefinition name $ convertTypedBinding ty defn
convertTypedModuleBindings :: ConversionMonad r m
=> [LHsBind GhcRn]
-> Map Qualid Signature
-> (ConvertedBinding -> m a)
-> Maybe (HsBind GhcRn -> GhcException -> m a)
-> m [a]
convertTypedModuleBindings = convertMultipleBindings convertTypedModuleBinding
-- | A variant of convertTypedModuleBinding that ignores the name in the HsBind
-- and uses the provided one instead
--
-- It also does not allow skipping or axiomatization, does not create fixpoints,
-- does not support a type, and always returns a binding (or fails with
-- convUnsupported).
--
-- It does, however, support redefinition.
convertMethodBinding :: ConversionMonad r m => Qualid -> HsBind GhcRn -> m ConvertedBinding
convertMethodBinding name VarBind{} = convUnsupportedIn "[internal] `VarBind'" "method" (showP name)
convertMethodBinding name AbsBinds{} = convUnsupportedIn "[internal?] `AbsBinds'" "method" (showP name)
convertMethodBinding name PatSynBind{} = convUnsupportedIn "pattern synonym bindings" "method" (showP name)
convertMethodBinding name PatBind{} = convUnsupportedIn "pattern bindings" "method" (showP name)
convertMethodBinding name FunBind{..} = withCurrentDefinition name $ do
definitionTask name >>= \case
SkipIt ->
convUnsupported "skipping instance method definitions (without `skip method')"
RedefineIt def ->
pure $ RedefinedBinding name def
AxiomatizeIt _ ->
convUnsupported "axiomatizing instance method definitions"
TranslateIt -> do
defn <-
if all (null . m_pats . unLoc) . unLoc $ mg_alts fun_matches
then case unLoc $ mg_alts fun_matches of
[L _ (GHC.Match NOEXTP _ [] grhss)] -> convertGRHSs [] grhss patternFailure
_ -> convUnsupported "malformed multi-match variable definitions"
else do
skipEqns <- view $ edits.skippedEquations.at name.non mempty
uncurry Fun <$> convertFunction skipEqns fun_matches
pure $ ConvertedDefinitionBinding $ ConvertedDefinition name [] Nothing defn
#if __GLASGOW_HASKELL__ >= 806
convertMethodBinding _ (XHsBindsLR v) = noExtCon v
#endif
convertTypedBindings :: LocalConvMonad r m
=> [LHsBind GhcRn] -> Map Qualid Signature
-> (ConvertedBinding -> m a)
-> Maybe (HsBind GhcRn -> GhcException -> m a)
-> m [a]
convertTypedBindings = convertMultipleBindings convertTypedBinding
convertMultipleBindings :: ConversionMonad r m
=> (Maybe Term -> HsBind GhcRn -> m (Maybe ConvertedBinding))
-> [LHsBind GhcRn]
-> Map Qualid Signature
-> (ConvertedBinding -> m a)
-> Maybe (HsBind GhcRn -> GhcException -> m a)
-> m [a]
convertMultipleBindings convertSingleBinding defns0 sigs build mhandler =
let defns = sortOn getLoc defns0
(handler, wrap) = case mhandler of
Just handler -> ( uncurry handler
, \defn -> ghandle $ pure . Left . (defn,))
Nothing -> ( const $ throwProgramError
"INTERNAL ERROR: convertMultipleBindings tried to both handle and ignore an exception"
-- Safe because the only place `Left' is introduced
-- is in the previous case branch
, flip const )
in traverse (either handler build) <=< addRecursion <=< fmap catMaybes . for defns $ \(L _ defn) ->
-- 'MaybeT' is responsible for handling the skipped definitions, and
-- nothing else
runMaybeT . wrap defn . fmap Right $ do
ty <- case defn of
FunBind{fun_id = L _ hsName} ->
fmap (fmap sigType) . (`lookupSig` sigs) =<< var ExprNS hsName
_ ->
pure Nothing
MaybeT $ convertSingleBinding ty defn
-- ALMOST a 'ConvertedDefinition', but:
-- (a) It's guaranteed to have arguments; and
-- (b) We store two types: the result type AFTER the argument types
-- ('rdResultType'), and the full type including the argument types
-- ('rdFullType')
data RecDef = RecDef { rdName :: !Qualid
, rdArgs :: !Binders
, rdStruct :: !(Maybe Order)
, rdResultType :: !(Maybe Term)
, rdFullType :: !(Maybe Term)
, rdBody :: !Term }
deriving (Eq, Ord, Show, Read)
-- CURRENT IMPLEMENTATION: If we can't move the type to arguments, then:
-- * If it was translated, fail-safe, and translate without the type
-- * If it was specified, abort
-- We can't unilaterally abort unless we can change type signatures.
rdToFixBody :: RecDef -> FixBody
rdToFixBody RecDef{..} = FixBody rdName rdArgs rdStruct rdResultType rdBody
rdToLet :: RecDef -> Term -> Term
rdToLet RecDef{..} = Let rdName (toList rdArgs) rdResultType rdBody
rdStripResultType :: RecDef -> RecDef
rdStripResultType rd = rd{rdResultType = Nothing}
splitInlinesWith :: Foldable f => Set Qualid -> f RecDef -> Maybe (Map Qualid RecDef, NonEmpty RecDef)
splitInlinesWith inlines =
bitraverse (pure . fold) nonEmpty .: mapPartitionEithers $ \rd@RecDef{..} ->
if rdName `elem` inlines
then Left $ M.singleton rdName rd
else Right rd
data RecType = Standalone | Mutual deriving (Eq, Ord, Enum, Bounded, Show, Read)
mutualRecursionInlining :: ConversionMonad r m => NonEmpty RecDef -> m (Map Qualid (RecType, RecDef))
mutualRecursionInlining mutGroup = do
-- TODO: Names of recursive functions in inlining errors
inlines <- view $ edits.inlinedMutuals
(lets, recs) <- splitInlinesWith inlines mutGroup
& maybe (editFailure "can't inline every function in a mutually-recursive group") pure
let rdFVs = getFreeVars . rdBody
letUses = rdFVs <$> lets
letDeps = transitiveClosure Reflexive letUses
orderedLets <- for (topoSortEnvironmentWith id letUses) $ \case
solo :| [] -> pure solo
_ :| _:_ -> editFailure "recursion forbidden amongst inlined mutually-recursive functions"
let recMap = flip foldMap recs $ \rd ->
let neededLets = foldMap (M.findWithDefault mempty ?? letDeps) $ rdFVs rd
inlinedDeps = filter (`elem` neededLets) orderedLets
in M.singleton (rdName rd)
(Mutual, rd{rdBody = foldr (rdToLet . (lets M.!)) (rdBody rd) inlinedDeps})
pure $ ((Standalone,) <$> lets) <> recMap
addRecursion :: ConversionMonad r m => [Either e ConvertedBinding] -> m [Either e ConvertedBinding]
addRecursion eBindings = do
fixedBindings <- M.fromList . fmap (view convDefName &&& id) . foldMap toList
<$> traverse fixConnComp (stronglyConnCompNE
[ (cd, cd^.convDefName, S.toAscList . getFreeVars $ cd^.convDefBody)
| Right (ConvertedDefinitionBinding cd) <- eBindings ])
pure . topoSortByVariablesBy ErrOrVars M.empty . flip map eBindings $ \case
Right (ConvertedDefinitionBinding cd) -> case M.lookup (cd^.convDefName) fixedBindings of
Just cd' -> Right $ ConvertedDefinitionBinding cd'
Nothing -> error "INTERNAL ERROR: lost track of converted definition during mutual recursion check"
untouched ->
untouched
where
fixConnComp (cd :| []) | cd^.convDefName `notElem` getFreeVars (cd^.convDefBody) =
pure $ cd :| []
fixConnComp cds = do
(commonArgs, cds) <- splitArgs cds
tbodies <- for cds fixConvertedDefinition
let bodies = fst <$> tbodies
let nonstructural = listToMaybe [t | (_, Just t) <- toList tbodies, isNonstructural t]
isNonstructural (StructOrderTA _) = False
isNonstructural _ = True
let getInfo = fmap $ rdName &&& rdFullType
(fixFor, recInfos, extraDefs) <- case (nonstructural, bodies) of
(Just order, body1 :| []) -> do
fixed <- wfFix order . rdToFixBody $ rdStripResultType body1
pure (const fixed, getInfo bodies, [])
(Just _, _ :| _ : _) ->
convUnsupportedIn "non-structural mutual recursion" "definitions"
(explainStrItems (showP . rdName) "" "," "and" "" "" bodies)
(Nothing, body1 :| []) ->
pure (const . Fix . FixOne $ rdToFixBody body1, getInfo bodies, [])
(Nothing, _ :| _ : _) -> do
mutRecInfo <- mutualRecursionInlining bodies
let (recs', lets) = flip mapPartitionEithers cds $ \cd ->
case M.lookup (cd^.convDefName) mutRecInfo of
Just (Standalone, _) -> Right $ cd & convDefArgs %~ (commonArgs ++)
Just (Mutual, rd) -> Left rd
Nothing -> error "INTERNAL ERROR: lost track of mutually-recursive function"
recs = fromMaybe (error "INTERNAL ERROR: \
\all mutually-recursive functions in this group vanished!")
$ nonEmpty recs'
let fixFor = case recs of
body1 :| [] ->
const . Fix . FixOne $ rdToFixBody body1
body1 :| body2 : bodies' ->
Fix . FixMany (rdToFixBody body1) (rdToFixBody <$> (body2 :| bodies'))
pure (fixFor, getInfo recs, lets)
let recDefs = recInfos <&> \(name,mty) ->
ConvertedDefinition { _convDefName = name
, _convDefArgs = commonArgs
, _convDefType = mty
, _convDefBody = fixFor name }
pure $ recDefs ++> extraDefs
fixConvertedDefinition ::
ConversionMonad r m => ConvertedDefinition -> m (RecDef, Maybe TerminationArgument)
fixConvertedDefinition (ConvertedDefinition{_convDefBody = Fun args body, ..}) = do
let fullType = maybeForall _convDefArgs <$> _convDefType
allArgs = _convDefArgs <++ args
(resultType, convArgs') = case fullType of
Just ty | Right (ty', args', UTIBIsTypeTooShort False) <- useTypeInBinders ty allArgs ->
(Just ty', args')
_ -> (Nothing, allArgs)
termination <- view (edits.termination.at _convDefName)
struct <- case termination of
Just (StructOrderTA (StructId_ n)) -> (pure . Just) (StructOrder n)
Just (StructOrderTA (StructPos_ i)) ->
case args ^? elementOf (traverse . binderNames) (i - 1) of
Just (Ident name) -> (pure . Just) (StructOrder name)
Just UnderscoreName ->
throwProgramError ("error: function " ++ showP _convDefName ++ ": its " ++ show i ++ "-th argument is unnamed")
Nothing -> throwProgramError ("error: function " ++ showP _convDefName ++ " has fewer than " ++ show i ++ " arguments")
_ -> pure Nothing
let b = RecDef
{ rdName = _convDefName
, rdArgs = convArgs'
, rdStruct = struct
, rdResultType = resultType
, rdFullType = fullType
, rdBody = body }
pure (b, termination)
fixConvertedDefinition cd =
convUnsupportedIn "recursion through non-lambda value" "definition" (showP $ cd^.convDefName)
splitArgs :: (ConversionMonad r m, Traversable t) => t ConvertedDefinition -> m ([Binder], t ConvertedDefinition)
splitArgs cds = do
polyrec <- findM (\rd -> view $ edits.polyrecs.at (_convDefName rd)) cds
case polyrec of
Nothing -> pure (splitCommonPrefixOf convDefArgs cds)
Just _ -> pure ([], cds)
--------------------------------------------------------------------------------
convertLocalBinds :: LocalConvMonad r m => HsLocalBinds GhcRn -> m Term -> m Term
#if __GLASGOW_HASKELL__ >= 806
convertLocalBinds (XHsLocalBindsLR v) _ = noExtCon v
convertLocalBinds (HsValBinds _ (ValBinds{})) _ =
convUnsupported "Unexpected ValBinds in post-renamer AST"
convertLocalBinds (HsValBinds _ (XValBindsLR (NValBinds recBinds lsigs))) body = do
#else
convertLocalBinds (HsValBinds (ValBindsIn{})) _ =
convUnsupported "Unexpected ValBindsIn in post-renamer AST"
convertLocalBinds (HsValBinds (ValBindsOut recBinds lsigs)) body = do
#endif
sigs <- convertLSigs lsigs
-- We are not actually using the rec_flag from GHC, because due to renamings
-- or `redefinition` edits, maybe the group is no longer recursive.
convDefss <- for recBinds $ \(_rec_flag, mut_group) ->
convertTypedBindings (bagToList mut_group) sigs pure Nothing
let convDefs = concat convDefss
let fromConvertedBinding cb body = case cb of
ConvertedDefinitionBinding (ConvertedDefinition{..}) ->
pure (Let _convDefName _convDefArgs _convDefType _convDefBody body)
ConvertedPatternBinding pat term -> do
is_complete <- isCompleteMultiPattern [MultPattern [pat]]
pure $ Coq.Match [MatchItem term Nothing Nothing] Nothing $
[ Equation [MultPattern [pat]] body] ++
[ Equation [MultPattern [UnderscorePat]] patternFailure | not is_complete ]
ConvertedAxiomBinding ax _ty ->
convUnsupported $ "local axiom `" ++ T.unpack (qualidToIdent ax) ++ "' unsupported"
RedefinedBinding _nm _sn -> convUnsupported "redefining local bindings"
SkippedBinding _nm -> convUnsupported "skipping local binding"
(foldrM fromConvertedBinding ?? convDefs) =<< body
convertLocalBinds (HsIPBinds NOEXTP _) _ =
convUnsupported "local implicit parameter bindings"
convertLocalBinds (EmptyLocalBinds NOEXTP) body =
body
--------------------------------------------------------------------------------
-- Create `let x := rhs in genBody x`
-- Unless the rhs is very small, in which case it creates `genBody rhs`
bindIn :: LocalConvMonad r m => Text -> Term -> (Term -> m Term) -> m Term
bindIn _ rhs@(Qualid _) genBody = genBody rhs
bindIn tmpl rhs genBody = do
j <- genqid tmpl
body <- genBody (Qualid j)
pure $ smartLet j rhs body
-- This prevents the pattern conversion code to create
-- `let j_24__ := … in j_24__`
-- and a few other common and obviously stupid forms
--
-- Originally, we avoided pushing the `rhs` past a binder. But it turned out
-- that we need to do that to get useful termination proof obligations out of
-- program fixpoint. So now we move the `rhs` past a binder if that binder is fresh (i.e. cannot be captured).
-- Let’s cross our fingers that we calculate all free variables properly.
smartLet :: Qualid -> Term -> Term -> Term
-- Move into the else branch
smartLet ident rhs (If is c Nothing t e)
| ident `S.notMember` getFreeVars c
, ident `S.notMember` getFreeVars t
= If is c Nothing t (smartLet ident rhs e)
-- Move into the scrutinee
smartLet ident rhs
(Coq.Match [MatchItem t Nothing Nothing] Nothing eqns)
| ident `S.notMember` getFreeVars eqns
= Coq.Match [MatchItem (smartLet ident rhs t) Nothing Nothing] Nothing eqns
-- Move into the last equation
-- (only if not mentioned in any earlier equation and only if no matched
-- variables is caught)
smartLet ident rhs
(Coq.Match scruts Nothing eqns)
| ident `S.notMember` getFreeVars (fmap NoBinding scruts)
, let intoEqns [] = Just []
intoEqns [Equation pats body] = do
let bound = S.fromList $ foldMap definedBy pats
guard $ ident `S.notMember` bound
guard $ S.null $ bound `S.intersection` getFreeVars rhs
return [Equation pats (smartLet ident rhs body)]
intoEqns (e:es) = do
guard $ ident `S.notMember` getFreeVars e
(e:) <$> intoEqns es
, Just eqns' <- intoEqns eqns
= Coq.Match scruts Nothing eqns'
smartLet ident rhs (Qualid v) | ident == v = rhs
smartLet ident rhs body = Let ident [] Nothing rhs body
patternFailure :: Term
patternFailure = "GHC.Err.patternFailure"
missingValue :: Term
missingValue = "missingValue"
-- | Program does not work nicely with if-then-else, so if we believe we are
-- producing a term that ends up in a Program Fixpoint or Program Definition,
-- then desguar if-then-else using case statements.
ifThenElse :: LocalConvMonad r m => m (IfStyle -> Term -> Term -> Term -> Term)
ifThenElse = useProgramHere >>= \case
False -> pure $ evalConstScrut IfBool
True -> pure $ evalConstScrut IfCase
where
-- Reduce `if true` and `if false`
evalConstScrut :: (IfStyle -> Term -> Term -> Term -> Term)
-> (IfStyle -> Term -> Term -> Term -> Term)
evalConstScrut _ _ "true" e _ = e
evalConstScrut _ _ "false" _ e = e
evalConstScrut ifComb is scrut e1 e2 = ifComb is scrut e1 e2
| antalsz/hs-to-coq | src/lib/HsToCoq/ConvertHaskell/Expr.hs | mit | 60,967 | 0 | 30 | 15,791 | 15,896 | 7,928 | 7,968 | -1 | -1 |
module Handler.Quizcreator where
import Assets (unsignedProcentField, unsignedIntField, maybeInt,
maybeDouble, encodeExamAttributes, titleTextField,
noSpacesTextField, getAllExams)
import Data.Text (splitOn)
import Data.List.Split (chunksOf)
import Data.List (cycle)
import Import
import Widgets (titleWidget, iconWidget, publicExamWidget, postWidget,
errorWidget, spacingScript, privateExamWidget)
-- | Checks if exam attributes have already been submitted
-- If so, proceed to question input
-- If not, let the user submit them
getQuizcreatorR :: Handler Html
getQuizcreatorR = do
setUltDestCurrent
memail <- lookupSession "_ID"
(publicExams, privateExams) <- runDB $ getAllExams memail
mayAttributes <- lookupSession "examAttributes"
let generatePost = case mayAttributes of
(Just text) -> generateFormPost $ examForm $ toExamAttributes text
_ -> generateFormPost $ examAttributesMForm
(widget, enctype) <- generatePost
let middleWidget = postWidget enctype widget
defaultLayout $(widgetFile "quizcreator")
-- | Checks if exam attributes have already been submitted
-- If so, checks if questions have been submitted correctly and saves the exam in that case (shows error otherwise)
-- If not, submits entered input and redirects to question input
postQuizcreatorR :: Handler Html
postQuizcreatorR = do
mayAttributes <- lookupSession "examAttributes"
memail <- lookupSession "_ID"
(publicExams, privateExams) <- runDB $ getAllExams memail
case mayAttributes of
(Just text) -> do ((res, _), _) <- runFormPost $ examForm $ toExamAttributes text
case res of
(FormSuccess exam) -> do
deleteSession "examAttributes"
_ <- runDB $ insert $ exam memail
redirect HomeR
(_) -> do
let middleWidget = errorWidget "Exam parsing"
defaultLayout $ do $(widgetFile "quizcreator")
(_) -> do ((res, _), _) <- runFormPost examAttributesMForm
case res of
(FormSuccess (ExamAttributes title percent qCount)) -> do
setSession "examAttributes" $ encodeExamAttributes title percent qCount
redirect QuizcreatorR
(_) -> do
deleteSession "examAttributes"
redirect QuizcreatorR
-- | Generates enumerated exam form based on previously submitted exam attributes
examForm :: ExamAttributes -> Html -> MForm Handler ((FormResult (Maybe Text -> Exam)), Widget)
examForm (ExamAttributes title passPercentage questCount) token = do
qTextFields <- replicateM questCount (mreq noSpacesTextField "" Nothing)
aTextFields <- replicateM (4 * questCount) (mreq noSpacesTextField "" Nothing)
aBoolFields <- replicateM (4 * questCount) (mreq boolField "" (Just False))
let (qTextResults, qTextViews) = unzip qTextFields
(aTextResults, aTextViews) = unzip aTextFields
(aBoolResults, aBoolViews) = unzip aBoolFields
answerResList = zipWith (\(FormSuccess x) (FormSuccess y) -> Answer x y) aTextResults aBoolResults
questions = FormSuccess $ zipWith (\(FormSuccess q) as -> Question q as) qTextResults (chunksOf 4 answerResList)
exam = Exam title passPercentage <$> questions
answerViews = zipWith3 zip3 (chunksOf 4 aTextViews) (chunksOf 4 aBoolViews) (cycle [[1..4::Int]])
questionViews = zip3 qTextViews answerViews ([1..]::[Int])
widget = [whamlet|
#{token}
<table class=questCreator>
$forall (qView, aList,n) <- questionViews
<tr>
<td class=questionTD>_{MsgQuestion 1} _{MsgNr}. #{show n}:
<td style="color:black"> ^{fvInput qView}
$forall (tview, bview, c) <- aList
<tr>
<td class=smallWhite>_{MsgAnswer 1} _{MsgNr}.#{show c}:
<td style="color:black;"> ^{fvInput tview}
<td class=smallWhite>_{MsgIsCorrect}
<td class=smallWhite>^{fvInput bview}
<td>
<tr>
<td style="text-align:left;">
<a class=questionTD href=@{SessionMasterR}> _{MsgGetBack}
<td>
<td colspan=2 style="text-align:right;"><input type=submit value="_{MsgSubmitQuest questCount}">
|]
return (exam, widget)
-- | Generates exam attributes form
examAttributesMForm :: Html -> MForm Handler ((FormResult ExamAttributes), Widget)
examAttributesMForm token = do
(eTitleResult, eTitleView) <- mreq (titleTextField MsgExamTitle) "" Nothing
(ePassResult, ePassView) <- mreq (unsignedProcentField MsgInputNeg) "" (Just 50.0)
(eCountResult, eCountView) <- mreq (unsignedIntField MsgInputNeg)"" (Just 5)
let examAttributes = ExamAttributes <$> eTitleResult <*> ePassResult <*> eCountResult
widget = [whamlet|
#{token}
<table class=questCreator>
<tr>
<td class=smallWhite> _{MsgExamTitle}:
<td style="color:black"> ^{fvInput eTitleView}
<td class=smallWhite style="text-align:left;"> _{MsgErrExamTitle}
<tr>
<td class=smallWhite> _{MsgPassPercentage}:
<td span style="color:black"> ^{fvInput ePassView}
<td class=smallWhite style="text-align:left;"> _{MsgErrPassPercentage}
<tr>
<td class=smallWhite> _{MsgQuestionNum}:
<td span style="color:black"> ^{fvInput eCountView}
<td class=smallWhite style="text-align:left;"> _{MsgErrQuestionNum}
<tr>
<td>
<td style="text-align:right;"><input type=submit value="_{MsgStartExam}">
|]
return (examAttributes, widget)
-- | Reads exam attributes from cookie
toExamAttributes :: Text -> ExamAttributes
toExamAttributes ((splitOn "($)") -> [a, b, c]) = let (Just passPercentage) = maybeDouble $ unpack b
(Just questCount) = maybeInt $ unpack c
title = (unwords . words) a in
ExamAttributes title passPercentage questCount
toExamAttributes _ = ExamAttributes msg 0.0 0
where msg = "Error in cookie" :: Text
data ExamAttributes = ExamAttributes {
title :: Text
, passPercentage :: Double
, questCount :: Int
}
| cirquit/quizlearner | quizlearner/Handler/Quizcreator.hs | mit | 7,317 | 0 | 22 | 2,604 | 1,247 | 641 | 606 | -1 | -1 |
module Handler.Home where
import Import
import Data.Maybe
import Yesod.Auth
getHomeR :: Handler Html
getHomeR = do
loggedIn <- isJust <$> maybeAuthId
defaultLayout $ do
setTitle "Home - Word Guesser"
$(widgetFile "home")
| dphilipson/word_guesser_web | Handler/Home.hs | mit | 247 | 0 | 12 | 57 | 66 | 33 | 33 | 10 | 1 |
module Lexer where
import Text.Parsec.String (Parser)
import Text.Parsec.Language (emptyDef)
import Text.Parsec.Prim (many)
import qualified Text.Parsec.Token as Tok
lexer :: Tok.TokenParser ()
lexer = Tok.makeTokenParser style
where
ops = ["+","*","-","/",";","=",",","<",">","|",":"]
names = ["def","extern","if","then","else","in","for"
,"binary", "unary", "var"]
style = emptyDef {
Tok.commentLine = "#"
, Tok.reservedOpNames = ops
, Tok.reservedNames = names
}
integer = Tok.integer lexer
float = Tok.float lexer
parens = Tok.parens lexer
commaSep = Tok.commaSep lexer
semiSep = Tok.semiSep lexer
identifier = Tok.identifier lexer
whitespace = Tok.whiteSpace lexer
reserved = Tok.reserved lexer
reservedOp = Tok.reservedOp lexer
operator :: Parser String
operator = do
c <- Tok.opStart emptyDef
cs <- many $ Tok.opLetter emptyDef
return (c:cs)
| TorosFanny/kaleidoscope | src/chapter6/Lexer.hs | mit | 959 | 0 | 10 | 216 | 318 | 180 | 138 | 28 | 1 |
module Main where
import LI11718
import qualified Tarefa3_2017li1g180 as T3
import System.Environment
import Text.Read
main = do
args <- getArgs
case args of
["movimenta"] -> do
str <- getContents
let params = readMaybe str
case params of
Nothing -> error "parâmetros inválidos"
Just (mapa,tempo,carro) -> print $ T3.movimenta mapa tempo carro
["testes"] -> print $ T3.testesT3
otherwise -> error "RunT3 argumentos inválidos" | hpacheco/HAAP | examples/plab/svn/2017li1g180/src/RunT3.hs | mit | 531 | 0 | 17 | 164 | 141 | 73 | 68 | 16 | 4 |
module Feature.Article.PG where
import ClassyPrelude
import Feature.Article.Types
import Feature.Auth.Types
import Feature.Common.Types
import Platform.PG
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.Types
addArticle :: PG r m => UserId -> CreateArticle -> Slug -> m ()
addArticle uId param slug =
void . withConn $ \conn -> execute conn qry
( slug, createArticleTitle param, createArticleDescription param
, createArticleBody param, uId, PGArray $ createArticleTagList param
)
where
qry = "insert into articles (slug, title, description, body, created_at, updated_at, author_id, tags) \
\values (?, ?, ?, ?, now(), now(), ?, ?)"
updateArticleBySlug :: PG r m => Slug -> UpdateArticle -> Slug -> m ()
updateArticleBySlug slug param newSlug =
void . withConn $ \conn -> execute conn qry (newSlug, updateArticleTitle param, updateArticleDescription param, updateArticleBody param, slug)
where
qry = "update articles \
\set slug = ?, title = coalesce(?, title), description = coalesce(?, description), \
\ body = coalesce(?, body), updated_at = now() \
\where slug = ?"
deleteArticleBySlug :: PG r m => Slug -> m ()
deleteArticleBySlug slug =
void . withConn $ \conn -> execute conn qry (Only slug)
where
qry = "delete from articles where slug = ?"
isArticleOwnedBy :: PG r m
=> UserId -> Slug -> m (Maybe Bool)
isArticleOwnedBy uId slug = do
result <- withConn $ \conn -> query conn qry (uId, slug)
case result of
[Only True] -> return $ Just True
[Only False] -> return $ Just False
_ -> return Nothing
where
qry = "select author_id = ? from articles where slug = ? limit 1"
favoriteArticleBySlug :: PG r m => UserId -> Slug -> m ()
favoriteArticleBySlug uId slug =
void . withConn $ \conn -> execute conn qry (uId, slug)
where
qry = "with cte as ( \
\ select id, ? from articles where slug = ? limit 1 \
\) \
\insert into favorites (article_id, favorited_by) (select * from cte) on conflict do nothing"
unfavoriteArticleBySlug :: PG r m => UserId -> Slug -> m ()
unfavoriteArticleBySlug uId slug =
void . withConn $ \conn -> execute conn qry (slug, uId)
where
qry = "with cte as ( \
\ select id from articles where slug = ? limit 1 \
\) \
\delete from favorites where article_id in (select id from cte) and favorited_by = ?"
findArticles :: PG r m
=> Maybe Slug -> Maybe Bool -> Maybe CurrentUser
-> ArticleFilter -> Pagination
-> m [Article]
findArticles maySlug mayFollowing mayCurrentUser articleFilter pagination =
withConn $ \conn -> query conn qry arg
where
qry = [sql|
with profiles as (
select
id, name, bio, image, exists(select 1 from followings where user_id = id and followed_by = ?) as following
from
users
),
formatted_articles as (
select
articles.id, slug, title, description, body, tags, created_at, updated_at,
exists(select 1 from favorites where article_id = articles.id and favorited_by = ?) as favorited,
(select count(1) from favorites where article_id = articles.id) as favorites_count,
profiles.name as pname, profiles.bio as pbio, profiles.image as pimage, profiles.following as pfollowing
from
articles join profiles on articles.author_id = profiles.id
)
select
cast (slug as text), title, description, body, cast (tags as text[]), created_at, updated_at,
favorited, favorites_count, cast (pname as text), pbio, pimage, pfollowing
from
formatted_articles
where
-- by slug (for find one)
coalesce(slug in ?, true) AND
-- by if user following author (for feed)
coalesce(pfollowing in ?, true) and
-- by tag (for normal filter)
(cast (tags as text[]) @> ?) and
-- by author (for normal filter)
coalesce (pname in ?, true) and
-- by fav by (for normal filter)
(? is null OR exists(
select 1
from favorites join users on users.id = favorites.favorited_by
where article_id = formatted_articles.id and users.name = ?)
)
order by id desc
limit greatest(0, ?) offset greatest(0, ?)
|]
curUserId = maybe (-1) snd mayCurrentUser
arg = ( curUserId, curUserId
-- ^ 2 slots for current user id
, In $ maybeToList maySlug
-- ^ 1 slot for slug
, In $ maybeToList $ mayFollowing
-- ^ 1 slot for following
, PGArray $ maybeToList $ articleFilterTag articleFilter
-- ^ 1 slot for tags
, In $ maybeToList $ articleFilterAuthor articleFilter
-- ^ 1 slot for author
, articleFilterFavoritedBy articleFilter, articleFilterFavoritedBy articleFilter
-- ^ 2 slots for favorited by user name
, paginationLimit pagination, paginationOffset pagination
-- ^ 2 slot for limit & offset
)
isArticleExist :: PG r m => Slug -> m Bool
isArticleExist slug = do
results <- withConn $ \conn -> query conn qry (Only slug)
return $ results == [Only True]
where
qry = "select true from articles where slug = ? limit 1"
allTags :: PG r m => m (Set Tag)
allTags = do
results <- withConn $ \conn -> query_ conn qry
return $ setFromList $ (\(Only tag) -> tag) <$> results
where
qry = "select cast(tag as text) from (select distinct unnest(tags) as tag from articles) tags"
| eckyputrady/haskell-scotty-realworld-example-app | src/Feature/Article/PG.hs | mit | 5,884 | 0 | 12 | 1,773 | 953 | 495 | 458 | -1 | -1 |
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.XAttrProtos.SetXAttrResponseProto (SetXAttrResponseProto(..)) 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 SetXAttrResponseProto = SetXAttrResponseProto{}
deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable SetXAttrResponseProto where
mergeAppend SetXAttrResponseProto SetXAttrResponseProto = SetXAttrResponseProto
instance P'.Default SetXAttrResponseProto where
defaultValue = SetXAttrResponseProto
instance P'.Wire SetXAttrResponseProto where
wireSize ft' self'@(SetXAttrResponseProto)
= case ft' of
10 -> calc'Size
11 -> P'.prependMessageSize calc'Size
_ -> P'.wireSizeErr ft' self'
where
calc'Size = 0
wirePut ft' self'@(SetXAttrResponseProto)
= case ft' of
10 -> put'Fields
11 -> do
P'.putSize (P'.wireSize 10 self')
put'Fields
_ -> P'.wirePutErr ft' self'
where
put'Fields
= do
Prelude'.return ()
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
_ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
instance P'.MessageAPI msg' (msg' -> SetXAttrResponseProto) SetXAttrResponseProto where
getVal m' f' = f' m'
instance P'.GPB SetXAttrResponseProto
instance P'.ReflectDescriptor SetXAttrResponseProto where
getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [])
reflectDescriptorInfo _
= Prelude'.read
"DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.hdfs.SetXAttrResponseProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"XAttrProtos\"], baseName = MName \"SetXAttrResponseProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"XAttrProtos\",\"SetXAttrResponseProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
instance P'.TextType SetXAttrResponseProto where
tellT = P'.tellSubMessage
getT = P'.getSubMessage
instance P'.TextMsg SetXAttrResponseProto where
textPut msg = Prelude'.return ()
textGet = Prelude'.return P'.defaultValue | alexbiehl/hoop | hadoop-protos/src/Hadoop/Protos/XAttrProtos/SetXAttrResponseProto.hs | mit | 2,810 | 1 | 16 | 531 | 554 | 291 | 263 | 53 | 0 |
-----------------------------------------------------------------------------
--
-- Module : SGC.Object.Internal.Generic
-- Copyright :
-- License : MIT
--
-- Maintainer :
-- Stability :
-- Portability :
--
-- |
--
-- {-# OPTIONS_GHC -fprint-explicit-kinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE GADTs #-}
module SGC.Object.Internal.Generic (
GenericObject(..), TMVar(..), GObject
, ObjectValuesList(..), ObjectKV(..)
, newGenericObject
, module Export
-- * Internal
, ObjectConstsCtx(..), ObjectVarsCtx(..), MkVarKeys, MkConstKeys -- TODO: hide on re-export
, gSubObject
-- , BuildSubObject(..)
) where
import SGC.Object.Definitions as Export
import SGC.Object.SomeObject as Export
import SGC.Object.Internal.TypeMap
import Data.Type.Bool
import Data.Proxy
import Data.Typeable -- (Typeable)
import Data.Maybe (fromJust)
import Control.Applicative ( (<|>) )
import TypeNum.TypeFunctions -- (type (++))
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
data GenericObject base (consts :: [*]) (vars :: [*]) = GenericObject{
objBase :: base,
objConsts :: TMap consts,
objVars :: TMap vars
}
type GObject base (consts :: [*]) (vars :: [*]) m =
GenericObject base (MkConstKeys consts) (MkVarKeys vars m)
type family MkConstKeys (cs :: [*]) :: [*] where
MkConstKeys '[] = '[]
MkConstKeys (c ': cs) = ContextMapKey ObjectConstsCtx c ': MkConstKeys cs
type family MkVarKeys (vs :: [*]) (m :: * -> *) :: [*] where
MkVarKeys '[] m = '[]
MkVarKeys (v ': vs) m = ContextMapKey (ObjectVarsCtx m) v ': MkVarKeys vs m
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
infixl 5 :::
infixl 6 ::$
newGenericObject :: (ObjectValuesList2TMap consts, ObjectValuesList2TMap vars) =>
base
-> ObjectValuesList ObjectConstant consts
-> ObjectValuesList ObjectVariable vars
-> GenericObject base consts vars
newGenericObject base cs vs = GenericObject base (tMap cs) (tMap vs)
-----------------------------------------------------------------------------
data ObjectValueAccessType = ObjectConstant | ObjectVariable
data ObjectKV k = (::$) k (KeyValue k)
data ObjectValuesList (t :: ObjectValueAccessType) (kl :: [*]) :: * where
ObjectVals :: ObjectValuesList ObjectConstant '[]
ObjectVars :: ObjectValuesList ObjectVariable '[]
(:::) :: ObjectValuesList t kl -> ObjectKV k -> ObjectValuesList t (k ': kl)
-----------------------------------------------------------------------------
class ObjectValuesList2TMap (kl :: [*]) where
tMap :: ObjectValuesList t kl -> TMap kl
instance ObjectValuesList2TMap '[] where tMap _ = tmEmpty
instance ( TMChange ks k ~ TypeMapGrowth, ObjectKey k
, TMKeyType k ~ TypeMapKeyUser
, ObjectValuesList2TMap ks
) =>
ObjectValuesList2TMap (k ': ks) where
tMap (t ::: (k ::$ v)) = tmUpdate (tMap t) k (TMSetValue v)
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
type instance HasConst' (GenericObject base consts vars) c =
TMContains consts (ContextMapKey ObjectConstsCtx c)
type instance HasVar' (GenericObject base consts vars) v m =
TMContains vars (ContextMapKey (ObjectVarsCtx m) v)
-----------------------------------------------------------------------------
data TMVar m v = TMVar {
tmVarRead :: m v
, tmVarWrite :: v -> m ()
, tmVarUpdate :: (v -> v) -> m ()
}
-----------------------------------------------------------------------------
newtype Id a = Id a
fromId (Id x) = x
instance Functor Id where fmap f = Id . f . fromId
instance Applicative Id where pure = Id
(<*>) f = Id . fromId f . fromId
instance Monad Id where (>>=) x = ($ fromId x)
-----------------------------------------------------------------------------
data ObjectConstsCtx = ObjectConstsCtx
data ObjectVarsCtx (m :: * -> *) = ObjectVarsCtx
instance (TypeMap tm) => TypeMapContext ObjectConstsCtx tm where
type CtxKeyValue ObjectConstsCtx = Id
instance (TypeMap tm, Typeable m) =>
TypeMapContext (ObjectVarsCtx m) tm where
type CtxKeyValue (ObjectVarsCtx m) = m
instance ( ObjectKey c, TypeMap cs
, HasConst (GenericObject base cs vs) c
) =>
ObjectConst (GenericObject base cs vs) c
where getConst v = fromId . flip (tmCtxGet ObjectConstsCtx) v . objConsts
instance ( ObjectKey v, Monad m, Typeable m, TypeMap vs
, HasVar (GenericObject base cs vs) v m
) =>
ObjectVar (GenericObject base cs vs) v m where
readVar = withVar tmVarRead
writeVar k v = withVar (`tmVarWrite` v) k
updateVar k f = withVar (`tmVarUpdate` f) k
withVar :: ( ObjectKey k, Typeable m, TypeMap vs ) =>
(TMVar m (KeyValue k) -> m b) -> k -> GenericObject base cs vs -> m b
withVar f k obj = f $ tmCtxGet ObjectVarsCtx (objVars obj) k
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
instance (TypeMap cs, TypeMap vs) =>
CreateSomeObject (GenericObject base cs vs) base where
someObject obj = SomeObject obj objBase
-----------------------------------------------------------------------------
instance (TypeMap cs) => ObjectMayHaveConst (GenericObject base cs vs) where
tryGetConst c = fmap fromId . flip (tmCtxFind ObjectConstsCtx) c . objConsts
instance (TypeMap cs, TypeMap vs, Monad m, Typeable m) =>
ObjectMayHave (GenericObject base cs vs) m where
tryReadVar = withVar' tmVarRead
tryWriteVar k v = withVar' (`tmVarWrite` v) k
tryUpdateVar k v = withVar' (`tmVarUpdate` v) k
tryReadValue k o = fmap return (tryGetConst k o) <|> tryReadVar k o
withVar' :: ( ObjectKey k, Typeable m, TypeMap vs ) =>
(TMVar m (KeyValue k) -> m b) -> k -> GenericObject base cs vs -> Maybe (m b)
withVar' f k obj = f <$> tmCtxFind ObjectVarsCtx (objVars obj) k
-----------------------------------------------------------------------------
-- subObject :: ( TypeSubMap (MkConstKeys cs'), TypeSubMap (MkVarKeys vs' m)
-- , TypeMap cs, TypeMap vs
-- ) =>
-- Proxy cs' -> Proxy vs' -> Proxy m
-- -> GenericObject base cs vs
-- -> Maybe (SomeObject NoCtx m '[ Has Consts (MkConstKeys cs')
-- , Has Vars (MkVarKeys vs' m)])
-- subObject cs' vs' m' obj = someObject <$> subObject' cs' vs' m' obj
-- cs <- subTMap (proxyMkConstKeys cs') $ objConsts obj
-- vs <- subTMap (proxyMkVarKeys m' vs') $ objVars obj
-- return . someObject $ GenericObject (objBase obj) cs vs
--
-- subObject' :: ( TypeSubMap (MkConstKeys cs'), TypeSubMap (MkVarKeys vs' m)
-- , TypeMap cs, TypeMap vs
-- , obj ~ GenericObject base (MkConstKeys cs') (MkVarKeys vs' m)
-- -- , MergeConstraints' ( ValueForEach Consts obj (MkConstKeys cs') m ++
-- -- ValueForEach Vars obj (MkVarKeys vs' m) m)
-- -- ()
-- ) =>
-- Proxy cs' -> Proxy vs' -> Proxy m
-- -> GenericObject base cs vs
-- -> Maybe obj
--
-- subObject' cs' vs' m' obj = undefined
gSubObject :: ( TypeSubMap (MkConstKeys cs')
, TypeSubMap (MkVarKeys vs' m)
, TypeMap cs, TypeMap vs
, obj ~ GenericObject base (MkConstKeys cs') (MkVarKeys vs' m)
-- , MergeConstraints' (ValueForEach Consts obj (MkConstKeys cs') m) ()
-- , MergeConstraints' (ValueForEach Vars obj (MkVarKeys vs' m) m) ()
, ObjectHas obj m Consts cs', ObjectHas obj m Vars vs'
) =>
Proxy cs' -> Proxy vs' -> Proxy m
-> GenericObject base cs vs
-> Maybe obj -- (GenericObject base (MkConstKeys cs') (MkVarKeys vs' m)) -- (GObject base cs' vs' m)
gSubObject cs' vs' m' obj = do
cs <- subTMap (proxyMkConstKeys cs') $ objConsts obj
vs <- subTMap (proxyMkVarKeys m' vs') $ objVars obj
return $ GenericObject (objBase obj) cs undefined
proxyMkConstKeys :: Proxy (xs :: [*]) -> Proxy (MkConstKeys xs)
proxyMkVarKeys :: Proxy (m :: * -> *) -> Proxy (xs :: [*]) -> Proxy (MkVarKeys xs m)
proxyMkConstKeys = const Proxy
proxyMkVarKeys _ = const Proxy
-----------------------------------------------------------------------------
-- class BuildSubObject (cs' :: [*]) (vs' :: [*]) (m :: * -> *) obj' obj where
-- buildSubObject :: Proxy cs' -> Proxy vs' -> Proxy m -> obj' -> Maybe obj
--
-- instance (ObjectHas obj m Consts cs', ObjectHas obj m Vars vs') =>
-- BuildSubObject cs' vs' m obj' obj where
class BuildSomeObject baseC (has :: [(ObjectValueType, [*])]) (m :: * -> *) where
buildSomeObject :: ( baseC base, TypeMap cs, TypeMap vs ) =>
GenericObject base cs vs
-> Proxy has -> Proxy m
-> SomeObject baseC m has'
-> Maybe (SomeObject baseC m (has' ++ has))
-- instance BuildSomeObject baseC '[] m where
-- buildSomeObject obj _ _ = Just $ someObject obj
--
-- instance BuildSomeObject baseC ('(t, ks) ': hasMore) m where
--
--
-- class BuildSomeObject' baseC (t :: ObjectValueType) (ks :: [*]) (m :: * -> *) where
-- buildSomeObject' :: () =>
-- GenericObject base cs vs
-- -> t -> Proxy ks -> Proxy m
-- -> Maybe (SomeObject baseC m has)
-- uniteSomeObjects :: SomeObject baseC m x -> SomeObject baseC m y
-- -> SomeObject baseC m (x ++ y)
-- uniteSomeObjects (SomeObject x get) (SomeObject y _) =
-- SomeObject (fromJust $ cast x) get
-----------------------------------------------------------------------------
| fehu/hsgc | SGC/Object/Internal/Generic.hs | mit | 10,150 | 20 | 16 | 2,270 | 2,255 | 1,242 | 1,013 | -1 | -1 |
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
{-|
Handles the "Language.LSP.Types.TextDocumentDidChange" \/
"Language.LSP.Types.TextDocumentDidOpen" \/
"Language.LSP.Types.TextDocumentDidClose" messages to keep an in-memory
`filesystem` of the current client workspace. The server can access and edit
files in the client workspace by operating on the "VFS" in "LspFuncs".
-}
module Language.LSP.VFS
(
VFS(..)
, VirtualFile(..)
, virtualFileText
, virtualFileVersion
-- * Managing the VFS
, initVFS
, openVFS
, changeFromClientVFS
, changeFromServerVFS
, persistFileVFS
, closeVFS
, updateVFS
-- * manipulating the file contents
, rangeLinesFromVfs
, PosPrefixInfo(..)
, getCompletionPrefix
-- * for tests
, applyChanges
, applyChange
, changeChars
) where
import Control.Lens hiding ( parts )
import Control.Monad
import Data.Char (isUpper, isAlphaNum)
import Data.Text ( Text )
import qualified Data.Text as T
import Data.List
import Data.Ord
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Rope.UTF16 ( Rope )
import qualified Data.Rope.UTF16 as Rope
import qualified Language.LSP.Types as J
import qualified Language.LSP.Types.Lens as J
import System.FilePath
import Data.Hashable
import System.Directory
import System.IO
import System.IO.Temp
import System.Log.Logger
-- ---------------------------------------------------------------------
{-# ANN module ("hlint: ignore Eta reduce" :: String) #-}
{-# ANN module ("hlint: ignore Redundant do" :: String) #-}
-- ---------------------------------------------------------------------
data VirtualFile =
VirtualFile {
_lsp_version :: !Int -- ^ The LSP version of the document
, _file_version :: !Int -- ^ This number is only incremented whilst the file
-- remains in the map.
, _text :: !Rope -- ^ The full contents of the document
} deriving (Show)
type VFSMap = Map.Map J.NormalizedUri VirtualFile
data VFS = VFS { vfsMap :: !(Map.Map J.NormalizedUri VirtualFile)
, vfsTempDir :: !FilePath -- ^ This is where all the temporary files will be written to
} deriving Show
---
virtualFileText :: VirtualFile -> Text
virtualFileText vf = Rope.toText (_text vf)
virtualFileVersion :: VirtualFile -> Int
virtualFileVersion vf = _lsp_version vf
---
initVFS :: (VFS -> IO r) -> IO r
initVFS k = withSystemTempDirectory "haskell-lsp" $ \temp_dir -> k (VFS mempty temp_dir)
-- ---------------------------------------------------------------------
-- | Applies the changes from a 'J.DidOpenTextDocument' to the 'VFS'
openVFS :: VFS -> J.Message 'J.TextDocumentDidOpen -> (VFS, [String])
openVFS vfs (J.NotificationMessage _ _ params) =
let J.DidOpenTextDocumentParams
(J.TextDocumentItem uri _ version text) = params
in (updateVFS (Map.insert (J.toNormalizedUri uri) (VirtualFile version 0 (Rope.fromText text))) vfs
, [])
-- ---------------------------------------------------------------------
-- ^ Applies a 'DidChangeTextDocumentNotification' to the 'VFS'
changeFromClientVFS :: VFS -> J.Message 'J.TextDocumentDidChange -> (VFS,[String])
changeFromClientVFS vfs (J.NotificationMessage _ _ params) =
let
J.DidChangeTextDocumentParams vid (J.List changes) = params
J.VersionedTextDocumentIdentifier (J.toNormalizedUri -> uri) version = vid
in
case Map.lookup uri (vfsMap vfs) of
Just (VirtualFile _ file_ver str) ->
let str' = applyChanges str changes
-- the client shouldn't be sending over a null version, only the server.
in (updateVFS (Map.insert uri (VirtualFile (fromMaybe 0 version) (file_ver + 1) str')) vfs, [])
Nothing ->
-- logs $ "haskell-lsp:changeVfs:can't find uri:" ++ show uri
-- return vfs
(vfs, ["haskell-lsp:changeVfs:can't find uri:" ++ show uri])
updateVFS :: (VFSMap -> VFSMap) -> VFS -> VFS
updateVFS f vfs@VFS{vfsMap} = vfs { vfsMap = f vfsMap }
-- ---------------------------------------------------------------------
applyCreateFile :: J.CreateFile -> VFS -> VFS
applyCreateFile (J.CreateFile uri options _ann) =
updateVFS $ Map.insertWith
(\ new old -> if shouldOverwrite then new else old)
(J.toNormalizedUri uri)
(VirtualFile 0 0 (Rope.fromText ""))
where
shouldOverwrite :: Bool
shouldOverwrite = case options of
Nothing -> False -- default
Just (J.CreateFileOptions Nothing Nothing ) -> False -- default
Just (J.CreateFileOptions Nothing (Just True) ) -> False -- `ignoreIfExists` is True
Just (J.CreateFileOptions Nothing (Just False)) -> True -- `ignoreIfExists` is False
Just (J.CreateFileOptions (Just True) Nothing ) -> True -- `overwrite` is True
Just (J.CreateFileOptions (Just True) (Just True) ) -> True -- `overwrite` wins over `ignoreIfExists`
Just (J.CreateFileOptions (Just True) (Just False)) -> True -- `overwrite` is True
Just (J.CreateFileOptions (Just False) Nothing ) -> False -- `overwrite` is False
Just (J.CreateFileOptions (Just False) (Just True) ) -> False -- `overwrite` is False
Just (J.CreateFileOptions (Just False) (Just False)) -> False -- `overwrite` wins over `ignoreIfExists`
applyRenameFile :: J.RenameFile -> VFS -> VFS
applyRenameFile (J.RenameFile oldUri' newUri' options _ann) vfs =
let oldUri = J.toNormalizedUri oldUri'
newUri = J.toNormalizedUri newUri'
in case Map.lookup oldUri (vfsMap vfs) of
-- nothing to rename
Nothing -> vfs
Just file -> case Map.lookup newUri (vfsMap vfs) of
-- the target does not exist, just move over
Nothing -> updateVFS (Map.insert newUri file . Map.delete oldUri) vfs
Just _ -> if shouldOverwrite
then updateVFS (Map.insert newUri file . Map.delete oldUri) vfs
else vfs
where
shouldOverwrite :: Bool
shouldOverwrite = case options of
Nothing -> False -- default
Just (J.RenameFileOptions Nothing Nothing ) -> False -- default
Just (J.RenameFileOptions Nothing (Just True) ) -> False -- `ignoreIfExists` is True
Just (J.RenameFileOptions Nothing (Just False)) -> True -- `ignoreIfExists` is False
Just (J.RenameFileOptions (Just True) Nothing ) -> True -- `overwrite` is True
Just (J.RenameFileOptions (Just True) (Just True) ) -> True -- `overwrite` wins over `ignoreIfExists`
Just (J.RenameFileOptions (Just True) (Just False)) -> True -- `overwrite` is True
Just (J.RenameFileOptions (Just False) Nothing ) -> False -- `overwrite` is False
Just (J.RenameFileOptions (Just False) (Just True) ) -> False -- `overwrite` is False
Just (J.RenameFileOptions (Just False) (Just False)) -> False -- `overwrite` wins over `ignoreIfExists`
-- NOTE: we are ignoring the `recursive` option here because we don't know which file is a directory
applyDeleteFile :: J.DeleteFile -> VFS -> VFS
applyDeleteFile (J.DeleteFile uri _options _ann) =
updateVFS $ Map.delete (J.toNormalizedUri uri)
applyTextDocumentEdit :: J.TextDocumentEdit -> VFS -> IO VFS
applyTextDocumentEdit (J.TextDocumentEdit vid (J.List edits)) vfs = do
-- all edits are supposed to be applied at once
-- so apply from bottom up so they don't affect others
let sortedEdits = sortOn (Down . editRange) edits
changeEvents = map editToChangeEvent sortedEdits
ps = J.DidChangeTextDocumentParams vid (J.List changeEvents)
notif = J.NotificationMessage "" J.STextDocumentDidChange ps
let (vfs',ls) = changeFromClientVFS vfs notif
mapM_ (debugM "haskell-lsp.applyTextDocumentEdit") ls
return vfs'
where
editRange :: J.TextEdit J.|? J.AnnotatedTextEdit -> J.Range
editRange (J.InR e) = e ^. J.range
editRange (J.InL e) = e ^. J.range
editToChangeEvent :: J.TextEdit J.|? J.AnnotatedTextEdit -> J.TextDocumentContentChangeEvent
editToChangeEvent (J.InR e) = J.TextDocumentContentChangeEvent (Just $ e ^. J.range) Nothing (e ^. J.newText)
editToChangeEvent (J.InL e) = J.TextDocumentContentChangeEvent (Just $ e ^. J.range) Nothing (e ^. J.newText)
applyDocumentChange :: J.DocumentChange -> VFS -> IO VFS
applyDocumentChange (J.InL change) = applyTextDocumentEdit change
applyDocumentChange (J.InR (J.InL change)) = return . applyCreateFile change
applyDocumentChange (J.InR (J.InR (J.InL change))) = return . applyRenameFile change
applyDocumentChange (J.InR (J.InR (J.InR change))) = return . applyDeleteFile change
-- ^ Applies the changes from a 'ApplyWorkspaceEditRequest' to the 'VFS'
changeFromServerVFS :: VFS -> J.Message 'J.WorkspaceApplyEdit -> IO VFS
changeFromServerVFS initVfs (J.RequestMessage _ _ _ params) = do
let J.ApplyWorkspaceEditParams _label edit = params
J.WorkspaceEdit mChanges mDocChanges _anns = edit
case mDocChanges of
Just (J.List docChanges) -> applyDocumentChanges docChanges
Nothing -> case mChanges of
Just cs -> applyDocumentChanges $ map J.InL $ HashMap.foldlWithKey' changeToTextDocumentEdit [] cs
Nothing -> do
debugM "haskell-lsp.changeVfs" "No changes"
return initVfs
where
changeToTextDocumentEdit acc uri edits =
acc ++ [J.TextDocumentEdit (J.VersionedTextDocumentIdentifier uri (Just 0)) (fmap J.InL edits)]
applyDocumentChanges :: [J.DocumentChange] -> IO VFS
applyDocumentChanges = foldM (flip applyDocumentChange) initVfs . sortOn project
-- for sorting [DocumentChange]
project :: J.DocumentChange -> J.TextDocumentVersion -- type TextDocumentVersion = Maybe Int
project (J.InL textDocumentEdit) = textDocumentEdit ^. J.textDocument . J.version
project _ = Nothing
-- ---------------------------------------------------------------------
virtualFileName :: FilePath -> J.NormalizedUri -> VirtualFile -> FilePath
virtualFileName prefix uri (VirtualFile _ file_ver _) =
let uri_raw = J.fromNormalizedUri uri
basename = maybe "" takeFileName (J.uriToFilePath uri_raw)
-- Given a length and a version number, pad the version number to
-- the given n. Does nothing if the version number string is longer
-- than the given length.
padLeft :: Int -> Int -> String
padLeft n num =
let numString = show num
in replicate (n - length numString) '0' ++ numString
in prefix </> basename ++ "-" ++ padLeft 5 file_ver ++ "-" ++ show (hash uri_raw) ++ ".hs"
-- | Write a virtual file to a temporary file if it exists in the VFS.
persistFileVFS :: VFS -> J.NormalizedUri -> Maybe (FilePath, IO ())
persistFileVFS vfs uri =
case Map.lookup uri (vfsMap vfs) of
Nothing -> Nothing
Just vf ->
let tfn = virtualFileName (vfsTempDir vfs) uri vf
action = do
exists <- doesFileExist tfn
unless exists $ do
let contents = Rope.toString (_text vf)
writeRaw h = do
-- We honour original file line endings
hSetNewlineMode h noNewlineTranslation
hSetEncoding h utf8
hPutStr h contents
debugM "haskell-lsp.persistFileVFS" $ "Writing virtual file: "
++ "uri = " ++ show uri ++ ", virtual file = " ++ show tfn
withFile tfn WriteMode writeRaw
in Just (tfn, action)
-- ---------------------------------------------------------------------
closeVFS :: VFS -> J.Message 'J.TextDocumentDidClose -> (VFS, [String])
closeVFS vfs (J.NotificationMessage _ _ params) =
let J.DidCloseTextDocumentParams (J.TextDocumentIdentifier uri) = params
in (updateVFS (Map.delete (J.toNormalizedUri uri)) vfs,["Closed: " ++ show uri])
-- ---------------------------------------------------------------------
{-
data TextDocumentContentChangeEvent =
TextDocumentContentChangeEvent
{ _range :: Maybe Range
, _rangeLength :: Maybe Int
, _text :: String
} deriving (Read,Show,Eq)
-}
-- | Apply the list of changes.
-- Changes should be applied in the order that they are
-- received from the client.
applyChanges :: Rope -> [J.TextDocumentContentChangeEvent] -> Rope
applyChanges = foldl' applyChange
-- ---------------------------------------------------------------------
applyChange :: Rope -> J.TextDocumentContentChangeEvent -> Rope
applyChange _ (J.TextDocumentContentChangeEvent Nothing Nothing str)
= Rope.fromText str
applyChange str (J.TextDocumentContentChangeEvent (Just (J.Range (J.Position sl sc) _to)) (Just len) txt)
= changeChars str start len txt
where
start = Rope.rowColumnCodeUnits (Rope.RowColumn sl sc) str
applyChange str (J.TextDocumentContentChangeEvent (Just (J.Range (J.Position sl sc) (J.Position el ec))) Nothing txt)
= changeChars str start len txt
where
start = Rope.rowColumnCodeUnits (Rope.RowColumn sl sc) str
end = Rope.rowColumnCodeUnits (Rope.RowColumn el ec) str
len = end - start
applyChange str (J.TextDocumentContentChangeEvent Nothing (Just _) _txt)
= str
-- ---------------------------------------------------------------------
changeChars :: Rope -> Int -> Int -> Text -> Rope
changeChars str start len new = mconcat [before, Rope.fromText new, after']
where
(before, after) = Rope.splitAt start str
after' = Rope.drop len after
-- ---------------------------------------------------------------------
-- TODO:AZ:move this to somewhere sane
-- | Describes the line at the current cursor position
data PosPrefixInfo = PosPrefixInfo
{ fullLine :: !T.Text
-- ^ The full contents of the line the cursor is at
, prefixModule :: !T.Text
-- ^ If any, the module name that was typed right before the cursor position.
-- For example, if the user has typed "Data.Maybe.from", then this property
-- will be "Data.Maybe"
, prefixText :: !T.Text
-- ^ The word right before the cursor position, after removing the module part.
-- For example if the user has typed "Data.Maybe.from",
-- then this property will be "from"
, cursorPos :: !J.Position
-- ^ The cursor position
} deriving (Show,Eq)
getCompletionPrefix :: (Monad m) => J.Position -> VirtualFile -> m (Maybe PosPrefixInfo)
getCompletionPrefix pos@(J.Position l c) (VirtualFile _ _ ropetext) =
return $ Just $ fromMaybe (PosPrefixInfo "" "" "" pos) $ do -- Maybe monad
let headMaybe [] = Nothing
headMaybe (x:_) = Just x
lastMaybe [] = Nothing
lastMaybe xs = Just $ last xs
curLine <- headMaybe $ T.lines $ Rope.toText
$ fst $ Rope.splitAtLine 1 $ snd $ Rope.splitAtLine l ropetext
let beforePos = T.take c curLine
curWord <-
if | T.null beforePos -> Just ""
| T.last beforePos == ' ' -> Just "" -- don't count abc as the curword in 'abc '
| otherwise -> lastMaybe (T.words beforePos)
let parts = T.split (=='.')
$ T.takeWhileEnd (\x -> isAlphaNum x || x `elem` ("._'"::String)) curWord
case reverse parts of
[] -> Nothing
(x:xs) -> do
let modParts = dropWhile (not . isUpper . T.head)
$ reverse $ filter (not .T.null) xs
modName = T.intercalate "." modParts
return $ PosPrefixInfo curLine modName x pos
-- ---------------------------------------------------------------------
rangeLinesFromVfs :: VirtualFile -> J.Range -> T.Text
rangeLinesFromVfs (VirtualFile _ _ ropetext) (J.Range (J.Position lf _cf) (J.Position lt _ct)) = r
where
(_ ,s1) = Rope.splitAtLine lf ropetext
(s2, _) = Rope.splitAtLine (lt - lf) s1
r = Rope.toText s2
-- ---------------------------------------------------------------------
| alanz/haskell-lsp | lsp-types/src/Language/LSP/VFS.hs | mit | 16,541 | 1 | 22 | 3,859 | 4,085 | 2,102 | 1,983 | -1 | -1 |
{- Copyright (C) 2014 Calvin Beck
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
{-# LANGUAGE OverloadedStrings #-}
module SurvivalPlot.Parser (parseDistributions, parseIntervals, Curve (..), TestInfo (..)) where
import Control.Applicative
import Data.Attoparsec.Text
data Curve = Curve { curvePoints :: [Double]
, tValue :: (Double,Double) -- Not really sure what to do for OUT_OF_RANGE
}
deriving (Show)
data TestInfo = TestInfo { concordance :: Double
, l1Loss :: Double
, l2Loss :: Double
, raeLoss :: Double
, l1LogLoss :: Double
, l2LogLoss :: Double
, logLikelihoodLoss :: Double
}
-- | MTLR Model data type
data Model = Model { numTimePoints :: Integer -- ^ Number of time points in the interval.
, timePoints :: [Double] -- ^ Time points in the interval.
, rForSomeReason :: Integer -- ^ I have no idea what is this even?
, dimension :: Integer -- ^ Number of features in the model.
, features :: [(Integer, Double)] -- ^ Feature, value pairs
}
-- | Parse a time intervals file.
parseIntervals :: Parser [Double]
parseIntervals = (many1 (double <* endOfLine)) <|> (do model <- parseModel; return (timePoints model))
-- | Parse an MTLR test distribution.
parseDistributions :: Parser ([Curve], TestInfo)
parseDistributions = do curves <- parseCurves
info <- parseTestInfo
endOfInput
return (curves, info)
-- | Parse PSSP model.
parseModel :: Parser Model
parseModel = do string "m:"
tps <- decimal
endOfLine'
timeInterval <- parseTimeInterval
endOfLine'
string "r:"
r <- decimal
endOfLine'
string "DIM:"
dim <- decimal
endOfLine'
feats <- many parseKeyWeight
many endOfLine'
endOfInput <?> "End of input not reached. Probably some bad padding at the end, or bad features."
return (Model tps timeInterval r dim feats)
-- | Parse the comma separated time points for the interval.
parseTimeInterval :: Parser [Double]
parseTimeInterval =
do point <- double
others <- (do char ',' *> parseTimeInterval) <|> (return [])
return (point : others)
-- | Parse a key:double pair for model weights.
parseKeyWeight :: Parser (Integer, Double)
parseKeyWeight = do key <- decimal
char ':'
value <- double
endOfLine'
return (key, value)
-- | Newline parser to handle all sorts of horrible.
endOfLine' :: Parser ()
endOfLine' = endOfLine <|> (char '\r' *> return ())
-- | Parse MTLR test error information.
parseTestInfo :: Parser TestInfo
parseTestInfo = do string "#concordance index: "
conc <- doubleInf
endOfLine
string "#avg l1-loss: "
l1 <- doubleInf
endOfLine
string "#avg l2-loss: "
l2 <- doubleInf
endOfLine
string "#avg rae-loss: "
rae <- doubleInf
endOfLine
string "#avg l1-log-loss: "
l1Log <- doubleInf
endOfLine
string "#avg l2-log-loss: "
l2Log <- doubleInf
endOfLine
string "#avg log-likelihood loss: "
logLikelihood <- doubleInf
endOfLine
return (TestInfo conc l1 l2 rae l1Log l2Log logLikelihood)
doubleInf :: Parser Double
doubleInf = double <|> (string "inf" *> (return 0))
-- | Parse all curves in a file.
parseCurves :: Parser [Curve]
parseCurves = many1 parseCurveLine
-- | Parse a single curve.
parseCurveLine :: Parser Curve
parseCurveLine = do points <- parsePoints
t <- parseTValue
return (Curve (drop 2 points) t)
-- | Get all points for a curve.
parsePoints :: Parser [Double]
parsePoints = do point <- double
otherPoints <- (char ',' *> skipSpace *> parsePoints) <|> return []
skipSpace
return (point:otherPoints)
-- | Parse the weird scary "t" values.
parseTValue :: Parser (Double,Double)
parseTValue = do string ", t:"
t1 <- double <|> (string "OUT_OF_RANGE" *> return 0)
char ':'
t2 <- double <|> (string "OUT_OF_RANGE" *> return 0)
endOfLine
return (t1, t2)
| Chobbes/SurvivalPlot | SurvivalPlot/Parser.hs | mit | 6,096 | 0 | 13 | 2,258 | 988 | 500 | 488 | 98 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Web.Scotty
-- Bare
main :: IO ()
main = scotty 3000 $ do
get "/" $ text "Hello Haskeller on Heroku with Stackage!"
| yogeshsajanikar/heroku-haskell-stackage-tutorial | src/Main.hs | mit | 180 | 0 | 9 | 36 | 46 | 24 | 22 | 6 | 1 |
module Main where
import qualified Data.Map as M
import Morse
import Test.QuickCheck
allowedChars :: String
allowedChars = M.keys letterToMorse
allowedMorse :: [Morse]
allowedMorse = M.elems letterToMorse
charGen :: Gen Char
charGen = elements allowedChars
morseGen :: Gen Morse
morseGen = elements allowedMorse
prop_thereAndBackAgain :: Property
prop_thereAndBackAgain =
forAll charGen
(\c -> (charToMorse c >>= morseToChar) == Just c)
main :: IO ()
main = quickCheck prop_thereAndBackAgain
| deciduously/Haskell-First-Principles-Exercises | 4-Getting real/14-Testing/code/morse/tests/tests.hs | mit | 536 | 0 | 11 | 110 | 143 | 78 | 65 | 18 | 1 |
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
module JsonSettings where
import Data.Yaml
import Data.Aeson
import qualified Data.ByteString.Lazy as BS
import Data.Functor
jsonSettingsMain :: IO ()
jsonSettingsMain = do
s <- either (error.show) id <$> decodeFileEither "gipeda.yaml"
let o = object [ "settings" .= (s :: Object) ]
BS.putStr (Data.Aeson.encode o)
| nomeata/gipeda | src/JsonSettings.hs | mit | 382 | 0 | 13 | 63 | 110 | 60 | 50 | 11 | 1 |
module GHCJS.DOM.SQLError (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/SQLError.hs | mit | 38 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
module Cenary.Crypto.Keccak where
import Crypto.Hash (Digest, Keccak_256, hash)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.Monoid ((<>))
import Text.Read (readMaybe)
keccak256 :: (Read b, Num b) => String -> Maybe b
keccak256 = readMaybe
. ("0x" <>)
. take 8
. show
. hash'
. BS8.pack
where
-- | Let's help out the compiler a little
hash' :: BS.ByteString -> Digest Keccak_256
hash' = hash
| yigitozkavci/ivy | src/Cenary/Crypto/Keccak.hs | mit | 540 | 0 | 10 | 165 | 145 | 86 | 59 | 15 | 1 |
module Main where
import Prelude hiding (getContents, putStr)
import Data.Fortran.Unformatted (fromUnformatted)
import Data.ByteString.Lazy (getContents, putStr)
import Control.Monad (liftM)
main :: IO ()
main = liftM fromUnformatted getContents >>= putStr
| albertov/funformatted | Main.hs | mit | 259 | 0 | 6 | 31 | 75 | 45 | 30 | 7 | 1 |
data Expr = Val Int | Div
eval :: Expr -> Int
eval (Val n) = n
eval (`Div` x y) = eval x / eval y
safediv :: Int -> Int -> Maybe Int
safediv n m = if m == 0 then
Nothing
else
Just (n / m) | ChristopherElliott/Portfolio | haskell/src/utility.hs | mit | 249 | 1 | 8 | 111 | 112 | 58 | 54 | -1 | -1 |
{-# LANGUAGE ViewPatterns #-}
module Data.MemoizingTable where
{--
Captures the idea that you get information on your data sets incrementally. So
you start with the known lookups, add the ones you don't know yet, refine those,
then add the refined lookups to the known sets.
--}
import Prelude hiding (init)
import Control.Arrow ((&&&))
import Control.Monad.State
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Tuple (swap)
-- Our memoizing table, partitioning what we know against what we do know
data MemoizingTable a b =
MT { fromTable :: Map a b, readIndex :: Map b a, newValues :: Set b }
deriving Show
type MemoizingState m a key val =
StateT (MemoizingTable key val, Map key [val]) m a
-- creates a new memoizing table
init :: Ord a => Ord b => (Map a b, Map b a) -> MemoizingTable a b
init = flip (uncurry MT) Set.empty
-- partitions a datum: do we know it? If not, add it to new information
-- for later processing
triage :: Ord a => Ord b => b -> MemoizingTable a b -> MemoizingTable a b
triage k (MT mapi mapk n00b) =
MT mapi mapk ((if containsKey k mapk then id else Set.insert k) n00b)
where containsKey k = Set.member k . Map.keysSet
-- triaging with state
type MemoizingS m a b c = StateT (MemoizingTable a b, Map a [b]) m c
triageM :: Monad m => Ord a => Ord b => a -> [b] -> MemoizingS m a b ()
triageM idx vals = get >>= \(mt0, reserve) ->
put ((foldr triage mt0 &&& flip (Map.insert idx) reserve) vals)
-- When we get indices for the new information, we update the memoizing table
update :: Ord a => Ord b => [(a,b)] -> MemoizingTable a b -> MemoizingTable a b
update (bifurcate -> (mi, mk)) (MT mi' mk' _) =
init (merge mi mi', merge mk mk')
where merge m1 = Map.fromList . (Map.toList m1 ++) . Map.toList
bifurcate :: Ord a => Ord b => [(a,b)] -> (Map a b, Map b a)
bifurcate = (Map.fromList &&& Map.fromList . map swap)
-- To start of a memoizing table from a single list:
start :: Ord a => Ord b => [(a, b)] -> MemoizingTable a b
start = init . bifurcate
| geophf/1HaskellADay | exercises/HAD/Data/MemoizingTable.hs | mit | 2,106 | 0 | 15 | 446 | 732 | 393 | 339 | -1 | -1 |
module Render.Setup where
import Data.IORef ( IORef, newIORef )
import Foreign ( newArray )
import Graphics.UI.GLUT hiding (Sphere, Plane)
import Geometry.Object
import Render.Antialias
data State = State { zoomFactor :: IORef GLfloat }
type Image = PixelData (Color3 GLfloat)
fstSphere :: Surface
fstSphere = Sphere 1 (-4, 0, -7) (Material (0.2, 0, 0) (1, 0, 0) (0, 0, 0) 0 0)
sndSphere :: Surface
sndSphere = Sphere 2 (0, 0, -7) (Material (0, 0.2, 0) (0, 0.5, 0) (0.5, 0.5, 0.5) 32 0)
thdSphere :: Surface
thdSphere = Sphere 1 (4, 0, -7) (Material (0, 0, 0.2) (0, 0, 1) (0, 0, 0) 0 0.8)
plane :: Surface
plane = Plane (0, 1, 0) (0, -2, 0) (Material (0.2, 0.2, 0.2) (1, 1, 1) (0, 0, 0) 0 0.5)
scene :: Scene
scene = [fstSphere, sndSphere, thdSphere, plane]
makeState :: IO State
makeState = do
z <- newIORef 1
return $ State { zoomFactor = z }
sceneImageSize :: Size
sceneImageSize = Size 512 512
display :: Image -> DisplayCallback
display pixelData = do
clear [ ColorBuffer ]
-- resolve overloading, not needed in "real" programs
let rasterPos2i = rasterPos :: Vertex2 GLint -> IO ()
rasterPos2i (Vertex2 0 0)
drawPixels sceneImageSize pixelData
flush
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
ortho2D 0 (fromIntegral w) 0 (fromIntegral h)
matrixMode $= Modelview 0
loadIdentity
rayTrace :: Size -> GLsizei -> IO Image
rayTrace (Size w h) n =
fmap (PixelData RGB Float) $
newArray [ c |
i <- [ 0 .. w - 1 ],
j <- [ 0 .. h - 1 ],
let c = convertToFloatColor $ boxFilter scene (fromIntegral j) (fromIntegral i) ]
createShadedImage :: IO Image
createShadedImage = do
clearColor $= Color4 0 0 0 0
shadeModel $= Flat
rowAlignment Unpack $= 1
rayTrace sceneImageSize 0x8
| dongy7/raytracer | src/Render/Setup.hs | mit | 1,970 | 0 | 15 | 529 | 790 | 427 | 363 | 52 | 1 |
{-| Unittest runner for ganeti-htools.
-}
{-
Copyright (C) 2009, 2011, 2012, 2013 Google Inc.
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Main(main) where
import Data.Monoid (mappend)
import Test.Framework
import System.Environment (getArgs)
import System.Log.Logger
import Test.AutoConf
import Test.Ganeti.TestImports ()
import Test.Ganeti.Attoparsec
import Test.Ganeti.BasicTypes
import Test.Ganeti.Common
import Test.Ganeti.Constants
import Test.Ganeti.Confd.Utils
import Test.Ganeti.Confd.Types
import Test.Ganeti.Daemon
import Test.Ganeti.Errors
import Test.Ganeti.HTools.Backend.Simu
import Test.Ganeti.HTools.Backend.Text
import Test.Ganeti.HTools.CLI
import Test.Ganeti.HTools.Cluster
import Test.Ganeti.HTools.Container
import Test.Ganeti.HTools.Graph
import Test.Ganeti.HTools.Instance
import Test.Ganeti.HTools.Loader
import Test.Ganeti.HTools.Node
import Test.Ganeti.HTools.PeerMap
import Test.Ganeti.HTools.Types
import Test.Ganeti.Hypervisor.Xen.XmParser
import Test.Ganeti.JSON
import Test.Ganeti.Jobs
import Test.Ganeti.JQueue
import Test.Ganeti.Kvmd
import Test.Ganeti.Locking.Allocation
import Test.Ganeti.Locking.Locks
import Test.Ganeti.Locking.Waiting
import Test.Ganeti.Luxi
import Test.Ganeti.Network
import Test.Ganeti.Objects
import Test.Ganeti.OpCodes
import Test.Ganeti.Query.Aliases
import Test.Ganeti.Query.Filter
import Test.Ganeti.Query.Instance
import Test.Ganeti.Query.Language
import Test.Ganeti.Query.Network
import Test.Ganeti.Query.Query
import Test.Ganeti.Rpc
import Test.Ganeti.Runtime
import Test.Ganeti.Ssconf
import Test.Ganeti.Storage.Diskstats.Parser
import Test.Ganeti.Storage.Drbd.Parser
import Test.Ganeti.Storage.Drbd.Types
import Test.Ganeti.Storage.Lvm.LVParser
import Test.Ganeti.THH
import Test.Ganeti.THH.Types
import Test.Ganeti.Types
import Test.Ganeti.Utils
-- | Our default test options, overring the built-in test-framework
-- ones (but not the supplied command line parameters).
defOpts :: TestOptions
defOpts = TestOptions
{ topt_seed = Nothing
, topt_maximum_generated_tests = Just 500
, topt_maximum_unsuitable_generated_tests = Just 5000
, topt_maximum_test_size = Nothing
, topt_maximum_test_depth = Nothing
, topt_timeout = Nothing
}
-- | All our defined tests.
allTests :: [Test]
allTests =
[ testAutoConf
, testBasicTypes
, testAttoparsec
, testCommon
, testConstants
, testConfd_Types
, testConfd_Utils
, testDaemon
, testBlock_Diskstats_Parser
, testBlock_Drbd_Parser
, testBlock_Drbd_Types
, testErrors
, testHTools_Backend_Simu
, testHTools_Backend_Text
, testHTools_CLI
, testHTools_Cluster
, testHTools_Container
, testHTools_Graph
, testHTools_Instance
, testHTools_Loader
, testHTools_Node
, testHTools_PeerMap
, testHTools_Types
, testHypervisor_Xen_XmParser
, testJSON
, testJobs
, testJQueue
, testKvmd
, testLocking_Allocation
, testLocking_Locks
, testLocking_Waiting
, testLuxi
, testNetwork
, testObjects
, testOpCodes
, testQuery_Aliases
, testQuery_Filter
, testQuery_Instance
, testQuery_Language
, testQuery_Network
, testQuery_Query
, testRpc
, testRuntime
, testSsconf
, testStorage_Lvm_LVParser
, testTHH
, testTHH_Types
, testTypes
, testUtils
]
-- | Main function. Note we don't use defaultMain since we want to
-- control explicitly our test sizes (and override the default).
main :: IO ()
main = do
ropts <- getArgs >>= interpretArgsOrExit
let opts = maybe defOpts (defOpts `mappend`) $ ropt_test_options ropts
-- silence the logging system, so that tests can execute I/O actions
-- which create logs without polluting stderr
-- FIXME: improve this by allowing tests to use logging if needed
updateGlobalLogger rootLoggerName (setLevel EMERGENCY)
defaultMainWithOpts allTests (ropts { ropt_test_options = Just opts })
| kawamuray/ganeti | test/hs/htest.hs | gpl-2.0 | 4,633 | 0 | 12 | 772 | 690 | 454 | 236 | 120 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
module Darcs.Patch.Prim.V1.Coalesce
()
where
import Prelude hiding ( pi )
import Control.Arrow ( second )
import Data.Maybe ( fromMaybe )
import Data.Map ( elems, fromListWith, mapWithKey )
import qualified Data.ByteString as B (ByteString, empty)
import System.FilePath ( (</>) )
import Darcs.Patch.Prim.Class ( PrimCanonize(..) )
import Darcs.Patch.Prim.V1.Commute ()
import Darcs.Patch.Prim.V1.Core
( Prim(..), FilePatchType(..), DirPatchType(..)
, comparePrim, isIdentity
)
import Darcs.Patch.Prim.V1.Show ()
import Darcs.Patch.Witnesses.Eq ( MyEq(..), EqCheck(..) )
import Darcs.Patch.Witnesses.Ordered
( FL(..), RL(..), (:>)(..), (:<)(..)
, reverseRL, mapFL, mapFL_FL
, concatFL, lengthFL, (+>+) )
import Darcs.Patch.Witnesses.Sealed
( unseal, Sealed2(..), unsafeUnseal2
, Gap(..), unFreeLeft
)
import Darcs.Patch.Witnesses.Unsafe ( unsafeCoerceP, unsafeCoercePEnd )
import Darcs.Patch.Invert ( Invert(..) )
import Darcs.Patch.Commute ( Commute(..) )
-- import Darcs.Patch.Permutations () -- for Invert instance of FL
import Darcs.Util.Diff ( getChanges )
import qualified Darcs.Util.Diff as D ( DiffAlgorithm )
import Darcs.Util.Global ( darcsdir )
import Darcs.Util.Path ( FileName, fp2fn )
#include "impossible.h"
-- | 'coalesceRev' @p2 :< p1@ tries to combine @p1@ and @p2@ into a single
-- patch without intermediary changes. For example, two hunk patches
-- modifying adjacent lines can be coalesced into a bigger hunk patch.
-- Or a patch which moves file A to file B can be coalesced with a
-- patch that moves file B into file C, yielding a patch that moves
-- file A to file C.
coalesceRev :: (Prim :< Prim) wX wY -> Maybe (FL Prim wX wY)
coalesceRev (FP f1 _ :< FP f2 _) | f1 /= f2 = Nothing
coalesceRev (p2 :< p1) | IsEq <- p2 =\/= invert p1 = Just NilFL
coalesceRev (FP f1 p1 :< FP _ p2) = fmap (:>: NilFL) $ coalesceFilePrim f1 (p1 :< p2) -- f1 = f2
coalesceRev (Move a b :< Move b' a') | a == a' = Just $ Move b' b :>: NilFL
coalesceRev (Move a b :< FP f AddFile) | f == a = Just $ FP b AddFile :>: NilFL
coalesceRev (Move a b :< DP f AddDir) | f == a = Just $ DP b AddDir :>: NilFL
coalesceRev (FP f RmFile :< Move a b) | b == f = Just $ FP a RmFile :>: NilFL
coalesceRev (DP f RmDir :< Move a b) | b == f = Just $ DP a RmDir :>: NilFL
coalesceRev (ChangePref p f1 t1 :< ChangePref p2 f2 t2) | p == p2 && t2 == f1 = Just $ ChangePref p f2 t1 :>: NilFL
coalesceRev _ = Nothing
mapPrimFL :: (forall wX wY . FL Prim wX wY -> FL Prim wX wY)
-> FL Prim wW wZ -> FL Prim wW wZ
mapPrimFL f x =
-- an optimisation; break the list up into independent sublists
-- and apply f to each of them
case mapM toSimpleSealed $ mapFL Sealed2 x of
Just sx -> concatFL $ unsealList $ elems $
mapWithKey (\ k p -> Sealed2 (f (fromSimples k (unsealList (p []))))) $
fromListWith (flip (.)) $
map (\ (a,b) -> (a,(b:))) sx
Nothing -> f x
where
unsealList :: [Sealed2 p] -> FL p wA wB
unsealList = foldr ((:>:) . unsafeUnseal2) (unsafeCoerceP NilFL)
toSimpleSealed :: Sealed2 Prim -> Maybe (FileName, Sealed2 Simple)
toSimpleSealed (Sealed2 p) = fmap (second Sealed2) (toSimple p)
data Simple wX wY = SFP !(FilePatchType wX wY) | SDP !(DirPatchType wX wY)
| SCP String String String
deriving ( Show )
toSimple :: Prim wX wY -> Maybe (FileName, Simple wX wY)
toSimple (FP a b) = Just (a, SFP b)
toSimple (DP a AddDir) = Just (a, SDP AddDir)
toSimple (DP _ RmDir) = Nothing -- ordering is trickier with rmdir present
toSimple (Move _ _) = Nothing
toSimple (ChangePref a b c) = Just (fp2fn $ darcsdir </> "prefs" </> "prefs", SCP a b c)
fromSimple :: FileName -> Simple wX wY -> Prim wX wY
fromSimple a (SFP b) = FP a b
fromSimple a (SDP b) = DP a b
fromSimple _ (SCP a b c) = ChangePref a b c
fromSimples :: FileName -> FL Simple wX wY -> FL Prim wX wY
fromSimples a = mapFL_FL (fromSimple a)
tryHarderToShrink :: FL Prim wX wY -> FL Prim wX wY
tryHarderToShrink x = tryToShrink2 $ fromMaybe x (tryShrinkingInverse x)
tryToShrink2 :: FL Prim wX wY -> FL Prim wX wY
tryToShrink2 psold =
let ps = sortCoalesceFL psold
ps_shrunk = shrinkABit ps
in
if lengthFL ps_shrunk < lengthFL ps
then tryToShrink2 ps_shrunk
else ps_shrunk
-- | @shrinkABit ps@ tries to simplify @ps@ by one patch,
-- the first one we find that coalesces with its neighbour
shrinkABit :: FL Prim wX wY -> FL Prim wX wY
shrinkABit NilFL = NilFL
shrinkABit (p:>:ps) = fromMaybe (p :>: shrinkABit ps) $ tryOne NilRL p ps
-- | @tryOne acc p ps@ pushes @p@ as far down @ps@ as we can go
-- until we can either coalesce it with something or it can't
-- go any further. Returns @Just@ if we manage to get any
-- coalescing out of this
tryOne :: RL Prim wW wX -> Prim wX wY -> FL Prim wY wZ
-> Maybe (FL Prim wW wZ)
tryOne _ _ NilFL = Nothing
tryOne sofar p (p1:>:ps) =
case coalesceRev (p1 :< p) of
Just p' -> Just (reverseRL sofar +>+ p' +>+ ps)
Nothing -> case commute (p :> p1) of
Nothing -> Nothing
Just (p1' :> p') -> tryOne (p1':<:sofar) p' ps
-- | The heart of "sortCoalesceFL"
sortCoalesceFL2 :: FL Prim wX wY -> FL Prim wX wY
sortCoalesceFL2 NilFL = NilFL
sortCoalesceFL2 (x:>:xs) | IsEq <- isIdentity x = sortCoalesceFL2 xs
sortCoalesceFL2 (x:>:xs) = either id id $ pushCoalescePatch x $ sortCoalesceFL2 xs
-- | 'pushCoalescePatch' @new ps@ is almost like @new :>: ps@ except
-- as an alternative to consing, we first try to coalesce @new@ with
-- the head of @ps@. If this fails, we try again, using commutation
-- to push @new@ down the list until we find a place where either
-- (a) @new@ is @LT@ the next member of the list [see 'comparePrim']
-- (b) commutation fails or
-- (c) coalescing succeeds.
-- The basic principle is to coalesce if we can and cons otherwise.
--
-- As an additional optimization, pushCoalescePatch outputs a Left
-- value if it wasn't able to shrink the patch sequence at all, and
-- a Right value if it was indeed able to shrink the patch sequence.
-- This avoids the O(N) calls to lengthFL that were in the older
-- code.
--
-- Also note that pushCoalescePatch is only ever used (and should
-- only ever be used) as an internal function in in
-- sortCoalesceFL2.
pushCoalescePatch :: Prim wX wY -> FL Prim wY wZ
-> Either (FL Prim wX wZ) (FL Prim wX wZ)
pushCoalescePatch new NilFL = Left (new:>:NilFL)
pushCoalescePatch new ps@(p:>:ps')
= case coalesceRev (p :< new) of
Just (new' :>: NilFL) -> Right $ either id id $ pushCoalescePatch new' ps'
Just NilFL -> Right ps'
Just _ -> impossible -- coalesce either returns a singleton or empty
Nothing -> if comparePrim new p == LT then Left (new:>:ps)
else case commute (new :> p) of
Just (p' :> new') ->
case pushCoalescePatch new' ps' of
Right r -> Right $ either id id $
pushCoalescePatch p' r
Left r -> Left (p' :>: r)
Nothing -> Left (new:>:ps)
coalesceFilePrim :: FileName -> (FilePatchType :< FilePatchType) wX wY
-> Maybe (Prim wX wY)
coalesceFilePrim f (Hunk line1 old1 new1 :< Hunk line2 old2 new2)
= coalesceHunk f line1 old1 new1 line2 old2 new2
-- Token replace patches operating right after (or before) AddFile (RmFile)
-- is an identity patch, as far as coalescing is concerned.
coalesceFilePrim f (TokReplace{} :< AddFile) = Just $ FP f AddFile
coalesceFilePrim f (RmFile :< TokReplace{}) = Just $ FP f RmFile
coalesceFilePrim f (TokReplace t1 o1 n1 :< TokReplace t2 o2 n2)
| t1 == t2 && n2 == o1 = Just $ FP f $ TokReplace t1 o2 n1
coalesceFilePrim f (Binary m n :< Binary o m')
| m == m' = Just $ FP f $ Binary o n
coalesceFilePrim _ _ = Nothing
coalesceHunk :: FileName
-> Int -> [B.ByteString] -> [B.ByteString]
-> Int -> [B.ByteString] -> [B.ByteString]
-> Maybe (Prim wX wY)
coalesceHunk f line1 old1 new1 line2 old2 new2
| line1 == line2 && lengthold1 < lengthnew2 =
if take lengthold1 new2 /= old1
then Nothing
else case drop lengthold1 new2 of
extranew -> Just (FP f (Hunk line1 old2 (new1 ++ extranew)))
| line1 == line2 && lengthold1 > lengthnew2 =
if take lengthnew2 old1 /= new2
then Nothing
else case drop lengthnew2 old1 of
extraold -> Just (FP f (Hunk line1 (old2 ++ extraold) new1))
| line1 == line2 = if new2 == old1 then Just (FP f (Hunk line1 old2 new1))
else Nothing
| line1 < line2 && lengthold1 >= line2 - line1 =
case take (line2 - line1) old1 of
extra-> coalesceHunk f line1 old1 new1 line1 (extra ++ old2) (extra ++ new2)
| line1 > line2 && lengthnew2 >= line1 - line2 =
case take (line1 - line2) new2 of
extra-> coalesceHunk f line2 (extra ++ old1) (extra ++ new1) line2 old2 new2
| otherwise = Nothing
where lengthold1 = length old1
lengthnew2 = length new2
canonizeHunk :: Gap w
=> D.DiffAlgorithm -> FileName -> Int -> [B.ByteString] -> [B.ByteString]
-> w (FL Prim)
canonizeHunk _ f line old new
| null old || null new || old == [B.empty] || new == [B.empty]
= freeGap (FP f (Hunk line old new) :>: NilFL)
canonizeHunk da f line old new = makeHoley f line $ getChanges da old new
makeHoley :: Gap w
=> FileName -> Int -> [(Int,[B.ByteString], [B.ByteString])]
-> w (FL Prim)
makeHoley f line =
foldr (joinGap (:>:) . (\(l,o,n) -> freeGap (FP f (Hunk (l+line) o n)))) (emptyGap NilFL)
instance PrimCanonize Prim where
tryToShrink = mapPrimFL tryHarderToShrink
tryShrinkingInverse (x:>:y:>:z)
| IsEq <- invert x =\/= y = Just z
| otherwise = case tryShrinkingInverse (y:>:z) of
Nothing -> Nothing
Just yz' -> Just $ fromMaybe (x :>: yz') $ tryShrinkingInverse (x:>:yz')
tryShrinkingInverse _ = Nothing
sortCoalesceFL = mapPrimFL sortCoalesceFL2
canonize _ p | IsEq <- isIdentity p = NilFL
canonize da (FP f (Hunk line old new)) = unseal unsafeCoercePEnd $ unFreeLeft $ canonizeHunk da f line old new
canonize _ p = p :>: NilFL
-- Running canonize twice is apparently necessary to fix issue525;
-- would be nice to understand why.
canonizeFL da = concatFL . mapFL_FL (canonize da) . sortCoalesceFL .
concatFL . mapFL_FL (canonize da)
coalesce (x :> y) = coalesceRev (y :< x)
| DavidAlphaFox/darcs | src/Darcs/Patch/Prim/V1/Coalesce.hs | gpl-2.0 | 10,881 | 0 | 23 | 2,848 | 3,618 | 1,865 | 1,753 | -1 | -1 |
{-
All properties from the article.
-}
module Properties where
import HipSpec
import Prelude(Bool(..))
import Definitions
-- Theorems
prop_T01 :: Nat -> Prop Nat
prop_T01 x = double x =:= x + x
prop_T02 :: [a] -> [a] -> Prop Nat
prop_T02 x y = length (x ++ y ) =:= length (y ++ x)
prop_T03 :: [a] -> [a] -> Prop Nat
prop_T03 x y = length (x ++ y ) =:= length (y ) + length x
prop_T04 :: [a] -> Prop Nat
prop_T04 x = length (x ++ x) =:= double (length x)
prop_T05 :: [a] -> Prop Nat
prop_T05 x = length (rev x) =:= length x
prop_T06 :: [a] -> [a] -> Prop Nat
prop_T06 x y = length (rev (x ++ y )) =:= length x + length y
prop_T07 :: [a] -> [a] -> Prop Nat
prop_T07 x y = length (qrev x y) =:= length x + length y
prop_T08 :: Nat -> Nat -> [a] -> Prop [a]
prop_T08 x y z = drop x (drop y z) =:= drop y (drop x z)
prop_T09 :: Nat -> Nat -> [a] -> Nat -> Prop [a]
prop_T09 x y z w = drop w (drop x (drop y z)) =:= drop y (drop x (drop w z))
prop_T10 :: [a] -> Prop [a]
prop_T10 x = rev (rev x) =:= x
prop_T11 :: [a] -> [a] -> Prop [a]
prop_T11 x y = rev (rev x ++ rev y) =:= y ++ x
prop_T12 :: [a] -> [a] -> Prop [a]
prop_T12 x y = qrev x y =:= rev x ++ y
prop_T13 :: Nat -> Prop Nat
prop_T13 x = half (x + x) =:= x
prop_T14 :: [Nat] -> Prop Bool
prop_T14 x = proveBool (sorted (isort x))
prop_T15 :: Nat -> Prop Nat
prop_T15 x = x + S x =:= S (x + x)
prop_T16 :: Nat -> Prop Bool
prop_T16 x = proveBool (even (x + x))
prop_T17 :: [a] -> [a] -> Prop [a]
prop_T17 x y = rev (rev (x ++ y)) =:= rev (rev x) ++ rev (rev y)
prop_T18 :: [a] -> [a] -> Prop [a]
prop_T18 x y = rev (rev x ++ y) =:= rev y ++ x
prop_T19 :: [a] -> [a] -> Prop [a]
prop_T19 x y = rev (rev x) ++ y =:= rev (rev (x ++ y))
prop_T20 :: [a] -> Prop Bool
prop_T20 x = proveBool (even (length (x ++ x)))
prop_T21 :: [a] -> [a] -> Prop [a]
prop_T21 x y = rotate (length x) (x ++ y) =:= y ++ x
prop_T22 :: [a] -> [a] -> Prop Bool
prop_T22 x y = even (length (x ++ y)) =:= even (length (y ++ x))
prop_T23 :: [a] -> [a] -> Prop Nat
prop_T23 x y = half (length (x ++ y)) =:= half (length (y ++ x))
prop_T24 :: Nat -> Nat -> Prop Bool
prop_T24 x y = even (x + y) =:= even (y + x)
prop_T25 :: [a] -> [a] -> Prop Bool
prop_T25 x y = even (length (x ++ y)) =:= even (length y + length x)
prop_T26 :: Nat -> Nat -> Prop Nat
prop_T26 x y = half (x + y) =:= half (y + x)
prop_T27 :: [a] -> Prop [a]
prop_T27 x = rev x =:= qrev x []
prop_T28 :: [[a]] -> Prop [a]
prop_T28 x = revflat x =:= qrevflat x []
prop_T29 :: [a] -> Prop [a]
prop_T29 x = rev (qrev x []) =:= x
prop_T30 :: [a] -> Prop [a]
prop_T30 x = rev (rev x ++ []) =:= x
prop_T31 :: [a] -> Prop [a]
prop_T31 x = qrev (qrev x []) [] =:= x
prop_T32 :: [a] -> Prop [a]
prop_T32 x = rotate (length x) x =:= x
prop_T33 :: Nat -> Prop Nat
prop_T33 x = fac x =:= qfac x one
prop_T34 :: Nat -> Nat -> Prop Nat
prop_T34 x y = x * y =:= mult x y zero
prop_T35 :: Nat -> Nat -> Prop Nat
prop_T35 x y = exp x y =:= qexp x y one
prop_T36 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T36 x y z = givenBool (x `elem` y) (proveBool (x `elem` (y ++ z)))
prop_T37 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T37 x y z = givenBool (x `elem` z) (proveBool (x `elem` (y ++ z)))
prop_T38 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T38 x y z = givenBool (x `elem` y)
( givenBool (x `elem` z)
( proveBool (x `elem` (y ++ z))))
prop_T39 :: Nat -> Nat -> [Nat] -> Prop Bool
prop_T39 x y z = givenBool (x `elem` drop y z) (proveBool (x `elem` z))
prop_T40 :: [Nat] -> [Nat] -> Prop [Nat]
prop_T40 x y = givenBool (x `subset` y) ((x `union` y) =:= y)
prop_T41 :: [Nat] -> [Nat] -> Prop [Nat]
prop_T41 x y = givenBool (x `subset` y) ((x `intersect` y) =:= x)
prop_T42 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T42 x y z = givenBool (x `elem` y) (proveBool (x `elem` (y `union` z)))
prop_T43 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T43 x y z = givenBool (x `elem` y) (proveBool (x `elem` (z `union` y)))
prop_T44 :: Nat -> [Nat] -> [Nat] -> Prop Bool
prop_T44 x y z = givenBool (x `elem` y)
( givenBool (x `elem` z)
( proveBool (x `elem` (y `intersect` z))))
prop_T45 :: Nat -> [Nat] -> Prop Bool
prop_T45 x y = proveBool (x `elem` insert x y)
prop_T46 :: Nat -> Nat -> [Nat] -> Prop Bool
prop_T46 x y z = x =:= y ==> proveBool (x `elem` insert y z)
prop_T47 :: Nat -> Nat -> [Nat] -> Prop Bool
prop_T47 x y z = givenBool (x /= y) ((x `elem` insert y z) =:= x `elem` z)
prop_T48 :: [Nat] -> Prop Nat
prop_T48 x = length (isort x) =:= length x
prop_T49 :: Nat -> [Nat] -> Prop Bool
prop_T49 x y = givenBool (x `elem` isort y) (proveBool (x `elem` y))
prop_T50 :: Nat -> [Nat] -> Prop Nat
prop_T50 x y = count x (isort y) =:= count x y
| danr/hipspec | testsuite/prod/Properties.hs | gpl-3.0 | 4,732 | 0 | 13 | 1,173 | 2,830 | 1,475 | 1,355 | 108 | 1 |
-- | Account transactions.
module ChimericLedgers.Transaction.Account where
import Control.Monad (mfilter)
import ChimericLedgers.Address
import ChimericLedgers.Value
-- | Account based transaction.
data AccTx = AccTx
{ -- | To allow transactions that create money and assign it to the
-- receiver the sender address is optional.
sender :: Maybe Address
-- | To allow for transaction that take money from the sender and spend
-- it as fee the receiver address is optional.
, receiver :: Maybe Address
, value :: Value
, forge :: Value
, fee :: Value
-- | To prevent replay attacks a transaction. Without this field nothing
-- prevents the receiver from an authorized transaction to include it
-- multiple times in the ledger.
, nonce :: Int
} deriving (Eq, Ord, Show)
-- | Validity condition on an account based transaction.
--
--
-- We have the following cases:
--
-- - Both sender and receiver are undefined. In which case the validity
-- condition simplifies to:
--
-- > valid t = forge t == fee t
--
-- which indicates that the money forged in the transaction must correspond to
-- the fee.
--
-- - Sender is undefined, receiver is defined. In which case the validity
-- condition simplifies to:
--
-- > valid t = forge t == fee t + value t
--
-- which is equivalent to:
--
-- > valid t = forge t - fee t == value t
--
-- which indicates that the money transferred to the receiver must be the money
-- forged in the transaction minus the fees (since the money does not come from
-- any account).
--
-- - Sender is defined, receiver is undefined. In which the validity condition
-- simplifies to:
--
-- > valid t = value t = 0
--
-- which indicates that no value can be assigned to the transaction (since
-- there is no recipient), and only money can be forged and fees can be paid.
--
-- - Sender is defined, receiver is defined. In which the validity condition
-- simplifies to:
--
-- > valid t = forge t + value t + fee t - forge t = fee t + value t
--
-- which simplifies to
--
-- > valid t = value t = value t
--
-- which is trivially try, indicating no restriction on a transaction to be
-- valid, if both sender and receiver are defined.
--
-- TODO: QUESTION: Does it make sense to use smart constructors? My fear is
-- that they will make the models a bit more cumbersome.
valid :: AccTx -> Bool
valid t = forge t + spendableMoney == fee t + spentMoney
where
spendableMoney = maybe 0 (const (value t + fee t - forge t)) (sender t)
spentMoney = maybe 0 (const (value t)) (receiver t)
-- | Balance of an account based transaction.
βAcc :: Address -> AccTx -> Value
βAcc a t = received - spent
where
spent = (value t + fee t - forge t) `whenAddressEquals` sender
-- maybe 0 (const (value t + fee t - forge t)) (mfilter (a ==) (sender t))
received = value t `whenAddressEquals` receiver
-- maybe 0 (const (value t)) (mfilter (a ==) (receiver t))
whenAddressEquals val who = maybe 0 (const val) (mfilter (a ==) (who t))
t1 :: AccTx
t1 = AccTx Nothing (Just 1) 1000 1000 0 0
x = βAcc 1 t1
t2 :: AccTx
t2 = AccTx (Just 1) (Just 2) 800 0 0 0
t3 :: AccTx
t3 = AccTx (Just 1) (Just 3) 199 0 1 0
t4 :: AccTx
t4 = AccTx (Just 3) (Just 2) 207 10 2 0
t5 :: AccTx
t5 = AccTx (Just 2) (Just 3) 500 0 7 0
t6 :: AccTx
t6 = AccTx (Just 2) (Just 3) 499 0 1 0
| capitanbatata/sandbox | chimeric-ledgers/src/ChimericLedgers/Transaction/Account.hs | gpl-3.0 | 3,446 | 0 | 13 | 841 | 593 | 340 | 253 | 34 | 1 |
module Main where
import Data.Tree
import System.Environment
import DocGraph
main :: IO ()
main = do
args <- getArgs
tree <- traverseAllIO $ if null args
then "test-data"
else head args
putStr $ drawTree $ fmap show tree
let dot = graph2dot tree
writeFile "test.dot" dot
putStrLn ""
putStrLn "-----"
putStrLn ""
putStrLn dot
| wldmr/haskell-docgraph | src/Main.hs | gpl-3.0 | 436 | 0 | 10 | 165 | 124 | 57 | 67 | 17 | 2 |
module WildFire.RunWFStatic where
import WildFire.WildFireModelStatic
import qualified Data.HashMap as Map
import qualified WildFire.WildFireFrontend as Front
import System.Random
import System.IO
import Data.Maybe
import Data.List
import Debug.Trace
import qualified Graphics.Gloss as GLO
import Graphics.Gloss.Interface.IO.Simulate
import qualified PureAgentsPar as PA
runWFStatic :: IO ()
runWFStatic = do
let dt = 1.0
let xCells = 50
let yCells = 50
let rngSeed = 42
let cells = (xCells, yCells)
let g = mkStdGen rngSeed
-- NOTE: need atomically as well, although nothing has been written yet. primarily to change into the IO - Monad
let (as, g') = createRandomWFAgents g cells
let ignitedAs = initialIgnition as (25, 25) cells
let (as', hdl) = PA.initStepSimulation ignitedAs Nothing
stepWithRendering hdl dt cells
initialIgnition :: [WFAgent] -> (Int, Int) -> (Int, Int) -> [WFAgent]
initialIgnition as pos cells
| isNothing mayAgentAtPos = as
| otherwise = infront ++ [ignitedAgentAtPos] ++ (tail behind)
where
mayAgentAtPos = find (\a -> pos == (agentToCell a cells)) as
agentAtPos = (fromJust mayAgentAtPos)
agentAtPosId = PA.agentId agentAtPos
ignitedAgentAtPos = agentAtPos{ PA.inBox = [(agentAtPosId, Ignite)]}
(infront, behind) = splitAt agentAtPosId as
stepWithRendering :: WFSimHandle -> Double -> (Int, Int) -> IO ()
stepWithRendering hdl dt cells = simulateIO Front.display
GLO.white
10
hdl
(modelToPicture cells)
(stepIteration dt)
-- A function to convert the model to a picture.
modelToPicture :: (Int, Int) -> WFSimHandle -> IO GLO.Picture
modelToPicture cells hdl = return (Front.renderFrame observableAgentStates cells)
where
as = PA.extractAgents hdl
observableAgentStates = map (wfAgentToObservableState cells) as
-- A function to step the model one iteration. It is passed the current viewport and the amount of time for this simulation step (in seconds)
-- NOTE: atomically is VERY important, if it is not there there then the STM-transactions would not occur!
-- NOTE: this is actually wrong, we can avoid atomically as long as we are running always on the same thread.
-- atomically would commit the changes and make them visible to other threads
stepIteration :: Double -> ViewPort -> Float -> WFSimHandle -> IO WFSimHandle
stepIteration fixedDt viewport dtRendering hdl = do
let (as', e', hdl') = PA.advanceSimulation hdl fixedDt
return hdl'
wfAgentToObservableState :: (Int, Int) -> WFAgent -> Front.RenderCell
wfAgentToObservableState (xCells, yCells) a = Front.RenderCell { Front.renderCellCoord = (x, y),
Front.renderCellShade = (burnable s),
Front.renderCellState = cellState }
where
aid = PA.agentId a
s = PA.state a
y = floor((fromIntegral aid) / (fromIntegral xCells))
x = mod aid yCells
cellState = case (wfState s) of
Living -> Front.ShadeGreen
Burning -> Front.ShadeRed
Dead -> Front.ShadeGray
| thalerjonathan/phd | coding/prototyping/haskell/PureAgentsPar/src/WildFire/RunWFStatic.hs | gpl-3.0 | 3,629 | 0 | 12 | 1,204 | 799 | 427 | 372 | 60 | 3 |
data Pair a b = P a b | hmemcpy/milewski-ctfp-pdf | src/content/1.6/code/haskell/snippet09.hs | gpl-3.0 | 21 | 0 | 6 | 7 | 14 | 8 | 6 | 1 | 0 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module CheckCommon where
import qualified Data.IntMap as IM
import qualified Data.Set as S
import qualified Data.List as L
import qualified Data.Vector as Vec
import Data.Vector (Vector)
import Test.QuickCheck
import Control.Applicative
import Control.Monad
import Linear.Vect
import DeUni.DeWall
import DeUni.Types
import DeUni.GeometricTools
import DeUni.Dim3.Base3D
import DeUni.Dim2.ReTri2D
import VTKRender
runChecker = do
let myArgs = Args { replay = Nothing
, maxSuccess = 1000
, maxDiscardRatio = 5
, maxSize = 1000
, chatty = True }
print "Testing Projection.."
quickCheckWith myArgs prop_Projection
print "Testing Parttition.."
quickCheckWith myArgs prop_partition
instance Arbitrary (Box Point3D) where
arbitrary = liftM2 getBox max min
where
getBox max min = Box3D {xMax3D=max, xMin3D=min, yMax3D=max, yMin3D=min, zMax3D=max, zMin3D=min}
min = choose (-200,-100)
max = choose (200,100)
instance Arbitrary Vec3 where
arbitrary = liftM3 Vec3 p p p
where p = choose (-100,100)
instance (Arbitrary a) => Arbitrary (WPoint a) where
arbitrary = WPoint 0 <$> arbitrary
instance (Arbitrary a) => Arbitrary (Vector a) where
arbitrary =Vec.fromList <$> arbitrary
instance Arbitrary Vec2 where
arbitrary = liftM2 Vec2 p p
where p = choose (-100,100)
instance Arbitrary Mat2 where
arbitrary = liftM2 Mat2 arbitrary arbitrary
error_precisson = (10e-4)
msgFail text = printTestCase ("\x1b[7m Fail: " ++ show text ++ "! \x1b[0m")
testIM :: (a -> Gen Prop) -> IM.IntMap a -> Gen Prop
testIM test map
| IM.null map = err
| otherwise = let (x, xs) = IM.deleteFindMin map
in IM.fold (\a acc -> acc .&&. test a) (test $ snd x) xs
where
err = msgFail "empty output" False
testSet :: (a -> Gen Prop) -> S.Set a -> Gen Prop
testSet test set
| S.null set = err
| otherwise = let (x, xs) = S.deleteFindMin set
in S.fold (\a b -> b .&&. test a) (test x) xs
where
err = msgFail "empty output" False
prop_Projection::Point3D -> Point3D -> Property
prop_Projection a b = msgFail "bad projection" $ c &. b < error_precisson
where c = normalofAtoB a b
prop_partition::Box Point3D -> SetPoint Point3D -> Property
prop_partition box sP = msgFail "bad points partition" (test1 || test2)
where
(plane, pairBox) = cutBox box []
p = let size = Vec.length sP in if size <= 0 then [] else [0 .. size - 1]
ppb = pointSetPartition (whichBoxIsIt pairBox) sP p
ppp = pointSetPartition (whichSideOfPlane plane) sP p
test1 = ((L.sort $ pointsOnB1 ppb) == (L.sort $ pointsOnB1 ppp))
&& ((L.sort $ pointsOnB2 ppb) == (L.sort $ pointsOnB2 ppp))
test2 = ((L.sort $ pointsOnB1 ppb) == (L.sort $ pointsOnB2 ppp))
&& ((L.sort $ pointsOnB2 ppb) == (L.sort $ pointsOnB1 ppp))
| lostbean/DeUni | profile/CheckCommon.hs | gpl-3.0 | 3,020 | 0 | 12 | 744 | 1,075 | 566 | 509 | 72 | 2 |
module Jinzamomi.Driver.Krkr (
Opt,
opt,
execute
) where
import qualified Data.ByteString.Lazy as B
import qualified Data.Aeson as JSON
import qualified Text.Parsec.Error as P
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import qualified Language.TJS as TJS
import qualified Language.KAG as KAG
import System.Log.Logger
import Options.Applicative
import qualified Jinzamomi.Driver.Krkr.TJS2IR as TJS2IR
import qualified Jinzamomi.Driver.Krkr.KAG2IR as KAG2IR
import qualified Jinzamomi.Driver.IR as IR
import Jinzamomi.Driver.Util
import Control.Monad (filterM)
import System.FilePath (dropFileName, takeExtension, (</>), (<.>), pathSeparator, makeRelative, normalise)
import System.Directory (createDirectoryIfMissing, getDirectoryContents, doesFileExist, doesDirectoryExist)
data Opt =
Build String String
deriving (Show)
tag :: String
tag = "Krkr"
opt :: Mod CommandFields Opt
opt = command "krkr" (info buildCmd (progDesc "Krkr Driver."))
where
buildCmd = hsubparser $
command "build" (
info buildOption
(progDesc "Build krkr"))
buildOption = Build <$>
argument str (metavar "FROM") <*>
argument str (metavar "TO")
compileTJS :: FilePath -> T.Text -> Either P.ParseError T.Text
compileTJS filepath content = do
ast <- TJS.parse filepath content
return (IR.compile (TJS2IR.compileStmt ast))
compileKAG :: FilePath -> T.Text -> Either P.ParseError T.Text
compileKAG filepath content = do
ast <- KAG.parse filepath content
return (IR.compile (KAG2IR.compile ast))
build :: FilePath -> FilePath -> IO ()
build from to = do
createDirectoryIfMissing True to
files <- enumAllFiles from
outFileList from to from
results <- mapM run files
let errors = length (filter not results)
if errors /= 0 then
errorM tag (concat ["compiling errors on ", show errors, "(/", show (length results), ") tjs2 files. done."])
else
return ()
where
runTask path ext runner = do
let inPath = from </> path
content <- TIO.readFile inPath
case runner inPath content of
Right res -> do
infoM tag ("[OK] " ++ inPath)
let outPath = to </> path <.> ext
createDirectoryIfMissing True (dropFileName outPath)
TIO.writeFile outPath res
return True
Left err -> do
errorM tag ("[NG] " ++ inPath)
mapM_ (errorM tag) (lines (show err))
return False
run path
| takeExtension path == ".tjs" = runTask path "js" compileTJS
| takeExtension path == ".ks" = runTask path "js" compileKAG
| otherwise = do
warningM tag ("Unknown file type: " ++ path)
return True
--
outFileList :: FilePath -> FilePath -> FilePath -> IO [FilePath]
outFileList base to path = do
let normpath = normalise path
allItems <- getDirectoryContents path
let items = (\f -> path ++ pathSeparator:f) <$> filter (\k -> k /= "." && k /= "..") allItems
files <- filterM doesFileExist items
justFolders <- filterM doesDirectoryExist items
leftFiles <- mapM (outFileList base to) justFolders
let allFiles = files ++ concat leftFiles
let outDir = to </> makeRelative base path
createDirectoryIfMissing True outDir
B.writeFile (outDir </> "files-list.json") (JSON.encode (fmap (makeRelative path) allFiles))
return allFiles
execute :: Opt -> IO ()
execute (Build from to) = build from to
| ledyba/Jinzamomi | src/Jinzamomi/Driver/Krkr.hs | gpl-3.0 | 3,444 | 0 | 18 | 760 | 1,134 | 576 | 558 | 87 | 3 |
module TestArgs where
import Args
args1 = ["-a", "--snap", "--init"]
t1 = compilerOpts args1
t2 = compilerOpts ["-a", "--start", "2015-11-01", "foo", "bar"]
t3 = compilerOpts ["-a"]
| blippy/sifi | test/TestArgs.hs | gpl-3.0 | 206 | 0 | 6 | 50 | 63 | 38 | 25 | 6 | 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.Compute.GlobalForwardingRules.SetTarget
-- 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)
--
-- Changes target URL for forwarding rule. The new target should be of the
-- same type as the old target.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.globalForwardingRules.setTarget@.
module Network.Google.Resource.Compute.GlobalForwardingRules.SetTarget
(
-- * REST Resource
GlobalForwardingRulesSetTargetResource
-- * Creating a Request
, globalForwardingRulesSetTarget
, GlobalForwardingRulesSetTarget
-- * Request Lenses
, gfrstProject
, gfrstForwardingRule
, gfrstPayload
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.globalForwardingRules.setTarget@ method which the
-- 'GlobalForwardingRulesSetTarget' request conforms to.
type GlobalForwardingRulesSetTargetResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"forwardingRules" :>
Capture "forwardingRule" Text :>
"setTarget" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] TargetReference :>
Post '[JSON] Operation
-- | Changes target URL for forwarding rule. The new target should be of the
-- same type as the old target.
--
-- /See:/ 'globalForwardingRulesSetTarget' smart constructor.
data GlobalForwardingRulesSetTarget = GlobalForwardingRulesSetTarget'
{ _gfrstProject :: !Text
, _gfrstForwardingRule :: !Text
, _gfrstPayload :: !TargetReference
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'GlobalForwardingRulesSetTarget' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gfrstProject'
--
-- * 'gfrstForwardingRule'
--
-- * 'gfrstPayload'
globalForwardingRulesSetTarget
:: Text -- ^ 'gfrstProject'
-> Text -- ^ 'gfrstForwardingRule'
-> TargetReference -- ^ 'gfrstPayload'
-> GlobalForwardingRulesSetTarget
globalForwardingRulesSetTarget pGfrstProject_ pGfrstForwardingRule_ pGfrstPayload_ =
GlobalForwardingRulesSetTarget'
{ _gfrstProject = pGfrstProject_
, _gfrstForwardingRule = pGfrstForwardingRule_
, _gfrstPayload = pGfrstPayload_
}
-- | Project ID for this request.
gfrstProject :: Lens' GlobalForwardingRulesSetTarget Text
gfrstProject
= lens _gfrstProject (\ s a -> s{_gfrstProject = a})
-- | Name of the ForwardingRule resource in which target is to be set.
gfrstForwardingRule :: Lens' GlobalForwardingRulesSetTarget Text
gfrstForwardingRule
= lens _gfrstForwardingRule
(\ s a -> s{_gfrstForwardingRule = a})
-- | Multipart request metadata.
gfrstPayload :: Lens' GlobalForwardingRulesSetTarget TargetReference
gfrstPayload
= lens _gfrstPayload (\ s a -> s{_gfrstPayload = a})
instance GoogleRequest GlobalForwardingRulesSetTarget
where
type Rs GlobalForwardingRulesSetTarget = Operation
type Scopes GlobalForwardingRulesSetTarget =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient GlobalForwardingRulesSetTarget'{..}
= go _gfrstProject _gfrstForwardingRule
(Just AltJSON)
_gfrstPayload
computeService
where go
= buildClient
(Proxy ::
Proxy GlobalForwardingRulesSetTargetResource)
mempty
| rueshyna/gogol | gogol-compute/gen/Network/Google/Resource/Compute/GlobalForwardingRules/SetTarget.hs | mpl-2.0 | 4,413 | 0 | 17 | 1,017 | 474 | 283 | 191 | 80 | 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.DFAReporting.ConnectionTypes.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 one connection type by ID.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.connectionTypes.get@.
module Network.Google.Resource.DFAReporting.ConnectionTypes.Get
(
-- * REST Resource
ConnectionTypesGetResource
-- * Creating a Request
, connectionTypesGet
, ConnectionTypesGet
-- * Request Lenses
, ctgProFileId
, ctgId
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.connectionTypes.get@ method which the
-- 'ConnectionTypesGet' request conforms to.
type ConnectionTypesGetResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"connectionTypes" :>
Capture "id" (Textual Int64) :>
QueryParam "alt" AltJSON :>
Get '[JSON] ConnectionType
-- | Gets one connection type by ID.
--
-- /See:/ 'connectionTypesGet' smart constructor.
data ConnectionTypesGet = ConnectionTypesGet'
{ _ctgProFileId :: !(Textual Int64)
, _ctgId :: !(Textual Int64)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ConnectionTypesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctgProFileId'
--
-- * 'ctgId'
connectionTypesGet
:: Int64 -- ^ 'ctgProFileId'
-> Int64 -- ^ 'ctgId'
-> ConnectionTypesGet
connectionTypesGet pCtgProFileId_ pCtgId_ =
ConnectionTypesGet'
{ _ctgProFileId = _Coerce # pCtgProFileId_
, _ctgId = _Coerce # pCtgId_
}
-- | User profile ID associated with this request.
ctgProFileId :: Lens' ConnectionTypesGet Int64
ctgProFileId
= lens _ctgProFileId (\ s a -> s{_ctgProFileId = a})
. _Coerce
-- | Connection type ID.
ctgId :: Lens' ConnectionTypesGet Int64
ctgId
= lens _ctgId (\ s a -> s{_ctgId = a}) . _Coerce
instance GoogleRequest ConnectionTypesGet where
type Rs ConnectionTypesGet = ConnectionType
type Scopes ConnectionTypesGet =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient ConnectionTypesGet'{..}
= go _ctgProFileId _ctgId (Just AltJSON)
dFAReportingService
where go
= buildClient
(Proxy :: Proxy ConnectionTypesGetResource)
mempty
| rueshyna/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/ConnectionTypes/Get.hs | mpl-2.0 | 3,305 | 0 | 14 | 773 | 421 | 249 | 172 | 64 | 1 |
module Search
( search
, searchComplex
, searchProxim
) where
import qualified Data.ByteString.Char8 as B
import qualified Data.Text as T
import qualified Postings as PS
import Control.Monad.Free
import Data.Maybe (fromMaybe)
import Data.Text.Encoding (decodeUtf8)
import Index
import Query
testIndex :: InMemoryIndex
testIndex = addTerm (T.pack "Name")
(T.pack "teresa") 1 [0,2]
(addTerm (T.pack "Name")
(T.pack "tony") 1 [1]
(addTerm (T.pack "Name")
(T.pack "casa") 1 [3] empty))
toText :: B.ByteString -> T.Text
toText = decodeUtf8
--------------------------------------------------------------------------------
-- Query interpreters
--------------------------------------------------------------------------------
runQuery :: Query QTerm -> InMemoryIndex -> PS.Postings
runQuery (Free (And e1 e2)) imi = PS.intersection (runQuery e1 imi) (runQuery e2 imi)
runQuery (Free (Or e1 e2)) imi = PS.union (runQuery e1 imi) (runQuery e2 imi)
runQuery (Free (Exp (QT fname x))) imi = fromMaybe PS.empty (Index.lookup (toText fname) (toText x) imi)
runQuery (Free (Wild (QT fname x))) imi = fromMaybe PS.empty (wildcard (toText fname) (toText x) imi)
runQuery (Free (Not e1)) imi = runQuery e1 imi
runQuery (Pure ()) _ = PS.empty
runProximityQuery :: Int -> Query QTerm -> InMemoryIndex -> PS.Postings
runProximityQuery n (Free (And e1 e2)) imi = PS.separatedBy n (runProximityQuery n e1 imi)
(runProximityQuery n e2 imi)
runProximityQuery n (Free (Or e1 e2)) imi = PS.union (runProximityQuery n e1 imi)
(runProximityQuery n e2 imi)
runProximityQuery _ (Free (Exp (QT fname x))) imi = fromMaybe PS.empty (Index.lookup (toText fname) (toText x) imi)
runProximityQuery _ (Free (Wild (QT fname x))) imi = fromMaybe PS.empty (wildcard (toText fname) (toText x) imi)
runProximityQuery n (Free (Not e1)) imi = runProximityQuery n e1 imi
runProximityQuery _ (Pure ()) _ = PS.empty
--------------------------------------------------------------------------------
-- Search API
--------------------------------------------------------------------------------
search :: InMemoryIndex -> B.ByteString -> B.ByteString -> Either String PS.Postings
search imi defField bs = runSimpleQParser defField bs >>= (\q -> return $ runQuery q imi)
searchComplex :: InMemoryIndex -> B.ByteString -> B.ByteString -> Either String PS.Postings
searchComplex imi defField bs = runComplexQParser defField bs >>= (\q -> return $ runQuery q imi)
searchProxim :: Int -> InMemoryIndex -> B.ByteString -> B.ByteString -> Either String PS.Postings
searchProxim d imi defField bs = runSimpleQParser defField bs >>= (\q -> return $ runProximityQuery d q imi)
| jagg/search | src/Search.hs | apache-2.0 | 2,975 | 0 | 12 | 705 | 996 | 513 | 483 | 43 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Forms.Post where
import Model.CoreTypes
import Data.Time
import Text.Blaze.Html (Html)
import Text.Digestive hiding (Post)
import Text.Digestive.Bootstrap
postForm :: Monad m => UTCTime -> Form Html m Post
postForm now =
Post <$> "title" .: text Nothing
<*> "date" .: stringRead "Couldn't parse as UTCTime" (Just now)
<*> "content" .: text Nothing
postFormSpec :: FormMeta
postFormSpec =
FormMeta
{ fm_method = POST
, fm_target = "/write"
, fm_elements =
[ FormElement "title" (Just "Title") InputText
, FormElement "date" (Just "Date") InputText
, FormElement "content" (Just "Content") $ InputTextArea (Just 30) (Just 10)
]
, fm_submitText = "Publish"
}
| julienchurch/julienchurch.com | app/Forms/Post.hs | apache-2.0 | 780 | 0 | 11 | 183 | 220 | 119 | 101 | 22 | 1 |
module Example.SingleCounter where
import Control.Monad
import Control.Monad.Crdt
import Control.Monad.Reader
import Data.Crdt.Counter
action :: Crdt Counter ()
action = do
Counter c <- ask
when (c < 10) $ do
update $ CounterUpdate 1
action
main = putStrLn $ unlines $ fmap (show . runCrdt action . Counter) [0..12]
| edofic/crdt | src/Example/SingleCounter.hs | apache-2.0 | 331 | 0 | 11 | 63 | 123 | 64 | 59 | 12 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Tersus.Cluster.TersusService where
-- | TersusService
-- Contains all the functions and datatypes that control a server side Tersus Application
-- Author: Ernesto Rodriguez
import Prelude
import Control.Distributed.Process
import Control.Monad.IO.Class
import Control.Monad (forever)
import Data.Typeable.Internal (Typeable)
import Tersus.Global
import Control.Monad.Maybe
import Control.Exception (Exception,throw)
import Data.Time.Clock (getCurrentTime,UTCTime)
import Database.Redis hiding (msgChannel)
import Data.Binary (Binary)
-- tersus
import Tersus.Cluster.Types
import Tersus.Cluster.MessageFrontend (broadcastNotificationsProcess)
import Tersus.DataTypes
-- | Exceptions that can result from server side applications
-- | NoStateException: raised if an application that dosen't use acid state tries to access it's acid state
data TersusServiceExceptions = NoStateException deriving (Show,Typeable)
instance Exception TersusServiceExceptions
-- | Represents a tersus server side app.
data TersusServerApp = TersusServerApp
{
-- | The Tersus Application that represents this app. This is here for messaging purposes
-- so normal tersus apps can communicate with it as if it were a tersus app.
applicationRep :: TApplication,
-- | The user that is `running` the app. It's just here because it's easier to integrate
-- it to the current app implementation
userRep :: User,
-- | The function that is executed every time a message is received by the application
msgFun :: TMessage -> TersusServiceM (),
-- | A optional function that is executed every time a message delivery status is
-- obtained
ackwFun :: Maybe (MessageResultEnvelope -> TersusServiceM ()),
-- | Function that is called when the session of a AppInstance expires
expireFun :: Maybe ([AppInstance] -> TersusServiceM ())
}
-- | The datatype that contains all necesary data to run a Tersus Server application
-- this datatype also represents the `state` of the application.
data TersusService = TersusService
{
-- | The port to receive messages and the port other applications use to
-- to send messages to this app
msgChannel :: MessagingPorts,
-- | The channel where message acknowlegements are received
ackwChannel :: AcknowledgementPorts,
-- | The redis connection for the database used by this application
serviceConnection :: Connection,
-- | The list of Tersus servers
tersusNode :: TersusClusterList,
-- | The Tersus Application that represents this app. This is here for messaging purposes
-- so normal tersus apps can communicate with it as if it were a tersus app.
serviceApplication :: TApplication,
-- | The channels that contain the send ports of the tersus applications
serviceSendChannels :: SendAddressTable,
-- | The channels that contain the receive ports of the tersus applications
serviceRecvChannels :: RecvAddressTable
}
-- | The monad on which a server side application runs. It passes a TersusService datatype
-- to represent the state and eventually collapses to a Process since they are intended to
-- be run with cloud haskell
data TersusServiceM a = TersusServiceM {runTersusServiceM :: TersusService -> Process (TersusService,a)}
instance Monad TersusServiceM where
-- | Apply runTersusServiceM to the first argument which is a monad to obtain a function that
-- goes from TersusService -> Process. Apply this function to the TersusService that will
-- be provided as ts and pind the resulting Process to the new state and the result of the
-- monad. Apply k to the result to get a new TersusServiceM and use the runTersusServiceM
-- function applied to the result of applying k and the new TersusService state ts'
m >>= k = TersusServiceM (\ts -> (runTersusServiceM m) ts >>= \(ts',a) -> runTersusServiceM (k a) ts')
return a = TersusServiceM $ (\ts -> return (ts,a))
-- | Use the liftIO function of Process to lift an IO monad into the
-- Process monad, then the resulting value is binded and the provided
-- TersusService state ts is coupled with the value to get back into
-- the TersusServiceM
instance MonadIO TersusServiceM where
liftIO ioVal = TersusServiceM $ \ts -> (liftIO ioVal >>= \x -> return (ts,x))
-- | Run a TersusServiceM with the given TersusService state ts. Usually the initial
-- state which are all the messaging pipeings as defined in the datatype
evalTersusServiceM :: TersusService -> TersusServiceM a -> Process (TersusService,a)
evalTersusServiceM ts (TersusServiceM service) = service ts >>= \a -> return a
recvListenerFun :: (Typeable a, Binary a) => TersusService -> ReceivePort a -> [(a -> TersusServiceM ())] -> Process ()
recvListenerFun ts recvPort funs = forever $ do
recvVal <- receiveChan recvPort
mapM_ (\f -> evalTersusServiceM ts (f recvVal)) funs
-- | Initialize a process that runs the given server side application
makeTersusService :: TersusServerApp -> Connection -> TersusClusterList -> SendAddressTable -> RecvAddressTable -> Process (ProcessId)
makeTersusService tersusServerApp conn server sSendChannels sRecvChannels = do
(aSendPort,aRecvPort) <- newChan
(mSendPort,mRecvPort) <- newChan
let
serverApp = TersusService{
msgChannel = (mSendPort,mRecvPort),
ackwChannel = (aSendPort,aRecvPort),
serviceApplication = applicationRep tersusServerApp,
serviceConnection = conn,
tersusNode = server,
serviceSendChannels = sSendChannels,
serviceRecvChannels = sRecvChannels
}
tAppInstance = AppInstance{
username = nickname $ userRep tersusServerApp,
application = identifier $ applicationRep tersusServerApp
}
broadcastNotificationsProcess [Initialized tAppInstance (mSendPort,aSendPort,"hashPelado")] server
spawnLocal $ recvListenerFun serverApp mRecvPort [recvFunction $ msgFun tersusServerApp]
recvFunction :: (TMessage -> TersusServiceM ()) -> TMessageEnvelope -> TersusServiceM ()
recvFunction f (msg,ackwPort) = do
ts <- getTersusService
-- liftProcess $ sendChan ackwPort $ (
f $ msg
getTersusService :: TersusServiceM (TersusService)
getTersusService = TersusServiceM $ \ts -> return (ts,ts)
-- Default acknowledgement function ignores the message
-- acknowledgement
-- defaultAckwFun :: MessageResultEnvelope -> TersusServiceM ()
-- defaultAckwFun _ = return ()
-- notifyCreateProcess' (TersusService nChannel deliveryChannel mPorts aPorts appInstance clusterList) = do
-- liftIO $ atomically $ writeTChan nChannel (Initialized' appInstance)
-- return (TersusService nChannel deliveryChannel mPorts aPorts appInstance clusterList,())
-- notifyCreateProcess = TersusServiceM $ notifyCreateProcess'
-- getMessages' (TersusService nChannel deliveryChannel mailBox (sChan,rChan) appInstance) = do
-- msgs <- liftIO $ atomically $ readTVar mailBox
-- return ((TersusService nChannel deliveryChannel mailBox (sChan,rChan) appInstance),msgs)
-- getMessages = TersusServiceM getMessages'
liftProcess :: Process a -> TersusServiceM a
liftProcess p = TersusServiceM $ \ts -> p >>= \r -> return (ts,r)
-- getMessage' :: TersusService -> Process (TersusService,TMessageEnvelope)
-- getMessage' (TersusService sDeliveryChannel (mSendPort,mRecvPort) aPorts appInstance' sClusterList state) = do
-- msg <- receiveChan mRecvPort
-- return (TersusService sDeliveryChannel (mSendPort,mRecvPort) aPorts appInstance' sClusterList state,msg)
-- Get the next message delivered to this particular server side application.
-- Ie. message located in the delivery channle created for this app
-- getMessage :: TersusServiceM (TMessageEnvelope)
-- getMessage = TersusServiceM getMessage'
-- sendMessageInt :: TMessage -> TersusService -> Process (TersusService,())
-- sendMessageInt msg (TersusService sDeliveryChannel mPorts (aSendPort,aRecvPort) appInstance' sClusterList state) = do
-- liftIO $ atomically $ writeTChan sDeliveryChannel (msg,aSendPort)
-- return (TersusService sDeliveryChannel mPorts (aSendPort,aRecvPort) appInstance' sClusterList state,())
-- -- Send a message from a server side application it uses the message queue
-- -- form the server where it's actually running
-- sendMessage :: TMessage -> TersusServiceM ()
-- sendMessage msg = TersusServiceM $ sendMessageInt msg
-- -- | Send a message without timestamp, the timestamp will be added automatically
-- sendMessage' :: (UTCTime -> TMessage) -> TersusServiceM ()
-- sendMessage' pMsg = do
-- msg <- (liftIO getCurrentTime) >>= return.pMsg
-- sendMessage msg
-- acknowledgeMsg' :: TMessageEnvelope -> TersusService -> Process (TersusService,())
-- acknowledgeMsg' (msg,aPort) ts = do
-- sendChan aPort (generateHash msg, Delivered , getSendAppInstance msg)
-- return (ts,())
-- | Get the acid state of the given Tersus Server Application
-- getDb :: TersusServiceM (AcidState store)
-- getDb = TersusServiceM getDb'
-- where
-- getDb' tersusService = case memDb tersusService of
-- Nothing -> throw NoStateException
-- Just s -> return (tersusService,s)
-- Acknowledge a received message as received and infomr the
-- sender that the message was received
-- acknowledgeMsg :: (SafeCopy store) => TMessageEnvelope -> TersusServiceM store ()
-- acknowledgeMsg msgEnv = TersusServiceM $ acknowledgeMsg' msgEnv
{-
type MaybeQuery = MaybeT (SqlPersist IO)
{-maybeGetBy :: forall (m :: * -> *) val. (PersistEntity val,
PersistUnique
(PersistEntityBackend val) m) =>
Unique val (PersistEntityBackend val)
-> MaybeT
(PersistEntityBackend val m) (Database.Persist.Store.Entity val)-}
maybeGetBy criterion = MaybeT $ getBy criterion
maybeGet :: forall a (backend :: (* -> *) -> * -> *) (m :: * -> *). (PersistEntity a, PersistStore backend m) => Key backend a -> MaybeT (backend m) a
maybeGet id' = MaybeT $ get id'
{-maybeSelectList :: forall val (m :: * -> *).
(PersistEntity val,
PersistQuery
(PersistEntityBackend val) m) =>
[Filter val]
-> [SelectOpt val]
-> MaybeT
(Database.Persist.Store.PersistEntityBackend val m)
[Database.Persist.Store.Entity val]-}
maybeSelectList l1 l2 = MaybeT $ selectList l1 l2 >>= \res -> case res of
[] -> return Nothing
a -> return $ Just a
-}
| kmels/tersus | Tersus/Cluster/TersusService.hs | bsd-2-clause | 10,769 | 0 | 13 | 2,208 | 1,078 | 634 | 444 | 71 | 1 |
{- Copyright (c) 2008, Scott E. Dillard. All rights reserved. -}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Type level naturals. @Ni@ is a type, @ni@ an undefined value of that type,
-- for @i <- [0..19]@
module Data.Vec.Nat where
data N0
data Succ a
type N1 = Succ N0
type N2 = Succ N1
type N3 = Succ N2
type N4 = Succ N3
type N5 = Succ N4
type N6 = Succ N5
type N7 = Succ N6
type N8 = Succ N7
type N9 = Succ N8
type N10 = Succ N9
type N11 = Succ N10
type N12 = Succ N11
type N13 = Succ N12
type N14 = Succ N13
type N15 = Succ N14
type N16 = Succ N15
type N17 = Succ N16
type N18 = Succ N17
type N19 = Succ N18
n0 :: N0 ; n0 = undefined
n1 :: N1 ; n1 = undefined
n2 :: N2 ; n2 = undefined
n3 :: N3 ; n3 = undefined
n4 :: N4 ; n4 = undefined
n5 :: N5 ; n5 = undefined
n6 :: N6 ; n6 = undefined
n7 :: N7 ; n7 = undefined
n8 :: N8 ; n8 = undefined
n9 :: N9 ; n9 = undefined
n10 :: N10 ; n10 = undefined
n11 :: N11 ; n11 = undefined
n12 :: N12 ; n12 = undefined
n13 :: N13 ; n13 = undefined
n14 :: N14 ; n14 = undefined
n15 :: N15 ; n15 = undefined
n16 :: N16 ; n16 = undefined
n17 :: N17 ; n17 = undefined
n18 :: N18 ; n18 = undefined
n19 :: N19 ; n19 = undefined
-- | @nat n@ yields the @Int@ value of the type-level natural @n@.
class Nat n where nat :: n -> Int
instance Nat N0 where nat _ = 0
instance Nat a => Nat (Succ a) where nat _ = 1+(nat (undefined::a))
class Pred x y | x -> y, y -> x
instance Pred (Succ N0) N0
instance Pred (Succ n) p => Pred (Succ (Succ n)) (Succ p)
| sedillard/Vec | Data/Vec/Nat.hs | bsd-2-clause | 1,798 | 0 | 9 | 436 | 573 | 336 | 237 | -1 | -1 |
module Emulator.Video.Util where
import Emulator.Memory
import Emulator.Types
import Control.Monad.IO.Class
import Data.Array.IArray
import Data.Bits
import Graphics.Rendering.OpenGL
import Utilities.Parser.TemplateHaskell
data ScreenObj =
BG [Tile] Priority Layer |
Sprite [Tile] Priority |
Hidden
deriving (Show, Read, Eq)
data Tile = Tile [HalfWord] QuadCoords
deriving (Show, Read, Eq)
type Layer = Int
type Priority = Int
type AddressIO m = (AddressSpace m, MonadIO m)
type AffineParameters = (GLdouble, GLdouble, GLdouble, GLdouble)
type AffineRefPoints = (GLdouble, GLdouble)
type PaletteFormat = Bool
type QuadCoords = ((GLdouble, GLdouble), (GLdouble, GLdouble), (GLdouble, GLdouble), (GLdouble, GLdouble))
type PixData = Array Address Byte
type TileMapBaseAddress = Address
type TileOffset = (GLdouble, GLdouble)
type TileSet = Array Address Byte
type TileSetBaseAddress = Address
type Centre = (GLdouble, GLdouble)
transformCoords :: [Tile] -> Centre -> AffineParameters -> [Tile]
transformCoords [] _ _ = []
transformCoords ((Tile pix coords):xs) centre params = Tile pix affCoords:transformCoords xs centre params
where
affCoords = affineCoords centre params coords
-- this will be the function that is used
affineCoords :: Centre -> AffineParameters -> QuadCoords -> QuadCoords
affineCoords (xCentre, yCentre) (pa, pb, pc, pd) coords = ((affx1, affy1), (affx2, affy2), (affx3, affy3), (affx4, affy4))
where
((x1, y1), (x2, y2), (x3, y3), (x4, y4)) = coords
affx1 = (pa * (x1 - xCentre)) + (pb * (y1 - yCentre)) + xCentre
affy1 = (pc * (x1 - xCentre)) + (pd * (y1 - yCentre)) + yCentre
affx2 = (pa * (x2 - xCentre)) + (pb * (y2 - yCentre)) + xCentre
affy2 = (pc * (x2 - xCentre)) + (pd * (y2 - yCentre)) + yCentre
affx3 = (pa * (x3 - xCentre)) + (pb * (y3 - yCentre)) + xCentre
affy3 = (pc * (x3 - xCentre)) + (pd * (y3 - yCentre)) + yCentre
affx4 = (pa * (x4 - xCentre)) + (pb * (y4 - yCentre)) + xCentre
affy4 = (pc * (x4 - xCentre)) + (pd * (y4 - yCentre)) + yCentre
bytesToHalfWord :: Byte -> Byte -> HalfWord
bytesToHalfWord lower upper = ((fromIntegral upper :: HalfWord) `shiftL` 8) .|. ((fromIntegral lower :: HalfWord) .&. 0xFF) :: HalfWord
-- If pixel format is 8bpp then the tileIndex read from the map is in steps of 40h
-- If pixel format is 4bpp then the tileIndex read from the map is in steps of 20h
convIntToAddr :: Int -> PaletteFormat -> Address
convIntToAddr n True = (0x00000040 * fromIntegral n)
convIntToAddr n _ = (0x00000020 * fromIntegral n)
-- If pixel format is 8bpp then TileSet is read in chunks of 40h
-- If not then TileSet is read in chunks of 20h
getTile :: PaletteFormat -> Address -> TileSet -> PixData
getTile True tileIdx tileSet = (ixmap (tileIdx, tileIdx + 0x0000003F) (id) tileSet :: PixData)
getTile _ tileIdx tileSet = (ixmap (tileIdx, tileIdx + 0x0000001F) (id) tileSet :: PixData)
convToFixedNum :: Byte -> Byte -> GLdouble
convToFixedNum low up
| sign = negate val
| otherwise = val
where
val = intPor + (fracPor / 256)
hword = bytesToHalfWord low up
fracPor = fromIntegral $ $(bitmask 7 0) hword
intPor = fromIntegral $ $(bitmask 14 8) hword
sign = testBit hword 15
referencePoint :: MWord -> GLdouble
referencePoint word
| sign = negate val
| otherwise = val
where
val = intPor + (frac / 256)
frac = fromIntegral $ $(bitmask 7 0) word :: GLdouble
intPor = fromIntegral $ $(bitmask 26 8) word :: GLdouble
sign = testBit word 27
affineParameters :: Address -> Address -> Address -> Address -> Array Address Byte -> AffineParameters
affineParameters addr0 addr1 addr2 addr3 mem = (pa, pb, pc, pd)
where
pa = convToFixedNum (mem!(addr0)) (mem!(addr0 + 0x00000001))
pb = convToFixedNum (mem!(addr1)) (mem!(addr1 + 0x00000001))
pc = convToFixedNum (mem!(addr2)) (mem!(addr2 + 0x00000001))
pd = convToFixedNum (mem!(addr3)) (mem!(addr3 + 0x00000001))
data BGControl = -- R/W. BGs 0-3
BGControl { bgPriority :: Int -- 0 = Highest
, characterBaseBlock :: TileSetBaseAddress -- =BG Tile Data. Indicates the start of tile counting
, mosaic :: Bool
, colorsPalettes :: Bool -- (0=16/16, 1=256/1)
, screenBaseBlock :: TileMapBaseAddress
, displayAreaFlow :: Bool -- BG 2 & BG 3 only
, screenSize :: Int }
deriving (Show, Read, Eq)
-- Reads a mem address that points to bgcnt register
recordBGControl :: AddressSpace m => Address -> m BGControl
recordBGControl addr = do
hword <- readAddressHalfWord addr
let bgCNT = BGControl (fromIntegral $ $(bitmask 1 0) hword)
(baseTileSetAddr (fromIntegral $ $(bitmask 3 2) hword))
(testBit hword 6)
(testBit hword 7)
(baseTileMapAddr (fromIntegral $ $(bitmask 12 8) hword))
(testBit hword 13)
(fromIntegral $ $(bitmask 15 14) hword)
return bgCNT
-- Gets the base memory addres for the tile
baseTileSetAddr :: Byte -> TileSetBaseAddress
baseTileSetAddr tileBase = 0x06000000 + (0x00004000 * (fromIntegral tileBase))
baseTileMapAddr :: Byte -> TileMapBaseAddress
baseTileMapAddr mapBase = 0x06000000 + (0x00000800 * (fromIntegral mapBase))
| intolerable/GroupProject | src/Emulator/Video/Util.hs | bsd-2-clause | 5,315 | 0 | 18 | 1,182 | 1,801 | 1,000 | 801 | -1 | -1 |
module TinyASM.ByteCode (
ByteCode(..),
size,
compileByteCode
)
where
import Text.Printf (printf)
data ByteCode = BC1 Int
| BC2 Int Int
| BC3 Int Int Int
| BC4 Int Int Int Int
instance Show ByteCode where
show (BC1 op) = "ByteCode " ++ (showHex op)
show (BC2 op b) = (show $ BC1 op) ++ " " ++ (showHex b)
show (BC3 op b c) = (show $ BC2 op b) ++ " " ++ (showHex c)
show (BC4 op b c d) = (show $ BC3 op b c) ++ " " ++ (showHex d)
size :: ByteCode -> Int
size (BC1 _) = 1
size (BC2 _ _) = 2
size (BC3 _ _ _) = 3
size (BC4 _ _ _ _) = 4
compileByteCode :: ByteCode -> [Int]
compileByteCode (BC1 op) = [op]
compileByteCode (BC2 op b) = [op, b]
compileByteCode (BC3 op b c) = [op, b, c]
compileByteCode (BC4 op b c d) = [op, b, c, d]
showHex :: Int -> String
showHex = printf "0x%02x"
| ocus/TinyASM_Haskell | library/TinyASM/ByteCode.hs | bsd-3-clause | 877 | 0 | 10 | 270 | 435 | 231 | 204 | 26 | 1 |
{-
Copyright (c) 2013, Genome Research Limited
Author: Nicholas Clarke <nicholas.clarke@sanger.ac.uk>
-}
module Hgc.Mount (
mkMountPoint
, mkFstabEntry
, mount
, umount
, SLM.MountFlag(..)
, Mount (..)
)
where
import System.Log.Logger
import System.Directory (canonicalizePath
, doesFileExist
, doesDirectoryExist
)
import System.FilePath
import qualified System.Linux.Mount as SLM
import Data.List (intercalate)
import Data.Maybe (catMaybes)
import qualified Data.ByteString.Char8 as B (pack)
import Hgc.Shell
data Mount = Mount
String -- ^ Mount from
FilePath -- ^ Mount to
String -- ^ Mount type
[SLM.MountFlag] -- ^ System independent mount options
[String] -- ^ System dependent mount options
-- | Convert SML option to a string suitable for use in
slmOptionString :: SLM.MountFlag -> Maybe String
slmOptionString opt = case opt of
SLM.Rdonly -> Just "ro"
SLM.Remount -> Just "remount"
SLM.Noatime -> Just "noatime"
SLM.Bind -> Just "bind"
_ -> Nothing
-- | Mount a filesystem.
mount :: Mount -> IO()
mount m @ (Mount from to typ opt1 opt2) =
debugM "hgc.mount" ("Mounting: " ++ mkFstabEntry m) >>
mkdir to >>
SLM.mount from to typ opt1 dd
where dd = B.pack . intercalate "," $ opt2
-- | Unmount a filesystem.
umount :: Mount -> IO ()
umount m@(Mount _ to _ _ _) =
debugM "hgc.mount" ("Unmounting: " ++ mkFstabEntry m) >>
SLM.umount to
mkFstabEntry :: Mount -> String
mkFstabEntry (Mount from to typ opt1 opt2) =
intercalate " " [from, to, typ, intercalate "," opts, "0", "0"]
where opts = (catMaybes $ map slmOptionString opt1) ++ opt2
-- Make a mount point in the container to mount on top of
mkMountPoint :: FilePath -- ^ Root mount point
-> FilePath -- ^ Thing to mount
-> IO (FilePath, FilePath) -- ^ Canoncal resource path, Created mountpoint relative to root
mkMountPoint mountLoc resource = do
resourceC <- canonicalizePath . dropTrailingPathSeparator $ resource
let resourceR = makeRelative "/" resource
isDir <- doesDirectoryExist resourceC
isFile <- doesFileExist resourceC
let mp = mountLoc </> resourceR
mkdir $ mountLoc </> (dropFileName resourceR)
case (isDir, isFile) of
(False, True) -> debugM "hgc.mount" ("Touching file mountpoint " ++ mp) >>
touch mp >> return (resourceC, resourceR)
(True, False) -> debugM "hgc.mount" ("Making directory mountpoint " ++ mp) >>
mkdir mp >> return (resourceC, resourceR)
(True, True) -> ioError . userError $
"Really weird: mount point is both file and directory: " ++ resourceC
(False, False) -> ioError . userError $
"Mount point does not exist or cannot be read: " ++ resourceC | wtsi-hgi/hgc-tools | Hgc/Mount.hs | bsd-3-clause | 2,815 | 53 | 12 | 679 | 706 | 386 | 320 | 63 | 5 |
-- tape something something something
module Tape where
import Zipper
type Tape = Zipper Integer
alterReg :: (Integer -> Integer) -> Tape -> Tape
alterReg f tape = replace (f (readReg tape)) tape
incrReg :: Tape -> Tape
incrReg t = alterReg incr t
where incr :: Integer -> Integer
incr n = n + 1
decrReg :: Tape -> Tape
decrReg t = alterReg decr t
where decr :: Integer -> Integer
decr n = n - 1
nextReg :: Tape -> Tape
nextReg tape =
case nextSafe tape of
Just tape' -> tape'
Nothing -> insertAfter 0 tape
prevReg :: Tape -> (Tape)
prevReg tape =
case prevSafe tape of
Just tape' -> tape'
Nothing -> insertBefore 0 tape
readReg :: Tape -> Integer
readReg tape =
case cursorSafe tape of
Just val -> val
Nothing -> error "Tape initialised incorrectly. Empty Tape can not be read."
writeReg :: Integer -> Tape -> Tape
writeReg = replace
| rodneyp290/Brainfunc | src/Tape.hs | bsd-3-clause | 895 | 0 | 9 | 219 | 305 | 155 | 150 | 30 | 2 |
{-#LANGUAGE BangPatterns #-}
module Main where
import Control.Foldl (Fold(..),FoldM(..))
import qualified Control.Foldl as L
import qualified Control.FoldM as M
import Pipes
import qualified Pipes.Prelude as P
import qualified Data.Vector.Unboxed as V
-- import qualified Data.Vector.Generic as VG
-- import qualified Data.Vector.Fusion.Bundle as VB
import Streaming
import qualified Streaming.Prelude as S
import Criterion.Main
import Data.Functor.Identity
import Data.Foldable (find)
import Data.List (elemIndex)
main :: IO ()
main = do
let size :: Int
size = 10
vfold :: Fold Int a -> V.Vector Int -> a
vfold = \(Fold step begin done) v -> done (V.foldl step begin v)
{-#INLINE vfold #-}
vfoldM :: FoldM Identity Int a -> V.Vector Int -> a
vfoldM = \(FoldM step begin done) vec -> runIdentity (
begin >>= flip (V.foldM step) vec >>= done )
{-#INLINE vfoldM #-}
pfold :: Fold Int a -> Producer Int Identity () -> a
pfold = \f p -> runIdentity (L.purely P.fold f p)
{-#INLINE pfold #-}
pfoldM :: FoldM Identity Int a -> Producer Int Identity () -> a
pfoldM = \f p -> runIdentity (L.impurely P.foldM f p)
{-#INLINE pfoldM #-}
sfold :: Fold Int a -> Stream (Of Int) Identity () -> (Of a ())
sfold = \f p -> runIdentity (L.purely S.fold f p)
{-#INLINE sfold #-}
sfoldM :: FoldM Identity Int a -> Stream (Of Int) Identity () -> (Of a ())
sfoldM = \f p -> runIdentity (L.impurely S.foldM f p)
{-#INLINE sfoldM #-}
lfoldm :: FoldM Identity Int a -> [Int] -> a
lfoldm = \f p -> runIdentity (L.foldM f p)
{-#INLINE lfoldm #-}
p /// q = p (whnf q (replicate size (1::Int)))
{-#INLINE (///) #-}
p //// q = p (whnf q (V.replicate size (1::Int)))
{-#INLINE (////) #-}
p /\ q = p (whnf q (each (replicate size (1::Int)):: Producer Int Identity ()))
-- p /\ q = p (whnf q (P.replicateM size (Identity (1::Int))))
{-#INLINE (/\) #-}
p \/ q = p (whnf q (S.each (replicate size (1::Int)):: Stream (Of Int) Identity ()))
-- p /\ q = p (whnf q (P.replicateM size (Identity (1::Int))))
{-#INLINE (\/) #-}
defaultMain
[ bgroup "list"
[ bgroup "sum" [bench "prelude" /// sum
, bench "pure" /// L.fold L.sum
, bench "impure" /// M.fold M.sum
, bench "generalize" /// lfoldm (L.generalize L.sum)
]
, bgroup "product" [bench "prelude" /// product
, bench "pure" /// L.fold L.product
, bench "impure" /// M.fold M.product
, bench "generalize" /// lfoldm (L.generalize L.product)
]
, bgroup "null" [bench "prelude" /// null
, bench "pure" /// L.fold L.null
, bench "impure" /// M.fold M.null
, bench "generalize" /// lfoldm (L.generalize L.null)
]
, bgroup "length" [bench "prelude" /// length
, bench "pure" /// L.fold L.length
, bench "impure" /// M.fold M.length
, bench "generalize" /// lfoldm (L.generalize L.length)
]
, bgroup "minimum" [bench "prelude" /// minimum
, bench "pure" /// L.fold L.minimum
, bench "impure" /// M.fold M.minimum
, bench "generalize" /// lfoldm (L.generalize L.minimum)
]
, bgroup "maximum" [bench "prelude" /// maximum
, bench "pure" /// L.fold L.maximum
, bench "impure" /// M.fold M.maximum
, bench "generalize" /// lfoldm (L.generalize L.maximum)
]
, bgroup "any" [bench "prelude" /// any even
, bench "pure" /// L.fold (L.any even)
, bench "impure" /// M.fold (M.any even)
, bench "generalize" /// lfoldm (L.generalize (L.any even))
]
, bgroup "elem" [bench "prelude" /// elem 12
, bench "pure" /// L.fold (L.elem 12)
, bench "impure" /// M.fold (M.elem 12)
, bench "generalize" /// lfoldm (L.generalize (L.elem 12))
]
, bgroup "find" [bench "prelude" /// find even
, bench "pure" /// L.fold (L.find even)
, bench "impure" /// M.fold (M.find even)
, bench "generalize" /// lfoldm (L.generalize (L.find even))
]
, bgroup "index" [bench "prelude" /// (!! (size-1))
, bench "pure" /// L.fold (L.index (size-1))
, bench "impure" /// M.fold (M.index (size-1))
, bench "generalize" /// lfoldm (L.generalize (L.index (size-1)))
]
, bgroup "elemIndex" [bench "prelude" /// elemIndex (size-1)
, bench "pure" /// L.fold (L.elemIndex (size-1))
, bench "impure" /// M.fold (M.elemIndex (size-1))
, bench "generalize" /// lfoldm (L.generalize (L.elemIndex (size-1)))
]
]
, bgroup "vector"
[ bgroup "sum"
[bench "prelude" //// V.sum
, bench "pure" //// vfold L.sum
, bench "impure" //// vfoldM M.sum
, bench "generalize" //// vfoldM (L.generalize L.sum)
]
, bgroup "product" [bench "prelude" //// V.product
, bench "pure" //// vfold L.product
, bench "impure" //// vfoldM M.product
, bench "generalize" //// vfoldM (L.generalize L.product)
]
, bgroup "null" [bench "prelude" //// V.null
, bench "pure" //// vfold L.null
, bench "impure" //// vfoldM M.null
, bench "generalize" //// vfoldM (L.generalize L.null)
]
, bgroup "length" [bench "prelude" //// V.length
, bench "pure" //// vfold L.length
, bench "impure" //// vfoldM M.length
, bench "generalize" //// vfoldM (L.generalize L.length)
]
, bgroup "minimum" [bench "prelude" //// V.minimum
, bench "pure" //// vfold L.minimum
, bench "impure" //// vfoldM M.minimum
, bench "generalize" //// vfoldM (L.generalize L.minimum)
]
, bgroup "any" [bench "prelude" //// V.all even
, bench "pure" //// vfold (L.all even)
, bench "impure" //// vfoldM (M.all even)
, bench "generalize" //// vfoldM (L.generalize (L.all even))
]
, bgroup "elem" [bench "prelude" //// V.elem 12
, bench "pure" //// vfold (L.elem 12)
, bench "impure" //// vfoldM (M.elem 12)
, bench "generalize" //// vfoldM (L.generalize (L.elem 12))
]
, bgroup "find" [bench "prelude" //// V.find even
, bench "pure" //// vfold (L.find even)
, bench "impure" //// vfoldM (M.find even)
, bench "generalize" //// vfoldM (L.generalize (L.find even))
]
, bgroup "index" [bench "prelude" //// (V.! (size-1))
, bench "pure" //// vfold (L.index (size-1))
, bench "impure" //// vfoldM (M.index (size-1))
, bench "generalize" //// vfoldM (L.generalize (L.index (size-1)))
]
, bgroup "elemIndex" [bench "prelude" //// V.elemIndex (size-1)
, bench "pure" //// vfold (L.elemIndex (size-1))
, bench "impure" //// vfoldM (M.elemIndex (size-1))
, bench "generalize" //// vfoldM (L.generalize (L.elemIndex (size-1)))
]
]
, bgroup "pipes"
[ bgroup "sum"
[bench "prelude" /\ P.sum
, bench "pure" /\ pfold L.sum
, bench "impure" /\ pfoldM M.sum
, bench "generalize" /\ pfoldM (L.generalize L.sum)
]
, bgroup "product" [bench "prelude" /\ P.product
, bench "pure" /\ pfold L.product
, bench "impure" /\ pfoldM M.product
, bench "generalize" /\ pfoldM (L.generalize L.product)
]
, bgroup "null" [bench "prelude" /\ P.null
, bench "pure" /\ pfold L.null
, bench "impure" /\ pfoldM M.null
, bench "generalize" /\ pfoldM (L.generalize L.null)
]
, bgroup "length" [bench "prelude" /\ P.length
, bench "pure" /\ pfold L.length
, bench "impure" /\ pfoldM M.length
, bench "generalize" /\ pfoldM (L.generalize L.length)
]
, bgroup "minimum" [bench "prelude" /\ P.minimum
, bench "pure" /\ pfold L.minimum
, bench "impure" /\ pfoldM M.minimum
, bench "generalize" /\ pfoldM (L.generalize L.minimum)
]
]
--
, bgroup "streaming"
[ bgroup "sum"
[bench "prelude" \/ S.sum
, bench "pure" \/ sfold L.sum
, bench "impure" \/ sfoldM M.sum
, bench "generalize" \/ sfoldM (L.generalize L.sum)
]
, bgroup "product" [bench "prelude" \/ S.product
, bench "pure" \/ sfold L.product
, bench "impure" \/ sfoldM M.product
, bench "generalize" \/ sfoldM (L.generalize L.product)
]
, bgroup "length" [bench "prelude" \/ S.length
, bench "pure" \/ sfold L.length
, bench "impure" \/ sfoldM M.length
, bench "generalize" \/ sfoldM (L.generalize L.length)
]
, bgroup "minimum" [bench "prelude" \/ S.minimum
, bench "pure" \/ sfold L.minimum
, bench "impure" \/ sfoldM M.minimum
, bench "generalize" \/ sfoldM (L.generalize L.minimum)
]
]
]
| michaelt/foldm | benchmarks/Bench.hs | bsd-3-clause | 10,913 | 0 | 20 | 4,536 | 3,355 | 1,667 | 1,688 | -1 | -1 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}
--
-- | Copy all arguments to a function in to variables which are named the same
-- as the function's parameters. This is known as Grail Normal Form [1] and
-- is the ANF equivalent of phi-elimination on SSA.
--
-- 1. Grail: a functional form for imperative mobile code.
-- Lennart Beringer, Kenneth MacKenzie and Ian Stark
-- http://homepages.inf.ed.ac.uk/stark/graffi.pdf
--
module River.Core.Transform.Grail (
grailOfProgram
, grailOfTerm
, GrailError(..)
) where
import Data.Map (Map)
import qualified Data.Map as Map
import River.Bifunctor
import River.Core.Syntax
data GrailError n a =
GrailFunctionNotFound !a !n ![Atom n a]
| GrailCallArityMismatch !a !n ![Atom n a] ![n]
deriving (Eq, Ord, Show, Functor)
grailOfProgram :: Ord n => Program k p n a -> Either (GrailError n a) (Program k p n a)
grailOfProgram = \case
Program a tm ->
Program a <$> grailOfTerm Map.empty tm
grailOfTerm :: Ord n => Map n [n] -> Term k p n a -> Either (GrailError n a) (Term k p n a)
grailOfTerm env0 = \case
Return a tl ->
grailOfTail env0 tl $ pure . Return a
If a k i t e ->
If a k i
<$> grailOfTerm env0 t
<*> grailOfTerm env0 e
Let a ns tl0 tm ->
grailOfTail env0 tl0 $ \tl ->
Let a ns tl <$>
grailOfTerm env0 tm
LetRec a bs0 tm -> do
(env, bs) <- grailOfBindings env0 bs0
LetRec a bs <$>
grailOfTerm env tm
grailOfBindings ::
Ord n =>
Map n [n] ->
Bindings k p n a ->
Either (GrailError n a) (Map n [n], Bindings k p n a)
grailOfBindings env0 = \case
Bindings a bs ->
let
env1 =
Map.fromList $ fmap (second paramsOfBinding) bs
env =
env1 `Map.union` env0
in
(env,) . Bindings a <$>
traverse (secondA (grailOfBinding env)) bs
paramsOfBinding :: Binding k p n a -> [n]
paramsOfBinding = \case
Lambda _ ns _ ->
ns
grailOfBinding :: Ord n => Map n [n] -> Binding k p n a -> Either (GrailError n a) (Binding k p n a)
grailOfBinding env = \case
Lambda a ns tm ->
Lambda a ns <$> grailOfTerm env tm
grailOfTail ::
Ord n =>
Map n [n] ->
Tail p n a ->
(Tail p n a -> Either (GrailError n a) (Term k p n a)) ->
Either (GrailError n a) (Term k p n a)
grailOfTail env tl mkTerm =
case tl of
Copy a xs ->
mkTerm $ Copy a xs
Call a n xs ->
case Map.lookup n env of
Nothing ->
Left $ GrailFunctionNotFound a n xs
Just ns ->
if length ns /= length xs then
Left $ GrailCallArityMismatch a n xs ns
else
Let a ns (Copy a xs) <$>
mkTerm (Call a n $ fmap (Variable a) ns)
Prim a n xs ->
mkTerm $ Prim a n xs
| jystic/river | src/River/Core/Transform/Grail.hs | bsd-3-clause | 2,817 | 0 | 18 | 832 | 1,047 | 518 | 529 | 92 | 5 |
module Main where
import AminoAcid (HydratedAminoAcid)
import AminoAcidPDB (pdbAminoParser)
import qualified Data.Text.IO as TIO (readFile)
import System.Environment (getArgs)
import Text.Parsec (parse)
main :: IO ()
main = do
args <- getArgs
contents <- TIO.readFile $ head args
result $ parse pdbAminoParser "pdb parser" contents
result :: (Show a) => Either a [HydratedAminoAcid] -> IO ()
result (Left err) = putStr "Parse error: " >> print err
result (Right pdbLines) = mconcat $ printLine <$> pdbLines
printLine :: HydratedAminoAcid -> IO ()
printLine = print
| mosigo/haskell-sandbox | app/AminoParser.hs | bsd-3-clause | 649 | 0 | 9 | 168 | 202 | 107 | 95 | 16 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
module LA.Instances () where
import Data.Vector.Fixed
import LA.Algebra
import Prelude hiding (foldl, zipWith, map, replicate)
instance (Additive a, Vector v a) => Additive (v a) where
add = zipWith add ; {-# INLINE add #-}
neg = map neg ; {-# INLINE neg #-}
zero = replicate zero ; {-# INLINE zero #-}
instance (Multiplicative a, Vector v a) => Multiplicative (v a) where
mul = zipWith mul ; {-# INLINE mul #-}
one = replicate one ; {-# INLINE one #-}
instance (Additive a, Multiplicative a, Vector v a) => VectorSpace (v a) where
type Scalar (v a) = a
scale = flip (map . mul) ; {-# INLINE scale #-}
instance (Additive a, Multiplicative a, Vector v a) => InnerSpace (v a) where
dot a = foldl add zero . (a .*)
| chalmers-kandidat14/LA | LA/Instances.hs | bsd-3-clause | 870 | 0 | 8 | 201 | 280 | 157 | 123 | 19 | 0 |
module Clean where
import Data.List.Split
import System.FilePath.Glob
import System.FilePath.Posix
import Data.List (intercalate)
import Control.Applicative
import Control.Concurrent
import Control.Monad
import Data.Monoid
import Data.Maybe
import ID3.Simple
import System
import Data.Rated
import Util
data MetaData = MetaData {
artist :: Rated String
, title :: Rated String
} deriving (Show)
data Song = Song {
songFileName :: FilePath
}
type Cleaner = Song -> IO MetaData
-- MetaData is a monoid
instance Monoid MetaData where
(MetaData a1 t1) `mappend` (MetaData a2 t2) = MetaData (a1 <|> a2) (t1 <|> t2)
mempty = MetaData Junk Junk
-- Pretty print metadata
prettyMeta :: MetaData -> String
prettyMeta m@(MetaData artist title) = joined <?> show m
where
joined = joinStr " - " <$> unk artist <*> unk title
joinStr sep a b = a ++ sep ++ b
unk m = m <|> pure "Unknown"
-- Parse metadata from filename
filenameMeta :: Song -> MetaData
filenameMeta s' = MetaData artist title
where
s = songFileName s'
rate = Rate 1
fileName = snd . splitFileName $ s
stripRate = rate . stripMp3
dashSplit = map trim $ splitOn "-" fileName
stripMp3 name = case splitOn "." name of
[] -> name
[s] -> name
ss -> intercalate "." . init $ ss
(artist, title) = case dashSplit of
[] -> (Junk, Junk)
[t] -> (Junk, stripRate t)
[a, t] -> (rate a, stripRate t)
a:t:rest -> (rate a, rate t)
-- Convert an ID3Tag to MetaData
tagToMeta :: Tag -> MetaData
tagToMeta t = let rate = (\f -> maybeToRated 10 . f $ t) in
MetaData (rate getArtist)
(rate getTitle)
-- Parse metadata from id3
id3Meta :: Song -> IO MetaData
id3Meta song = readTag file >>= return . metaFromMaybeTag
where
file = songFileName song
metaFromMaybeTag Nothing = mempty
metaFromMaybeTag (Just t) = tagToMeta t
-- Get our data from many different sources
getMeta :: [Cleaner] -> Song -> IO MetaData
getMeta cleaners song = mconcat <$> mapM ($song) cleaners
| jb55/hmetadata | Clean.hs | bsd-3-clause | 2,302 | 0 | 13 | 732 | 701 | 370 | 331 | 56 | 6 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main where
import Prelude hiding (lookup)
import Control.Applicative
import Control.Monad.IO.Class
import Control.Monad.Trans.Either
import Data.Aeson
import Data.ByteString.Char8 (ByteString, pack, unpack)
import qualified Data.ByteString.Base64 as BS64
import Data.List
import Data.Monoid
import Data.Proxy
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time
import Network.Wai.Handler.Warp
import Servant.API
import Servant.Common.Text
import Servant.Server
import Network.Wai (Request)
import Network.Wai.Middleware.Cors
import Network.Wai.Middleware.RequestLogger
import Network.HTTP.Types.Method
import qualified Crypto.Hash.SHA256 as SHA256
import OptionsApp
--------------------------------------------------------------------------------
-- | Packs username and password login requests into a consistent structure
data AuthPack = AuthPack {
username :: String,
password :: String
}
instance FromJSON AuthPack where
parseJSON (Object o) = AuthPack <$> o .: "username" <*> o .: "password"
-- | Results of login attempts: either you're authenticated, or you're not.
data AuthResult = Authenticated {
identity :: String,
token :: String,
expiry :: UTCTime
} | Unauthenticated
instance ToJSON AuthResult where
toJSON Authenticated{..} = object [ "success" .= True
, "identity" .= identity
, "token" .= token
, "expiry" .= expiry ]
toJSON Unauthenticated = object [ "success" .= False ]
-- | HTTP Headers
newtype HttpHeader = HttpHeader Text
deriving (Eq, Show, FromText, ToText)
-- | String denoting computing resources.
type CompResource = String
-- | Results of resource lookup.
data GetResourceResult = FoundResources [CompResource] | NoResources | NoUser deriving (Show)
instance ToJSON GetResourceResult where
toJSON (FoundResources r) = object [ "success" .= True
, "resources" .= r ]
toJSON NoResources = object [ "success" .= True
, "resources" .= ([] :: CompResource) ]
toJSON NoUser = object [ "success" .= False ]
--------------------------------------------------------------------------------
-- POST /auth
-- Authenticate a given consumer username & password
-- against a given resource
-- Returns a 201 Created
type MetaDataAPI = "auth" :> ReqBody AuthPack
:> Post AuthResult
-- GET /resource
-- Get resources for a current token
:<|> "resource" :> Header "authorization" HttpHeader
:> Get GetResourceResult
server :: Server MetaDataAPI
server = doAuth :<|> doGetResources
doAuth :: AuthPack -> EitherT (Int, String) IO AuthResult
doAuth ap = liftIO $ tryAuth ap
doGetResources :: Maybe HttpHeader -> EitherT (Int, String) IO GetResourceResult
doGetResources t = liftIO $ tryGetResources t
metaAPI :: Proxy MetaDataAPI
metaAPI = Proxy
--------------------------------------------------------------------------------
-- | Try and authenticate user against a hardcoded list of credentials
tryAuth :: AuthPack -> IO AuthResult
tryAuth AuthPack{..} =
case lookup username defaultUsers of
Just p ->
if p == password
then do
t <- getCurrentTime
return $ Authenticated username (makeKey username p) t
else return Unauthenticated
_ -> return Unauthenticated
-- | Make me a key.
-- Don't do this in production.
makeKey :: String -> String -> String
makeKey u p = unpack $ BS64.encode $ SHA256.hash $ pack $ u <> p
-- | Gets a username from a key using a stupid lousy slow method.
-- Don't do this in production.
isOkKey :: String -> IO (Maybe String)
isOkKey ('O':'A':'u':'t':'h':' ':k) = return $ lookup k allKeys
where
allKeys = map toKey defaultUsers
toKey (u,p) = (makeKey u p, u)
-- | Try and get resources that matches a user that owns a given token.
tryGetResources :: Maybe HttpHeader -> IO GetResourceResult
tryGetResources (Just (HttpHeader k)) = do
maybeUsername <- isOkKey (T.unpack k)
case maybeUsername of
Just u -> do
case lookup u defaultUserResources of
Just r -> do
return $ FoundResources r
_ -> return $ NoResources
_ -> return NoUser
tryGetResources _ = return NoUser
-- | Hardcoded credentials
defaultUsers :: [(String, String)]
defaultUsers = [ ("jim@anchor.net.au", "bob")
, ("hi@anchor.net.au", "there")
, ("jane@anchor.net.au", "doe")
, ("hoob@anchor.net.au", "adoob")]
-- | User resources
defaultUserResources :: [(String, [CompResource])]
defaultUserResources = [ ("jim@anchor.net.au", [ "server:banjo"
, "server:timpani"])
, ("jane@anchor.net.au", [ "server:gamelan"
, "server:theremin"
, "server:lfo"]) ]
--------------------------------------------------------------------------------
-- | Run app
main :: IO ()
main = do
putStrLn "Running on http://localhost:8080"
Network.Wai.Handler.Warp.run 8080 $
logStdoutDev $
cors myCors $
handleOptions $
serve metaAPI server
-- | My CORS policy
myCors :: Request -> Maybe CorsResourcePolicy
myCors _ = Just $ simpleCorsResourcePolicy {
corsOrigins = Just (["http://localhost:8000"], True)
, corsMethods = [methodGet, methodPost, methodOptions]
, corsRequestHeaders = ["Content-Type", "Authorization"]
, corsVaryOrigin = True
, corsRequireOrigin = True
}
| anchor/purescript-ui-sandbox | server/Main.hs | bsd-3-clause | 6,265 | 0 | 18 | 1,760 | 1,276 | 716 | 560 | 122 | 3 |
module Main where
import Control.Exception
import Control.Monad
import System.FilePath
import System.Directory
import System.Process
import Control.Concurrent
import Data.List.Split
import qualified Data.HashTable.IO as H
import qualified Data.ByteString.Lazy as L
import Data.Time.Clock
import qualified Codec.Archive.Tar as Tar
import Network
import System.Environment
import System.IO
import System.IO.Unsafe
import Utils
-- hashtable of app identifiers and process handles
ht :: (H.BasicHashTable Int ProcessHandle)
{-# NOINLINE ht #-}
ht = unsafePerformIO $ H.new
tmpDir :: FilePath
tmpDir = "tmp"
main :: IO ()
main = do
portstr <- head `fmap` getArgs
let port = PortNumber $ toEnum $ read portstr
bracket (listenOn port) sClose $ \s -> do
exists <- doesDirectoryExist tmpDir
when exists $ removeDirectoryRecursive tmpDir
createDirectory tmpDir
htMutex <- newMVar 0
forever $ do
(h, _, _) <- accept s
forkIO $ handleConnection h htMutex
`finally` hClose h
handleConnection :: Handle -> MVar Int -> IO ()
handleConnection h htMutex = foreverOrEOF2 h $ do
cmd <- trim `fmap` hGetLine h
case cmd of
"statuses" -> do -- prints list of processes
statusList <- atomic htMutex $ H.toList ht
hPutStrLn h (show $ map fst statusList)
"launch" -> do -- prints pid
putStrLn "launch called!"
-- format:
-- shell cmd
-- identifier (as an int)
-- var1=val1
-- var2=val2
-- ...
--
-- num bytes
-- tar data
shellcmd <- trim `fmap` hGetLine h
putStrLn $ "SHELL: " ++ (show shellcmd)
identifier <- (read . trim) `fmap` hGetLine h
putStrLn $ "ID: " ++ (show (identifier :: Int))
envs <- readenvs h
nbytes <- read `fmap` hGetLine h
tarfile <- L.hGet h nbytes
let entries = Tar.read tarfile
Tar.unpack tmpDir entries
void $ forkIO $ startApp htMutex shellcmd envs tmpDir identifier 0
"kill" -> atomic htMutex $ do -- OK or NOT FOUND
-- format:
-- app identifier
key <- (read . trim) `fmap` hGetLine h
mPHandle <- H.lookup ht key
case mPHandle of
Nothing -> hPutStrLn h "NOT FOUND"
Just pHandle -> do
terminateProcess pHandle
H.delete ht key
hPutStrLn h "OK"
_ -> do
hPutStrLn h $ "INVALID COMMAND (" ++ cmd ++ ")"
startApp :: MVar Int
-> String -- Command
-> [(String, String)] -- Environment
-> FilePath -- cwd
-> Int -- Identifier
-> Int -- Retries
-> IO ()
startApp htMutex command envs cwdpath identifier retries = when (retries < 5) $ do
output <- openFile (cwdpath </> "log.out") AppendMode
err <- openFile (cwdpath </> "log.err") AppendMode
input <- openFile "/dev/null" ReadMode
let createProc = (shell command) { env = Just envs
, cwd = Just cwdpath
, std_in = UseHandle input
, std_out = UseHandle output
, std_err = UseHandle err }
pHandle <- atomic htMutex $ do
(_, _, _, pHandle) <- createProcess createProc
hClose output
hClose err
hClose input
H.insert ht identifier pHandle
return pHandle
startTime <- getCurrentTime
_ <- waitForProcess pHandle
endTime <- getCurrentTime
mPHandle <- withMVar htMutex $ \_ -> H.lookup ht identifier
case mPHandle of
Nothing -> removeDirectoryRecursive cwdpath
Just _ -> do
atomic htMutex $ H.delete ht identifier
removeFromController command identifier
let nextRetries = if (diffUTCTime endTime startTime < 30) then
retries + 1
else 0
startApp htMutex command envs cwdpath identifier nextRetries
-- Utils
removeFromController :: Show a => String -> a -> IO ()
removeFromController appname identifier = do
let hostname = "localhost" -- hostname of the app controller
port = PortNumber 1234 -- port of the app controller
h <- connectTo hostname port -- handle for the app controller
hPutStrLn h "remove"
hPutStrLn h appname
hPutStrLn h $ show identifier
readenvs :: Handle -> IO [(String,String)]
readenvs h = go h []
where go hand list = do
line <- trim `fmap` hGetLine hand
putStrLn line
if line == "" then
return $ reverse list
else go hand $ (parseEnv line):list
parseEnv :: String -> (String, String)
parseEnv envString =
let (key:value:[]) = splitOn "=" envString
in (key, value)
| scslab/appdeploy | src/appdeployer.hs | bsd-3-clause | 4,973 | 0 | 20 | 1,695 | 1,395 | 691 | 704 | 121 | 5 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module TCRError where
import Control.Monad.Reader
import Control.Monad.Error
import Database.TokyoCabinet
(
TCM
, runTCM
, new
, OpenMode(..)
, TCDB
, HDB
, BDB
, FDB
)
import Database.TokyoCabinet.Storable
import qualified Database.TokyoCabinet as TC
newtype TCRError tc e a =
TCRError { runTCRError :: ErrorT e (ReaderT tc TCM) a}
deriving (Monad, MonadReader tc, MonadError e)
runTCRE :: TCRError tc e a -> tc -> TCM (Either e a)
runTCRE = runReaderT . runErrorT . runTCRError
liftT :: (Error e) => TCM a -> TCRError tc e a
liftT = TCRError . lift . lift
open :: (TCDB tc) => String -> [OpenMode] -> TCRError tc String ()
open name mode = do tc <- ask
res <- liftT $ TC.open tc name mode
if res then return () else throwError "open failed"
close :: (TCDB tc) => TCRError tc String ()
close = ask >>= liftT . TC.close >>= \res ->
if res then return () else throwError "close failed"
put :: (TCDB tc) => String -> String -> TCRError tc String ()
put key val = do tc <- ask
res <- liftT $ TC.put tc key val
if res then return () else throwError "put failed"
get :: (TCDB tc) => String -> TCRError tc String (Maybe String)
get key = do tc <- ask
liftT $ TC.get tc key
kvstore :: (TCDB tc) => [(String, String)] -> TCRError tc String ()
kvstore kv = do open "abcd.tch" [OREADER]
mapM_ (uncurry put) kv
close
main :: IO ()
main = runTCM $ do h <- new :: TCM BDB
let kv = [("foo", "100"), ("bar", "200")]
flip runTCRE h $ catchError (kvstore kv) (\e -> error e)
>> return ()
| tom-lpsd/tokyocabinet-haskell | examples/TCRError.hs | bsd-3-clause | 1,773 | 0 | 13 | 544 | 675 | 353 | 322 | 46 | 2 |
-- 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.Ordinal.RU.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Ordinal.RU.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "RU Tests"
[ makeCorpusTest [This Ordinal] corpus
]
| rfranek/duckling | tests/Duckling/Ordinal/RU/Tests.hs | bsd-3-clause | 600 | 0 | 9 | 96 | 80 | 51 | 29 | 11 | 1 |
module EFA.Example.Topology.LinearTwo where
import EFA.Application.Utility ( topologyFromEdges )
import qualified EFA.Graph.Topology.Node as Node
import qualified EFA.Graph.Topology as Topo
import qualified EFA.Report.Format as Format
data Node = Source | Crossing | Sink deriving (Eq, Ord, Enum, Show)
node0, node1, node2 :: Node
node0 = Source
node1 = Crossing
node2 = Sink
instance Node.C Node where
display Source = Format.literal "Quelle"
display Crossing = Format.literal "Kreuzung"
display Sink = Format.literal "Senke"
subscript = Format.integer . fromIntegral . fromEnum
dotId = Node.dotIdDefault
typ Source = Node.AlwaysSource
typ Crossing = Node.Crossing
typ Sink = Node.AlwaysSink
topology :: Topo.Topology Node
topology = topologyFromEdges [(Source, Crossing), (Crossing, Sink)]
| energyflowanalysis/efa-2.1 | src/EFA/Example/Topology/LinearTwo.hs | bsd-3-clause | 839 | 0 | 8 | 149 | 240 | 140 | 100 | 21 | 1 |
module SkeletonTemplates.IUnzipFilter2D
( iunzipFilter2DActor
) where
import AstMappings
import qualified AbsCAL as C
import qualified AbsRIPL as R
import Debug.Trace
import SkeletonTemplates.CalTypes
import Types
iunzipFilter2DActor :: String -> Dimension -> R.AnonFun -> R.AnonFun -> C.Type -> C.Type -> C.Actor
iunzipFilter2DActor actorName (Dimension width height) anonFun1 anonFun2 incomingType outgoingType =
let ioSig =
C.IOSg
[C.PortDcl inType (C.Ident "In1")]
[C.PortDcl outType (C.Ident "Out1")
,C.PortDcl outType (C.Ident "Out2")]
inType = incomingType
outType = outgoingType
functions =
[ C.UnitCode (C.UFunDecl maxFun)
, C.UnitCode (C.UFunDecl (kernelFun "applyKernel1" anonFun1))
, C.UnitCode (C.UFunDecl (kernelFun "applyKernel2" anonFun2))
, C.UnitCode (C.UFunDecl mkModFunctionMod)
]
-- , C.UnitCode (C.UFunDecl mkModFunctionModTwoArgs)]
actions =
[ C.ActionCode (populateBufferAction width)
, C.ActionCode (donePopulateBufferAction width)
, C.ActionCode (topLeftAction width)
, C.ActionCode (topRowAction width)
, C.ActionCode (topRightAction width)
, C.ActionCode (midLeftAction1 width height)
, C.ActionCode (midLeftAction2 width height)
, C.ActionCode (midLeftActionNoConsume1 width height)
, C.ActionCode (midLeftActionNoConsume2 width height)
, C.ActionCode (midAction1 width height)
, C.ActionCode (midAction2 width height)
, C.ActionCode (midActionNoConsume1 width height)
, C.ActionCode (midActionNoConsume2 width height)
, C.ActionCode (midRightAction1 width height)
, C.ActionCode (midRightAction2 width height)
, C.ActionCode (midRightActionNoConsume1 width height)
, C.ActionCode (midRightActionNoConsume2 width height)
, C.ActionCode (bottomLeftActionNoConsume1 width height)
, C.ActionCode (bottomLeftActionNoConsume2 width height)
, C.ActionCode (bottomRowActionNoConsume1 width height)
, C.ActionCode (bottomRowActionNoConsume2 width height)
, C.ActionCode (bottomRightActionNoConsume1 width height)
, C.ActionCode (bottomRightActionNoConsume2 width height)
]
in C.ActrSchd
(C.PathN [C.PNameCons (C.Ident "cal")])
[]
(C.Ident actorName)
[]
ioSig
(globalVars width)
(functions ++ actions)
fsmSchedule
[]
globalVars width
-- uint(size=16) bufferSize = imageWidth * 2 + 3;
=
[ C.GlobVarDecl
(C.VDeclExpIMut
(uintCalType 16)
(C.Ident "bufferSize")
[]
(C.BEAdd (C.BEMult (mkInt width) (mkInt 2)) (mkInt 3)))
-- uint(size=16) buffer[bufferSize];
, C.GlobVarDecl
(C.VDecl
(intCalType 16)
(C.Ident "buffer")
[C.BExp (C.EIdent (C.Ident "bufferSize"))])
-- uint(size=16) idx := 0;
, C.GlobVarDecl (C.VDeclExpMut (intCalType 16) (C.Ident "idx") [] (mkInt 0))
-- uint(size=16) populatePtr := 0;
, C.GlobVarDecl
(C.VDeclExpMut (intCalType 16) (C.Ident "populatePtr") [] (mkInt 0))
-- uint(size=16) processedMidRows := 0;
, C.GlobVarDecl
(C.VDeclExpMut (intCalType 16) (C.Ident "processedRows") [] (mkInt 0))
-- uint(size=32) consumed := 0;
, C.GlobVarDecl
(C.VDeclExpMut (uintCalType 32) (C.Ident "consumed") [] (mkInt 0))
, C.GlobVarDecl
(C.VDeclExpMut (uintCalType 16) (C.Ident "midPtr") [] (mkInt 0))
, C.GlobVarDecl
(C.VDeclExpMut (boolCalType) (C.Ident "isEven") [] (mkBool True))
]
fsmSchedule :: C.ActionSchedule
fsmSchedule =
C.SchedfsmFSM
(C.Ident "s0")
[ C.StTrans (C.Ident "s0") (C.Ident "populateBuffer") (C.Ident "s0")
, C.StTrans (C.Ident "s0") (C.Ident "donePopulateBuffer") (C.Ident "s1")
, C.StTrans (C.Ident "s1") (C.Ident "topLeft") (C.Ident "s2")
, C.StTrans (C.Ident "s2") (C.Ident "topRow") (C.Ident "s2")
, C.StTrans (C.Ident "s2") (C.Ident "topRight") (C.Ident "s3")
, C.StTrans (C.Ident "s3") (C.Ident "midLeft1") (C.Ident "s4")
, C.StTrans (C.Ident "s3") (C.Ident "midLeft2") (C.Ident "s4")
, C.StTrans (C.Ident "s3") (C.Ident "midLeftNoConsume1") (C.Ident "s4")
, C.StTrans (C.Ident "s3") (C.Ident "midLeftNoConsume2") (C.Ident "s4")
, C.StTrans (C.Ident "s4") (C.Ident "mid1") (C.Ident "s4")
, C.StTrans (C.Ident "s4") (C.Ident "mid2") (C.Ident "s4")
, C.StTrans (C.Ident "s4") (C.Ident "midNoConsume1") (C.Ident "s4")
, C.StTrans (C.Ident "s4") (C.Ident "midNoConsume2") (C.Ident "s4")
, C.StTrans (C.Ident "s4") (C.Ident "midRight1") (C.Ident "s5")
, C.StTrans (C.Ident "s4") (C.Ident "midRight2") (C.Ident "s5")
, C.StTrans (C.Ident "s4") (C.Ident "midRightNoConsume1") (C.Ident "s5")
, C.StTrans (C.Ident "s4") (C.Ident "midRightNoConsume2") (C.Ident "s5")
, C.StTrans (C.Ident "s5") (C.Ident "midLeft1") (C.Ident "s4")
, C.StTrans (C.Ident "s5") (C.Ident "midLeft2") (C.Ident "s4")
, C.StTrans (C.Ident "s5") (C.Ident "midLeftNoConsume1") (C.Ident "s4")
, C.StTrans (C.Ident "s5") (C.Ident "midLeftNoConsume2") (C.Ident "s4")
, C.StTrans (C.Ident "s5") (C.Ident "bottomLeftNoConsume1") (C.Ident "s6")
, C.StTrans (C.Ident "s5") (C.Ident "bottomLeftNoConsume2") (C.Ident "s6")
, C.StTrans (C.Ident "s6") (C.Ident "bottomRowNoConsume1") (C.Ident "s6")
, C.StTrans (C.Ident "s6") (C.Ident "bottomRowNoConsume2") (C.Ident "s6")
, C.StTrans (C.Ident "s6") (C.Ident "bottomRightNoConsume1") (C.Ident "s0")
, C.StTrans (C.Ident "s6") (C.Ident "bottomRightNoConsume2") (C.Ident "s0")
]
-- priorityBlock :: [C.PriorityBlock]
-- priorityBlock = [ C.PriOrd
-- [ C.PriInEQ (C.Ident "midLeftNoConsume") (C.Ident "midLeft") []
-- , C.PriInEQ (C.Ident "midNoConsume") (C.Ident "mid") []
-- , C.PriInEQ (C.Ident "midRightNoConsume") (C.Ident "midRight") []
-- ]
-- ]
maxFun :: C.FunctionDecl
maxFun = C.FDecl (C.Ident "max") args returnType localVars body
where
args =
[ (C.ArgPar (intCalType 16) (C.Ident "i"))
, (C.ArgPar (intCalType 16) (C.Ident "j"))
]
localVars = C.FNVarDecl
returnType = intCalType 16
body =
C.IfExpCons
(C.IfExpr
(C.BEGT (identCalExp "i") (identCalExp "j"))
(identCalExp "i")
(identCalExp "j"))
mkModFunctionMod :: C.FunctionDecl
mkModFunctionMod = C.FDecl (C.Ident "myMod") args returnType localVars body
where
args = [C.ArgPar (mkIntType 16) (C.Ident "x")]
localVars = C.FNVarDecl
returnType = mkIntType 16
body = C.IfExpCons (C.IfExpr ifCond ifThen ifElse)
ifCond =
C.BEGT
(C.EIdent (C.Ident "x"))
(C.BENeg (C.BEMult (mkInt 2) (mkVar "bufferSize")) (mkInt 1))
ifThen = C.BENeg (mkVar "x") (C.BEMult (mkInt 2) (mkVar "bufferSize"))
ifElse = C.IfExpCons (C.IfExpr elseCond elseThen elseElse)
elseCond = C.BEGT (mkVar "x") (C.BENeg (mkVar "bufferSize") (mkInt 1))
elseThen = C.BENeg (mkVar "x") (mkVar "bufferSize")
elseElse = mkVar "x"
kernelFun :: String -> R.AnonFun -> C.FunctionDecl
kernelFun kernelName (R.AnonFunC lambdaExps userDefinedFunc) =
C.FDecl (C.Ident kernelName) args returnType localVars body
where
args =
map
(\(R.ExpSpaceSepC (R.ExprVar (R.VarC lambdaIdent))) ->
(C.ArgPar (mkIntType 16) (idRiplToCal lambdaIdent)))
lambdaExps
localVars = C.FVarDecl [resultAssignment]
resultAssignment =
C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "result")
[]
(expRiplToCal userDefinedFunc))
returnType = mkIntType 16
body = C.IdBrSExpCons (C.Ident "max") [mkInt 0, C.EIdent (C.Ident "result")]
midLeftAction1 width height = midLeftAction (C.EIdent (C.Ident "isEven")) "applyKernel1" "midLeft1" "Out1" width height
midLeftAction2 width height = midLeftAction (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "midLeft2" "Out2" width height
midLeftActionNoConsume1 width height = midLeftActionNoConsume (C.EIdent (C.Ident "isEven")) "applyKernel1" "midLeftNoConsume1" "Out1" width height
midLeftActionNoConsume2 width height = midLeftActionNoConsume (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "midLeftNoConsume2" "Out2" width height
midAction1 width height = midAction (C.EIdent (C.Ident "isEven")) "applyKernel1" "mid1" "Out1" width height
midAction2 width height = midAction (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "mid2" "Out2" width height
midActionNoConsume1 width height = midActionNoConsume (C.EIdent (C.Ident "isEven")) "applyKernel1" "midNoConsume1" "Out1" width height
midActionNoConsume2 width height = midActionNoConsume (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "midNoConsume2" "Out2" width height
midRightAction1 width height = midRightAction (C.EIdent (C.Ident "isEven")) "applyKernel1" "midRight1" "Out1" width height
midRightAction2 width height = midRightAction (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "midRight2" "Out2" width height
midRightActionNoConsume1 width height = midRightActionNoConsume (C.EIdent (C.Ident "isEven")) "applyKernel1" "midRightNoConsume1" "Out1" width height
midRightActionNoConsume2 width height = midRightActionNoConsume (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "midRightNoConsume2" "Out2" width height
bottomLeftActionNoConsume1 width height = bottomLeftActionNoConsume (C.EIdent (C.Ident "isEven")) "applyKernel1" "bottomLeftNoConsume1" "Out1" width height
bottomLeftActionNoConsume2 width height = bottomLeftActionNoConsume (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "bottomLeftNoConsume2" "Out2" width height
bottomRowActionNoConsume1 width height = bottomRowActionNoConsume (C.EIdent (C.Ident "isEven")) "applyKernel1" "bottomRowNoConsume1" "Out1" width height
bottomRowActionNoConsume2 width height = bottomRowActionNoConsume (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "bottomRowNoConsume2" "Out2" width height
bottomRightActionNoConsume1 width height = bottomRightActionNoConsume (C.EIdent (C.Ident "isEven")) "applyKernel1" "bottomRightNoConsume1" "Out1" width height
bottomRightActionNoConsume2 width height = bottomRightActionNoConsume (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "bottomRightNoConsume2" "Out2" width height
populateBufferAction width = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident "populateBuffer"]
head = C.ActnHeadGuarded [inPattern] [] [guardExp]
inPattern = C.InPattTagIds (C.Ident "In1") [C.Ident "x"]
guardExp =
C.BELT
(C.EIdent (C.Ident "populatePtr"))
(C.BEAdd (mkInt width) (mkInt 3))
stmts =
[ arrayUpdate "buffer" "populatePtr" "x"
, varIncr "consumed"
, varIncr "populatePtr"
]
donePopulateBufferAction width = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident "donePopulateBuffer"]
head = C.ActnHeadGuarded [] [] [guardExp]
guardExp =
C.BEEQ (identCalExp "populatePtr") (C.BEAdd (mkInt width) (mkInt 3))
stmts = [varSetInt "populatePtr" 0]
-- in1:[token]
streamInPattern = C.InPattTagIds (C.Ident "In1") [C.Ident "token"]
-- out1:[v] or out2:[v]
streamOutPattern portName =
C.OutPattTagIds (C.Ident portName) [C.OutTokenExp (identCalExp "v")]
mkBufferIdxAssignment lhsIdent idxExp =
C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident lhsIdent)
[]
(C.EIdentArr (C.Ident "buffer") [(C.BExp idxExp)]))
topLeftAction width = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident "topLeft"]
head = C.ActnHeadVars [streamInPattern] [streamOutPattern "Out1"] localVars
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment "p2" (identCalExp "idx")
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment "p4" (identCalExp "idx")
, mkBufferIdxAssignment "p5" (identCalExp "idx")
, mkBufferIdxAssignment
"p6"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BENeg (mkInt width) (mkInt 1))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BENeg (mkInt width) (mkInt 1))))
, mkBufferIdxAssignment
"p9"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident "applyKernel1")
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ arrayUpdate "buffer" "consumed" "token"
, varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
, varIncr "consumed"
]
topRowAction width = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident "topRow"]
head =
C.ActnHeadGuardedVars
[streamInPattern]
[streamOutPattern "Out1"]
[guardExp]
localVars
guardExp = C.BELT (mkVar "midPtr") (mkInt (width - 1))
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 2)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 3)))
, mkBufferIdxAssignment "p4" (identCalExp "idx")
, mkBufferIdxAssignment
"p5"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 2)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 3)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEAdd (mkInt width) (mkInt 1))))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEAdd (mkInt width) (mkInt 2))))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident "applyKernel1")
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ arrayExpUpdate
"buffer"
(C.BExp (findIndexFunc (C.BEAdd (mkVar "idx") (mkVar "bufferSize"))))
("token")
, varIncr "consumed"
, varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
, varIncr "processedRows"
]
topRightAction width = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident "topRight"]
head =
C.ActnHeadGuardedVars
[streamInPattern]
[streamOutPattern "Out1"]
[guardExp]
localVars
guardExp = C.BEEQ (mkVar "midPtr") (mkInt (width - 1))
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment "p4" (identCalExp "idx")
, mkBufferIdxAssignment
"p5"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEAdd (mkInt width) (mkInt 1))))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEAdd (mkInt width) (mkInt 2))))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident "applyKernel1")
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ arrayExpUpdate
"buffer"
(C.BExp (findIndexFunc (C.BEAdd (mkVar "idx") (mkVar "bufferSize"))))
("token")
, varIncr "consumed"
, varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varSetInt "midPtr" 0
, varSetInt "processedRows" 1
, varNot "isEven"
]
midLeftAction predicateExp kernelName actionName outPortName width height = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head =
C.ActnHeadGuardedVars
[streamInPattern]
[streamOutPattern outPortName]
guardExps
localVars
guardExps =
[ C.BEEQ (mkVar "midPtr") (mkInt 0)
, C.BELT (mkVar "processedRows") (mkInt (height - 1))
, C.BELT (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment "p2" (identCalExp "idx")
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ arrayExpUpdate
"buffer"
(C.BExp (findIndexFunc (C.BEAdd (mkVar "idx") (mkVar "bufferSize"))))
("token")
, varIncr "consumed"
, varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
]
midLeftActionNoConsume predicateExp kernelName actionName outPortName width height = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head = C.ActnHeadGuardedVars [] [streamOutPattern outPortName] guardExps localVars
guardExps =
[ C.BEEQ (mkVar "midPtr") (mkInt 0)
, C.BELT (mkVar "processedRows") (mkInt (height - 1))
, C.BEEQ (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment "p2" (identCalExp "idx")
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ C.SemiColonSeparatedStmt
(C.AssignStt
(C.AssStmt
(C.Ident "idx")
(C.IdBrSExpCons (C.Ident "myMod") [mkVar "consumed"])))
, varIncr "midPtr"
]
midAction predicateExp kernelName actionName outPortName width height = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head =
C.ActnHeadGuardedVars
[streamInPattern]
[streamOutPattern outPortName]
guardExps
localVars
guardExps =
[ C.BELT (mkVar "midPtr") (mkInt (width - 1))
, C.BELT (mkVar "processedRows") (mkInt (height - 1))
, C.BELT (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 2)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 2)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 2)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ arrayExpUpdate
"buffer"
(C.BExp (findIndexFunc (C.BEAdd (mkVar "idx") (mkVar "bufferSize"))))
("token")
, varIncr "consumed"
, varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
]
midActionNoConsume predicateExp kernelName actionName outPortName width height = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head = C.ActnHeadGuardedVars [] [streamOutPattern outPortName] guardExps localVars
guardExps =
[ C.BELT (mkVar "midPtr") (mkInt (width - 1))
, C.BEEQ (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 2)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 2)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 2)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
]
midRightAction predicateExp kernelName actionName outPortName width height = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head =
C.ActnHeadGuardedVars
[streamInPattern]
[streamOutPattern outPortName]
guardExps
localVars
guardExps =
[ C.BEEQ (mkVar "midPtr") (mkInt (width - 1))
, C.BELT (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ arrayExpUpdate
"buffer"
(C.BExp (findIndexFunc (C.BEAdd (mkVar "idx") (mkVar "bufferSize"))))
("token")
, varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "consumed"
, varIncr "processedRows"
, varSetInt "midPtr" 0
, varNot "isEven"
]
midRightActionNoConsume predicateExp kernelName actionName outPortName width height = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head = C.ActnHeadGuardedVars [] [streamOutPattern outPortName] guardExps localVars
guardExps =
[ C.BEEQ (mkVar "midPtr") (mkInt (width - 1))
, C.BEEQ (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts = [ varIncr "processedRows"
, varSetInt "midPtr" 0
, varNot "isEven"
]
bottomLeftActionNoConsume predicateExp kernelName actionName outPortName width height =
C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head = C.ActnHeadGuardedVars [] [streamOutPattern outPortName] guardExps localVars
guardExps =
[ C.BEEQ (mkVar "midPtr") (mkInt 0)
, C.BEEQ (mkVar "processedRows") (mkInt (height - 1))
, C.BEEQ (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment "p2" (identCalExp "idx")
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p8"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
]
bottomRowActionNoConsume predicateExp kernelName actionName outPortName width height =
C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head = C.ActnHeadGuardedVars [] [streamOutPattern outPortName] guardExps localVars
guardExps =
[ C.BELT (mkVar "midPtr") (mkInt (width - 1))
, C.BEEQ (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 2)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 2)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 2)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
]
bottomRightActionNoConsume predicateExp kernelName actionName outPortName width height =
C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head = C.ActnHeadGuardedVars [] [streamOutPattern outPortName] guardExps localVars
guardExps =
[ C.BEEQ (mkVar "midPtr") (mkInt (width - 1))
, C.BEEQ (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ varSetInt "processedRows" 0
, varSetInt "idx" 0
, varSetInt "midPtr" 0
, varSetInt "consumed" 0
, varNot "isEven"
]
findIndexFunc offset = C.IdBrSExpCons (C.Ident "myMod") [offset]
| robstewart57/ripl | src/SkeletonTemplates/IUnzipFilter2D.hs | bsd-3-clause | 38,100 | 0 | 19 | 12,225 | 12,111 | 6,151 | 5,960 | 895 | 1 |
{-|
Module : Types
Description : Type information, used internally by Obsídian.
Copyright : (c) Joel Svensson, 2014
License : BSD
Maintainer : bo.joel.svensson@gmail.com
Stability : experimental
-}
module Obsidian.Types where
---------------------------------------------------------------------------
-- Types
---------------------------------------------------------------------------
data Type
-- The allowed scalar types
= Bool
| Int | Word -- A bit problematic since the size of
-- of these are platform dependent
| Int8 | Int16 | Int32 | Int64
| Word8 | Word16 | Word32 | Word64
| Float | Double
-- Used by CUDA, C And OpenCL generators
| Volatile Type -- For warp local computations.
| Pointer Type -- Pointer to a @type@
| Global Type -- OpenCL thing
| Local Type -- OpenCL thing
deriving (Eq, Ord, Show)
typeSize Int8 = 1
typeSize Int16 = 2
typeSize Int32 = 4
typeSize Int64 = 8
typeSize Word8 = 1
typeSize Word16 = 2
typeSize Word32 = 4
typeSize Word64 = 8
typeSize Bool = 4
typeSize Float = 4
typeSize Double = 8
| svenssonjoel/ObsidianGFX | Obsidian/Types.hs | bsd-3-clause | 1,157 | 0 | 6 | 298 | 184 | 108 | 76 | 23 | 1 |
module Main where
import HTIG
main :: IO ()
main = htig defaultConfig
| nakamuray/htig | htig.hs | bsd-3-clause | 72 | 0 | 6 | 15 | 25 | 14 | 11 | 4 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.