_id stringlengths 64 64 | repository stringlengths 6 84 | name stringlengths 4 110 | content stringlengths 0 248k | license null | download_url stringlengths 89 454 | language stringclasses 7
values | comments stringlengths 0 74.6k | code stringlengths 0 248k |
|---|---|---|---|---|---|---|---|---|
a18d86d51ca48d3c60614815792a7ec82bf6756cac87838dcd0187ad1291a173 | input-output-hk/ouroboros-network | Ledger.hs | {-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingVia #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
{-# OPTIONS -Wno-orphans #-}
module Ouroboros.Consensus.ByronSpec.Ledger.Ledger (
ByronSpecLedgerError (..)
, initByronSpecLedgerState
-- * Type family instances
, LedgerState (..)
, Ticked (..)
) where
import Codec.Serialise
import Control.Monad.Except
import GHC.Generics (Generic)
import NoThunks.Class (AllowThunk (..), NoThunks)
import qualified Byron.Spec.Chain.STS.Rule.Chain as Spec
import qualified Byron.Spec.Ledger.Update as Spec
import qualified Control.State.Transition as Spec
import Ouroboros.Consensus.Block
import Ouroboros.Consensus.Ledger.Abstract
import Ouroboros.Consensus.Ledger.CommonProtocolParams
import Ouroboros.Consensus.Ticked
import Ouroboros.Consensus.Util ((..:))
import Ouroboros.Consensus.ByronSpec.Ledger.Accessors
import Ouroboros.Consensus.ByronSpec.Ledger.Block
import Ouroboros.Consensus.ByronSpec.Ledger.Conversions
import Ouroboros.Consensus.ByronSpec.Ledger.Genesis (ByronSpecGenesis)
import Ouroboros.Consensus.ByronSpec.Ledger.Orphans ()
import qualified Ouroboros.Consensus.ByronSpec.Ledger.Rules as Rules
------------------------------------------------------------------------------
State
------------------------------------------------------------------------------
State
-------------------------------------------------------------------------------}
data instance LedgerState ByronSpecBlock = ByronSpecLedgerState {
-- | Tip of the ledger (most recently applied block, if any)
--
-- The spec state stores the last applied /hash/, but not the /slot/.
byronSpecLedgerTip :: Maybe SlotNo
-- | The spec state proper
, byronSpecLedgerState :: Spec.State Spec.CHAIN
}
deriving stock (Show, Eq, Generic)
deriving anyclass (Serialise)
deriving NoThunks via AllowThunk (LedgerState ByronSpecBlock)
newtype ByronSpecLedgerError = ByronSpecLedgerError {
unByronSpecLedgerError :: [Spec.PredicateFailure Spec.CHAIN]
}
deriving (Show, Eq)
deriving NoThunks via AllowThunk ByronSpecLedgerError
type instance LedgerCfg (LedgerState ByronSpecBlock) = ByronSpecGenesis
instance UpdateLedger ByronSpecBlock
initByronSpecLedgerState :: ByronSpecGenesis -> LedgerState ByronSpecBlock
initByronSpecLedgerState cfg = ByronSpecLedgerState {
byronSpecLedgerTip = Nothing
, byronSpecLedgerState = Rules.initStateCHAIN cfg
}
------------------------------------------------------------------------------
GetTip
------------------------------------------------------------------------------
GetTip
-------------------------------------------------------------------------------}
instance GetTip (LedgerState ByronSpecBlock) where
getTip (ByronSpecLedgerState tip state) = castPoint $
getByronSpecTip tip state
instance GetTip (Ticked (LedgerState ByronSpecBlock)) where
getTip (TickedByronSpecLedgerState tip state) = castPoint $
getByronSpecTip tip state
getByronSpecTip :: Maybe SlotNo -> Spec.State Spec.CHAIN -> Point ByronSpecBlock
getByronSpecTip Nothing _ = GenesisPoint
getByronSpecTip (Just slot) state = BlockPoint
slot
(getChainStateHash state)
{-------------------------------------------------------------------------------
Ticking
-------------------------------------------------------------------------------}
data instance Ticked (LedgerState ByronSpecBlock) = TickedByronSpecLedgerState {
untickedByronSpecLedgerTip :: Maybe SlotNo
, tickedByronSpecLedgerState :: Spec.State Spec.CHAIN
}
deriving stock (Show, Eq)
deriving NoThunks via AllowThunk (Ticked (LedgerState ByronSpecBlock))
instance IsLedger (LedgerState ByronSpecBlock) where
type LedgerErr (LedgerState ByronSpecBlock) = ByronSpecLedgerError
type AuxLedgerEvent (LedgerState ByronSpecBlock) =
VoidLedgerEvent (LedgerState ByronSpecBlock)
applyChainTickLedgerResult cfg slot (ByronSpecLedgerState tip state) =
pureLedgerResult
$ TickedByronSpecLedgerState {
untickedByronSpecLedgerTip = tip
, tickedByronSpecLedgerState = Rules.applyChainTick
cfg
(toByronSpecSlotNo slot)
state
}
{-------------------------------------------------------------------------------
Applying blocks
-------------------------------------------------------------------------------}
instance ApplyBlock (LedgerState ByronSpecBlock) ByronSpecBlock where
applyBlockLedgerResult cfg block (TickedByronSpecLedgerState _tip state) =
withExcept ByronSpecLedgerError
$ fmap (pureLedgerResult . ByronSpecLedgerState (Just (blockSlot block)))
Note that the CHAIN rule also applies the chain tick . So even
-- though the ledger we received has already been ticked with
-- 'applyChainTick', we do it again as part of CHAIN. This is safe, as
-- it is idempotent. If we wanted to avoid the repeated tick, we would
-- have to call the subtransitions of CHAIN (except for ticking).
Rules.liftCHAIN
cfg
(byronSpecBlock block)
state
reapplyBlockLedgerResult =
-- The spec doesn't have a "reapply" mode
dontExpectError ..: applyBlockLedgerResult
where
dontExpectError :: Except a b -> b
dontExpectError mb = case runExcept mb of
Left _ -> error "reapplyBlockLedgerResult: unexpected error"
Right b -> b
{-------------------------------------------------------------------------------
CommonProtocolParams
-------------------------------------------------------------------------------}
instance CommonProtocolParams ByronSpecBlock where
maxHeaderSize = fromIntegral . Spec._maxHdrSz . getPParams
maxTxSize = fromIntegral . Spec._maxTxSz . getPParams
getPParams :: LedgerState ByronSpecBlock -> Spec.PParams
getPParams =
Spec.protocolParameters
. getChainStateUPIState
. byronSpecLedgerState
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/af14789baae3df5c5c67ac0447954475bab9ba67/ouroboros-consensus-byronspec/src/Ouroboros/Consensus/ByronSpec/Ledger/Ledger.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# OPTIONS -Wno-orphans #
* Type family instances
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
| Tip of the ledger (most recently applied block, if any)
The spec state stores the last applied /hash/, but not the /slot/.
| The spec state proper
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
------------------------------------------------------------------------------
Ticking
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Applying blocks
------------------------------------------------------------------------------
though the ledger we received has already been ticked with
'applyChainTick', we do it again as part of CHAIN. This is safe, as
it is idempotent. If we wanted to avoid the repeated tick, we would
have to call the subtransitions of CHAIN (except for ticking).
The spec doesn't have a "reapply" mode
------------------------------------------------------------------------------
CommonProtocolParams
------------------------------------------------------------------------------ | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
module Ouroboros.Consensus.ByronSpec.Ledger.Ledger (
ByronSpecLedgerError (..)
, initByronSpecLedgerState
, LedgerState (..)
, Ticked (..)
) where
import Codec.Serialise
import Control.Monad.Except
import GHC.Generics (Generic)
import NoThunks.Class (AllowThunk (..), NoThunks)
import qualified Byron.Spec.Chain.STS.Rule.Chain as Spec
import qualified Byron.Spec.Ledger.Update as Spec
import qualified Control.State.Transition as Spec
import Ouroboros.Consensus.Block
import Ouroboros.Consensus.Ledger.Abstract
import Ouroboros.Consensus.Ledger.CommonProtocolParams
import Ouroboros.Consensus.Ticked
import Ouroboros.Consensus.Util ((..:))
import Ouroboros.Consensus.ByronSpec.Ledger.Accessors
import Ouroboros.Consensus.ByronSpec.Ledger.Block
import Ouroboros.Consensus.ByronSpec.Ledger.Conversions
import Ouroboros.Consensus.ByronSpec.Ledger.Genesis (ByronSpecGenesis)
import Ouroboros.Consensus.ByronSpec.Ledger.Orphans ()
import qualified Ouroboros.Consensus.ByronSpec.Ledger.Rules as Rules
State
State
data instance LedgerState ByronSpecBlock = ByronSpecLedgerState {
byronSpecLedgerTip :: Maybe SlotNo
, byronSpecLedgerState :: Spec.State Spec.CHAIN
}
deriving stock (Show, Eq, Generic)
deriving anyclass (Serialise)
deriving NoThunks via AllowThunk (LedgerState ByronSpecBlock)
newtype ByronSpecLedgerError = ByronSpecLedgerError {
unByronSpecLedgerError :: [Spec.PredicateFailure Spec.CHAIN]
}
deriving (Show, Eq)
deriving NoThunks via AllowThunk ByronSpecLedgerError
type instance LedgerCfg (LedgerState ByronSpecBlock) = ByronSpecGenesis
instance UpdateLedger ByronSpecBlock
initByronSpecLedgerState :: ByronSpecGenesis -> LedgerState ByronSpecBlock
initByronSpecLedgerState cfg = ByronSpecLedgerState {
byronSpecLedgerTip = Nothing
, byronSpecLedgerState = Rules.initStateCHAIN cfg
}
GetTip
GetTip
instance GetTip (LedgerState ByronSpecBlock) where
getTip (ByronSpecLedgerState tip state) = castPoint $
getByronSpecTip tip state
instance GetTip (Ticked (LedgerState ByronSpecBlock)) where
getTip (TickedByronSpecLedgerState tip state) = castPoint $
getByronSpecTip tip state
getByronSpecTip :: Maybe SlotNo -> Spec.State Spec.CHAIN -> Point ByronSpecBlock
getByronSpecTip Nothing _ = GenesisPoint
getByronSpecTip (Just slot) state = BlockPoint
slot
(getChainStateHash state)
data instance Ticked (LedgerState ByronSpecBlock) = TickedByronSpecLedgerState {
untickedByronSpecLedgerTip :: Maybe SlotNo
, tickedByronSpecLedgerState :: Spec.State Spec.CHAIN
}
deriving stock (Show, Eq)
deriving NoThunks via AllowThunk (Ticked (LedgerState ByronSpecBlock))
instance IsLedger (LedgerState ByronSpecBlock) where
type LedgerErr (LedgerState ByronSpecBlock) = ByronSpecLedgerError
type AuxLedgerEvent (LedgerState ByronSpecBlock) =
VoidLedgerEvent (LedgerState ByronSpecBlock)
applyChainTickLedgerResult cfg slot (ByronSpecLedgerState tip state) =
pureLedgerResult
$ TickedByronSpecLedgerState {
untickedByronSpecLedgerTip = tip
, tickedByronSpecLedgerState = Rules.applyChainTick
cfg
(toByronSpecSlotNo slot)
state
}
instance ApplyBlock (LedgerState ByronSpecBlock) ByronSpecBlock where
applyBlockLedgerResult cfg block (TickedByronSpecLedgerState _tip state) =
withExcept ByronSpecLedgerError
$ fmap (pureLedgerResult . ByronSpecLedgerState (Just (blockSlot block)))
Note that the CHAIN rule also applies the chain tick . So even
Rules.liftCHAIN
cfg
(byronSpecBlock block)
state
reapplyBlockLedgerResult =
dontExpectError ..: applyBlockLedgerResult
where
dontExpectError :: Except a b -> b
dontExpectError mb = case runExcept mb of
Left _ -> error "reapplyBlockLedgerResult: unexpected error"
Right b -> b
instance CommonProtocolParams ByronSpecBlock where
maxHeaderSize = fromIntegral . Spec._maxHdrSz . getPParams
maxTxSize = fromIntegral . Spec._maxTxSz . getPParams
getPParams :: LedgerState ByronSpecBlock -> Spec.PParams
getPParams =
Spec.protocolParameters
. getChainStateUPIState
. byronSpecLedgerState
|
aa4e0d03adb1851089178c01ee0c267599c5b8749898e3b63a810753d2709a47 | cpeikert/Lol | KHPRF.hs | |
Module : Crypto . Lol . Applications . Examples . KHPRF
Description : Example using .
Copyright : ( c ) , 2018
, 2018
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Example usage of ' Crypto . Lol . Applications . ' .
Module : Crypto.Lol.Applications.Examples.KHPRF
Description : Example using KeyHomomorphicPRF.
Copyright : (c) Chris Peikert, 2018
Bogdan Manga, 2018
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Example usage of 'Crypto.Lol.Applications.KeyHomomorphicPRF'.
-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE PartialTypeSignatures #
# LANGUAGE QuantifiedConstraints #
{-# LANGUAGE ScopedTypeVariables #-}
# OPTIONS_GHC -fno - warn - partial - type - signatures #
module Crypto.Lol.Applications.Examples.KHPRF (khprfMain) where
import Crypto.Lol
import Crypto.Lol.Applications.KeyHomomorphicPRF
import Crypto.Lol.Types
type SimpleTop = 'Intern ('Intern 'Leaf 'Leaf) 'Leaf
type M = F64
type N = 1
type Q = 257
type P = 2
type Rq t = Cyc t M (ZqBasic Q Int64)
type Rp t = Cyc t M (ZqBasic P Int64)
type Gad = BaseBGad 2
-- | Simple example of how to use the
" Crypto . Lol . Applications . " application .
khprfMain :: forall t . (forall m r . (Fact m, Show r) => Show (t m r), _)
=> Proxy t -> IO ()
khprfMain _ = do
key <- genKey
params :: PRFParams N Gad (Rq t) <- genParams
let t = singFBT :: SFBT SimpleTop
let result :: [Matrix (Rp t)] =
run $ sequence $ prfAmortized t params key <$> values
print result
| null | https://raw.githubusercontent.com/cpeikert/Lol/4416ac4f03b0bff08cb1115c72a45eed1fa48ec3/lol-apps/Crypto/Lol/Applications/Examples/KHPRF.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
| Simple example of how to use the | |
Module : Crypto . Lol . Applications . Examples . KHPRF
Description : Example using .
Copyright : ( c ) , 2018
, 2018
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Example usage of ' Crypto . Lol . Applications . ' .
Module : Crypto.Lol.Applications.Examples.KHPRF
Description : Example using KeyHomomorphicPRF.
Copyright : (c) Chris Peikert, 2018
Bogdan Manga, 2018
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Example usage of 'Crypto.Lol.Applications.KeyHomomorphicPRF'.
-}
# LANGUAGE PartialTypeSignatures #
# LANGUAGE QuantifiedConstraints #
# OPTIONS_GHC -fno - warn - partial - type - signatures #
module Crypto.Lol.Applications.Examples.KHPRF (khprfMain) where
import Crypto.Lol
import Crypto.Lol.Applications.KeyHomomorphicPRF
import Crypto.Lol.Types
type SimpleTop = 'Intern ('Intern 'Leaf 'Leaf) 'Leaf
type M = F64
type N = 1
type Q = 257
type P = 2
type Rq t = Cyc t M (ZqBasic Q Int64)
type Rp t = Cyc t M (ZqBasic P Int64)
type Gad = BaseBGad 2
" Crypto . Lol . Applications . " application .
khprfMain :: forall t . (forall m r . (Fact m, Show r) => Show (t m r), _)
=> Proxy t -> IO ()
khprfMain _ = do
key <- genKey
params :: PRFParams N Gad (Rq t) <- genParams
let t = singFBT :: SFBT SimpleTop
let result :: [Matrix (Rp t)] =
run $ sequence $ prfAmortized t params key <$> values
print result
|
b3ec48b3a83ff376a0f44413dc2e9d04107660a51d84975744e2cb0a9e7d139f | xebia/VisualReview | integration_test.clj | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Copyright 2015 Xebia B.V.
;
Licensed under the Apache License , Version 2.0 ( the " License " )
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; -2.0
;
; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns com.xebia.visualreview.itest.integration-test
(:require [clojure.test :refer :all]
[com.xebia.visualreview.api-test :as api]
[com.xebia.visualreview.mock :as mock]
[com.xebia.visualreview.itest-util :refer [start-server stop-server]]))
(def project-name-1 "A Test Project")
(def project-name-2 "Another Project")
(def suite-name "Test suite")
(def screenshot-properties {:os "LINUX"
:browser "firefox"
:resolution "1024x786"
:version "40.0"})
(use-fixtures :each mock/logging-fixture mock/rebind-db-spec-fixture mock/setup-screenshot-dir-fixture mock/setup-db-fixture mock/test-server-fixture)
(deftest projects
(testing "Initial state"
(is (= (:body (api/get-projects)) []) "Initially there are no projects"))
(testing "Creating projects"
(testing "Request validation"
(let [response (api/put-project! {})]
(is (re-find #"'name' is missing" (:body response)) "The request parameters are validated")
(is (= 422 (:status response)) "Unprocessable entity is returned for invalid input")))
(testing "Two valid projects"
(let [response1 (api/put-project! {:name project-name-1})
response2 (api/put-project! {:name project-name-2})]
(is (= (:status response1) 201) "Create project 1")
(is (= (:status response2) 201) "Create project 2")
(is (= {:id 1 :name project-name-1 :suites []} (:body response1)))
(is (= (:body (api/get-projects)) [{:id 1 :name project-name-1} {:id 2 :name project-name-2}]))))
(testing "Single project endpoint"
(is (= {:id 1 :name project-name-1 :suites []} (:body (api/get-project 1)))))
(testing "Project names are unique"
(let [response (api/put-project! {:name project-name-1})]
(is (= 409 (:status response)) "Conflict status code")
(is (re-find #"already exists" (:body response)) "Return error message")))
(testing "Project name can not be empty"
(let [response (api/put-project! {:name ""})]
(is (= 422 (:status response)) "Unprocessable entity status code")
(is (re-find #"can not be empty" (:body response)) "Return error message"))))
(testing "Deleting projects"
(testing "Project can be deleted and returns true"
(let [created-project (:body (api/put-project! {:name "my soon-to-be-deleted project"}))
project-before-deletion (:body (api/get-project (:id created-project)))
response-status (:status (api/delete-project! (:id project-before-deletion)))
project-after-deletion-status (:status (api/get-project (:id project-before-deletion)))]
(is (not (nil? project-before-deletion)))
(is (= response-status 204))
(is (= project-after-deletion-status 404)))))
(testing "Deleting runs"
(testing "Run can be deleted but leaves other runs and the baseline intact"
test for regression of issue # 49 :
; deletion of a run which contains images that were added to the baseline causes links to these baseline images
; in other runs to be removed as well
(let [run-1 (:body (api/post-run! project-name-1 suite-name))
run-1-screenshot (:body (mock/upload-tapir (:id run-1) {} screenshot-properties))
status-update (api/update-diff-status-of-screenshot (:id run-1) (:id run-1-screenshot) "accepted")
run-2 (:body (api/post-run! project-name-1 suite-name))
run-2-screenshot (:body (mock/upload-tapir (:id run-2) {} screenshot-properties))
run-1-analysis-before-deletion (api/get-analysis (:id run-1))
run-2-analysis-before-deletion (api/get-analysis (:id run-2))
run-1-deletion (api/delete-run! (:id run-1))
run-1-after-deletion (api/get-run (:id run-1))
run-2-after-deletion (api/get-run (:id run-2))
run-1-analysis-after-deletion (api/get-analysis (:id run-1))
run-2-analysis-after-deletion (api/get-analysis (:id run-2))
run-1-screenshot-after-deletion (api/get-image (:imageId run-1-screenshot))
run-2-screenshot-after-deletion (api/get-image (:imageId run-2-screenshot))]
; sanity checks
(is (= (not (nil? (:id run-1)))))
(is (= (not (nil? (:id run-2)))))
(is (= (not (nil? (:id run-1-analysis-before-deletion)))))
(is (= (not (nil? (:id run-2-analysis-before-deletion)))))
(is (= (:status status-update) 201))
(is (= (not (nil? (:id run-1-screenshot)))))
(is (= (not (nil? (:id run-2-screenshot)))))
; is run-1 properly deleted?
(is (= (:status run-1-deletion) 204))
(is (= (:status run-1-after-deletion) 404))
(is (= (:status run-1-analysis-after-deletion) 404))
; is run-2 still available and is all the data for it still there?
(is (:status run-2-after-deletion) 200)
(is (= (:body run-2-after-deletion) run-2))
(is (= (:body run-2-analysis-before-deletion) (:body run-2-analysis-after-deletion)))
(is (= (:status run-1-screenshot-after-deletion) 200)) ; still there because of baseline
(is (= (:status run-2-screenshot-after-deletion) 200)) ; still there because its run stil exists
(is (= (not (nil? (:body run-1-screenshot-after-deletion)))))
(is (= (not (nil? (:body run-2-screenshot-after-deletion)))))))))
| null | https://raw.githubusercontent.com/xebia/VisualReview/c74c18ff73cbf11ece23203cb7a7768e626a03e2/src/integration/clojure/com/xebia/visualreview/itest/integration_test.clj | clojure |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
deletion of a run which contains images that were added to the baseline causes links to these baseline images
in other runs to be removed as well
sanity checks
is run-1 properly deleted?
is run-2 still available and is all the data for it still there?
still there because of baseline
still there because its run stil exists | Copyright 2015 Xebia B.V.
Licensed under the Apache License , Version 2.0 ( the " License " )
distributed under the License is distributed on an " AS IS " BASIS ,
(ns com.xebia.visualreview.itest.integration-test
(:require [clojure.test :refer :all]
[com.xebia.visualreview.api-test :as api]
[com.xebia.visualreview.mock :as mock]
[com.xebia.visualreview.itest-util :refer [start-server stop-server]]))
(def project-name-1 "A Test Project")
(def project-name-2 "Another Project")
(def suite-name "Test suite")
(def screenshot-properties {:os "LINUX"
:browser "firefox"
:resolution "1024x786"
:version "40.0"})
(use-fixtures :each mock/logging-fixture mock/rebind-db-spec-fixture mock/setup-screenshot-dir-fixture mock/setup-db-fixture mock/test-server-fixture)
(deftest projects
(testing "Initial state"
(is (= (:body (api/get-projects)) []) "Initially there are no projects"))
(testing "Creating projects"
(testing "Request validation"
(let [response (api/put-project! {})]
(is (re-find #"'name' is missing" (:body response)) "The request parameters are validated")
(is (= 422 (:status response)) "Unprocessable entity is returned for invalid input")))
(testing "Two valid projects"
(let [response1 (api/put-project! {:name project-name-1})
response2 (api/put-project! {:name project-name-2})]
(is (= (:status response1) 201) "Create project 1")
(is (= (:status response2) 201) "Create project 2")
(is (= {:id 1 :name project-name-1 :suites []} (:body response1)))
(is (= (:body (api/get-projects)) [{:id 1 :name project-name-1} {:id 2 :name project-name-2}]))))
(testing "Single project endpoint"
(is (= {:id 1 :name project-name-1 :suites []} (:body (api/get-project 1)))))
(testing "Project names are unique"
(let [response (api/put-project! {:name project-name-1})]
(is (= 409 (:status response)) "Conflict status code")
(is (re-find #"already exists" (:body response)) "Return error message")))
(testing "Project name can not be empty"
(let [response (api/put-project! {:name ""})]
(is (= 422 (:status response)) "Unprocessable entity status code")
(is (re-find #"can not be empty" (:body response)) "Return error message"))))
(testing "Deleting projects"
(testing "Project can be deleted and returns true"
(let [created-project (:body (api/put-project! {:name "my soon-to-be-deleted project"}))
project-before-deletion (:body (api/get-project (:id created-project)))
response-status (:status (api/delete-project! (:id project-before-deletion)))
project-after-deletion-status (:status (api/get-project (:id project-before-deletion)))]
(is (not (nil? project-before-deletion)))
(is (= response-status 204))
(is (= project-after-deletion-status 404)))))
(testing "Deleting runs"
(testing "Run can be deleted but leaves other runs and the baseline intact"
test for regression of issue # 49 :
(let [run-1 (:body (api/post-run! project-name-1 suite-name))
run-1-screenshot (:body (mock/upload-tapir (:id run-1) {} screenshot-properties))
status-update (api/update-diff-status-of-screenshot (:id run-1) (:id run-1-screenshot) "accepted")
run-2 (:body (api/post-run! project-name-1 suite-name))
run-2-screenshot (:body (mock/upload-tapir (:id run-2) {} screenshot-properties))
run-1-analysis-before-deletion (api/get-analysis (:id run-1))
run-2-analysis-before-deletion (api/get-analysis (:id run-2))
run-1-deletion (api/delete-run! (:id run-1))
run-1-after-deletion (api/get-run (:id run-1))
run-2-after-deletion (api/get-run (:id run-2))
run-1-analysis-after-deletion (api/get-analysis (:id run-1))
run-2-analysis-after-deletion (api/get-analysis (:id run-2))
run-1-screenshot-after-deletion (api/get-image (:imageId run-1-screenshot))
run-2-screenshot-after-deletion (api/get-image (:imageId run-2-screenshot))]
(is (= (not (nil? (:id run-1)))))
(is (= (not (nil? (:id run-2)))))
(is (= (not (nil? (:id run-1-analysis-before-deletion)))))
(is (= (not (nil? (:id run-2-analysis-before-deletion)))))
(is (= (:status status-update) 201))
(is (= (not (nil? (:id run-1-screenshot)))))
(is (= (not (nil? (:id run-2-screenshot)))))
(is (= (:status run-1-deletion) 204))
(is (= (:status run-1-after-deletion) 404))
(is (= (:status run-1-analysis-after-deletion) 404))
(is (:status run-2-after-deletion) 200)
(is (= (:body run-2-after-deletion) run-2))
(is (= (:body run-2-analysis-before-deletion) (:body run-2-analysis-after-deletion)))
(is (= (not (nil? (:body run-1-screenshot-after-deletion)))))
(is (= (not (nil? (:body run-2-screenshot-after-deletion)))))))))
|
b2c54b2b3e613eb75ff8cdaae2abdbe8440f40700aacb9584c9d147411eb1a8c | batsh-dev-team/Batsh | bash_ast.ml | open Core_kernel
type identifier = string
and identifiers = identifier list
and leftvalue =
| Identifier of identifier
| ListAccess of (leftvalue * arithmetic)
| EntireList of leftvalue
| Cardinal of leftvalue
and arithmetic =
| Leftvalue of leftvalue
| Int of int
| Float of float
| ArithUnary of (string * arithmetic)
| ArithBinary of (string * arithmetic * arithmetic)
and expression =
| Variable of leftvalue
| String of string
| Result of arithmetic
| StrBinary of (string * expression * expression)
| TestUnary of (string * expression)
| Command of (expression * expressions)
| List of expressions
| Raw of string
and expressions = expression list
and statement =
| Comment of string
| Local of identifier
| Assignment of (leftvalue * expression)
| Expression of expression
| If of (expression * statement)
| IfElse of (expression * statement * statement)
| While of (expression * statement)
| Block of statements
| Return
| Empty
and statements = statement list
and toplevel =
| Statement of statement
| Function of (identifier * statements)
and t = toplevel list
[@@deriving sexp]
| null | https://raw.githubusercontent.com/batsh-dev-team/Batsh/5c8ae421e0eea5dcb3da01643152ad96af941f07/lib/bash_ast.ml | ocaml | open Core_kernel
type identifier = string
and identifiers = identifier list
and leftvalue =
| Identifier of identifier
| ListAccess of (leftvalue * arithmetic)
| EntireList of leftvalue
| Cardinal of leftvalue
and arithmetic =
| Leftvalue of leftvalue
| Int of int
| Float of float
| ArithUnary of (string * arithmetic)
| ArithBinary of (string * arithmetic * arithmetic)
and expression =
| Variable of leftvalue
| String of string
| Result of arithmetic
| StrBinary of (string * expression * expression)
| TestUnary of (string * expression)
| Command of (expression * expressions)
| List of expressions
| Raw of string
and expressions = expression list
and statement =
| Comment of string
| Local of identifier
| Assignment of (leftvalue * expression)
| Expression of expression
| If of (expression * statement)
| IfElse of (expression * statement * statement)
| While of (expression * statement)
| Block of statements
| Return
| Empty
and statements = statement list
and toplevel =
| Statement of statement
| Function of (identifier * statements)
and t = toplevel list
[@@deriving sexp]
| |
cb161ef087a10db75b254f1fb1b11d802ed6638c179337cd4a1d0a7834559917 | dnlkrgr/hsreduce | Inline.hs | module Inline where
data Arst = Arst String
type Brst = Int
f :: Arst -> ()
f (Arst "arst") = ()
g :: Brst -> ()
g 3 = ()
| null | https://raw.githubusercontent.com/dnlkrgr/hsreduce/8f66fdee036f8639053067572b55d9a64359d22c/test-cases/trying-out/Inline.hs | haskell | module Inline where
data Arst = Arst String
type Brst = Int
f :: Arst -> ()
f (Arst "arst") = ()
g :: Brst -> ()
g 3 = ()
| |
04ba0f033e94fd5429aad22490f3e7ab76c6d0a1c10e3c95ea7a982336fea4a4 | edicl/hunchentoot | util.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
Copyright ( c ) 2004 - 2010 , Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :url-rewrite)
(declaim (inline skip-whitespace))
(defun skip-whitespace (&key (skip t) (write-through t))
"Read characters from *STANDARD-INPUT* as long as they are
whitespace. Returns the string which was read unless SKIP is true. On
EOF the string read so far is returned. Writes all characters read to
*STANDARD-OUTPUT* if WRITE-THROUGH is true."
(read-while #'whitespacep
:skip skip
:write-through write-through))
(defun read-delimited-string (&key (skip t) (write-through t))
"Reads and returns as its first value a string from
*STANDARD-INPUT*. The string is either delimited by ' or \" in which
case the delimiters aren't part of the string but the second return
value is the delimiter character or it is assumed to extend to the
next character which is not a name constituent \(see NAME-CHAR-P). On
EOF the string read so far is returned. If SKIP is true NIL is
returned. Writes all characters read to *STANDARD-OUTPUT* if
WRITE-THROUGH is true."
;; note that this function has no means to signal to the caller
that it encountered EOF before the closing delimiter was read ,
;; i.e. "'foo' bar='baz'" and "'foo" yield the same result, namely
;; the values "foo" and #\'
(handler-case
(let* ((peek-char (peek-char))
(delimiter (find peek-char '(#\' #\"))))
(when delimiter
(read-char)
(when write-through
(write-char delimiter)))
(multiple-value-prog1
(values
(read-while (if delimiter
(lambda (c) (char/= c delimiter))
(lambda (c) (name-char-p c)))
:skip skip
:write-through write-through)
delimiter)
(when delimiter
(read-char)
(when write-through
(write-char delimiter)))))
(end-of-file ()
;; this can only happen if the very first PEEK-CHAR fails,
otherwise EOF is handled by READ - WHILE
nil)))
(declaim (inline read-name))
(defun read-name (&key (skip t) (write-through t))
"Read characters from *STANDARD-INPUT* as long as they are name
constituents. Returns the string which was read unless SKIP is
true. On EOF the string read so far is returned. Writes all characters
read to *STANDARD-OUTPUT* if WRITE-THROUGH is true."
(read-while #'name-char-p :skip skip :write-through write-through))
(defun read-attribute (&key (skip t) (write-through t))
"Read characters from *STANDARD-INPUT* assuming that they constitue
a SGML-style attribute/value pair. Returns three values - the name of
the attribute, its value, and the whole string which was read. On EOF
the string(s) read so far is/are returned. If SKIP is true NIL is
returned. Writes all characters read to *STANDARD-OUTPUT* if
WRITE-THROUGH is true."
(let* ((name (read-name :skip skip
:write-through write-through))
(whitespace1 (skip-whitespace :skip skip
:write-through write-through)))
(cond ((eql (peek-char*) #\=)
(read-char)
(when write-through
(write-char #\=))
(let ((whitespace2 (skip-whitespace :skip skip :write-through write-through)))
(multiple-value-bind (value delimiter)
(read-delimited-string :skip skip :write-through write-through)
(let ((delimiter-string (if delimiter (string delimiter) "")))
(if skip
nil
(values name value
(concatenate 'string
name whitespace1 "=" whitespace2
delimiter-string value delimiter-string)))))))
(t (if skip
nil
(values name nil
(concatenate 'string name whitespace1)))))))
(defun skip-comment ()
"Skip SGML comment from *STANDARD-INPUT*, i.e. a string enclosed in
'--' on both sides. Returns no values. Writes all characters read to
*STANDARD-OUTPUT*. This function assumes \(without checking) that the
current position of *STANDARD-INPUT* is at the beginning of a comment,
after the first hyphen - see COMMENT-START-P."
(read-char)
(write-string "--")
(read-until "--")
(values))
| null | https://raw.githubusercontent.com/edicl/hunchentoot/0023dd3927e5840f1f02f9a8bdab2b4a7037c652/url-rewrite/util.lisp | lisp | Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
note that this function has no means to signal to the caller
i.e. "'foo' bar='baz'" and "'foo" yield the same result, namely
the values "foo" and #\'
this can only happen if the very first PEEK-CHAR fails, |
Copyright ( c ) 2004 - 2010 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :url-rewrite)
(declaim (inline skip-whitespace))
(defun skip-whitespace (&key (skip t) (write-through t))
"Read characters from *STANDARD-INPUT* as long as they are
whitespace. Returns the string which was read unless SKIP is true. On
EOF the string read so far is returned. Writes all characters read to
*STANDARD-OUTPUT* if WRITE-THROUGH is true."
(read-while #'whitespacep
:skip skip
:write-through write-through))
(defun read-delimited-string (&key (skip t) (write-through t))
"Reads and returns as its first value a string from
*STANDARD-INPUT*. The string is either delimited by ' or \" in which
case the delimiters aren't part of the string but the second return
value is the delimiter character or it is assumed to extend to the
next character which is not a name constituent \(see NAME-CHAR-P). On
EOF the string read so far is returned. If SKIP is true NIL is
returned. Writes all characters read to *STANDARD-OUTPUT* if
WRITE-THROUGH is true."
that it encountered EOF before the closing delimiter was read ,
(handler-case
(let* ((peek-char (peek-char))
(delimiter (find peek-char '(#\' #\"))))
(when delimiter
(read-char)
(when write-through
(write-char delimiter)))
(multiple-value-prog1
(values
(read-while (if delimiter
(lambda (c) (char/= c delimiter))
(lambda (c) (name-char-p c)))
:skip skip
:write-through write-through)
delimiter)
(when delimiter
(read-char)
(when write-through
(write-char delimiter)))))
(end-of-file ()
otherwise EOF is handled by READ - WHILE
nil)))
(declaim (inline read-name))
(defun read-name (&key (skip t) (write-through t))
"Read characters from *STANDARD-INPUT* as long as they are name
constituents. Returns the string which was read unless SKIP is
true. On EOF the string read so far is returned. Writes all characters
read to *STANDARD-OUTPUT* if WRITE-THROUGH is true."
(read-while #'name-char-p :skip skip :write-through write-through))
(defun read-attribute (&key (skip t) (write-through t))
"Read characters from *STANDARD-INPUT* assuming that they constitue
a SGML-style attribute/value pair. Returns three values - the name of
the attribute, its value, and the whole string which was read. On EOF
the string(s) read so far is/are returned. If SKIP is true NIL is
returned. Writes all characters read to *STANDARD-OUTPUT* if
WRITE-THROUGH is true."
(let* ((name (read-name :skip skip
:write-through write-through))
(whitespace1 (skip-whitespace :skip skip
:write-through write-through)))
(cond ((eql (peek-char*) #\=)
(read-char)
(when write-through
(write-char #\=))
(let ((whitespace2 (skip-whitespace :skip skip :write-through write-through)))
(multiple-value-bind (value delimiter)
(read-delimited-string :skip skip :write-through write-through)
(let ((delimiter-string (if delimiter (string delimiter) "")))
(if skip
nil
(values name value
(concatenate 'string
name whitespace1 "=" whitespace2
delimiter-string value delimiter-string)))))))
(t (if skip
nil
(values name nil
(concatenate 'string name whitespace1)))))))
(defun skip-comment ()
"Skip SGML comment from *STANDARD-INPUT*, i.e. a string enclosed in
'--' on both sides. Returns no values. Writes all characters read to
*STANDARD-OUTPUT*. This function assumes \(without checking) that the
current position of *STANDARD-INPUT* is at the beginning of a comment,
after the first hyphen - see COMMENT-START-P."
(read-char)
(write-string "--")
(read-until "--")
(values))
|
b896a19237862e5d4f6ead0b1bf8ed1a601aeddf6177e138711c72dc713f8c07 | greghendershott/frog | load.rkt | #lang racket/base
(require (for-syntax racket/base
racket/function
racket/syntax))
(begin-for-syntax
(define provide-syms '(init
enhance-body
clean))
(provide provide-syms))
(define-syntax (define-the-things stx)
(with-syntax ([(id ...) (map (curry format-id stx "~a") provide-syms)]
[load (format-id stx "load")])
#'(begin
(define id
(λ _ (error 'id "not yet dynamic-required from frog.rkt"))) ...
(provide id ...)
(define (load top)
(define frog.rkt (build-path top "frog.rkt"))
(let ([fn (with-handlers ([exn:fail:filesystem? cannot-find-frog.rkt])
(dynamic-require frog.rkt 'id))])
(when fn (set! id fn))) ...)
(provide load))))
(define-the-things)
(define (cannot-find-frog.rkt . _)
(eprintf "Cannot open frog.rkt.\nMaybe you need to `raco frog --init` ?\n")
(exit 1))
(module+ test
(require rackunit
racket/runtime-path)
(test-case "before loading example/frog.rkt"
(check-exn #rx"init: not yet dynamic-required from frog.rkt"
(λ () (init)))
(check-exn #rx"enhance-body: not yet dynamic-required from frog.rkt"
(λ () (enhance-body '((p () "hi")))))
(check-exn #rx"clean: not yet dynamic-required from frog.rkt"
(λ () (clean))))
(define-runtime-path example "../../../example/")
(test-case "after loading example/frog.rkt"
(load example)
(check-not-exn (λ () (init)))
(check-not-exn (λ () (enhance-body '((p () "hi")))))
(check-not-exn (λ () (clean)))))
| null | https://raw.githubusercontent.com/greghendershott/frog/93d8b442c2e619334612b7e2d091e4eb33995021/frog/config/private/load.rkt | racket | #lang racket/base
(require (for-syntax racket/base
racket/function
racket/syntax))
(begin-for-syntax
(define provide-syms '(init
enhance-body
clean))
(provide provide-syms))
(define-syntax (define-the-things stx)
(with-syntax ([(id ...) (map (curry format-id stx "~a") provide-syms)]
[load (format-id stx "load")])
#'(begin
(define id
(λ _ (error 'id "not yet dynamic-required from frog.rkt"))) ...
(provide id ...)
(define (load top)
(define frog.rkt (build-path top "frog.rkt"))
(let ([fn (with-handlers ([exn:fail:filesystem? cannot-find-frog.rkt])
(dynamic-require frog.rkt 'id))])
(when fn (set! id fn))) ...)
(provide load))))
(define-the-things)
(define (cannot-find-frog.rkt . _)
(eprintf "Cannot open frog.rkt.\nMaybe you need to `raco frog --init` ?\n")
(exit 1))
(module+ test
(require rackunit
racket/runtime-path)
(test-case "before loading example/frog.rkt"
(check-exn #rx"init: not yet dynamic-required from frog.rkt"
(λ () (init)))
(check-exn #rx"enhance-body: not yet dynamic-required from frog.rkt"
(λ () (enhance-body '((p () "hi")))))
(check-exn #rx"clean: not yet dynamic-required from frog.rkt"
(λ () (clean))))
(define-runtime-path example "../../../example/")
(test-case "after loading example/frog.rkt"
(load example)
(check-not-exn (λ () (init)))
(check-not-exn (λ () (enhance-body '((p () "hi")))))
(check-not-exn (λ () (clean)))))
| |
1eaaa577ef6360b8d0e6d658f57c915046412197d8eb2e551910ebb9a83560df | ConsumerDataStandardsAustralia/validation-prototype | PayeesGens.hs | module Web.ConsumerData.Au.Api.Types.Banking.PayeesGens where
import Control.Applicative (liftA2)
import Control.Monad (replicateM)
import Country.Gens (countryGen)
import Data.Text (Text)
import qualified Data.Text as Text
import Hedgehog
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Data.Text.Gens
import Web.ConsumerData.Au.Api.Types
import Web.ConsumerData.Au.Api.Types.Data.CommonFieldTypesGens (dateStringGen)
payeeGen :: Gen Payee
payeeGen = Payee
<$> payeeIdGen
<*> textGen
<*> Gen.maybe textGen
<*> payeeTypeGen
<*> Gen.maybe dateStringGen
payeeIdGen :: Gen PayeeId
payeeIdGen = PayeeId <$> Gen.text (Range.linear 5 20) Gen.unicode
payeeTypeGen :: Gen PayeeType
payeeTypeGen = Gen.element [Domestic, International, Biller]
payeeDetailGen :: Gen PayeeDetail
payeeDetailGen = PayeeDetail <$> payeeGen <*> payeeTypeDataGen
payeeTypeDataGen :: Gen PayeeTypeData
payeeTypeDataGen = Gen.choice
[ PTDDomestic <$> domesticPayeeGen
, PTDInternational <$> internationalPayeeGen
, PTDBiller <$> billerPayeeGen
]
domesticPayeeGen :: Gen DomesticPayee
domesticPayeeGen = Gen.choice
[ DPAccount <$> domesticPayeeAccountGen
, DPCard <$> domesticPayeeCardGen
, DPPayeeId <$> domesticPayeePayIdGen
]
domesticPayeeAccountGen :: Gen DomesticPayeeAccount
domesticPayeeAccountGen =
DomesticPayeeAccount <$> textGen <*> bsbGen <*> textGen
bsbGen :: Gen Text
bsbGen =
let d3 = replicateM 3 Gen.digit
(<<>>) = liftA2 (<>)
in Text.pack <$> (d3 <<>> pure "-" <<>> d3)
domesticPayeeCardGen :: Gen DomesticPayeeCard
domesticPayeeCardGen = DomesticPayeeCard <$> textGen
domesticPayeePayIdGen :: Gen DomesticPayeePayId
domesticPayeePayIdGen =
DomesticPayeePayId <$> Gen.maybe textGen <*> textGen <*> domesticPayeePayIdTypeGen
domesticPayeePayIdTypeGen :: Gen DomesticPayeePayIdType
domesticPayeePayIdTypeGen = Gen.element [Email, Mobile, OrgNumber, OrgName]
internationalPayeeGen :: Gen InternationalPayee
internationalPayeeGen =
InternationalPayee <$> beneficiaryDetailsGen <*> bankDetailsGen
beneficiaryDetailsGen :: Gen BeneficiaryDetails
beneficiaryDetailsGen = BeneficiaryDetails <$> Gen.maybe textGen <*> countryGen <*> Gen.maybe textGen
bankDetailsGen :: Gen BankDetails
bankDetailsGen =
BankDetails <$> countryGen <*> textGen <*> Gen.maybe bankAddressGen <*>
Gen.maybe textGen <*> Gen.maybe textGen <*> Gen.maybe textGen <*> Gen.maybe textGen
<*> Gen.maybe textGen <*> Gen.maybe textGen
bankAddressGen :: Gen BankAddress
bankAddressGen = BankAddress <$> textGen <*> textGen
billerPayeeGen :: Gen BillerPayee
billerPayeeGen =
let numText = Text.pack . show <$> Gen.int (Range.linear 0 maxBound)
in BillerPayee <$> numText <*> Gen.maybe numText <*> textGen
| null | https://raw.githubusercontent.com/ConsumerDataStandardsAustralia/validation-prototype/ff63338b77339ee49fa3e0be5bb9d7f74e50c28b/consumer-data-au-api-types/tests/Web/ConsumerData/Au/Api/Types/Banking/PayeesGens.hs | haskell | module Web.ConsumerData.Au.Api.Types.Banking.PayeesGens where
import Control.Applicative (liftA2)
import Control.Monad (replicateM)
import Country.Gens (countryGen)
import Data.Text (Text)
import qualified Data.Text as Text
import Hedgehog
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Data.Text.Gens
import Web.ConsumerData.Au.Api.Types
import Web.ConsumerData.Au.Api.Types.Data.CommonFieldTypesGens (dateStringGen)
payeeGen :: Gen Payee
payeeGen = Payee
<$> payeeIdGen
<*> textGen
<*> Gen.maybe textGen
<*> payeeTypeGen
<*> Gen.maybe dateStringGen
payeeIdGen :: Gen PayeeId
payeeIdGen = PayeeId <$> Gen.text (Range.linear 5 20) Gen.unicode
payeeTypeGen :: Gen PayeeType
payeeTypeGen = Gen.element [Domestic, International, Biller]
payeeDetailGen :: Gen PayeeDetail
payeeDetailGen = PayeeDetail <$> payeeGen <*> payeeTypeDataGen
payeeTypeDataGen :: Gen PayeeTypeData
payeeTypeDataGen = Gen.choice
[ PTDDomestic <$> domesticPayeeGen
, PTDInternational <$> internationalPayeeGen
, PTDBiller <$> billerPayeeGen
]
domesticPayeeGen :: Gen DomesticPayee
domesticPayeeGen = Gen.choice
[ DPAccount <$> domesticPayeeAccountGen
, DPCard <$> domesticPayeeCardGen
, DPPayeeId <$> domesticPayeePayIdGen
]
domesticPayeeAccountGen :: Gen DomesticPayeeAccount
domesticPayeeAccountGen =
DomesticPayeeAccount <$> textGen <*> bsbGen <*> textGen
bsbGen :: Gen Text
bsbGen =
let d3 = replicateM 3 Gen.digit
(<<>>) = liftA2 (<>)
in Text.pack <$> (d3 <<>> pure "-" <<>> d3)
domesticPayeeCardGen :: Gen DomesticPayeeCard
domesticPayeeCardGen = DomesticPayeeCard <$> textGen
domesticPayeePayIdGen :: Gen DomesticPayeePayId
domesticPayeePayIdGen =
DomesticPayeePayId <$> Gen.maybe textGen <*> textGen <*> domesticPayeePayIdTypeGen
domesticPayeePayIdTypeGen :: Gen DomesticPayeePayIdType
domesticPayeePayIdTypeGen = Gen.element [Email, Mobile, OrgNumber, OrgName]
internationalPayeeGen :: Gen InternationalPayee
internationalPayeeGen =
InternationalPayee <$> beneficiaryDetailsGen <*> bankDetailsGen
beneficiaryDetailsGen :: Gen BeneficiaryDetails
beneficiaryDetailsGen = BeneficiaryDetails <$> Gen.maybe textGen <*> countryGen <*> Gen.maybe textGen
bankDetailsGen :: Gen BankDetails
bankDetailsGen =
BankDetails <$> countryGen <*> textGen <*> Gen.maybe bankAddressGen <*>
Gen.maybe textGen <*> Gen.maybe textGen <*> Gen.maybe textGen <*> Gen.maybe textGen
<*> Gen.maybe textGen <*> Gen.maybe textGen
bankAddressGen :: Gen BankAddress
bankAddressGen = BankAddress <$> textGen <*> textGen
billerPayeeGen :: Gen BillerPayee
billerPayeeGen =
let numText = Text.pack . show <$> Gen.int (Range.linear 0 maxBound)
in BillerPayee <$> numText <*> Gen.maybe numText <*> textGen
| |
0071f8cd44f69afa8896cac4c078042bedd8be3edc7c7f008bcdece76175ac0f | kupl/FixML | sub6.ml | type nat = ZERO | SUCC of nat
let rec natadd (a, b) = match a
with ZERO -> b
| SUCC ap -> SUCC (natadd (ap, b))
let rec natmul (a, b) =
if a=ZERO || b=ZERO then ZERO
else match a
with SUCC ZERO -> b
| SUCC ap -> (natadd (a, (natmul (ap, b))));;
| null | https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/nat/nat/submissions/sub6.ml | ocaml | type nat = ZERO | SUCC of nat
let rec natadd (a, b) = match a
with ZERO -> b
| SUCC ap -> SUCC (natadd (ap, b))
let rec natmul (a, b) =
if a=ZERO || b=ZERO then ZERO
else match a
with SUCC ZERO -> b
| SUCC ap -> (natadd (a, (natmul (ap, b))));;
| |
0b1f896d9aa32bbbc766438ed523b70e6867a262d8edd2ad6a5b1bb654b1f4bb | lispnik/iup | counter.lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(ql:quickload "iup"))
(defpackage #:iup-examples.counter
(:use #:common-lisp)
(:export #:counter))
(in-package #:iup-examples.counter)
(defun counter ()
(iup:with-iup ()
(let* ((count (iup:text :readonly :yes :value 0 :size 60))
(button (iup:button :title "Count"
:size 60
:action #'(lambda (handle)
(declare (ignore handle))
(setf (iup:attribute count :value)
(1+ (iup:attribute count :value 'number)))
iup:+default+)))
(hbox (iup:hbox (list count button) :gap 10 :margin "10x10"))
(dialog (iup:dialog hbox :title "Counter")))
(iup:show dialog)
(iup:main-loop))))
#+sbcl
(sb-int:with-float-traps-masked
(:divide-by-zero :invalid)
(counter))
#-sbcl
(counter)
| null | https://raw.githubusercontent.com/lispnik/iup/f8e5f090bae47bf8f91ac6fed41ec3bc01061186/examples/7guis/counter.lisp | lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(ql:quickload "iup"))
(defpackage #:iup-examples.counter
(:use #:common-lisp)
(:export #:counter))
(in-package #:iup-examples.counter)
(defun counter ()
(iup:with-iup ()
(let* ((count (iup:text :readonly :yes :value 0 :size 60))
(button (iup:button :title "Count"
:size 60
:action #'(lambda (handle)
(declare (ignore handle))
(setf (iup:attribute count :value)
(1+ (iup:attribute count :value 'number)))
iup:+default+)))
(hbox (iup:hbox (list count button) :gap 10 :margin "10x10"))
(dialog (iup:dialog hbox :title "Counter")))
(iup:show dialog)
(iup:main-loop))))
#+sbcl
(sb-int:with-float-traps-masked
(:divide-by-zero :invalid)
(counter))
#-sbcl
(counter)
| |
83fac62b2e9a6bd6ae1e2c5a55c47d4dbc44c0a353c125dd9e48e15e4ba754b0 | shayne-fletcher/zen | ml_typedtree.mli | (** Abstract syntax tree after typing *)
open Ml_asttypes (*[type rec_flag], [type 'a loc]*)
open Ml_types (*Constructor and value descriptions*)
(**{2 Types}*)
(**The type of "partiality" information indiciating partial or total
patten matchings*)
type partial = | Partial | Total
(**The type of a pattern*)
type pattern = {
pat_desc : pattern_desc;
pat_loc : Ml_location.t;
}
(**The type of a pattern description*)
and pattern_desc =
| Tpat_any
(** _ *)
| Tpat_var of Ml_ident.t * string loc
(** x *)
| Tpat_alias of pattern * Ml_ident.t * string loc
(** P as a*)
| Tpat_constant of constant
* 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Tpat_tuple of pattern list
* ( P1 , ... , Pn )
Invariant : n > = 2
Invariant : n >= 2
*)
| Tpat_construct of
Ml_longident.t loc * Ml_types.constructor_description * pattern list
* C [ ]
C P [ P ]
C ( P1 , ... , Pn ) [ P1 ; ... ; Pn ]
C P [P]
C (P1, ..., Pn) [P1; ...; Pn]
*)
| Tpat_or of pattern * pattern
(** P1 | P2 *)
(**The type of an expression*)
and expression =
{ exp_desc : expression_desc;
exp_loc : Ml_location.t;
}
(**The type of an expression description*)
and expression_desc =
| Texp_ident of Ml_path.t * Ml_longident.t loc * Ml_types.value_description
* x
M.x
*)
| Texp_constant of constant
* 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Texp_let of rec_flag * value_binding list * expression
* let P1 = E1 and ... and Pn = EN in E ( flag = )
let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive)
*)
| Texp_function of case list * partial
* [ Pexp_fun ] and [ Pexp_function ] both translate to [ Texp_function ] .
See { ! for more details .
partial =
[ Partial ] if the pattern match is partial
[ Total ] otherwise .
See {!Parsetree} for more details.
partial =
[Partial] if the pattern match is partial
[Total] otherwise.
*)
| Texp_apply of expression * expression list
* E0 E1 ... En
For example :
let f x y = x + y in
f 3
The resulting typedtree for the application is :
Texp_apply ( Texp_ident " f/1490 " ,
[ Texp_constant Const_int 3 ] )
For example:
let f x y = x + y in
f 3
The resulting typedtree for the application is:
Texp_apply (Texp_ident "f/1490",
[Texp_constant Const_int 3])
*)
| Texp_match of expression * case list * case list * partial
* match E0 with
| P1 - > E1
| P2 - > E2
| exception P3 - > E3
[ Texp_match ( E0 , [ ( P1 , E1 ) ; ( P2 , E2 ) ] , [ ( P3 , E3 ) ] , _ ) ]
| P1 -> E1
| P2 -> E2
| exception P3 -> E3
[Texp_match (E0, [(P1, E1); (P2, E2)], [(P3, E3)], _)]
*)
| Texp_tuple of expression list
(** (E1, ..., EN) *)
| Texp_construct of
Ml_longident.t loc * Ml_types.constructor_description * expression list
(** C []
C E [E]
C (E1, ..., En) [E1;...;En]
*)
| T_expifthenelse of expression * expression * expression
(**The type of a case*)
and case =
{
c_lhs : pattern;
c_rhs : expression;
}
(**The type of a structure*)
and structure =
{
str_desc : structure_item_desc;
str_loc : Ml_location.t;
}
(**The type of a structure item*)
and structure_item_desc =
| Tstr_eval of expression
| Tstr_value of rec_flag * value_binding list
| Tstr_primitive of Ml_types.value_description
(**The type of a value binding*)
and value_binding =
{
vb_pat : pattern;
vb_expr : expression;
vb_loc : Ml_location.t;
}
* { 2 Functions over the AST }
* An alisas for [ Ml_location.mknoloc ]
val mknoloc : 'a -> 'a Ml_asttypes.loc
(**An alias for [Ml_location.loc]*)
val mkloc : 'a -> Ml_location.t -> 'a Ml_asttypes.loc
(**[iter_pattern_desc f p] iterates [f] over [p]*)
val iter_pattern_desc : (pattern -> unit) -> pattern_desc -> unit
(**[map_pattern_desc f p] produces a new pattern description by
mapping [f] over [p]*)
val map_pattern_desc : (pattern -> pattern) -> pattern_desc -> pattern_desc
(**[let_bound_idents vbs] produces a list of the identifiers in the
bound in a let (value binding list) [vbs]*)
val let_bound_idents : value_binding list -> Ml_ident.t list
(**[rev_let_bound_idents vbs] as above but in reverse order*)
val rev_let_bound_idents : value_binding list -> Ml_ident.t list
(**Like [let_bind_idents_with_loc] but with locations*)
val let_bound_idents_with_loc :
value_binding list -> (Ml_ident.t * string loc) list
(**[pat_bound_idents p] produces a list of the identifiers in the
bound in the pattern [p]*)
val pat_bound_idents : pattern -> Ml_ident.t list
* [ alpha_pat env p ] produces a new pattern from [ p ] by substitution
of identifiers in [ env ]
of identifiers in [env]*)
val alpha_pat : (Ml_ident.t * Ml_ident.t) list -> pattern -> pattern
| null | https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/cos/src/typing/ml_typedtree.mli | ocaml | * Abstract syntax tree after typing
[type rec_flag], [type 'a loc]
Constructor and value descriptions
*{2 Types}
*The type of "partiality" information indiciating partial or total
patten matchings
*The type of a pattern
*The type of a pattern description
* _
* x
* P as a
* P1 | P2
*The type of an expression
*The type of an expression description
* (E1, ..., EN)
* C []
C E [E]
C (E1, ..., En) [E1;...;En]
*The type of a case
*The type of a structure
*The type of a structure item
*The type of a value binding
*An alias for [Ml_location.loc]
*[iter_pattern_desc f p] iterates [f] over [p]
*[map_pattern_desc f p] produces a new pattern description by
mapping [f] over [p]
*[let_bound_idents vbs] produces a list of the identifiers in the
bound in a let (value binding list) [vbs]
*[rev_let_bound_idents vbs] as above but in reverse order
*Like [let_bind_idents_with_loc] but with locations
*[pat_bound_idents p] produces a list of the identifiers in the
bound in the pattern [p] |
type partial = | Partial | Total
type pattern = {
pat_desc : pattern_desc;
pat_loc : Ml_location.t;
}
and pattern_desc =
| Tpat_any
| Tpat_var of Ml_ident.t * string loc
| Tpat_alias of pattern * Ml_ident.t * string loc
| Tpat_constant of constant
* 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Tpat_tuple of pattern list
* ( P1 , ... , Pn )
Invariant : n > = 2
Invariant : n >= 2
*)
| Tpat_construct of
Ml_longident.t loc * Ml_types.constructor_description * pattern list
* C [ ]
C P [ P ]
C ( P1 , ... , Pn ) [ P1 ; ... ; Pn ]
C P [P]
C (P1, ..., Pn) [P1; ...; Pn]
*)
| Tpat_or of pattern * pattern
and expression =
{ exp_desc : expression_desc;
exp_loc : Ml_location.t;
}
and expression_desc =
| Texp_ident of Ml_path.t * Ml_longident.t loc * Ml_types.value_description
* x
M.x
*)
| Texp_constant of constant
* 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Texp_let of rec_flag * value_binding list * expression
* let P1 = E1 and ... and Pn = EN in E ( flag = )
let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive)
*)
| Texp_function of case list * partial
* [ Pexp_fun ] and [ Pexp_function ] both translate to [ Texp_function ] .
See { ! for more details .
partial =
[ Partial ] if the pattern match is partial
[ Total ] otherwise .
See {!Parsetree} for more details.
partial =
[Partial] if the pattern match is partial
[Total] otherwise.
*)
| Texp_apply of expression * expression list
* E0 E1 ... En
For example :
let f x y = x + y in
f 3
The resulting typedtree for the application is :
Texp_apply ( Texp_ident " f/1490 " ,
[ Texp_constant Const_int 3 ] )
For example:
let f x y = x + y in
f 3
The resulting typedtree for the application is:
Texp_apply (Texp_ident "f/1490",
[Texp_constant Const_int 3])
*)
| Texp_match of expression * case list * case list * partial
* match E0 with
| P1 - > E1
| P2 - > E2
| exception P3 - > E3
[ Texp_match ( E0 , [ ( P1 , E1 ) ; ( P2 , E2 ) ] , [ ( P3 , E3 ) ] , _ ) ]
| P1 -> E1
| P2 -> E2
| exception P3 -> E3
[Texp_match (E0, [(P1, E1); (P2, E2)], [(P3, E3)], _)]
*)
| Texp_tuple of expression list
| Texp_construct of
Ml_longident.t loc * Ml_types.constructor_description * expression list
| T_expifthenelse of expression * expression * expression
and case =
{
c_lhs : pattern;
c_rhs : expression;
}
and structure =
{
str_desc : structure_item_desc;
str_loc : Ml_location.t;
}
and structure_item_desc =
| Tstr_eval of expression
| Tstr_value of rec_flag * value_binding list
| Tstr_primitive of Ml_types.value_description
and value_binding =
{
vb_pat : pattern;
vb_expr : expression;
vb_loc : Ml_location.t;
}
* { 2 Functions over the AST }
* An alisas for [ Ml_location.mknoloc ]
val mknoloc : 'a -> 'a Ml_asttypes.loc
val mkloc : 'a -> Ml_location.t -> 'a Ml_asttypes.loc
val iter_pattern_desc : (pattern -> unit) -> pattern_desc -> unit
val map_pattern_desc : (pattern -> pattern) -> pattern_desc -> pattern_desc
val let_bound_idents : value_binding list -> Ml_ident.t list
val rev_let_bound_idents : value_binding list -> Ml_ident.t list
val let_bound_idents_with_loc :
value_binding list -> (Ml_ident.t * string loc) list
val pat_bound_idents : pattern -> Ml_ident.t list
* [ alpha_pat env p ] produces a new pattern from [ p ] by substitution
of identifiers in [ env ]
of identifiers in [env]*)
val alpha_pat : (Ml_ident.t * Ml_ident.t) list -> pattern -> pattern
|
822da27f30f44a2dfb8adcea470c85222039d22652b1879f2b6f718181e878a6 | tmattio/js-bindings | es2020_intl.ml | [@@@js.dummy "!! This code has been generated by gen_js_api !!"]
[@@@ocaml.warning "-7-32-39"]
[@@@ocaml.warning "-7-11-32-33-39"]
open Es2019
module Intl =
struct
include struct include Intl end
module BCP47LanguageTag =
struct
type t = string
let rec t_of_js : Ojs.t -> t =
fun (x2 : Ojs.t) -> Ojs.string_of_js x2
and t_to_js : t -> Ojs.t = fun (x1 : string) -> Ojs.string_to_js x1
end
module RelativeTimeFormatUnit =
struct
type t =
[ `day | `days | `hour | `hours | `minute | `minutes
| `month | `months | `quarter | `quarters | `second
| `seconds | `week | `weeks | `year | `years ]
let rec t_of_js : Ojs.t -> t =
fun (x4 : Ojs.t) ->
let x5 = x4 in
match Ojs.string_of_js x5 with
| "day" -> `day
| "days" -> `days
| "hour" -> `hour
| "hours" -> `hours
| "minute" -> `minute
| "minutes" -> `minutes
| "month" -> `month
| "months" -> `months
| "quarter" -> `quarter
| "quarters" -> `quarters
| "second" -> `second
| "seconds" -> `seconds
| "week" -> `week
| "weeks" -> `weeks
| "year" -> `year
| "years" -> `years
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun
(x3 :
[ `day | `days | `hour | `hours | `minute | `minutes
| `month | `months | `quarter | `quarters | `second
| `seconds | `week | `weeks | `year | `years ])
->
match x3 with
| `day -> Ojs.string_to_js "day"
| `days -> Ojs.string_to_js "days"
| `hour -> Ojs.string_to_js "hour"
| `hours -> Ojs.string_to_js "hours"
| `minute -> Ojs.string_to_js "minute"
| `minutes -> Ojs.string_to_js "minutes"
| `month -> Ojs.string_to_js "month"
| `months -> Ojs.string_to_js "months"
| `quarter -> Ojs.string_to_js "quarter"
| `quarters -> Ojs.string_to_js "quarters"
| `second -> Ojs.string_to_js "second"
| `seconds -> Ojs.string_to_js "seconds"
| `week -> Ojs.string_to_js "week"
| `weeks -> Ojs.string_to_js "weeks"
| `year -> Ojs.string_to_js "year"
| `years -> Ojs.string_to_js "years"
end
module RelativeTimeFormatLocaleMatcher =
struct
type t = [ `best_fit | `lookup ]
let rec t_of_js : Ojs.t -> t =
fun (x7 : Ojs.t) ->
let x8 = x7 in
match Ojs.string_of_js x8 with
| "best fit" -> `best_fit
| "lookup" -> `lookup
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun (x6 : [ `best_fit | `lookup ]) ->
match x6 with
| `best_fit -> Ojs.string_to_js "best fit"
| `lookup -> Ojs.string_to_js "lookup"
end
module RelativeTimeFormatNumeric =
struct
type t = [ `always | `auto ]
let rec t_of_js : Ojs.t -> t =
fun (x10 : Ojs.t) ->
let x11 = x10 in
match Ojs.string_of_js x11 with
| "always" -> `always
| "auto" -> `auto
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun (x9 : [ `always | `auto ]) ->
match x9 with
| `always -> Ojs.string_to_js "always"
| `auto -> Ojs.string_to_js "auto"
end
module RelativeTimeFormatStyle =
struct
type t = [ `long | `narrow | `short ]
let rec t_of_js : Ojs.t -> t =
fun (x13 : Ojs.t) ->
let x14 = x13 in
match Ojs.string_of_js x14 with
| "long" -> `long
| "narrow" -> `narrow
| "short" -> `short
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun (x12 : [ `long | `narrow | `short ]) ->
match x12 with
| `long -> Ojs.string_to_js "long"
| `narrow -> Ojs.string_to_js "narrow"
| `short -> Ojs.string_to_js "short"
end
module Calendar =
struct
type t =
[ `buddhist | `chinese | `coptic | `dangi | `ethioaa
| `ethiopic | `ethiopic_amete_alem | `gregorian | `gregory
| `hebrew | `indian | `islamic | `islamic_civil
| `islamic_rgsa | `islamic_tbla | `islamic_umalqura | `islamicc
| `iso8601 | `japanese | `persian | `roc ]
let rec t_of_js : Ojs.t -> t =
fun (x16 : Ojs.t) ->
let x17 = x16 in
match Ojs.string_of_js x17 with
| "buddhist" -> `buddhist
| "chinese" -> `chinese
| "coptic" -> `coptic
| "dangi" -> `dangi
| "ethioaa" -> `ethioaa
| "ethiopic" -> `ethiopic
| "ethiopic-amete-alem" -> `ethiopic_amete_alem
| "gregorian" -> `gregorian
| "gregory" -> `gregory
| "hebrew" -> `hebrew
| "indian" -> `indian
| "islamic" -> `islamic
| "islamic-civil" -> `islamic_civil
| "islamic-rgsa" -> `islamic_rgsa
| "islamic-tbla" -> `islamic_tbla
| "islamic-umalqura" -> `islamic_umalqura
| "islamicc" -> `islamicc
| "iso8601" -> `iso8601
| "japanese" -> `japanese
| "persian" -> `persian
| "roc" -> `roc
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun
(x15 :
[ `buddhist | `chinese | `coptic | `dangi | `ethioaa
| `ethiopic | `ethiopic_amete_alem | `gregorian | `gregory
| `hebrew | `indian | `islamic | `islamic_civil
| `islamic_rgsa | `islamic_tbla | `islamic_umalqura
| `islamicc | `iso8601 | `japanese | `persian | `roc ])
->
match x15 with
| `buddhist -> Ojs.string_to_js "buddhist"
| `chinese -> Ojs.string_to_js "chinese"
| `coptic -> Ojs.string_to_js "coptic"
| `dangi -> Ojs.string_to_js "dangi"
| `ethioaa -> Ojs.string_to_js "ethioaa"
| `ethiopic -> Ojs.string_to_js "ethiopic"
| `ethiopic_amete_alem -> Ojs.string_to_js "ethiopic-amete-alem"
| `gregorian -> Ojs.string_to_js "gregorian"
| `gregory -> Ojs.string_to_js "gregory"
| `hebrew -> Ojs.string_to_js "hebrew"
| `indian -> Ojs.string_to_js "indian"
| `islamic -> Ojs.string_to_js "islamic"
| `islamic_civil -> Ojs.string_to_js "islamic-civil"
| `islamic_rgsa -> Ojs.string_to_js "islamic-rgsa"
| `islamic_tbla -> Ojs.string_to_js "islamic-tbla"
| `islamic_umalqura -> Ojs.string_to_js "islamic-umalqura"
| `islamicc -> Ojs.string_to_js "islamicc"
| `iso8601 -> Ojs.string_to_js "iso8601"
| `japanese -> Ojs.string_to_js "japanese"
| `persian -> Ojs.string_to_js "persian"
| `roc -> Ojs.string_to_js "roc"
end
module NumberingSystem =
struct
type t =
[ `adlm | `ahom | `arab | `arabext | `armn | `armnlow
| `bali | `beng | `bhks | `brah | `cakm | `cham | `cyrl
| `deva | `diak | `ethi | `finance | `fullwide | `geor
| `gong | `gonm | `grek | `greklow | `gujr | `guru
| `hanidays | `hanidec | `hans | `hansfin | `hant | `hantfin
| `hebr | `hmng | `hmnp | `java | `jpan | `jpanfin
| `jpanyear | `kali | `khmr | `knda | `lana | `lanatham
| `laoo | `latn | `lepc | `limb | `mathbold | `mathdbl
| `mathmono | `mathsanb | `mathsans | `mlym | `modi |
`mong
| `mroo | `mtei | `mymr | `mymrshan | `mymrtlng | `native
| `newa | `nkoo | `olck | `orya | `osma | `rohg | `roman
| `romanlow | `saur | `shrd | `sind | `sinh | `sora |
`sund
| `takr | `talu | `taml | `tamldec | `telu | `thai |
`tibt
| `tirh | `traditio | `traditional | `vaii | `wara | `wcho ]
let rec t_of_js : Ojs.t -> t =
fun (x19 : Ojs.t) ->
let x20 = x19 in
match Ojs.string_of_js x20 with
| "adlm" -> `adlm
| "ahom" -> `ahom
| "arab" -> `arab
| "arabext" -> `arabext
| "armn" -> `armn
| "armnlow" -> `armnlow
| "bali" -> `bali
| "beng" -> `beng
| "bhks" -> `bhks
| "brah" -> `brah
| "cakm" -> `cakm
| "cham" -> `cham
| "cyrl" -> `cyrl
| "deva" -> `deva
| "diak" -> `diak
| "ethi" -> `ethi
| "finance" -> `finance
| "fullwide" -> `fullwide
| "geor" -> `geor
| "gong" -> `gong
| "gonm" -> `gonm
| "grek" -> `grek
| "greklow" -> `greklow
| "gujr" -> `gujr
| "guru" -> `guru
| "hanidays" -> `hanidays
| "hanidec" -> `hanidec
| "hans" -> `hans
| "hansfin" -> `hansfin
| "hant" -> `hant
| "hantfin" -> `hantfin
| "hebr" -> `hebr
| "hmng" -> `hmng
| "hmnp" -> `hmnp
| "java" -> `java
| "jpan" -> `jpan
| "jpanfin" -> `jpanfin
| "jpanyear" -> `jpanyear
| "kali" -> `kali
| "khmr" -> `khmr
| "knda" -> `knda
| "lana" -> `lana
| "lanatham" -> `lanatham
| "laoo" -> `laoo
| "latn" -> `latn
| "lepc" -> `lepc
| "limb" -> `limb
| "mathbold" -> `mathbold
| "mathdbl" -> `mathdbl
| "mathmono" -> `mathmono
| "mathsanb" -> `mathsanb
| "mathsans" -> `mathsans
| "mlym" -> `mlym
| "modi" -> `modi
| "mong" -> `mong
| "mroo" -> `mroo
| "mtei" -> `mtei
| "mymr" -> `mymr
| "mymrshan" -> `mymrshan
| "mymrtlng" -> `mymrtlng
| "native" -> `native
| "newa" -> `newa
| "nkoo" -> `nkoo
| "olck" -> `olck
| "orya" -> `orya
| "osma" -> `osma
| "rohg" -> `rohg
| "roman" -> `roman
| "romanlow" -> `romanlow
| "saur" -> `saur
| "shrd" -> `shrd
| "sind" -> `sind
| "sinh" -> `sinh
| "sora" -> `sora
| "sund" -> `sund
| "takr" -> `takr
| "talu" -> `talu
| "taml" -> `taml
| "tamldec" -> `tamldec
| "telu" -> `telu
| "thai" -> `thai
| "tibt" -> `tibt
| "tirh" -> `tirh
| "traditio" -> `traditio
| "traditional" -> `traditional
| "vaii" -> `vaii
| "wara" -> `wara
| "wcho" -> `wcho
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun
(x18 :
[ `adlm | `ahom | `arab | `arabext | `armn | `armnlow
| `bali | `beng | `bhks | `brah | `cakm | `cham |
`cyrl
| `deva | `diak | `ethi | `finance | `fullwide | `geor
| `gong | `gonm | `grek | `greklow | `gujr | `guru
| `hanidays | `hanidec | `hans | `hansfin | `hant
| `hantfin | `hebr | `hmng | `hmnp | `java | `jpan
| `jpanfin | `jpanyear | `kali | `khmr | `knda | `lana
| `lanatham | `laoo | `latn | `lepc | `limb | `mathbold
| `mathdbl | `mathmono | `mathsanb | `mathsans | `mlym
| `modi | `mong | `mroo | `mtei | `mymr | `mymrshan
| `mymrtlng | `native | `newa | `nkoo | `olck | `orya
| `osma | `rohg | `roman | `romanlow | `saur | `shrd
| `sind | `sinh | `sora | `sund | `takr | `talu |
`taml
| `tamldec | `telu | `thai | `tibt | `tirh | `traditio
| `traditional | `vaii | `wara | `wcho ])
->
match x18 with
| `adlm -> Ojs.string_to_js "adlm"
| `ahom -> Ojs.string_to_js "ahom"
| `arab -> Ojs.string_to_js "arab"
| `arabext -> Ojs.string_to_js "arabext"
| `armn -> Ojs.string_to_js "armn"
| `armnlow -> Ojs.string_to_js "armnlow"
| `bali -> Ojs.string_to_js "bali"
| `beng -> Ojs.string_to_js "beng"
| `bhks -> Ojs.string_to_js "bhks"
| `brah -> Ojs.string_to_js "brah"
| `cakm -> Ojs.string_to_js "cakm"
| `cham -> Ojs.string_to_js "cham"
| `cyrl -> Ojs.string_to_js "cyrl"
| `deva -> Ojs.string_to_js "deva"
| `diak -> Ojs.string_to_js "diak"
| `ethi -> Ojs.string_to_js "ethi"
| `finance -> Ojs.string_to_js "finance"
| `fullwide -> Ojs.string_to_js "fullwide"
| `geor -> Ojs.string_to_js "geor"
| `gong -> Ojs.string_to_js "gong"
| `gonm -> Ojs.string_to_js "gonm"
| `grek -> Ojs.string_to_js "grek"
| `greklow -> Ojs.string_to_js "greklow"
| `gujr -> Ojs.string_to_js "gujr"
| `guru -> Ojs.string_to_js "guru"
| `hanidays -> Ojs.string_to_js "hanidays"
| `hanidec -> Ojs.string_to_js "hanidec"
| `hans -> Ojs.string_to_js "hans"
| `hansfin -> Ojs.string_to_js "hansfin"
| `hant -> Ojs.string_to_js "hant"
| `hantfin -> Ojs.string_to_js "hantfin"
| `hebr -> Ojs.string_to_js "hebr"
| `hmng -> Ojs.string_to_js "hmng"
| `hmnp -> Ojs.string_to_js "hmnp"
| `java -> Ojs.string_to_js "java"
| `jpan -> Ojs.string_to_js "jpan"
| `jpanfin -> Ojs.string_to_js "jpanfin"
| `jpanyear -> Ojs.string_to_js "jpanyear"
| `kali -> Ojs.string_to_js "kali"
| `khmr -> Ojs.string_to_js "khmr"
| `knda -> Ojs.string_to_js "knda"
| `lana -> Ojs.string_to_js "lana"
| `lanatham -> Ojs.string_to_js "lanatham"
| `laoo -> Ojs.string_to_js "laoo"
| `latn -> Ojs.string_to_js "latn"
| `lepc -> Ojs.string_to_js "lepc"
| `limb -> Ojs.string_to_js "limb"
| `mathbold -> Ojs.string_to_js "mathbold"
| `mathdbl -> Ojs.string_to_js "mathdbl"
| `mathmono -> Ojs.string_to_js "mathmono"
| `mathsanb -> Ojs.string_to_js "mathsanb"
| `mathsans -> Ojs.string_to_js "mathsans"
| `mlym -> Ojs.string_to_js "mlym"
| `modi -> Ojs.string_to_js "modi"
| `mong -> Ojs.string_to_js "mong"
| `mroo -> Ojs.string_to_js "mroo"
| `mtei -> Ojs.string_to_js "mtei"
| `mymr -> Ojs.string_to_js "mymr"
| `mymrshan -> Ojs.string_to_js "mymrshan"
| `mymrtlng -> Ojs.string_to_js "mymrtlng"
| `native -> Ojs.string_to_js "native"
| `newa -> Ojs.string_to_js "newa"
| `nkoo -> Ojs.string_to_js "nkoo"
| `olck -> Ojs.string_to_js "olck"
| `orya -> Ojs.string_to_js "orya"
| `osma -> Ojs.string_to_js "osma"
| `rohg -> Ojs.string_to_js "rohg"
| `roman -> Ojs.string_to_js "roman"
| `romanlow -> Ojs.string_to_js "romanlow"
| `saur -> Ojs.string_to_js "saur"
| `shrd -> Ojs.string_to_js "shrd"
| `sind -> Ojs.string_to_js "sind"
| `sinh -> Ojs.string_to_js "sinh"
| `sora -> Ojs.string_to_js "sora"
| `sund -> Ojs.string_to_js "sund"
| `takr -> Ojs.string_to_js "takr"
| `talu -> Ojs.string_to_js "talu"
| `taml -> Ojs.string_to_js "taml"
| `tamldec -> Ojs.string_to_js "tamldec"
| `telu -> Ojs.string_to_js "telu"
| `thai -> Ojs.string_to_js "thai"
| `tibt -> Ojs.string_to_js "tibt"
| `tirh -> Ojs.string_to_js "tirh"
| `traditio -> Ojs.string_to_js "traditio"
| `traditional -> Ojs.string_to_js "traditional"
| `vaii -> Ojs.string_to_js "vaii"
| `wara -> Ojs.string_to_js "wara"
| `wcho -> Ojs.string_to_js "wcho"
end
module RelativeTimeFormatOptions =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x22 : Ojs.t) -> x22
and t_to_js : t -> Ojs.t = fun (x21 : Ojs.t) -> x21
let (get_locale_matcher : t -> RelativeTimeFormatLocaleMatcher.t) =
fun (x23 : t) ->
RelativeTimeFormatLocaleMatcher.t_of_js
(Ojs.get_prop_ascii (t_to_js x23) "localeMatcher")
let (set_locale_matcher :
t -> RelativeTimeFormatLocaleMatcher.t -> unit) =
fun (x24 : t) ->
fun (x25 : RelativeTimeFormatLocaleMatcher.t) ->
Ojs.set_prop_ascii (t_to_js x24) "localeMatcher"
(RelativeTimeFormatLocaleMatcher.t_to_js x25)
let (get_numeric : t -> RelativeTimeFormatNumeric.t) =
fun (x26 : t) ->
RelativeTimeFormatNumeric.t_of_js
(Ojs.get_prop_ascii (t_to_js x26) "numeric")
let (set_numeric : t -> RelativeTimeFormatNumeric.t -> unit) =
fun (x27 : t) ->
fun (x28 : RelativeTimeFormatNumeric.t) ->
Ojs.set_prop_ascii (t_to_js x27) "numeric"
(RelativeTimeFormatNumeric.t_to_js x28)
let (get_style : t -> RelativeTimeFormatStyle.t) =
fun (x29 : t) ->
RelativeTimeFormatStyle.t_of_js
(Ojs.get_prop_ascii (t_to_js x29) "style")
let (set_style : t -> RelativeTimeFormatStyle.t -> unit) =
fun (x30 : t) ->
fun (x31 : RelativeTimeFormatStyle.t) ->
Ojs.set_prop_ascii (t_to_js x30) "style"
(RelativeTimeFormatStyle.t_to_js x31)
end
module ResolvedRelativeTimeFormatOptions =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x33 : Ojs.t) -> x33
and t_to_js : t -> Ojs.t = fun (x32 : Ojs.t) -> x32
let (get_locale : t -> string) =
fun (x34 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x34) "locale")
let (set_locale : t -> string -> unit) =
fun (x35 : t) ->
fun (x36 : string) ->
Ojs.set_prop_ascii (t_to_js x35) "locale"
(Ojs.string_to_js x36)
let (get_style : t -> RelativeTimeFormatStyle.t) =
fun (x37 : t) ->
RelativeTimeFormatStyle.t_of_js
(Ojs.get_prop_ascii (t_to_js x37) "style")
let (set_style : t -> RelativeTimeFormatStyle.t -> unit) =
fun (x38 : t) ->
fun (x39 : RelativeTimeFormatStyle.t) ->
Ojs.set_prop_ascii (t_to_js x38) "style"
(RelativeTimeFormatStyle.t_to_js x39)
let (get_numeric : t -> RelativeTimeFormatNumeric.t) =
fun (x40 : t) ->
RelativeTimeFormatNumeric.t_of_js
(Ojs.get_prop_ascii (t_to_js x40) "numeric")
let (set_numeric : t -> RelativeTimeFormatNumeric.t -> unit) =
fun (x41 : t) ->
fun (x42 : RelativeTimeFormatNumeric.t) ->
Ojs.set_prop_ascii (t_to_js x41) "numeric"
(RelativeTimeFormatNumeric.t_to_js x42)
let (get_numbering_system : t -> string) =
fun (x43 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x43) "numberingSystem")
let (set_numbering_system : t -> string -> unit) =
fun (x44 : t) ->
fun (x45 : string) ->
Ojs.set_prop_ascii (t_to_js x44) "numberingSystem"
(Ojs.string_to_js x45)
end
module RelativeTimeFormatPart =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x47 : Ojs.t) -> x47
and t_to_js : t -> Ojs.t = fun (x46 : Ojs.t) -> x46
let (get_type : t -> string) =
fun (x48 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x48) "type")
let (set_type : t -> string -> unit) =
fun (x49 : t) ->
fun (x50 : string) ->
Ojs.set_prop_ascii (t_to_js x49) "type" (Ojs.string_to_js x50)
let (get_value : t -> string) =
fun (x51 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x51) "value")
let (set_value : t -> string -> unit) =
fun (x52 : t) ->
fun (x53 : string) ->
Ojs.set_prop_ascii (t_to_js x52) "value" (Ojs.string_to_js x53)
let (get_unit : t -> RelativeTimeFormatUnit.t) =
fun (x54 : t) ->
RelativeTimeFormatUnit.t_of_js
(Ojs.get_prop_ascii (t_to_js x54) "unit")
let (set_unit : t -> RelativeTimeFormatUnit.t -> unit) =
fun (x55 : t) ->
fun (x56 : RelativeTimeFormatUnit.t) ->
Ojs.set_prop_ascii (t_to_js x55) "unit"
(RelativeTimeFormatUnit.t_to_js x56)
end
module RelativeTimeFormat =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x58 : Ojs.t) -> x58
and t_to_js : t -> Ojs.t = fun (x57 : Ojs.t) -> x57
let (format :
t -> value:int -> unit:RelativeTimeFormatUnit.t -> string) =
fun (x61 : t) ->
fun ~value:(x59 : int) ->
fun ~unit:(x60 : RelativeTimeFormatUnit.t) ->
Ojs.string_of_js
(Ojs.call (t_to_js x61) "format"
[|(Ojs.int_to_js x59);(RelativeTimeFormatUnit.t_to_js
x60)|])
let (format_to_parts :
t ->
value:int ->
unit:RelativeTimeFormatUnit.t -> RelativeTimeFormatPart.t list)
=
fun (x64 : t) ->
fun ~value:(x62 : int) ->
fun ~unit:(x63 : RelativeTimeFormatUnit.t) ->
Ojs.list_of_js RelativeTimeFormatPart.t_of_js
(Ojs.call (t_to_js x64) "formatToParts"
[|(Ojs.int_to_js x62);(RelativeTimeFormatUnit.t_to_js
x63)|])
let (resolved_options : t -> ResolvedRelativeTimeFormatOptions.t) =
fun (x66 : t) ->
ResolvedRelativeTimeFormatOptions.t_of_js
(Ojs.call (t_to_js x66) "resolvedOptions" [||])
end
module AnonymousInterface0 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x68 : Ojs.t) -> x68
and t_to_js : t -> Ojs.t = fun (x67 : Ojs.t) -> x67
let (create :
t ->
?locales:(string, string) or_array ->
?options:RelativeTimeFormatOptions.t ->
unit -> RelativeTimeFormat.t)
=
fun (x76 : t) ->
fun ?locales:(x69 : (string, string) or_array option) ->
fun ?options:(x70 : RelativeTimeFormatOptions.t option) ->
fun () ->
RelativeTimeFormat.t_of_js
(Ojs.new_obj_arr (t_to_js x76)
(let x71 =
Ojs.new_obj (Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x69 with
| Some x73 ->
ignore
(Ojs.call x71 "push"
[|(or_array_to_js Ojs.string_to_js
Ojs.string_to_js x73)|])
| None -> ());
(match x70 with
| Some x72 ->
ignore
(Ojs.call x71 "push"
[|(RelativeTimeFormatOptions.t_to_js x72)|])
| None -> ());
x71))
let (supported_locales_of :
t ->
locales:(string, string) or_array ->
?options:RelativeTimeFormatOptions.t -> unit -> string list)
=
fun (x83 : t) ->
fun ~locales:(x77 : (string, string) or_array) ->
fun ?options:(x78 : RelativeTimeFormatOptions.t option) ->
fun () ->
Ojs.list_of_js Ojs.string_of_js
(let x84 = t_to_js x83 in
Ojs.call (Ojs.get_prop_ascii x84 "supportedLocalesOf")
"apply"
[|x84;((let x79 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x79 "push"
[|(or_array_to_js Ojs.string_to_js
Ojs.string_to_js x77)|]);
(match x78 with
| Some x80 ->
ignore
(Ojs.call x79 "push"
[|(RelativeTimeFormatOptions.t_to_js
x80)|])
| None -> ());
x79))|])
end
let (relative_time_format : AnonymousInterface0.t) =
AnonymousInterface0.t_of_js
(Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "Intl")
"RelativeTimeFormat")
module NumberFormatOptions =
struct
include struct include NumberFormatOptions end
let (get_compact_display : t -> string) =
fun (x86 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x86) "compactDisplay")
let (set_compact_display : t -> string -> unit) =
fun (x87 : t) ->
fun (x88 : string) ->
Ojs.set_prop_ascii (t_to_js x87) "compactDisplay"
(Ojs.string_to_js x88)
let (get_notation : t -> string) =
fun (x89 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x89) "notation")
let (set_notation : t -> string -> unit) =
fun (x90 : t) ->
fun (x91 : string) ->
Ojs.set_prop_ascii (t_to_js x90) "notation"
(Ojs.string_to_js x91)
let (get_sign_display : t -> string) =
fun (x92 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x92) "signDisplay")
let (set_sign_display : t -> string -> unit) =
fun (x93 : t) ->
fun (x94 : string) ->
Ojs.set_prop_ascii (t_to_js x93) "signDisplay"
(Ojs.string_to_js x94)
let (get_unit : t -> string) =
fun (x95 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x95) "unit")
let (set_unit : t -> string -> unit) =
fun (x96 : t) ->
fun (x97 : string) ->
Ojs.set_prop_ascii (t_to_js x96) "unit" (Ojs.string_to_js x97)
let (get_unit_display : t -> string) =
fun (x98 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x98) "unitDisplay")
let (set_unit_display : t -> string -> unit) =
fun (x99 : t) ->
fun (x100 : string) ->
Ojs.set_prop_ascii (t_to_js x99) "unitDisplay"
(Ojs.string_to_js x100)
end
module ResolvedNumberFormatOptions =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x102 : Ojs.t) -> x102
and t_to_js : t -> Ojs.t = fun (x101 : Ojs.t) -> x101
let (get_compact_display : t -> string) =
fun (x103 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x103) "compactDisplay")
let (set_compact_display : t -> string -> unit) =
fun (x104 : t) ->
fun (x105 : string) ->
Ojs.set_prop_ascii (t_to_js x104) "compactDisplay"
(Ojs.string_to_js x105)
let (get_notation : t -> string) =
fun (x106 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x106) "notation")
let (set_notation : t -> string -> unit) =
fun (x107 : t) ->
fun (x108 : string) ->
Ojs.set_prop_ascii (t_to_js x107) "notation"
(Ojs.string_to_js x108)
let (get_sign_display : t -> string) =
fun (x109 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x109) "signDisplay")
let (set_sign_display : t -> string -> unit) =
fun (x110 : t) ->
fun (x111 : string) ->
Ojs.set_prop_ascii (t_to_js x110) "signDisplay"
(Ojs.string_to_js x111)
let (get_unit : t -> string) =
fun (x112 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x112) "unit")
let (set_unit : t -> string -> unit) =
fun (x113 : t) ->
fun (x114 : string) ->
Ojs.set_prop_ascii (t_to_js x113) "unit"
(Ojs.string_to_js x114)
let (get_unit_display : t -> string) =
fun (x115 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x115) "unitDisplay")
let (set_unit_display : t -> string -> unit) =
fun (x116 : t) ->
fun (x117 : string) ->
Ojs.set_prop_ascii (t_to_js x116) "unitDisplay"
(Ojs.string_to_js x117)
end
module DateTimeFormatOptions =
struct
include struct include DateTimeFormatOptions end
let (get_date_style : t -> [ `full | `long | `medium | `short ]) =
fun (x118 : t) ->
let x119 = Ojs.get_prop_ascii (t_to_js x118) "dateStyle" in
match Ojs.string_of_js x119 with
| "full" -> `full
| "long" -> `long
| "medium" -> `medium
| "short" -> `short
| _ -> assert false
let (set_date_style :
t -> [ `full | `long | `medium | `short ] -> unit) =
fun (x120 : t) ->
fun (x121 : [ `full | `long | `medium | `short ]) ->
Ojs.set_prop_ascii (t_to_js x120) "dateStyle"
(match x121 with
| `full -> Ojs.string_to_js "full"
| `long -> Ojs.string_to_js "long"
| `medium -> Ojs.string_to_js "medium"
| `short -> Ojs.string_to_js "short")
let (get_time_style : t -> [ `full | `long | `medium | `short ]) =
fun (x122 : t) ->
let x123 = Ojs.get_prop_ascii (t_to_js x122) "timeStyle" in
match Ojs.string_of_js x123 with
| "full" -> `full
| "long" -> `long
| "medium" -> `medium
| "short" -> `short
| _ -> assert false
let (set_time_style :
t -> [ `full | `long | `medium | `short ] -> unit) =
fun (x124 : t) ->
fun (x125 : [ `full | `long | `medium | `short ]) ->
Ojs.set_prop_ascii (t_to_js x124) "timeStyle"
(match x125 with
| `full -> Ojs.string_to_js "full"
| `long -> Ojs.string_to_js "long"
| `medium -> Ojs.string_to_js "medium"
| `short -> Ojs.string_to_js "short")
let (get_calendar : t -> Calendar.t) =
fun (x126 : t) ->
Calendar.t_of_js (Ojs.get_prop_ascii (t_to_js x126) "calendar")
let (set_calendar : t -> Calendar.t -> unit) =
fun (x127 : t) ->
fun (x128 : Calendar.t) ->
Ojs.set_prop_ascii (t_to_js x127) "calendar"
(Calendar.t_to_js x128)
let (get_day_period : t -> [ `long | `narrow | `short ]) =
fun (x129 : t) ->
let x130 = Ojs.get_prop_ascii (t_to_js x129) "dayPeriod" in
match Ojs.string_of_js x130 with
| "long" -> `long
| "narrow" -> `narrow
| "short" -> `short
| _ -> assert false
let (set_day_period : t -> [ `long | `narrow | `short ] -> unit) =
fun (x131 : t) ->
fun (x132 : [ `long | `narrow | `short ]) ->
Ojs.set_prop_ascii (t_to_js x131) "dayPeriod"
(match x132 with
| `long -> Ojs.string_to_js "long"
| `narrow -> Ojs.string_to_js "narrow"
| `short -> Ojs.string_to_js "short")
let (get_numbering_system : t -> NumberingSystem.t) =
fun (x133 : t) ->
NumberingSystem.t_of_js
(Ojs.get_prop_ascii (t_to_js x133) "numberingSystem")
let (set_numbering_system : t -> NumberingSystem.t -> unit) =
fun (x134 : t) ->
fun (x135 : NumberingSystem.t) ->
Ojs.set_prop_ascii (t_to_js x134) "numberingSystem"
(NumberingSystem.t_to_js x135)
let (get_hour_cycle : t -> [ `h11 | `h12 | `h23 | `h24 ]) =
fun (x136 : t) ->
let x137 = Ojs.get_prop_ascii (t_to_js x136) "hourCycle" in
match Ojs.string_of_js x137 with
| "h11" -> `h11
| "h12" -> `h12
| "h23" -> `h23
| "h24" -> `h24
| _ -> assert false
let (set_hour_cycle : t -> [ `h11 | `h12 | `h23 | `h24 ] -> unit)
=
fun (x138 : t) ->
fun (x139 : [ `h11 | `h12 | `h23 | `h24 ]) ->
Ojs.set_prop_ascii (t_to_js x138) "hourCycle"
(match x139 with
| `h11 -> Ojs.string_to_js "h11"
| `h12 -> Ojs.string_to_js "h12"
| `h23 -> Ojs.string_to_js "h23"
| `h24 -> Ojs.string_to_js "h24")
let (get_fractional_second_digits :
t -> [ `L_n_0 | `L_n_1 | `L_n_2 | `L_n_3 ]) =
fun (x140 : t) ->
let x141 =
Ojs.get_prop_ascii (t_to_js x140) "fractionalSecondDigits" in
match Ojs.int_of_js x141 with
| 0 -> `L_n_0
| 1 -> `L_n_1
| 2 -> `L_n_2
| 3 -> `L_n_3
| _ -> assert false
let (set_fractional_second_digits :
t -> [ `L_n_0 | `L_n_1 | `L_n_2 | `L_n_3 ] -> unit) =
fun (x142 : t) ->
fun (x143 : [ `L_n_0 | `L_n_1 | `L_n_2 | `L_n_3 ]) ->
Ojs.set_prop_ascii (t_to_js x142) "fractionalSecondDigits"
(match x143 with
| `L_n_0 -> Ojs.string_to_js "LN0"
| `L_n_1 -> Ojs.string_to_js "LN1"
| `L_n_2 -> Ojs.string_to_js "LN2"
| `L_n_3 -> Ojs.string_to_js "LN3")
end
end
| null | https://raw.githubusercontent.com/tmattio/js-bindings/f1d36bba378e4ecd5310542a0244dce9258b6496/lib/es2020/es2020_intl.ml | ocaml | [@@@js.dummy "!! This code has been generated by gen_js_api !!"]
[@@@ocaml.warning "-7-32-39"]
[@@@ocaml.warning "-7-11-32-33-39"]
open Es2019
module Intl =
struct
include struct include Intl end
module BCP47LanguageTag =
struct
type t = string
let rec t_of_js : Ojs.t -> t =
fun (x2 : Ojs.t) -> Ojs.string_of_js x2
and t_to_js : t -> Ojs.t = fun (x1 : string) -> Ojs.string_to_js x1
end
module RelativeTimeFormatUnit =
struct
type t =
[ `day | `days | `hour | `hours | `minute | `minutes
| `month | `months | `quarter | `quarters | `second
| `seconds | `week | `weeks | `year | `years ]
let rec t_of_js : Ojs.t -> t =
fun (x4 : Ojs.t) ->
let x5 = x4 in
match Ojs.string_of_js x5 with
| "day" -> `day
| "days" -> `days
| "hour" -> `hour
| "hours" -> `hours
| "minute" -> `minute
| "minutes" -> `minutes
| "month" -> `month
| "months" -> `months
| "quarter" -> `quarter
| "quarters" -> `quarters
| "second" -> `second
| "seconds" -> `seconds
| "week" -> `week
| "weeks" -> `weeks
| "year" -> `year
| "years" -> `years
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun
(x3 :
[ `day | `days | `hour | `hours | `minute | `minutes
| `month | `months | `quarter | `quarters | `second
| `seconds | `week | `weeks | `year | `years ])
->
match x3 with
| `day -> Ojs.string_to_js "day"
| `days -> Ojs.string_to_js "days"
| `hour -> Ojs.string_to_js "hour"
| `hours -> Ojs.string_to_js "hours"
| `minute -> Ojs.string_to_js "minute"
| `minutes -> Ojs.string_to_js "minutes"
| `month -> Ojs.string_to_js "month"
| `months -> Ojs.string_to_js "months"
| `quarter -> Ojs.string_to_js "quarter"
| `quarters -> Ojs.string_to_js "quarters"
| `second -> Ojs.string_to_js "second"
| `seconds -> Ojs.string_to_js "seconds"
| `week -> Ojs.string_to_js "week"
| `weeks -> Ojs.string_to_js "weeks"
| `year -> Ojs.string_to_js "year"
| `years -> Ojs.string_to_js "years"
end
module RelativeTimeFormatLocaleMatcher =
struct
type t = [ `best_fit | `lookup ]
let rec t_of_js : Ojs.t -> t =
fun (x7 : Ojs.t) ->
let x8 = x7 in
match Ojs.string_of_js x8 with
| "best fit" -> `best_fit
| "lookup" -> `lookup
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun (x6 : [ `best_fit | `lookup ]) ->
match x6 with
| `best_fit -> Ojs.string_to_js "best fit"
| `lookup -> Ojs.string_to_js "lookup"
end
module RelativeTimeFormatNumeric =
struct
type t = [ `always | `auto ]
let rec t_of_js : Ojs.t -> t =
fun (x10 : Ojs.t) ->
let x11 = x10 in
match Ojs.string_of_js x11 with
| "always" -> `always
| "auto" -> `auto
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun (x9 : [ `always | `auto ]) ->
match x9 with
| `always -> Ojs.string_to_js "always"
| `auto -> Ojs.string_to_js "auto"
end
module RelativeTimeFormatStyle =
struct
type t = [ `long | `narrow | `short ]
let rec t_of_js : Ojs.t -> t =
fun (x13 : Ojs.t) ->
let x14 = x13 in
match Ojs.string_of_js x14 with
| "long" -> `long
| "narrow" -> `narrow
| "short" -> `short
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun (x12 : [ `long | `narrow | `short ]) ->
match x12 with
| `long -> Ojs.string_to_js "long"
| `narrow -> Ojs.string_to_js "narrow"
| `short -> Ojs.string_to_js "short"
end
module Calendar =
struct
type t =
[ `buddhist | `chinese | `coptic | `dangi | `ethioaa
| `ethiopic | `ethiopic_amete_alem | `gregorian | `gregory
| `hebrew | `indian | `islamic | `islamic_civil
| `islamic_rgsa | `islamic_tbla | `islamic_umalqura | `islamicc
| `iso8601 | `japanese | `persian | `roc ]
let rec t_of_js : Ojs.t -> t =
fun (x16 : Ojs.t) ->
let x17 = x16 in
match Ojs.string_of_js x17 with
| "buddhist" -> `buddhist
| "chinese" -> `chinese
| "coptic" -> `coptic
| "dangi" -> `dangi
| "ethioaa" -> `ethioaa
| "ethiopic" -> `ethiopic
| "ethiopic-amete-alem" -> `ethiopic_amete_alem
| "gregorian" -> `gregorian
| "gregory" -> `gregory
| "hebrew" -> `hebrew
| "indian" -> `indian
| "islamic" -> `islamic
| "islamic-civil" -> `islamic_civil
| "islamic-rgsa" -> `islamic_rgsa
| "islamic-tbla" -> `islamic_tbla
| "islamic-umalqura" -> `islamic_umalqura
| "islamicc" -> `islamicc
| "iso8601" -> `iso8601
| "japanese" -> `japanese
| "persian" -> `persian
| "roc" -> `roc
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun
(x15 :
[ `buddhist | `chinese | `coptic | `dangi | `ethioaa
| `ethiopic | `ethiopic_amete_alem | `gregorian | `gregory
| `hebrew | `indian | `islamic | `islamic_civil
| `islamic_rgsa | `islamic_tbla | `islamic_umalqura
| `islamicc | `iso8601 | `japanese | `persian | `roc ])
->
match x15 with
| `buddhist -> Ojs.string_to_js "buddhist"
| `chinese -> Ojs.string_to_js "chinese"
| `coptic -> Ojs.string_to_js "coptic"
| `dangi -> Ojs.string_to_js "dangi"
| `ethioaa -> Ojs.string_to_js "ethioaa"
| `ethiopic -> Ojs.string_to_js "ethiopic"
| `ethiopic_amete_alem -> Ojs.string_to_js "ethiopic-amete-alem"
| `gregorian -> Ojs.string_to_js "gregorian"
| `gregory -> Ojs.string_to_js "gregory"
| `hebrew -> Ojs.string_to_js "hebrew"
| `indian -> Ojs.string_to_js "indian"
| `islamic -> Ojs.string_to_js "islamic"
| `islamic_civil -> Ojs.string_to_js "islamic-civil"
| `islamic_rgsa -> Ojs.string_to_js "islamic-rgsa"
| `islamic_tbla -> Ojs.string_to_js "islamic-tbla"
| `islamic_umalqura -> Ojs.string_to_js "islamic-umalqura"
| `islamicc -> Ojs.string_to_js "islamicc"
| `iso8601 -> Ojs.string_to_js "iso8601"
| `japanese -> Ojs.string_to_js "japanese"
| `persian -> Ojs.string_to_js "persian"
| `roc -> Ojs.string_to_js "roc"
end
module NumberingSystem =
struct
type t =
[ `adlm | `ahom | `arab | `arabext | `armn | `armnlow
| `bali | `beng | `bhks | `brah | `cakm | `cham | `cyrl
| `deva | `diak | `ethi | `finance | `fullwide | `geor
| `gong | `gonm | `grek | `greklow | `gujr | `guru
| `hanidays | `hanidec | `hans | `hansfin | `hant | `hantfin
| `hebr | `hmng | `hmnp | `java | `jpan | `jpanfin
| `jpanyear | `kali | `khmr | `knda | `lana | `lanatham
| `laoo | `latn | `lepc | `limb | `mathbold | `mathdbl
| `mathmono | `mathsanb | `mathsans | `mlym | `modi |
`mong
| `mroo | `mtei | `mymr | `mymrshan | `mymrtlng | `native
| `newa | `nkoo | `olck | `orya | `osma | `rohg | `roman
| `romanlow | `saur | `shrd | `sind | `sinh | `sora |
`sund
| `takr | `talu | `taml | `tamldec | `telu | `thai |
`tibt
| `tirh | `traditio | `traditional | `vaii | `wara | `wcho ]
let rec t_of_js : Ojs.t -> t =
fun (x19 : Ojs.t) ->
let x20 = x19 in
match Ojs.string_of_js x20 with
| "adlm" -> `adlm
| "ahom" -> `ahom
| "arab" -> `arab
| "arabext" -> `arabext
| "armn" -> `armn
| "armnlow" -> `armnlow
| "bali" -> `bali
| "beng" -> `beng
| "bhks" -> `bhks
| "brah" -> `brah
| "cakm" -> `cakm
| "cham" -> `cham
| "cyrl" -> `cyrl
| "deva" -> `deva
| "diak" -> `diak
| "ethi" -> `ethi
| "finance" -> `finance
| "fullwide" -> `fullwide
| "geor" -> `geor
| "gong" -> `gong
| "gonm" -> `gonm
| "grek" -> `grek
| "greklow" -> `greklow
| "gujr" -> `gujr
| "guru" -> `guru
| "hanidays" -> `hanidays
| "hanidec" -> `hanidec
| "hans" -> `hans
| "hansfin" -> `hansfin
| "hant" -> `hant
| "hantfin" -> `hantfin
| "hebr" -> `hebr
| "hmng" -> `hmng
| "hmnp" -> `hmnp
| "java" -> `java
| "jpan" -> `jpan
| "jpanfin" -> `jpanfin
| "jpanyear" -> `jpanyear
| "kali" -> `kali
| "khmr" -> `khmr
| "knda" -> `knda
| "lana" -> `lana
| "lanatham" -> `lanatham
| "laoo" -> `laoo
| "latn" -> `latn
| "lepc" -> `lepc
| "limb" -> `limb
| "mathbold" -> `mathbold
| "mathdbl" -> `mathdbl
| "mathmono" -> `mathmono
| "mathsanb" -> `mathsanb
| "mathsans" -> `mathsans
| "mlym" -> `mlym
| "modi" -> `modi
| "mong" -> `mong
| "mroo" -> `mroo
| "mtei" -> `mtei
| "mymr" -> `mymr
| "mymrshan" -> `mymrshan
| "mymrtlng" -> `mymrtlng
| "native" -> `native
| "newa" -> `newa
| "nkoo" -> `nkoo
| "olck" -> `olck
| "orya" -> `orya
| "osma" -> `osma
| "rohg" -> `rohg
| "roman" -> `roman
| "romanlow" -> `romanlow
| "saur" -> `saur
| "shrd" -> `shrd
| "sind" -> `sind
| "sinh" -> `sinh
| "sora" -> `sora
| "sund" -> `sund
| "takr" -> `takr
| "talu" -> `talu
| "taml" -> `taml
| "tamldec" -> `tamldec
| "telu" -> `telu
| "thai" -> `thai
| "tibt" -> `tibt
| "tirh" -> `tirh
| "traditio" -> `traditio
| "traditional" -> `traditional
| "vaii" -> `vaii
| "wara" -> `wara
| "wcho" -> `wcho
| _ -> assert false
and t_to_js : t -> Ojs.t =
fun
(x18 :
[ `adlm | `ahom | `arab | `arabext | `armn | `armnlow
| `bali | `beng | `bhks | `brah | `cakm | `cham |
`cyrl
| `deva | `diak | `ethi | `finance | `fullwide | `geor
| `gong | `gonm | `grek | `greklow | `gujr | `guru
| `hanidays | `hanidec | `hans | `hansfin | `hant
| `hantfin | `hebr | `hmng | `hmnp | `java | `jpan
| `jpanfin | `jpanyear | `kali | `khmr | `knda | `lana
| `lanatham | `laoo | `latn | `lepc | `limb | `mathbold
| `mathdbl | `mathmono | `mathsanb | `mathsans | `mlym
| `modi | `mong | `mroo | `mtei | `mymr | `mymrshan
| `mymrtlng | `native | `newa | `nkoo | `olck | `orya
| `osma | `rohg | `roman | `romanlow | `saur | `shrd
| `sind | `sinh | `sora | `sund | `takr | `talu |
`taml
| `tamldec | `telu | `thai | `tibt | `tirh | `traditio
| `traditional | `vaii | `wara | `wcho ])
->
match x18 with
| `adlm -> Ojs.string_to_js "adlm"
| `ahom -> Ojs.string_to_js "ahom"
| `arab -> Ojs.string_to_js "arab"
| `arabext -> Ojs.string_to_js "arabext"
| `armn -> Ojs.string_to_js "armn"
| `armnlow -> Ojs.string_to_js "armnlow"
| `bali -> Ojs.string_to_js "bali"
| `beng -> Ojs.string_to_js "beng"
| `bhks -> Ojs.string_to_js "bhks"
| `brah -> Ojs.string_to_js "brah"
| `cakm -> Ojs.string_to_js "cakm"
| `cham -> Ojs.string_to_js "cham"
| `cyrl -> Ojs.string_to_js "cyrl"
| `deva -> Ojs.string_to_js "deva"
| `diak -> Ojs.string_to_js "diak"
| `ethi -> Ojs.string_to_js "ethi"
| `finance -> Ojs.string_to_js "finance"
| `fullwide -> Ojs.string_to_js "fullwide"
| `geor -> Ojs.string_to_js "geor"
| `gong -> Ojs.string_to_js "gong"
| `gonm -> Ojs.string_to_js "gonm"
| `grek -> Ojs.string_to_js "grek"
| `greklow -> Ojs.string_to_js "greklow"
| `gujr -> Ojs.string_to_js "gujr"
| `guru -> Ojs.string_to_js "guru"
| `hanidays -> Ojs.string_to_js "hanidays"
| `hanidec -> Ojs.string_to_js "hanidec"
| `hans -> Ojs.string_to_js "hans"
| `hansfin -> Ojs.string_to_js "hansfin"
| `hant -> Ojs.string_to_js "hant"
| `hantfin -> Ojs.string_to_js "hantfin"
| `hebr -> Ojs.string_to_js "hebr"
| `hmng -> Ojs.string_to_js "hmng"
| `hmnp -> Ojs.string_to_js "hmnp"
| `java -> Ojs.string_to_js "java"
| `jpan -> Ojs.string_to_js "jpan"
| `jpanfin -> Ojs.string_to_js "jpanfin"
| `jpanyear -> Ojs.string_to_js "jpanyear"
| `kali -> Ojs.string_to_js "kali"
| `khmr -> Ojs.string_to_js "khmr"
| `knda -> Ojs.string_to_js "knda"
| `lana -> Ojs.string_to_js "lana"
| `lanatham -> Ojs.string_to_js "lanatham"
| `laoo -> Ojs.string_to_js "laoo"
| `latn -> Ojs.string_to_js "latn"
| `lepc -> Ojs.string_to_js "lepc"
| `limb -> Ojs.string_to_js "limb"
| `mathbold -> Ojs.string_to_js "mathbold"
| `mathdbl -> Ojs.string_to_js "mathdbl"
| `mathmono -> Ojs.string_to_js "mathmono"
| `mathsanb -> Ojs.string_to_js "mathsanb"
| `mathsans -> Ojs.string_to_js "mathsans"
| `mlym -> Ojs.string_to_js "mlym"
| `modi -> Ojs.string_to_js "modi"
| `mong -> Ojs.string_to_js "mong"
| `mroo -> Ojs.string_to_js "mroo"
| `mtei -> Ojs.string_to_js "mtei"
| `mymr -> Ojs.string_to_js "mymr"
| `mymrshan -> Ojs.string_to_js "mymrshan"
| `mymrtlng -> Ojs.string_to_js "mymrtlng"
| `native -> Ojs.string_to_js "native"
| `newa -> Ojs.string_to_js "newa"
| `nkoo -> Ojs.string_to_js "nkoo"
| `olck -> Ojs.string_to_js "olck"
| `orya -> Ojs.string_to_js "orya"
| `osma -> Ojs.string_to_js "osma"
| `rohg -> Ojs.string_to_js "rohg"
| `roman -> Ojs.string_to_js "roman"
| `romanlow -> Ojs.string_to_js "romanlow"
| `saur -> Ojs.string_to_js "saur"
| `shrd -> Ojs.string_to_js "shrd"
| `sind -> Ojs.string_to_js "sind"
| `sinh -> Ojs.string_to_js "sinh"
| `sora -> Ojs.string_to_js "sora"
| `sund -> Ojs.string_to_js "sund"
| `takr -> Ojs.string_to_js "takr"
| `talu -> Ojs.string_to_js "talu"
| `taml -> Ojs.string_to_js "taml"
| `tamldec -> Ojs.string_to_js "tamldec"
| `telu -> Ojs.string_to_js "telu"
| `thai -> Ojs.string_to_js "thai"
| `tibt -> Ojs.string_to_js "tibt"
| `tirh -> Ojs.string_to_js "tirh"
| `traditio -> Ojs.string_to_js "traditio"
| `traditional -> Ojs.string_to_js "traditional"
| `vaii -> Ojs.string_to_js "vaii"
| `wara -> Ojs.string_to_js "wara"
| `wcho -> Ojs.string_to_js "wcho"
end
module RelativeTimeFormatOptions =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x22 : Ojs.t) -> x22
and t_to_js : t -> Ojs.t = fun (x21 : Ojs.t) -> x21
let (get_locale_matcher : t -> RelativeTimeFormatLocaleMatcher.t) =
fun (x23 : t) ->
RelativeTimeFormatLocaleMatcher.t_of_js
(Ojs.get_prop_ascii (t_to_js x23) "localeMatcher")
let (set_locale_matcher :
t -> RelativeTimeFormatLocaleMatcher.t -> unit) =
fun (x24 : t) ->
fun (x25 : RelativeTimeFormatLocaleMatcher.t) ->
Ojs.set_prop_ascii (t_to_js x24) "localeMatcher"
(RelativeTimeFormatLocaleMatcher.t_to_js x25)
let (get_numeric : t -> RelativeTimeFormatNumeric.t) =
fun (x26 : t) ->
RelativeTimeFormatNumeric.t_of_js
(Ojs.get_prop_ascii (t_to_js x26) "numeric")
let (set_numeric : t -> RelativeTimeFormatNumeric.t -> unit) =
fun (x27 : t) ->
fun (x28 : RelativeTimeFormatNumeric.t) ->
Ojs.set_prop_ascii (t_to_js x27) "numeric"
(RelativeTimeFormatNumeric.t_to_js x28)
let (get_style : t -> RelativeTimeFormatStyle.t) =
fun (x29 : t) ->
RelativeTimeFormatStyle.t_of_js
(Ojs.get_prop_ascii (t_to_js x29) "style")
let (set_style : t -> RelativeTimeFormatStyle.t -> unit) =
fun (x30 : t) ->
fun (x31 : RelativeTimeFormatStyle.t) ->
Ojs.set_prop_ascii (t_to_js x30) "style"
(RelativeTimeFormatStyle.t_to_js x31)
end
module ResolvedRelativeTimeFormatOptions =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x33 : Ojs.t) -> x33
and t_to_js : t -> Ojs.t = fun (x32 : Ojs.t) -> x32
let (get_locale : t -> string) =
fun (x34 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x34) "locale")
let (set_locale : t -> string -> unit) =
fun (x35 : t) ->
fun (x36 : string) ->
Ojs.set_prop_ascii (t_to_js x35) "locale"
(Ojs.string_to_js x36)
let (get_style : t -> RelativeTimeFormatStyle.t) =
fun (x37 : t) ->
RelativeTimeFormatStyle.t_of_js
(Ojs.get_prop_ascii (t_to_js x37) "style")
let (set_style : t -> RelativeTimeFormatStyle.t -> unit) =
fun (x38 : t) ->
fun (x39 : RelativeTimeFormatStyle.t) ->
Ojs.set_prop_ascii (t_to_js x38) "style"
(RelativeTimeFormatStyle.t_to_js x39)
let (get_numeric : t -> RelativeTimeFormatNumeric.t) =
fun (x40 : t) ->
RelativeTimeFormatNumeric.t_of_js
(Ojs.get_prop_ascii (t_to_js x40) "numeric")
let (set_numeric : t -> RelativeTimeFormatNumeric.t -> unit) =
fun (x41 : t) ->
fun (x42 : RelativeTimeFormatNumeric.t) ->
Ojs.set_prop_ascii (t_to_js x41) "numeric"
(RelativeTimeFormatNumeric.t_to_js x42)
let (get_numbering_system : t -> string) =
fun (x43 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x43) "numberingSystem")
let (set_numbering_system : t -> string -> unit) =
fun (x44 : t) ->
fun (x45 : string) ->
Ojs.set_prop_ascii (t_to_js x44) "numberingSystem"
(Ojs.string_to_js x45)
end
module RelativeTimeFormatPart =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x47 : Ojs.t) -> x47
and t_to_js : t -> Ojs.t = fun (x46 : Ojs.t) -> x46
let (get_type : t -> string) =
fun (x48 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x48) "type")
let (set_type : t -> string -> unit) =
fun (x49 : t) ->
fun (x50 : string) ->
Ojs.set_prop_ascii (t_to_js x49) "type" (Ojs.string_to_js x50)
let (get_value : t -> string) =
fun (x51 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x51) "value")
let (set_value : t -> string -> unit) =
fun (x52 : t) ->
fun (x53 : string) ->
Ojs.set_prop_ascii (t_to_js x52) "value" (Ojs.string_to_js x53)
let (get_unit : t -> RelativeTimeFormatUnit.t) =
fun (x54 : t) ->
RelativeTimeFormatUnit.t_of_js
(Ojs.get_prop_ascii (t_to_js x54) "unit")
let (set_unit : t -> RelativeTimeFormatUnit.t -> unit) =
fun (x55 : t) ->
fun (x56 : RelativeTimeFormatUnit.t) ->
Ojs.set_prop_ascii (t_to_js x55) "unit"
(RelativeTimeFormatUnit.t_to_js x56)
end
module RelativeTimeFormat =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x58 : Ojs.t) -> x58
and t_to_js : t -> Ojs.t = fun (x57 : Ojs.t) -> x57
let (format :
t -> value:int -> unit:RelativeTimeFormatUnit.t -> string) =
fun (x61 : t) ->
fun ~value:(x59 : int) ->
fun ~unit:(x60 : RelativeTimeFormatUnit.t) ->
Ojs.string_of_js
(Ojs.call (t_to_js x61) "format"
[|(Ojs.int_to_js x59);(RelativeTimeFormatUnit.t_to_js
x60)|])
let (format_to_parts :
t ->
value:int ->
unit:RelativeTimeFormatUnit.t -> RelativeTimeFormatPart.t list)
=
fun (x64 : t) ->
fun ~value:(x62 : int) ->
fun ~unit:(x63 : RelativeTimeFormatUnit.t) ->
Ojs.list_of_js RelativeTimeFormatPart.t_of_js
(Ojs.call (t_to_js x64) "formatToParts"
[|(Ojs.int_to_js x62);(RelativeTimeFormatUnit.t_to_js
x63)|])
let (resolved_options : t -> ResolvedRelativeTimeFormatOptions.t) =
fun (x66 : t) ->
ResolvedRelativeTimeFormatOptions.t_of_js
(Ojs.call (t_to_js x66) "resolvedOptions" [||])
end
module AnonymousInterface0 =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x68 : Ojs.t) -> x68
and t_to_js : t -> Ojs.t = fun (x67 : Ojs.t) -> x67
let (create :
t ->
?locales:(string, string) or_array ->
?options:RelativeTimeFormatOptions.t ->
unit -> RelativeTimeFormat.t)
=
fun (x76 : t) ->
fun ?locales:(x69 : (string, string) or_array option) ->
fun ?options:(x70 : RelativeTimeFormatOptions.t option) ->
fun () ->
RelativeTimeFormat.t_of_js
(Ojs.new_obj_arr (t_to_js x76)
(let x71 =
Ojs.new_obj (Ojs.get_prop_ascii Ojs.global "Array")
[||] in
(match x69 with
| Some x73 ->
ignore
(Ojs.call x71 "push"
[|(or_array_to_js Ojs.string_to_js
Ojs.string_to_js x73)|])
| None -> ());
(match x70 with
| Some x72 ->
ignore
(Ojs.call x71 "push"
[|(RelativeTimeFormatOptions.t_to_js x72)|])
| None -> ());
x71))
let (supported_locales_of :
t ->
locales:(string, string) or_array ->
?options:RelativeTimeFormatOptions.t -> unit -> string list)
=
fun (x83 : t) ->
fun ~locales:(x77 : (string, string) or_array) ->
fun ?options:(x78 : RelativeTimeFormatOptions.t option) ->
fun () ->
Ojs.list_of_js Ojs.string_of_js
(let x84 = t_to_js x83 in
Ojs.call (Ojs.get_prop_ascii x84 "supportedLocalesOf")
"apply"
[|x84;((let x79 =
Ojs.new_obj
(Ojs.get_prop_ascii Ojs.global "Array")
[||] in
ignore
(Ojs.call x79 "push"
[|(or_array_to_js Ojs.string_to_js
Ojs.string_to_js x77)|]);
(match x78 with
| Some x80 ->
ignore
(Ojs.call x79 "push"
[|(RelativeTimeFormatOptions.t_to_js
x80)|])
| None -> ());
x79))|])
end
let (relative_time_format : AnonymousInterface0.t) =
AnonymousInterface0.t_of_js
(Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "Intl")
"RelativeTimeFormat")
module NumberFormatOptions =
struct
include struct include NumberFormatOptions end
let (get_compact_display : t -> string) =
fun (x86 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x86) "compactDisplay")
let (set_compact_display : t -> string -> unit) =
fun (x87 : t) ->
fun (x88 : string) ->
Ojs.set_prop_ascii (t_to_js x87) "compactDisplay"
(Ojs.string_to_js x88)
let (get_notation : t -> string) =
fun (x89 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x89) "notation")
let (set_notation : t -> string -> unit) =
fun (x90 : t) ->
fun (x91 : string) ->
Ojs.set_prop_ascii (t_to_js x90) "notation"
(Ojs.string_to_js x91)
let (get_sign_display : t -> string) =
fun (x92 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x92) "signDisplay")
let (set_sign_display : t -> string -> unit) =
fun (x93 : t) ->
fun (x94 : string) ->
Ojs.set_prop_ascii (t_to_js x93) "signDisplay"
(Ojs.string_to_js x94)
let (get_unit : t -> string) =
fun (x95 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x95) "unit")
let (set_unit : t -> string -> unit) =
fun (x96 : t) ->
fun (x97 : string) ->
Ojs.set_prop_ascii (t_to_js x96) "unit" (Ojs.string_to_js x97)
let (get_unit_display : t -> string) =
fun (x98 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x98) "unitDisplay")
let (set_unit_display : t -> string -> unit) =
fun (x99 : t) ->
fun (x100 : string) ->
Ojs.set_prop_ascii (t_to_js x99) "unitDisplay"
(Ojs.string_to_js x100)
end
module ResolvedNumberFormatOptions =
struct
type t = Ojs.t
let rec t_of_js : Ojs.t -> t = fun (x102 : Ojs.t) -> x102
and t_to_js : t -> Ojs.t = fun (x101 : Ojs.t) -> x101
let (get_compact_display : t -> string) =
fun (x103 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x103) "compactDisplay")
let (set_compact_display : t -> string -> unit) =
fun (x104 : t) ->
fun (x105 : string) ->
Ojs.set_prop_ascii (t_to_js x104) "compactDisplay"
(Ojs.string_to_js x105)
let (get_notation : t -> string) =
fun (x106 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x106) "notation")
let (set_notation : t -> string -> unit) =
fun (x107 : t) ->
fun (x108 : string) ->
Ojs.set_prop_ascii (t_to_js x107) "notation"
(Ojs.string_to_js x108)
let (get_sign_display : t -> string) =
fun (x109 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x109) "signDisplay")
let (set_sign_display : t -> string -> unit) =
fun (x110 : t) ->
fun (x111 : string) ->
Ojs.set_prop_ascii (t_to_js x110) "signDisplay"
(Ojs.string_to_js x111)
let (get_unit : t -> string) =
fun (x112 : t) ->
Ojs.string_of_js (Ojs.get_prop_ascii (t_to_js x112) "unit")
let (set_unit : t -> string -> unit) =
fun (x113 : t) ->
fun (x114 : string) ->
Ojs.set_prop_ascii (t_to_js x113) "unit"
(Ojs.string_to_js x114)
let (get_unit_display : t -> string) =
fun (x115 : t) ->
Ojs.string_of_js
(Ojs.get_prop_ascii (t_to_js x115) "unitDisplay")
let (set_unit_display : t -> string -> unit) =
fun (x116 : t) ->
fun (x117 : string) ->
Ojs.set_prop_ascii (t_to_js x116) "unitDisplay"
(Ojs.string_to_js x117)
end
module DateTimeFormatOptions =
struct
include struct include DateTimeFormatOptions end
let (get_date_style : t -> [ `full | `long | `medium | `short ]) =
fun (x118 : t) ->
let x119 = Ojs.get_prop_ascii (t_to_js x118) "dateStyle" in
match Ojs.string_of_js x119 with
| "full" -> `full
| "long" -> `long
| "medium" -> `medium
| "short" -> `short
| _ -> assert false
let (set_date_style :
t -> [ `full | `long | `medium | `short ] -> unit) =
fun (x120 : t) ->
fun (x121 : [ `full | `long | `medium | `short ]) ->
Ojs.set_prop_ascii (t_to_js x120) "dateStyle"
(match x121 with
| `full -> Ojs.string_to_js "full"
| `long -> Ojs.string_to_js "long"
| `medium -> Ojs.string_to_js "medium"
| `short -> Ojs.string_to_js "short")
let (get_time_style : t -> [ `full | `long | `medium | `short ]) =
fun (x122 : t) ->
let x123 = Ojs.get_prop_ascii (t_to_js x122) "timeStyle" in
match Ojs.string_of_js x123 with
| "full" -> `full
| "long" -> `long
| "medium" -> `medium
| "short" -> `short
| _ -> assert false
let (set_time_style :
t -> [ `full | `long | `medium | `short ] -> unit) =
fun (x124 : t) ->
fun (x125 : [ `full | `long | `medium | `short ]) ->
Ojs.set_prop_ascii (t_to_js x124) "timeStyle"
(match x125 with
| `full -> Ojs.string_to_js "full"
| `long -> Ojs.string_to_js "long"
| `medium -> Ojs.string_to_js "medium"
| `short -> Ojs.string_to_js "short")
let (get_calendar : t -> Calendar.t) =
fun (x126 : t) ->
Calendar.t_of_js (Ojs.get_prop_ascii (t_to_js x126) "calendar")
let (set_calendar : t -> Calendar.t -> unit) =
fun (x127 : t) ->
fun (x128 : Calendar.t) ->
Ojs.set_prop_ascii (t_to_js x127) "calendar"
(Calendar.t_to_js x128)
let (get_day_period : t -> [ `long | `narrow | `short ]) =
fun (x129 : t) ->
let x130 = Ojs.get_prop_ascii (t_to_js x129) "dayPeriod" in
match Ojs.string_of_js x130 with
| "long" -> `long
| "narrow" -> `narrow
| "short" -> `short
| _ -> assert false
let (set_day_period : t -> [ `long | `narrow | `short ] -> unit) =
fun (x131 : t) ->
fun (x132 : [ `long | `narrow | `short ]) ->
Ojs.set_prop_ascii (t_to_js x131) "dayPeriod"
(match x132 with
| `long -> Ojs.string_to_js "long"
| `narrow -> Ojs.string_to_js "narrow"
| `short -> Ojs.string_to_js "short")
let (get_numbering_system : t -> NumberingSystem.t) =
fun (x133 : t) ->
NumberingSystem.t_of_js
(Ojs.get_prop_ascii (t_to_js x133) "numberingSystem")
let (set_numbering_system : t -> NumberingSystem.t -> unit) =
fun (x134 : t) ->
fun (x135 : NumberingSystem.t) ->
Ojs.set_prop_ascii (t_to_js x134) "numberingSystem"
(NumberingSystem.t_to_js x135)
let (get_hour_cycle : t -> [ `h11 | `h12 | `h23 | `h24 ]) =
fun (x136 : t) ->
let x137 = Ojs.get_prop_ascii (t_to_js x136) "hourCycle" in
match Ojs.string_of_js x137 with
| "h11" -> `h11
| "h12" -> `h12
| "h23" -> `h23
| "h24" -> `h24
| _ -> assert false
let (set_hour_cycle : t -> [ `h11 | `h12 | `h23 | `h24 ] -> unit)
=
fun (x138 : t) ->
fun (x139 : [ `h11 | `h12 | `h23 | `h24 ]) ->
Ojs.set_prop_ascii (t_to_js x138) "hourCycle"
(match x139 with
| `h11 -> Ojs.string_to_js "h11"
| `h12 -> Ojs.string_to_js "h12"
| `h23 -> Ojs.string_to_js "h23"
| `h24 -> Ojs.string_to_js "h24")
let (get_fractional_second_digits :
t -> [ `L_n_0 | `L_n_1 | `L_n_2 | `L_n_3 ]) =
fun (x140 : t) ->
let x141 =
Ojs.get_prop_ascii (t_to_js x140) "fractionalSecondDigits" in
match Ojs.int_of_js x141 with
| 0 -> `L_n_0
| 1 -> `L_n_1
| 2 -> `L_n_2
| 3 -> `L_n_3
| _ -> assert false
let (set_fractional_second_digits :
t -> [ `L_n_0 | `L_n_1 | `L_n_2 | `L_n_3 ] -> unit) =
fun (x142 : t) ->
fun (x143 : [ `L_n_0 | `L_n_1 | `L_n_2 | `L_n_3 ]) ->
Ojs.set_prop_ascii (t_to_js x142) "fractionalSecondDigits"
(match x143 with
| `L_n_0 -> Ojs.string_to_js "LN0"
| `L_n_1 -> Ojs.string_to_js "LN1"
| `L_n_2 -> Ojs.string_to_js "LN2"
| `L_n_3 -> Ojs.string_to_js "LN3")
end
end
| |
e92019538ab5323c50660ac3951d56d6386576a2d597562e780c9b28dfeb6921 | slyrus/clem | defmatrix-mult-block.lisp |
(in-package :clem)
(defparameter *max-block-size* 32)
(declaim (type fixnum *max-block-size*))
(defmacro fixnum1+ (place)
`(the fixnum (1+ ,place)))
(defgeneric %mat-mult-block (m n p
mstartr mendr mstartc mendc
nstartr nendr nstartc nendc))
(defgeneric %mat-mult-with-blocks (m n p
mstartr mendr mstartc mendc
nstartr nendr nstartc nendc))
(defmacro def-matrix-mult-block (type-1 type-2 accumulator-type &key suffix)
(declare (ignore suffix))
(let ((element-type-1 (element-type (find-class `,type-1)))
(element-type-2 (element-type (find-class `,type-2)))
(accumulator-element-type (element-type (find-class `,accumulator-type))))
`(progn
(defmethod %mat-mult-block
((m ,type-1) (n ,type-2) (p ,accumulator-type)
mstartr mendr mstartc mendc
nstartr nendr nstartc nendc)
(declare (type fixnum mstartr mendr mstartc mendc
nstartr nendr nstartc nendc)
(optimize (speed 3) (safety 0) (space 0)))
(let ((a (clem::matrix-vals m))
(b (clem::matrix-vals n))
(c (clem::matrix-vals p))
(atemp (coerce 0 ',accumulator-element-type)))
(declare (type (simple-array ,element-type-1 *) a)
(type (simple-array ,element-type-2 *) b)
(type (simple-array ,accumulator-element-type *) c)
(type ,accumulator-element-type atemp))
(when (eql (- mendc mstartc) (- nendr nstartr))
(let ((ci 0))
(declare (type fixnum ci))
(do ((k mstartc (fixnum1+ k)))
((> k mendc))
(declare (type fixnum k))
(setf ci 0)
(do ((i mstartr (fixnum1+ i)))
((> i mendr))
(declare (type fixnum i))
(setf atemp (aref a i k))
(do ((j nstartc (fixnum1+ j)))
((> j nendc))
(declare (type fixnum j))
(incf (row-major-aref c ci) (* (aref b k j) atemp))
(incf ci))))))))
(defmethod %mat-mult-with-blocks
((m ,type-1) (n ,type-2) (p ,accumulator-type)
mstartr mendr mstartc mendc
nstartr nendr nstartc nendc)
(declare (type fixnum mstartr mendr mstartc mendc
nstartr nendr nstartc nendc)
(optimize (speed 3) (safety 0)))
(if (and (> (- mendr mstartr) *max-block-size*)
(> (- mendc mstartc) *max-block-size*)
(> (- nendr nstartr) *max-block-size*)
(> (- nendc nstartc) *max-block-size*))
(let ((mblock-row-end (the fixnum
(+ (the fixnum mstartr)
(the fixnum (ash (the fixnum (- mendr mstartr (the fixnum -1))) (the fixnum -1)))
(the fixnum -1))))
(mblock-col-end (the fixnum (+ mstartc (ash (- mendc mstartc -1) -1) -1)))
(nblock-row-end (the fixnum (+ nstartr (ash (- nendr nstartr -1) -1) -1)))
(nblock-col-end (the fixnum (+ nstartc (the fixnum (ash (- nendc nstartc -1) -1)) -1))))
(declare (type fixnum mblock-row-end mblock-col-end nblock-row-end nblock-col-end))
;; m_11 * n_11
(%mat-mult-with-blocks m n p
mstartr mblock-row-end
mstartc mblock-col-end
nstartr nblock-row-end
nstartc nblock-col-end)
m_11 *
(%mat-mult-with-blocks m n p
mstartr mblock-row-end
mstartc mblock-col-end
nstartr nblock-row-end
(the fixnum (1+ nblock-col-end)) nendc)
;; m_21 * n_11
(%mat-mult-with-blocks m n p
(the fixnum (1+ mblock-row-end)) mendr
mstartc mblock-col-end
nstartr nblock-row-end
nstartc nblock-col-end)
m_21 *
(%mat-mult-with-blocks m n p
(the fixnum (1+ mblock-row-end)) mendr
mstartc mblock-col-end
nstartr nblock-row-end
(fixnum1+ nblock-col-end) nendc)
m_12 *
(%mat-mult-with-blocks m n p
mstartr mblock-row-end
(fixnum1+ mblock-col-end) mendc
(fixnum1+ nblock-row-end) nendr
nstartc nblock-col-end)
m_12 * n_22
(%mat-mult-with-blocks m n p
mstartr mblock-row-end
(fixnum1+ mblock-col-end) mendc
(fixnum1+ nblock-row-end) nendr
(fixnum1+ nblock-col-end) nendc)
m_22 *
(%mat-mult-with-blocks m n p
(fixnum1+ mblock-row-end) mendr
(fixnum1+ mblock-col-end) mendc
(fixnum1+ nblock-row-end) nendr
nstartc nblock-col-end)
m_22 * n_22
(%mat-mult-with-blocks m n p
(fixnum1+ mblock-row-end) mendr
(fixnum1+ mblock-col-end) mendc
(fixnum1+ nblock-row-end) nendr
(fixnum1+ nblock-col-end) nendc)
)
(%mat-mult-block m n p
mstartr mendr
mstartc mendc
nstartr nendr
nstartc nendc)))
(defmethod mat-mult-3-block ((m ,type-1) (n ,type-2) (p ,accumulator-type))
(destructuring-bind (mr mc) (dim m)
(destructuring-bind (nr nc) (dim n)
(%mat-mult-with-blocks m n p
0 (1- mr) 0 (1- mc)
0 (1- nr) 0 (1- nc))))
p))))
(macrolet ((frob (type-1 type-2 type-3 &key suffix)
`(def-matrix-mult-block ,type-1 ,type-2 ,type-3 :suffix ,suffix)))
(frob double-float-matrix double-float-matrix double-float-matrix)
(frob single-float-matrix single-float-matrix single-float-matrix))
| null | https://raw.githubusercontent.com/slyrus/clem/5eb055bb3f45840b24fd44825b975aa36bd6d97c/src/typed-ops/defmatrix-mult-block.lisp | lisp | m_11 * n_11
m_21 * n_11 |
(in-package :clem)
(defparameter *max-block-size* 32)
(declaim (type fixnum *max-block-size*))
(defmacro fixnum1+ (place)
`(the fixnum (1+ ,place)))
(defgeneric %mat-mult-block (m n p
mstartr mendr mstartc mendc
nstartr nendr nstartc nendc))
(defgeneric %mat-mult-with-blocks (m n p
mstartr mendr mstartc mendc
nstartr nendr nstartc nendc))
(defmacro def-matrix-mult-block (type-1 type-2 accumulator-type &key suffix)
(declare (ignore suffix))
(let ((element-type-1 (element-type (find-class `,type-1)))
(element-type-2 (element-type (find-class `,type-2)))
(accumulator-element-type (element-type (find-class `,accumulator-type))))
`(progn
(defmethod %mat-mult-block
((m ,type-1) (n ,type-2) (p ,accumulator-type)
mstartr mendr mstartc mendc
nstartr nendr nstartc nendc)
(declare (type fixnum mstartr mendr mstartc mendc
nstartr nendr nstartc nendc)
(optimize (speed 3) (safety 0) (space 0)))
(let ((a (clem::matrix-vals m))
(b (clem::matrix-vals n))
(c (clem::matrix-vals p))
(atemp (coerce 0 ',accumulator-element-type)))
(declare (type (simple-array ,element-type-1 *) a)
(type (simple-array ,element-type-2 *) b)
(type (simple-array ,accumulator-element-type *) c)
(type ,accumulator-element-type atemp))
(when (eql (- mendc mstartc) (- nendr nstartr))
(let ((ci 0))
(declare (type fixnum ci))
(do ((k mstartc (fixnum1+ k)))
((> k mendc))
(declare (type fixnum k))
(setf ci 0)
(do ((i mstartr (fixnum1+ i)))
((> i mendr))
(declare (type fixnum i))
(setf atemp (aref a i k))
(do ((j nstartc (fixnum1+ j)))
((> j nendc))
(declare (type fixnum j))
(incf (row-major-aref c ci) (* (aref b k j) atemp))
(incf ci))))))))
(defmethod %mat-mult-with-blocks
((m ,type-1) (n ,type-2) (p ,accumulator-type)
mstartr mendr mstartc mendc
nstartr nendr nstartc nendc)
(declare (type fixnum mstartr mendr mstartc mendc
nstartr nendr nstartc nendc)
(optimize (speed 3) (safety 0)))
(if (and (> (- mendr mstartr) *max-block-size*)
(> (- mendc mstartc) *max-block-size*)
(> (- nendr nstartr) *max-block-size*)
(> (- nendc nstartc) *max-block-size*))
(let ((mblock-row-end (the fixnum
(+ (the fixnum mstartr)
(the fixnum (ash (the fixnum (- mendr mstartr (the fixnum -1))) (the fixnum -1)))
(the fixnum -1))))
(mblock-col-end (the fixnum (+ mstartc (ash (- mendc mstartc -1) -1) -1)))
(nblock-row-end (the fixnum (+ nstartr (ash (- nendr nstartr -1) -1) -1)))
(nblock-col-end (the fixnum (+ nstartc (the fixnum (ash (- nendc nstartc -1) -1)) -1))))
(declare (type fixnum mblock-row-end mblock-col-end nblock-row-end nblock-col-end))
(%mat-mult-with-blocks m n p
mstartr mblock-row-end
mstartc mblock-col-end
nstartr nblock-row-end
nstartc nblock-col-end)
m_11 *
(%mat-mult-with-blocks m n p
mstartr mblock-row-end
mstartc mblock-col-end
nstartr nblock-row-end
(the fixnum (1+ nblock-col-end)) nendc)
(%mat-mult-with-blocks m n p
(the fixnum (1+ mblock-row-end)) mendr
mstartc mblock-col-end
nstartr nblock-row-end
nstartc nblock-col-end)
m_21 *
(%mat-mult-with-blocks m n p
(the fixnum (1+ mblock-row-end)) mendr
mstartc mblock-col-end
nstartr nblock-row-end
(fixnum1+ nblock-col-end) nendc)
m_12 *
(%mat-mult-with-blocks m n p
mstartr mblock-row-end
(fixnum1+ mblock-col-end) mendc
(fixnum1+ nblock-row-end) nendr
nstartc nblock-col-end)
m_12 * n_22
(%mat-mult-with-blocks m n p
mstartr mblock-row-end
(fixnum1+ mblock-col-end) mendc
(fixnum1+ nblock-row-end) nendr
(fixnum1+ nblock-col-end) nendc)
m_22 *
(%mat-mult-with-blocks m n p
(fixnum1+ mblock-row-end) mendr
(fixnum1+ mblock-col-end) mendc
(fixnum1+ nblock-row-end) nendr
nstartc nblock-col-end)
m_22 * n_22
(%mat-mult-with-blocks m n p
(fixnum1+ mblock-row-end) mendr
(fixnum1+ mblock-col-end) mendc
(fixnum1+ nblock-row-end) nendr
(fixnum1+ nblock-col-end) nendc)
)
(%mat-mult-block m n p
mstartr mendr
mstartc mendc
nstartr nendr
nstartc nendc)))
(defmethod mat-mult-3-block ((m ,type-1) (n ,type-2) (p ,accumulator-type))
(destructuring-bind (mr mc) (dim m)
(destructuring-bind (nr nc) (dim n)
(%mat-mult-with-blocks m n p
0 (1- mr) 0 (1- mc)
0 (1- nr) 0 (1- nc))))
p))))
(macrolet ((frob (type-1 type-2 type-3 &key suffix)
`(def-matrix-mult-block ,type-1 ,type-2 ,type-3 :suffix ,suffix)))
(frob double-float-matrix double-float-matrix double-float-matrix)
(frob single-float-matrix single-float-matrix single-float-matrix))
|
26699b52600c60965bb85298f49c79fe3f146a7076272be933a177d786e876bc | spell-music/amsterdam | Comparison.hs | | additional parameters : none
In instrument 1 PLUCK uses a set of random numbers , made by PLUCK itself ,
while in instrument 2 the table f77 is created from the soundfile " Sflib/10_02_1.SF " .
This soundfile also contains random numbers , but gives additional control over the
bandwidth of the noise . For both instruments the cyclic buffer of PLUCK contains
128 numbers and the chosen decay method is simple averaging . From each instrument
two notes with a duration of a second are played .
NB : The instrument has no envelope to give the net impression of this unit generator .
Suggestions :
Use other audio soundfiles as well .
In instrument 1 PLUCK uses a set of random numbers, made by PLUCK itself,
while in instrument 2 the table f77 is created from the soundfile "Sflib/10_02_1.SF".
This soundfile also contains random numbers, but gives additional control over the
bandwidth of the noise. For both instruments the cyclic buffer of PLUCK contains
128 numbers and the chosen decay method is simple averaging. From each instrument
two notes with a duration of a second are played.
NB: The instrument has no envelope to give the net impression of this unit generator.
Suggestions:
Use other audio soundfiles as well.
-}
module Comparison where
import Csound
instr1 :: (D, D) -> Sig
instr1 (amp, cps) = pluck (sig amp) (sig cps) buf ft meth
where buf = 128
zero ftable ? ? ?
meth = 1
instr2 :: (D, D) -> Sig
instr2 (amp, cps) = pluck (sig amp) (sig cps) buf ft meth
where buf = 128
ft = undefined -- how to read tables from files ???
meth = 1
notes = line $ fmap (\x -> delay 1 $ temp (0.5, x)) [220, 440]
res = line [sco instr1 notes, sco instr2 notes]
main = dac $ runMix res
| null | https://raw.githubusercontent.com/spell-music/amsterdam/ab491022c7826c74eab557ecd11794268f5a5ae0/15-karplus-strong/Comparison.hs | haskell | how to read tables from files ??? | | additional parameters : none
In instrument 1 PLUCK uses a set of random numbers , made by PLUCK itself ,
while in instrument 2 the table f77 is created from the soundfile " Sflib/10_02_1.SF " .
This soundfile also contains random numbers , but gives additional control over the
bandwidth of the noise . For both instruments the cyclic buffer of PLUCK contains
128 numbers and the chosen decay method is simple averaging . From each instrument
two notes with a duration of a second are played .
NB : The instrument has no envelope to give the net impression of this unit generator .
Suggestions :
Use other audio soundfiles as well .
In instrument 1 PLUCK uses a set of random numbers, made by PLUCK itself,
while in instrument 2 the table f77 is created from the soundfile "Sflib/10_02_1.SF".
This soundfile also contains random numbers, but gives additional control over the
bandwidth of the noise. For both instruments the cyclic buffer of PLUCK contains
128 numbers and the chosen decay method is simple averaging. From each instrument
two notes with a duration of a second are played.
NB: The instrument has no envelope to give the net impression of this unit generator.
Suggestions:
Use other audio soundfiles as well.
-}
module Comparison where
import Csound
instr1 :: (D, D) -> Sig
instr1 (amp, cps) = pluck (sig amp) (sig cps) buf ft meth
where buf = 128
zero ftable ? ? ?
meth = 1
instr2 :: (D, D) -> Sig
instr2 (amp, cps) = pluck (sig amp) (sig cps) buf ft meth
where buf = 128
meth = 1
notes = line $ fmap (\x -> delay 1 $ temp (0.5, x)) [220, 440]
res = line [sco instr1 notes, sco instr2 notes]
main = dac $ runMix res
|
0fd04ce6341c3ff0bd0a1d6cb36e08b336b6fc484128f436362f1cc4cb1ac38e | coding-robots/iwl | app.rkt | #lang racket
(require web-server/servlet
web-server/servlet-env
web-server/templates
srfi/43
net/uri-codec
racket/runtime-path
mzlib/defmacro)
(require "bayes.rkt"
"crc32.rkt"
"utils.rkt")
(define *app-version* 10)
(define *app-date* "November 2010")
(load-data!)
; Hash with crc32 mappings to author names
(define *authors-hash*
(for/hash ([author *categories*])
(values (string->crc32/hex author) author)))
(define-values (app-dispatch req)
(dispatch-rules
[("") show-index]
[("") #:method "post" process-submission]
[("b" (string-arg)) show-badge]
[("s" (string-arg)) show-shared]
[("w" (string-arg)) show-writer]
[("api") #:method "post" api]
[("newsletter") show-newsletter]
[("newsletter" (string-arg)) (lambda (r a) (redirect-to "/newsletter"))]
[else not-found]))
(define (base-template title menu body)
(include-template "templates/base.html"))
(define (get-author text)
(and (> (string-length text) 30)
(get-category (safe-substring text 0 3000))))
(define (index-template short?)
(response/full
200 #"Okay"
(current-seconds) TEXT/HTML-MIME-TYPE
empty
(list (string->bytes/utf-8 (base-template "" "analyzer"
(include-template "templates/index.html"))))))
(define (badge-url author)
(string-append "/b/" (string->crc32/hex author)))
(define (show-index req)
(index-template #f))
(define (process-submission req)
(aif (dict-ref (request-bindings req) 'text #f)
(aif (get-author it)
(redirect-to (badge-url it))
(index-template #t))
(index-template #f)))
(define (json-out s)
(response/full
200 #"Okay"
(current-seconds) #"application/json; charset=utf-8"
empty
(list (string->bytes/utf-8 s))))
(define (json-error desc)
(json-out (format "{\"error\": \"~a\"}" desc)))
(define (json-result wrapper author)
(let ([crc (string->crc32/hex author)])
(json-out (format "{\"share_link\": \"/~a\",
\"writer_link\": \"/~a\",
\"writer\": \"~a\",
\"id\": \"~a\",
\"badge_link\": \"/~a\"}"
crc crc author crc crc))))
(define (api req)
(let* ([bindings (request-bindings req)]
[text (dict-ref bindings 'text #f)]
[wrapper (dict-ref bindings 'function "")]
[client-id (dict-ref bindings 'client_id #f)] ; unused, but required
[permalink (dict-ref bindings 'permalink #f)]) ; -"-
(if (and text client-id permalink)
(aif (get-author text)
(json-result wrapper it)
(json-error "text is too short or doesn't have words"))
(json-error "not enough arguments"))))
(define (not-found req)
(response/full 404 #"Not Found" (current-seconds)
TEXT/HTML-MIME-TYPE empty (list #"not found")))
(define (crc->author crc)
(hash-ref *authors-hash* crc #f))
(define-macro (badge-template req crc tpl)
`(let ([writer (crc->author ,crc)])
(if writer
(response/full
200 #"Okay"
(current-seconds) TEXT/HTML-MIME-TYPE
empty
(list (string->bytes/utf-8
(base-template writer "" (include-template ,tpl)))))
(not-found ,req))))
(define (show-badge req crc)
(badge-template req crc "templates/show-badge.html"))
(define (show-shared req crc)
(badge-template req crc "templates/show-shared.html"))
(define (show-writer req crc)
(aif (crc->author crc)
(redirect-to
(format (string-append
"=~a"
"&tag=blogjetblog-20&index=books&linkCode=ur2"
"&camp=1789&creative=9325") it))
(not-found req)))
(define (show-newsletter req)
(response/full
200 #"Okay"
(current-seconds) TEXT/HTML-MIME-TYPE
empty
(list (string->bytes/utf-8
(base-template "Newsletter" "newsletter"
(include-template "templates/show-newsletter.html"))))))
(define (start req)
(app-dispatch req))
(define-runtime-path srvpath ".")
(define (get-port-from-env)
(string->number (or (getenv "PORT") "8080")))
(serve/servlet start
#:servlet-path ""
#:port (get-port-from-env)
#:servlet-regexp #rx"^((?!/static/).)*$"
#:extra-files-paths (list srvpath)
#:launch-browser? #f
#:stateless? #t)
| null | https://raw.githubusercontent.com/coding-robots/iwl/bf13ab3f75aff0fe63c07555a41574e919bb11db/app.rkt | racket | Hash with crc32 mappings to author names
unused, but required
-"- | #lang racket
(require web-server/servlet
web-server/servlet-env
web-server/templates
srfi/43
net/uri-codec
racket/runtime-path
mzlib/defmacro)
(require "bayes.rkt"
"crc32.rkt"
"utils.rkt")
(define *app-version* 10)
(define *app-date* "November 2010")
(load-data!)
(define *authors-hash*
(for/hash ([author *categories*])
(values (string->crc32/hex author) author)))
(define-values (app-dispatch req)
(dispatch-rules
[("") show-index]
[("") #:method "post" process-submission]
[("b" (string-arg)) show-badge]
[("s" (string-arg)) show-shared]
[("w" (string-arg)) show-writer]
[("api") #:method "post" api]
[("newsletter") show-newsletter]
[("newsletter" (string-arg)) (lambda (r a) (redirect-to "/newsletter"))]
[else not-found]))
(define (base-template title menu body)
(include-template "templates/base.html"))
(define (get-author text)
(and (> (string-length text) 30)
(get-category (safe-substring text 0 3000))))
(define (index-template short?)
(response/full
200 #"Okay"
(current-seconds) TEXT/HTML-MIME-TYPE
empty
(list (string->bytes/utf-8 (base-template "" "analyzer"
(include-template "templates/index.html"))))))
(define (badge-url author)
(string-append "/b/" (string->crc32/hex author)))
(define (show-index req)
(index-template #f))
(define (process-submission req)
(aif (dict-ref (request-bindings req) 'text #f)
(aif (get-author it)
(redirect-to (badge-url it))
(index-template #t))
(index-template #f)))
(define (json-out s)
(response/full
200 #"Okay"
(current-seconds) #"application/json; charset=utf-8"
empty
(list (string->bytes/utf-8 s))))
(define (json-error desc)
(json-out (format "{\"error\": \"~a\"}" desc)))
(define (json-result wrapper author)
(let ([crc (string->crc32/hex author)])
(json-out (format "{\"share_link\": \"/~a\",
\"writer_link\": \"/~a\",
\"writer\": \"~a\",
\"id\": \"~a\",
\"badge_link\": \"/~a\"}"
crc crc author crc crc))))
(define (api req)
(let* ([bindings (request-bindings req)]
[text (dict-ref bindings 'text #f)]
[wrapper (dict-ref bindings 'function "")]
(if (and text client-id permalink)
(aif (get-author text)
(json-result wrapper it)
(json-error "text is too short or doesn't have words"))
(json-error "not enough arguments"))))
(define (not-found req)
(response/full 404 #"Not Found" (current-seconds)
TEXT/HTML-MIME-TYPE empty (list #"not found")))
(define (crc->author crc)
(hash-ref *authors-hash* crc #f))
(define-macro (badge-template req crc tpl)
`(let ([writer (crc->author ,crc)])
(if writer
(response/full
200 #"Okay"
(current-seconds) TEXT/HTML-MIME-TYPE
empty
(list (string->bytes/utf-8
(base-template writer "" (include-template ,tpl)))))
(not-found ,req))))
(define (show-badge req crc)
(badge-template req crc "templates/show-badge.html"))
(define (show-shared req crc)
(badge-template req crc "templates/show-shared.html"))
(define (show-writer req crc)
(aif (crc->author crc)
(redirect-to
(format (string-append
"=~a"
"&tag=blogjetblog-20&index=books&linkCode=ur2"
"&camp=1789&creative=9325") it))
(not-found req)))
(define (show-newsletter req)
(response/full
200 #"Okay"
(current-seconds) TEXT/HTML-MIME-TYPE
empty
(list (string->bytes/utf-8
(base-template "Newsletter" "newsletter"
(include-template "templates/show-newsletter.html"))))))
(define (start req)
(app-dispatch req))
(define-runtime-path srvpath ".")
(define (get-port-from-env)
(string->number (or (getenv "PORT") "8080")))
(serve/servlet start
#:servlet-path ""
#:port (get-port-from-env)
#:servlet-regexp #rx"^((?!/static/).)*$"
#:extra-files-paths (list srvpath)
#:launch-browser? #f
#:stateless? #t)
|
876abda94e2b425a0df8c7039926e3b3a539ba2863e9a9f22d621ce6e9955d47 | pink-gorilla/pinkie | resolve.cljc | (ns viz.resolve
(:require
[viz.unknown :refer [no-renderer]]))
(defn resolve-fn
[resolve fn-symbol]
(if-let [f (resolve fn-symbol)]
f
(no-renderer (pr-str fn-symbol))))
(comment
(defn clj-vega [spec]
(str "vega spec: " (pr-str spec)))
(clj-vega "test")
(defn clj [s]
(cond
(= s 'vega) clj-vega))
(get-render-fn clj 'vega)
(get-render-fn clj 'vega-lite)
((get-render-fn clj 'vega) "spec1")
((get-render-fn clj 'vega-lite) "spec2")
;
)
| null | https://raw.githubusercontent.com/pink-gorilla/pinkie/a0d26fdc6e6b8499dd957c8ad5f16493a35b4bc3/src/viz/resolve.cljc | clojure | (ns viz.resolve
(:require
[viz.unknown :refer [no-renderer]]))
(defn resolve-fn
[resolve fn-symbol]
(if-let [f (resolve fn-symbol)]
f
(no-renderer (pr-str fn-symbol))))
(comment
(defn clj-vega [spec]
(str "vega spec: " (pr-str spec)))
(clj-vega "test")
(defn clj [s]
(cond
(= s 'vega) clj-vega))
(get-render-fn clj 'vega)
(get-render-fn clj 'vega-lite)
((get-render-fn clj 'vega) "spec1")
((get-render-fn clj 'vega-lite) "spec2")
)
| |
fe7e649778a11fe0fcf3db0c80c01938647b19150e38b222f56507485c5b9cac | tnelson/Forge | always-tests.rkt | #lang forge
option run_sterling off
option verbose 0
option problem_type temporal
sig Node {
first : set Node,
var second : set Node
}
pred secondIsFirst {
first = second implies first' = second'
}
// WHOOPS I NEVER FINISHED THIS ONE
| null | https://raw.githubusercontent.com/tnelson/Forge/a7187ef110f46493c1d45011035b05646b9ccd22/forge/tests/forge/electrum/always-tests.rkt | racket | #lang forge
option run_sterling off
option verbose 0
option problem_type temporal
sig Node {
first : set Node,
var second : set Node
}
pred secondIsFirst {
first = second implies first' = second'
}
// WHOOPS I NEVER FINISHED THIS ONE
| |
a64e89af3addbe512ccd51bddb2701e1398696479ae9fd63d75c99b59d89d3aa | nominolo/lambdachine | ReadP.hs | # LANGUAGE NoImplicitPrelude , Rank2Types , MagicHash #
module Text.ParserCombinators.ReadP
(
: : * - > * ; instance Functor , Monad , MonadPlus
: :
look, -- :: ReadP String
(+++), -- :: ReadP a -> ReadP a -> ReadP a
(<++), -- :: ReadP a -> ReadP a -> ReadP a
gather, -- :: ReadP a -> ReadP (String, a)
-- * Other operations
pfail, -- :: ReadP a
: : ( )
: : ( Bool ) - > ReadP Char
: : ReadP Char
string, -- :: String -> ReadP String
: : ( Bool ) - > ReadP String
: : ( Bool ) - > ReadP String
: : ( )
choice, -- :: [ReadP a] -> ReadP a
count, -- :: Int -> ReadP a -> ReadP [a]
between, -- :: ReadP open -> ReadP close -> ReadP a -> ReadP a
option, -- :: a -> ReadP a -> ReadP a
optional, -- :: ReadP a -> ReadP ()
many, -- :: ReadP a -> ReadP [a]
many1, -- :: ReadP a -> ReadP [a]
skipMany, -- :: ReadP a -> ReadP ()
skipMany1, -- :: ReadP a -> ReadP ()
sepBy, -- :: ReadP a -> ReadP sep -> ReadP [a]
sepBy1, -- :: ReadP a -> ReadP sep -> ReadP [a]
endBy, -- :: ReadP a -> ReadP sep -> ReadP [a]
endBy1, -- :: ReadP a -> ReadP sep -> ReadP [a]
chainr, -- :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a
chainl, -- :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a
chainl1, -- :: ReadP a -> ReadP (a -> a -> a) -> ReadP a
chainr1, -- :: ReadP a -> ReadP (a -> a -> a) -> ReadP a
manyTill, -- :: ReadP a -> ReadP end -> ReadP [a]
ReadS,
readP_to_S,
readS_to_P, -- :: ReadS a -> ReadP a
)
where
import GHC.Base
import Control.Monad ( MonadPlus(..), sequence, liftM2 )
import Data.List ( replicate, null )
import Data.Char ( isSpace )
infixr 5 +++, <++
type ReadS a = String -> [(a,String)]
data P a
= Get (Char -> P a)
| Look (String -> P a)
| Fail
| Result a (P a)
| Final [(a,String)] -- invariant: list is non-empty!
instance Monad P where
return x = Result x Fail
(Get f) >>= k = Get (\c -> f c >>= k)
(Look f) >>= k = Look (\s -> f s >>= k)
Fail >>= _ = Fail
(Result x p) >>= k = k x `mplus` (p >>= k)
(Final r) >>= k = final [ys' | (x,s) <- r, ys' <- run (k x) s]
fail _ = Fail
instance MonadPlus P where
mzero = Fail
most common case : two gets are combined
Get f1 `mplus` Get f2 = Get (\c -> f1 c `mplus` f2 c)
-- results are delivered as soon as possible
Result x p `mplus` q = Result x (p `mplus` q)
p `mplus` Result x q = Result x (p `mplus` q)
-- fail disappears
Fail `mplus` p = p
p `mplus` Fail = p
two finals are combined
final + look becomes one look and one final (= optimization )
final + sthg else becomes one look and one final
Final r `mplus` Final t = Final (r ++ t)
Final r `mplus` Look f = Look (\s -> Final (r ++ run (f s) s))
Final r `mplus` p = Look (\s -> Final (r ++ run p s))
Look f `mplus` Final r = Look (\s -> Final (run (f s) s ++ r))
p `mplus` Final r = Look (\s -> Final (run p s ++ r))
two looks are combined (= optimization )
-- look + sthg else floats upwards
Look f `mplus` Look g = Look (\s -> f s `mplus` g s)
Look f `mplus` p = Look (\s -> f s `mplus` p)
p `mplus` Look f = Look (\s -> p `mplus` f s)
newtype ReadP a = R (forall b . (a -> P b) -> P b)
instance Functor ReadP where
fmap h (R f) = R (\k -> f (k . h))
instance Monad ReadP where
return x = R (\k -> k x)
fail _ = R (\_ -> Fail)
R m >>= f = R (\k -> m (\a -> let R m' = f a in m' k))
instance MonadPlus ReadP where
mzero = pfail
mplus = (+++)
final :: [(a,String)] -> P a
-- Maintains invariant for Final constructor
final [] = Fail
final r = Final r
run :: P a -> ReadS a
run (Get f) (c:s) = run (f c) s
run (Look f) s = run (f s) s
run (Result x p) s = (x,s) : run p s
run (Final r) _ = r
run _ _ = []
get :: ReadP Char
get = R Get
look :: ReadP String
look = R Look
pfail :: ReadP a
pfail = R (\_ -> Fail)
(+++) :: ReadP a -> ReadP a -> ReadP a
R f1 +++ R f2 = R (\k -> f1 k `mplus` f2 k)
(<++) :: ReadP a -> ReadP a -> ReadP a
R f0 <++ q =
do s <- look
probe (f0 return) s 0#
where
probe (Get f) (c:s) n = probe (f c) s (n+#1#)
probe (Look f) s n = probe (f s) s n
probe p@(Result _ _) _ n = discard n >> R (p >>=)
probe (Final r) _ _ = R (Final r >>=)
probe _ _ _ = q
discard 0# = return ()
discard n = get >> discard (n-#1#)
gather :: ReadP a -> ReadP (String, a)
gather (R m)
= R (\k -> gath id (m (\a -> return (\s -> k (s,a)))))
where
gath :: (String -> String) -> P (String -> P b) -> P b
gath l (Get f) = Get (\c -> gath (l.(c:)) (f c))
gath _ Fail = Fail
gath l (Look f) = Look (\s -> gath l (f s))
gath l (Result k p) = k (l []) `mplus` gath l p
gath _ (Final _) = error "do not use readS_to_P in gather!"
-- ---------------------------------------------------------------------------
satisfy :: (Char -> Bool) -> ReadP Char
satisfy p = do c <- get; if p c then return c else pfail
char :: Char -> ReadP Char
char c = satisfy (c ==)
eof :: ReadP ()
eof = do { s <- look
; if null s then return ()
else pfail }
string :: String -> ReadP String
string this = do s <- look; scan this s
where
scan [] _ = do return this
scan (x:xs) (y:ys) | x == y = do _ <- get; scan xs ys
scan _ _ = do pfail
munch :: (Char -> Bool) -> ReadP String
munch p =
do s <- look
scan s
where
scan (c:cs) | p c = do _ <- get; s <- scan cs; return (c:s)
scan _ = do return ""
munch1 :: (Char -> Bool) -> ReadP String
munch1 p =
do c <- get
if p c then do s <- munch p; return (c:s)
else pfail
choice :: [ReadP a] -> ReadP a
choice [] = pfail
choice [p] = p
choice (p:ps) = p +++ choice ps
skipSpaces :: ReadP ()
skipSpaces =
do s <- look
skip s
where
skip (c:s) | isSpace c = do _ <- get; skip s
skip _ = do return ()
count :: Int -> ReadP a -> ReadP [a]
count n p = sequence (replicate n p)
between :: ReadP open -> ReadP close -> ReadP a -> ReadP a
between open close p = do _ <- open
x <- p
_ <- close
return x
option :: a -> ReadP a -> ReadP a
option x p = p +++ return x
optional :: ReadP a -> ReadP ()
optional p = (p >> return ()) +++ return ()
many :: ReadP a -> ReadP [a]
many p = return [] +++ many1 p
many1 :: ReadP a -> ReadP [a]
many1 p = liftM2 (:) p (many p)
skipMany :: ReadP a -> ReadP ()
skipMany p = many p >> return ()
skipMany1 :: ReadP a -> ReadP ()
skipMany1 p = p >> skipMany p
sepBy :: ReadP a -> ReadP sep -> ReadP [a]
sepBy p sep = sepBy1 p sep +++ return []
sepBy1 :: ReadP a -> ReadP sep -> ReadP [a]
sepBy1 p sep = liftM2 (:) p (many (sep >> p))
endBy :: ReadP a -> ReadP sep -> ReadP [a]
endBy p sep = many (do x <- p ; _ <- sep ; return x)
endBy1 :: ReadP a -> ReadP sep -> ReadP [a]
endBy1 p sep = many1 (do x <- p ; _ <- sep ; return x)
chainr :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a
chainr p op x = chainr1 p op +++ return x
chainl :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a
chainl p op x = chainl1 p op +++ return x
chainr1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a
chainr1 p op = scan
where scan = p >>= rest
rest x = do f <- op
y <- scan
return (f x y)
+++ return x
chainl1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a
chainl1 p op = p >>= rest
where rest x = do f <- op
y <- p
rest (f x y)
+++ return x
manyTill :: ReadP a -> ReadP end -> ReadP [a]
manyTill p end = scan
where scan = (end >> return []) <++ (liftM2 (:) p scan)
readP_to_S :: ReadP a -> ReadS a
readP_to_S (R f) = run (f return)
readS_to_P :: ReadS a -> ReadP a
readS_to_P r =
R (\k -> Look (\s -> final [bs'' | (a,s') <- r s, bs'' <- run (k a) s']))
| null | https://raw.githubusercontent.com/nominolo/lambdachine/49d97cf7a367a650ab421f7aa19feb90bfe14731/libraries/base/Text/ParserCombinators/ReadP.hs | haskell | :: ReadP String
:: ReadP a -> ReadP a -> ReadP a
:: ReadP a -> ReadP a -> ReadP a
:: ReadP a -> ReadP (String, a)
* Other operations
:: ReadP a
:: String -> ReadP String
:: [ReadP a] -> ReadP a
:: Int -> ReadP a -> ReadP [a]
:: ReadP open -> ReadP close -> ReadP a -> ReadP a
:: a -> ReadP a -> ReadP a
:: ReadP a -> ReadP ()
:: ReadP a -> ReadP [a]
:: ReadP a -> ReadP [a]
:: ReadP a -> ReadP ()
:: ReadP a -> ReadP ()
:: ReadP a -> ReadP sep -> ReadP [a]
:: ReadP a -> ReadP sep -> ReadP [a]
:: ReadP a -> ReadP sep -> ReadP [a]
:: ReadP a -> ReadP sep -> ReadP [a]
:: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a
:: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a
:: ReadP a -> ReadP (a -> a -> a) -> ReadP a
:: ReadP a -> ReadP (a -> a -> a) -> ReadP a
:: ReadP a -> ReadP end -> ReadP [a]
:: ReadS a -> ReadP a
invariant: list is non-empty!
results are delivered as soon as possible
fail disappears
look + sthg else floats upwards
Maintains invariant for Final constructor
--------------------------------------------------------------------------- | # LANGUAGE NoImplicitPrelude , Rank2Types , MagicHash #
module Text.ParserCombinators.ReadP
(
: : * - > * ; instance Functor , Monad , MonadPlus
: :
: : ( )
: : ( Bool ) - > ReadP Char
: : ReadP Char
: : ( Bool ) - > ReadP String
: : ( Bool ) - > ReadP String
: : ( )
ReadS,
readP_to_S,
)
where
import GHC.Base
import Control.Monad ( MonadPlus(..), sequence, liftM2 )
import Data.List ( replicate, null )
import Data.Char ( isSpace )
infixr 5 +++, <++
type ReadS a = String -> [(a,String)]
data P a
= Get (Char -> P a)
| Look (String -> P a)
| Fail
| Result a (P a)
instance Monad P where
return x = Result x Fail
(Get f) >>= k = Get (\c -> f c >>= k)
(Look f) >>= k = Look (\s -> f s >>= k)
Fail >>= _ = Fail
(Result x p) >>= k = k x `mplus` (p >>= k)
(Final r) >>= k = final [ys' | (x,s) <- r, ys' <- run (k x) s]
fail _ = Fail
instance MonadPlus P where
mzero = Fail
most common case : two gets are combined
Get f1 `mplus` Get f2 = Get (\c -> f1 c `mplus` f2 c)
Result x p `mplus` q = Result x (p `mplus` q)
p `mplus` Result x q = Result x (p `mplus` q)
Fail `mplus` p = p
p `mplus` Fail = p
two finals are combined
final + look becomes one look and one final (= optimization )
final + sthg else becomes one look and one final
Final r `mplus` Final t = Final (r ++ t)
Final r `mplus` Look f = Look (\s -> Final (r ++ run (f s) s))
Final r `mplus` p = Look (\s -> Final (r ++ run p s))
Look f `mplus` Final r = Look (\s -> Final (run (f s) s ++ r))
p `mplus` Final r = Look (\s -> Final (run p s ++ r))
two looks are combined (= optimization )
Look f `mplus` Look g = Look (\s -> f s `mplus` g s)
Look f `mplus` p = Look (\s -> f s `mplus` p)
p `mplus` Look f = Look (\s -> p `mplus` f s)
newtype ReadP a = R (forall b . (a -> P b) -> P b)
instance Functor ReadP where
fmap h (R f) = R (\k -> f (k . h))
instance Monad ReadP where
return x = R (\k -> k x)
fail _ = R (\_ -> Fail)
R m >>= f = R (\k -> m (\a -> let R m' = f a in m' k))
instance MonadPlus ReadP where
mzero = pfail
mplus = (+++)
final :: [(a,String)] -> P a
final [] = Fail
final r = Final r
run :: P a -> ReadS a
run (Get f) (c:s) = run (f c) s
run (Look f) s = run (f s) s
run (Result x p) s = (x,s) : run p s
run (Final r) _ = r
run _ _ = []
get :: ReadP Char
get = R Get
look :: ReadP String
look = R Look
pfail :: ReadP a
pfail = R (\_ -> Fail)
(+++) :: ReadP a -> ReadP a -> ReadP a
R f1 +++ R f2 = R (\k -> f1 k `mplus` f2 k)
(<++) :: ReadP a -> ReadP a -> ReadP a
R f0 <++ q =
do s <- look
probe (f0 return) s 0#
where
probe (Get f) (c:s) n = probe (f c) s (n+#1#)
probe (Look f) s n = probe (f s) s n
probe p@(Result _ _) _ n = discard n >> R (p >>=)
probe (Final r) _ _ = R (Final r >>=)
probe _ _ _ = q
discard 0# = return ()
discard n = get >> discard (n-#1#)
gather :: ReadP a -> ReadP (String, a)
gather (R m)
= R (\k -> gath id (m (\a -> return (\s -> k (s,a)))))
where
gath :: (String -> String) -> P (String -> P b) -> P b
gath l (Get f) = Get (\c -> gath (l.(c:)) (f c))
gath _ Fail = Fail
gath l (Look f) = Look (\s -> gath l (f s))
gath l (Result k p) = k (l []) `mplus` gath l p
gath _ (Final _) = error "do not use readS_to_P in gather!"
satisfy :: (Char -> Bool) -> ReadP Char
satisfy p = do c <- get; if p c then return c else pfail
char :: Char -> ReadP Char
char c = satisfy (c ==)
eof :: ReadP ()
eof = do { s <- look
; if null s then return ()
else pfail }
string :: String -> ReadP String
string this = do s <- look; scan this s
where
scan [] _ = do return this
scan (x:xs) (y:ys) | x == y = do _ <- get; scan xs ys
scan _ _ = do pfail
munch :: (Char -> Bool) -> ReadP String
munch p =
do s <- look
scan s
where
scan (c:cs) | p c = do _ <- get; s <- scan cs; return (c:s)
scan _ = do return ""
munch1 :: (Char -> Bool) -> ReadP String
munch1 p =
do c <- get
if p c then do s <- munch p; return (c:s)
else pfail
choice :: [ReadP a] -> ReadP a
choice [] = pfail
choice [p] = p
choice (p:ps) = p +++ choice ps
skipSpaces :: ReadP ()
skipSpaces =
do s <- look
skip s
where
skip (c:s) | isSpace c = do _ <- get; skip s
skip _ = do return ()
count :: Int -> ReadP a -> ReadP [a]
count n p = sequence (replicate n p)
between :: ReadP open -> ReadP close -> ReadP a -> ReadP a
between open close p = do _ <- open
x <- p
_ <- close
return x
option :: a -> ReadP a -> ReadP a
option x p = p +++ return x
optional :: ReadP a -> ReadP ()
optional p = (p >> return ()) +++ return ()
many :: ReadP a -> ReadP [a]
many p = return [] +++ many1 p
many1 :: ReadP a -> ReadP [a]
many1 p = liftM2 (:) p (many p)
skipMany :: ReadP a -> ReadP ()
skipMany p = many p >> return ()
skipMany1 :: ReadP a -> ReadP ()
skipMany1 p = p >> skipMany p
sepBy :: ReadP a -> ReadP sep -> ReadP [a]
sepBy p sep = sepBy1 p sep +++ return []
sepBy1 :: ReadP a -> ReadP sep -> ReadP [a]
sepBy1 p sep = liftM2 (:) p (many (sep >> p))
endBy :: ReadP a -> ReadP sep -> ReadP [a]
endBy p sep = many (do x <- p ; _ <- sep ; return x)
endBy1 :: ReadP a -> ReadP sep -> ReadP [a]
endBy1 p sep = many1 (do x <- p ; _ <- sep ; return x)
chainr :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a
chainr p op x = chainr1 p op +++ return x
chainl :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a
chainl p op x = chainl1 p op +++ return x
chainr1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a
chainr1 p op = scan
where scan = p >>= rest
rest x = do f <- op
y <- scan
return (f x y)
+++ return x
chainl1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a
chainl1 p op = p >>= rest
where rest x = do f <- op
y <- p
rest (f x y)
+++ return x
manyTill :: ReadP a -> ReadP end -> ReadP [a]
manyTill p end = scan
where scan = (end >> return []) <++ (liftM2 (:) p scan)
readP_to_S :: ReadP a -> ReadS a
readP_to_S (R f) = run (f return)
readS_to_P :: ReadS a -> ReadP a
readS_to_P r =
R (\k -> Look (\s -> final [bs'' | (a,s') <- r s, bs'' <- run (k a) s']))
|
7084f2bebd1bbbb2fe76145cbd945c30414937e59d5e39bbd32d2ca1e70eb5d0 | eryx67/vk-api-example | Pagination.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
# LANGUAGE TupleSections #
{-# LANGUAGE TypeFamilies #-}
-- | Common widgets for views
module VK.App.Widgets.Pagination where
import Control.Monad (join)
import Data.Foldable (forM_)
import Data.List (unfoldr)
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import React.Flux
class Pagination pg where
type PageIndex pg :: *
type PageData pg :: *
firstPage :: pg -> Maybe (PageIndex pg)
lastPage :: pg -> Maybe (PageIndex pg)
currentPage :: pg -> Maybe (PageIndex pg)
prevPage :: pg -> PageIndex pg -> Maybe (PageIndex pg)
nextPage :: pg -> PageIndex pg -> Maybe (PageIndex pg)
pageNum :: pg -> PageIndex pg -> Int
pageData :: pg -> Maybe (PageData pg)
pagerView :: (Pagination pg, Eq (PageIndex pg), Show (PageIndex pg)) =>
pg -> Int
-> (PageData pg -> ReactElementM ViewEventHandler ())
-> (PageIndex pg -> T.Text)
-> ReactElementM ViewEventHandler ()
pagerView pg navLen dataView pageAction = do
let curPage = currentPage pg
mps = pages <$> curPage
(prevHide, nextHide) =
fromMaybe (True, True) $ do
ps <- mps
if null ps
then
return (True, True)
else
return (firstPage pg == Just (head ps),
lastPage pg == Just (last ps))
pageIdxs = fromMaybe [] mps
prevPageAction = maybe "" pageAction (join $ prevPage pg <$> curPage)
nextPageAction = maybe "" pageAction (join $ nextPage pg <$> curPage)
div_ $ do
maybe mempty dataView $ pageData pg
nav_ $
ul_ ["className" $= "pagination"] $ do
li_ ["className" $= "disabled" | prevHide] $
if prevHide
then
span_ ["aria-hidden" $= "true"] $ elemText "<<"
else
a_ ["href" $= prevPageAction
, "aria-label" $= "Previous"] $
span_ [] $ elemText "<<"
forM_ pageIdxs (\pidx ->
li_ ["className" $= "active" | Just pidx == curPage] $
a_ ["href" $= pageAction pidx] $
elemShow $ pageNum pg pidx)
li_ ["className" $= "disabled" | nextHide] $
if nextHide
then
span_ ["aria-hidden" $= "true"] $ elemText ">>"
else
a_ ["href" $= nextPageAction
, "aria-label" $= "Next"] $
span_ [] $ elemText ">>"
where
pages p =
let pps = reverse . take (navLen `div` 2 - 1) $ prevPages p navLen
nps = nextPages p (navLen - length pps - 1)
in
pps ++ p:nps
findPages nxt p len =
unfoldr (\(l, cp) ->
if null l
then Nothing
else (\np -> (np , (tail l, np))) <$> nxt cp)
([1..len], p)
prevPages p = findPages (prevPage pg) p
nextPages = findPages (nextPage pg)
| null | https://raw.githubusercontent.com/eryx67/vk-api-example/4ce634e2f72cf0ab6ef3b80387ad489de9d8c0ee/src/VK/App/Widgets/Pagination.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeFamilies #
| Common widgets for views | # LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
# LANGUAGE TupleSections #
module VK.App.Widgets.Pagination where
import Control.Monad (join)
import Data.Foldable (forM_)
import Data.List (unfoldr)
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import React.Flux
class Pagination pg where
type PageIndex pg :: *
type PageData pg :: *
firstPage :: pg -> Maybe (PageIndex pg)
lastPage :: pg -> Maybe (PageIndex pg)
currentPage :: pg -> Maybe (PageIndex pg)
prevPage :: pg -> PageIndex pg -> Maybe (PageIndex pg)
nextPage :: pg -> PageIndex pg -> Maybe (PageIndex pg)
pageNum :: pg -> PageIndex pg -> Int
pageData :: pg -> Maybe (PageData pg)
pagerView :: (Pagination pg, Eq (PageIndex pg), Show (PageIndex pg)) =>
pg -> Int
-> (PageData pg -> ReactElementM ViewEventHandler ())
-> (PageIndex pg -> T.Text)
-> ReactElementM ViewEventHandler ()
pagerView pg navLen dataView pageAction = do
let curPage = currentPage pg
mps = pages <$> curPage
(prevHide, nextHide) =
fromMaybe (True, True) $ do
ps <- mps
if null ps
then
return (True, True)
else
return (firstPage pg == Just (head ps),
lastPage pg == Just (last ps))
pageIdxs = fromMaybe [] mps
prevPageAction = maybe "" pageAction (join $ prevPage pg <$> curPage)
nextPageAction = maybe "" pageAction (join $ nextPage pg <$> curPage)
div_ $ do
maybe mempty dataView $ pageData pg
nav_ $
ul_ ["className" $= "pagination"] $ do
li_ ["className" $= "disabled" | prevHide] $
if prevHide
then
span_ ["aria-hidden" $= "true"] $ elemText "<<"
else
a_ ["href" $= prevPageAction
, "aria-label" $= "Previous"] $
span_ [] $ elemText "<<"
forM_ pageIdxs (\pidx ->
li_ ["className" $= "active" | Just pidx == curPage] $
a_ ["href" $= pageAction pidx] $
elemShow $ pageNum pg pidx)
li_ ["className" $= "disabled" | nextHide] $
if nextHide
then
span_ ["aria-hidden" $= "true"] $ elemText ">>"
else
a_ ["href" $= nextPageAction
, "aria-label" $= "Next"] $
span_ [] $ elemText ">>"
where
pages p =
let pps = reverse . take (navLen `div` 2 - 1) $ prevPages p navLen
nps = nextPages p (navLen - length pps - 1)
in
pps ++ p:nps
findPages nxt p len =
unfoldr (\(l, cp) ->
if null l
then Nothing
else (\np -> (np , (tail l, np))) <$> nxt cp)
([1..len], p)
prevPages p = findPages (prevPage pg) p
nextPages = findPages (nextPage pg)
|
0a8dac708bece366dc027390243eeba5e7a7eba49aec4d77fb1df2fc1632cbd7 | pokepay/aws-sdk-lisp | api.lisp | ;; DO NOT EDIT: File is generated by AWS-SDK/GENERATOR.
(common-lisp:defpackage #:aws-sdk/services/importexport/api
(:use)
(:nicknames #:aws/importexport)
(:import-from #:aws-sdk/generator/shape)
(:import-from #:aws-sdk/generator/operation)
(:import-from #:aws-sdk/api)
(:import-from #:aws-sdk/request)
(:import-from #:aws-sdk/error))
(common-lisp:in-package #:aws-sdk/services/importexport/api)
(common-lisp:progn
(common-lisp:defclass importexport-request (aws-sdk/request:request)
common-lisp:nil
(:default-initargs :service "importexport"))
(common-lisp:export 'importexport-request))
(common-lisp:progn
(common-lisp:define-condition importexport-error
(aws-sdk/error:aws-error)
common-lisp:nil)
(common-lisp:export 'importexport-error))
(common-lisp:defvar *error-map*
'(("BucketPermissionException" . bucket-permission-exception)
("CanceledJobIdException" . canceled-job-id-exception)
("CreateJobQuotaExceededException" . create-job-quota-exceeded-exception)
("ExpiredJobIdException" . expired-job-id-exception)
("InvalidAccessKeyIdException" . invalid-access-key-id-exception)
("InvalidAddressException" . invalid-address-exception)
("InvalidCustomsException" . invalid-customs-exception)
("InvalidFileSystemException" . invalid-file-system-exception)
("InvalidJobIdException" . invalid-job-id-exception)
("InvalidManifestFieldException" . invalid-manifest-field-exception)
("InvalidParameterException" . invalid-parameter-exception)
("InvalidVersionException" . invalid-version-exception)
("MalformedManifestException" . malformed-manifest-exception)
("MissingCustomsException" . missing-customs-exception)
("MissingManifestFieldException" . missing-manifest-field-exception)
("MissingParameterException" . missing-parameter-exception)
("MultipleRegionsException" . multiple-regions-exception)
("NoSuchBucketException" . no-such-bucket-exception)
("UnableToCancelJobIdException" . unable-to-cancel-job-id-exception)
("UnableToUpdateJobIdException" . unable-to-update-job-id-exception)))
(common-lisp:deftype apiversion () 'common-lisp:string)
(common-lisp:progn
(common-lisp:defstruct
(artifact (:copier common-lisp:nil) (:conc-name "struct-shape-artifact-"))
(description common-lisp:nil :type
(common-lisp:or description common-lisp:null))
(url common-lisp:nil :type (common-lisp:or url common-lisp:null)))
(common-lisp:export (common-lisp:list 'artifact 'make-artifact))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input artifact))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input artifact))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'description))
(common-lisp:list
(common-lisp:cons "Description"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'url))
(common-lisp:list
(common-lisp:cons "URL"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input artifact))
common-lisp:nil))
(common-lisp:progn
(common-lisp:deftype artifact-list () '(trivial-types:proper-list artifact))
(common-lisp:defun |make-artifact-list|
(common-lisp:&rest aws-sdk/generator/shape::members)
(common-lisp:check-type aws-sdk/generator/shape::members
(trivial-types:proper-list artifact))
aws-sdk/generator/shape::members))
(common-lisp:progn
(common-lisp:define-condition bucket-permission-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
bucket-permission-exception-message)))
(common-lisp:export
(common-lisp:list 'bucket-permission-exception
'bucket-permission-exception-message)))
(common-lisp:progn
(common-lisp:defstruct
(cancel-job-input (:copier common-lisp:nil)
(:conc-name "struct-shape-cancel-job-input-"))
(job-id (common-lisp:error ":job-id is required") :type
(common-lisp:or job-id common-lisp:null))
(apiversion common-lisp:nil :type
(common-lisp:or apiversion common-lisp:null)))
(common-lisp:export
(common-lisp:list 'cancel-job-input 'make-cancel-job-input))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input cancel-job-input))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input cancel-job-input))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-id))
(common-lisp:list
(common-lisp:cons "JobId"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'apiversion))
(common-lisp:list
(common-lisp:cons "APIVersion"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input cancel-job-input))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(cancel-job-output (:copier common-lisp:nil)
(:conc-name "struct-shape-cancel-job-output-"))
(success common-lisp:nil :type (common-lisp:or success common-lisp:null)))
(common-lisp:export
(common-lisp:list 'cancel-job-output 'make-cancel-job-output))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input cancel-job-output))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input cancel-job-output))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'success))
(common-lisp:list
(common-lisp:cons "Success"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input cancel-job-output))
common-lisp:nil))
(common-lisp:progn
(common-lisp:define-condition canceled-job-id-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
canceled-job-id-exception-message)))
(common-lisp:export
(common-lisp:list 'canceled-job-id-exception
'canceled-job-id-exception-message)))
(common-lisp:deftype carrier () 'common-lisp:string)
(common-lisp:progn
(common-lisp:defstruct
(create-job-input (:copier common-lisp:nil)
(:conc-name "struct-shape-create-job-input-"))
(job-type (common-lisp:error ":job-type is required") :type
(common-lisp:or job-type common-lisp:null))
(manifest (common-lisp:error ":manifest is required") :type
(common-lisp:or manifest common-lisp:null))
(manifest-addendum common-lisp:nil :type
(common-lisp:or manifest-addendum common-lisp:null))
(validate-only (common-lisp:error ":validate-only is required") :type
(common-lisp:or validate-only common-lisp:null))
(apiversion common-lisp:nil :type
(common-lisp:or apiversion common-lisp:null)))
(common-lisp:export
(common-lisp:list 'create-job-input 'make-create-job-input))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input create-job-input))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input create-job-input))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-type))
(common-lisp:list
(common-lisp:cons "JobType"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'manifest))
(common-lisp:list
(common-lisp:cons "Manifest"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'manifest-addendum))
(common-lisp:list
(common-lisp:cons "ManifestAddendum"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'validate-only))
(common-lisp:list
(common-lisp:cons "ValidateOnly"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'apiversion))
(common-lisp:list
(common-lisp:cons "APIVersion"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input create-job-input))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(create-job-output (:copier common-lisp:nil)
(:conc-name "struct-shape-create-job-output-"))
(job-id common-lisp:nil :type (common-lisp:or job-id common-lisp:null))
(job-type common-lisp:nil :type (common-lisp:or job-type common-lisp:null))
(signature common-lisp:nil :type
(common-lisp:or signature common-lisp:null))
(signature-file-contents common-lisp:nil :type
(common-lisp:or signature-file-contents common-lisp:null))
(warning-message common-lisp:nil :type
(common-lisp:or warning-message common-lisp:null))
(artifact-list common-lisp:nil :type
(common-lisp:or artifact-list common-lisp:null)))
(common-lisp:export
(common-lisp:list 'create-job-output 'make-create-job-output))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input create-job-output))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input create-job-output))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-id))
(common-lisp:list
(common-lisp:cons "JobId"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-type))
(common-lisp:list
(common-lisp:cons "JobType"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'signature))
(common-lisp:list
(common-lisp:cons "Signature"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input
'signature-file-contents))
(common-lisp:list
(common-lisp:cons "SignatureFileContents"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'warning-message))
(common-lisp:list
(common-lisp:cons "WarningMessage"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'artifact-list))
(common-lisp:list
(common-lisp:cons "ArtifactList"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input create-job-output))
common-lisp:nil))
(common-lisp:progn
(common-lisp:define-condition create-job-quota-exceeded-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
create-job-quota-exceeded-exception-message)))
(common-lisp:export
(common-lisp:list 'create-job-quota-exceeded-exception
'create-job-quota-exceeded-exception-message)))
(common-lisp:deftype creation-date () 'common-lisp:string)
(common-lisp:deftype current-manifest () 'common-lisp:string)
(common-lisp:deftype description () 'common-lisp:string)
(common-lisp:deftype error-count () 'common-lisp:integer)
(common-lisp:deftype error-message () 'common-lisp:string)
(common-lisp:progn
(common-lisp:define-condition expired-job-id-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
expired-job-id-exception-message)))
(common-lisp:export
(common-lisp:list 'expired-job-id-exception
'expired-job-id-exception-message)))
(common-lisp:deftype generic-string () 'common-lisp:string)
(common-lisp:progn
(common-lisp:defstruct
(get-shipping-label-input (:copier common-lisp:nil)
(:conc-name "struct-shape-get-shipping-label-input-"))
(job-ids (common-lisp:error ":jobids is required") :type
(common-lisp:or job-id-list common-lisp:null))
(name common-lisp:nil :type (common-lisp:or |name| common-lisp:null))
(company common-lisp:nil :type (common-lisp:or |company| common-lisp:null))
(phone-number common-lisp:nil :type
(common-lisp:or |phoneNumber| common-lisp:null))
(country common-lisp:nil :type (common-lisp:or |country| common-lisp:null))
(state-or-province common-lisp:nil :type
(common-lisp:or |stateOrProvince| common-lisp:null))
(city common-lisp:nil :type (common-lisp:or |city| common-lisp:null))
(postal-code common-lisp:nil :type
(common-lisp:or |postalCode| common-lisp:null))
(street1 common-lisp:nil :type (common-lisp:or |street1| common-lisp:null))
(street2 common-lisp:nil :type (common-lisp:or |street2| common-lisp:null))
(street3 common-lisp:nil :type (common-lisp:or |street3| common-lisp:null))
(apiversion common-lisp:nil :type
(common-lisp:or apiversion common-lisp:null)))
(common-lisp:export
(common-lisp:list 'get-shipping-label-input 'make-get-shipping-label-input))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
(
(aws-sdk/generator/shape::input
get-shipping-label-input))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
(
(aws-sdk/generator/shape::input
get-shipping-label-input))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-ids))
(common-lisp:list
(common-lisp:cons "jobIds"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'name))
(common-lisp:list
(common-lisp:cons "name"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'company))
(common-lisp:list
(common-lisp:cons "company"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'phone-number))
(common-lisp:list
(common-lisp:cons "phoneNumber"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'country))
(common-lisp:list
(common-lisp:cons "country"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'state-or-province))
(common-lisp:list
(common-lisp:cons "stateOrProvince"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'city))
(common-lisp:list
(common-lisp:cons "city"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'postal-code))
(common-lisp:list
(common-lisp:cons "postalCode"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'street1))
(common-lisp:list
(common-lisp:cons "street1"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'street2))
(common-lisp:list
(common-lisp:cons "street2"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'street3))
(common-lisp:list
(common-lisp:cons "street3"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'apiversion))
(common-lisp:list
(common-lisp:cons "APIVersion"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
(
(aws-sdk/generator/shape::input
get-shipping-label-input))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(get-shipping-label-output (:copier common-lisp:nil)
(:conc-name "struct-shape-get-shipping-label-output-"))
(shipping-label-url common-lisp:nil :type
(common-lisp:or generic-string common-lisp:null))
(warning common-lisp:nil :type
(common-lisp:or generic-string common-lisp:null)))
(common-lisp:export
(common-lisp:list 'get-shipping-label-output
'make-get-shipping-label-output))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
(
(aws-sdk/generator/shape::input
get-shipping-label-output))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
(
(aws-sdk/generator/shape::input
get-shipping-label-output))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'shipping-label-url))
(common-lisp:list
(common-lisp:cons "ShippingLabelURL"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'warning))
(common-lisp:list
(common-lisp:cons "Warning"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
(
(aws-sdk/generator/shape::input
get-shipping-label-output))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(get-status-input (:copier common-lisp:nil)
(:conc-name "struct-shape-get-status-input-"))
(job-id (common-lisp:error ":job-id is required") :type
(common-lisp:or job-id common-lisp:null))
(apiversion common-lisp:nil :type
(common-lisp:or apiversion common-lisp:null)))
(common-lisp:export
(common-lisp:list 'get-status-input 'make-get-status-input))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input get-status-input))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input get-status-input))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-id))
(common-lisp:list
(common-lisp:cons "JobId"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'apiversion))
(common-lisp:list
(common-lisp:cons "APIVersion"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input get-status-input))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(get-status-output (:copier common-lisp:nil)
(:conc-name "struct-shape-get-status-output-"))
(job-id common-lisp:nil :type (common-lisp:or job-id common-lisp:null))
(job-type common-lisp:nil :type (common-lisp:or job-type common-lisp:null))
(location-code common-lisp:nil :type
(common-lisp:or location-code common-lisp:null))
(location-message common-lisp:nil :type
(common-lisp:or location-message common-lisp:null))
(progress-code common-lisp:nil :type
(common-lisp:or progress-code common-lisp:null))
(progress-message common-lisp:nil :type
(common-lisp:or progress-message common-lisp:null))
(carrier common-lisp:nil :type (common-lisp:or carrier common-lisp:null))
(tracking-number common-lisp:nil :type
(common-lisp:or tracking-number common-lisp:null))
(log-bucket common-lisp:nil :type
(common-lisp:or log-bucket common-lisp:null))
(log-key common-lisp:nil :type (common-lisp:or log-key common-lisp:null))
(error-count common-lisp:nil :type
(common-lisp:or error-count common-lisp:null))
(signature common-lisp:nil :type
(common-lisp:or signature common-lisp:null))
(signature-file-contents common-lisp:nil :type
(common-lisp:or signature common-lisp:null))
(current-manifest common-lisp:nil :type
(common-lisp:or current-manifest common-lisp:null))
(creation-date common-lisp:nil :type
(common-lisp:or creation-date common-lisp:null))
(artifact-list common-lisp:nil :type
(common-lisp:or artifact-list common-lisp:null)))
(common-lisp:export
(common-lisp:list 'get-status-output 'make-get-status-output))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input get-status-output))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input get-status-output))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-id))
(common-lisp:list
(common-lisp:cons "JobId"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-type))
(common-lisp:list
(common-lisp:cons "JobType"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'location-code))
(common-lisp:list
(common-lisp:cons "LocationCode"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'location-message))
(common-lisp:list
(common-lisp:cons "LocationMessage"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'progress-code))
(common-lisp:list
(common-lisp:cons "ProgressCode"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'progress-message))
(common-lisp:list
(common-lisp:cons "ProgressMessage"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'carrier))
(common-lisp:list
(common-lisp:cons "Carrier"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'tracking-number))
(common-lisp:list
(common-lisp:cons "TrackingNumber"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'log-bucket))
(common-lisp:list
(common-lisp:cons "LogBucket"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'log-key))
(common-lisp:list
(common-lisp:cons "LogKey"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'error-count))
(common-lisp:list
(common-lisp:cons "ErrorCount"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'signature))
(common-lisp:list
(common-lisp:cons "Signature"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input
'signature-file-contents))
(common-lisp:list
(common-lisp:cons "SignatureFileContents"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'current-manifest))
(common-lisp:list
(common-lisp:cons "CurrentManifest"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'creation-date))
(common-lisp:list
(common-lisp:cons "CreationDate"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'artifact-list))
(common-lisp:list
(common-lisp:cons "ArtifactList"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input get-status-output))
common-lisp:nil))
(common-lisp:progn
(common-lisp:define-condition invalid-access-key-id-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-access-key-id-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-access-key-id-exception
'invalid-access-key-id-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-address-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-address-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-address-exception
'invalid-address-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-customs-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-customs-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-customs-exception
'invalid-customs-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-file-system-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-file-system-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-file-system-exception
'invalid-file-system-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-job-id-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-job-id-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-job-id-exception
'invalid-job-id-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-manifest-field-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-manifest-field-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-manifest-field-exception
'invalid-manifest-field-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-parameter-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-parameter-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-parameter-exception
'invalid-parameter-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-version-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-version-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-version-exception
'invalid-version-exception-message)))
(common-lisp:deftype is-canceled () 'common-lisp:boolean)
(common-lisp:deftype is-truncated () 'common-lisp:boolean)
(common-lisp:progn
(common-lisp:defstruct
(job (:copier common-lisp:nil) (:conc-name "struct-shape-job-"))
(job-id common-lisp:nil :type (common-lisp:or job-id common-lisp:null))
(creation-date common-lisp:nil :type
(common-lisp:or creation-date common-lisp:null))
(is-canceled common-lisp:nil :type
(common-lisp:or is-canceled common-lisp:null))
(job-type common-lisp:nil :type (common-lisp:or job-type common-lisp:null)))
(common-lisp:export (common-lisp:list 'job 'make-job))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input job))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input job))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-id))
(common-lisp:list
(common-lisp:cons "JobId"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'creation-date))
(common-lisp:list
(common-lisp:cons "CreationDate"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'is-canceled))
(common-lisp:list
(common-lisp:cons "IsCanceled"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-type))
(common-lisp:list
(common-lisp:cons "JobType"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input job))
common-lisp:nil))
(common-lisp:deftype job-id () 'common-lisp:string)
(common-lisp:progn
(common-lisp:deftype job-id-list ()
'(trivial-types:proper-list generic-string))
(common-lisp:defun |make-job-id-list|
(common-lisp:&rest aws-sdk/generator/shape::members)
(common-lisp:check-type aws-sdk/generator/shape::members
(trivial-types:proper-list generic-string))
aws-sdk/generator/shape::members))
(common-lisp:deftype job-type () 'common-lisp:string)
(common-lisp:progn
(common-lisp:deftype jobs-list () '(trivial-types:proper-list job))
(common-lisp:defun |make-jobs-list|
(common-lisp:&rest aws-sdk/generator/shape::members)
(common-lisp:check-type aws-sdk/generator/shape::members
(trivial-types:proper-list job))
aws-sdk/generator/shape::members))
(common-lisp:progn
(common-lisp:defstruct
(list-jobs-input (:copier common-lisp:nil)
(:conc-name "struct-shape-list-jobs-input-"))
(max-jobs common-lisp:nil :type (common-lisp:or max-jobs common-lisp:null))
(marker common-lisp:nil :type (common-lisp:or marker common-lisp:null))
(apiversion common-lisp:nil :type
(common-lisp:or apiversion common-lisp:null)))
(common-lisp:export (common-lisp:list 'list-jobs-input 'make-list-jobs-input))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input list-jobs-input))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input list-jobs-input))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'max-jobs))
(common-lisp:list
(common-lisp:cons "MaxJobs"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'marker))
(common-lisp:list
(common-lisp:cons "Marker"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'apiversion))
(common-lisp:list
(common-lisp:cons "APIVersion"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input list-jobs-input))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(list-jobs-output (:copier common-lisp:nil)
(:conc-name "struct-shape-list-jobs-output-"))
(jobs common-lisp:nil :type (common-lisp:or jobs-list common-lisp:null))
(is-truncated common-lisp:nil :type
(common-lisp:or is-truncated common-lisp:null)))
(common-lisp:export
(common-lisp:list 'list-jobs-output 'make-list-jobs-output))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input list-jobs-output))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input list-jobs-output))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'jobs))
(common-lisp:list
(common-lisp:cons "Jobs"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'is-truncated))
(common-lisp:list
(common-lisp:cons "IsTruncated"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input list-jobs-output))
common-lisp:nil))
(common-lisp:deftype location-code () 'common-lisp:string)
(common-lisp:deftype location-message () 'common-lisp:string)
(common-lisp:deftype log-bucket () 'common-lisp:string)
(common-lisp:deftype log-key () 'common-lisp:string)
(common-lisp:progn
(common-lisp:define-condition malformed-manifest-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
malformed-manifest-exception-message)))
(common-lisp:export
(common-lisp:list 'malformed-manifest-exception
'malformed-manifest-exception-message)))
(common-lisp:deftype manifest () 'common-lisp:string)
(common-lisp:deftype manifest-addendum () 'common-lisp:string)
(common-lisp:deftype marker () 'common-lisp:string)
(common-lisp:deftype max-jobs () 'common-lisp:integer)
(common-lisp:progn
(common-lisp:define-condition missing-customs-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
missing-customs-exception-message)))
(common-lisp:export
(common-lisp:list 'missing-customs-exception
'missing-customs-exception-message)))
(common-lisp:progn
(common-lisp:define-condition missing-manifest-field-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
missing-manifest-field-exception-message)))
(common-lisp:export
(common-lisp:list 'missing-manifest-field-exception
'missing-manifest-field-exception-message)))
(common-lisp:progn
(common-lisp:define-condition missing-parameter-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
missing-parameter-exception-message)))
(common-lisp:export
(common-lisp:list 'missing-parameter-exception
'missing-parameter-exception-message)))
(common-lisp:progn
(common-lisp:define-condition multiple-regions-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
multiple-regions-exception-message)))
(common-lisp:export
(common-lisp:list 'multiple-regions-exception
'multiple-regions-exception-message)))
(common-lisp:progn
(common-lisp:define-condition no-such-bucket-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
no-such-bucket-exception-message)))
(common-lisp:export
(common-lisp:list 'no-such-bucket-exception
'no-such-bucket-exception-message)))
(common-lisp:deftype progress-code () 'common-lisp:string)
(common-lisp:deftype progress-message () 'common-lisp:string)
(common-lisp:deftype signature () 'common-lisp:string)
(common-lisp:deftype signature-file-contents () 'common-lisp:string)
(common-lisp:deftype success () 'common-lisp:boolean)
(common-lisp:deftype tracking-number () 'common-lisp:string)
(common-lisp:deftype url () 'common-lisp:string)
(common-lisp:progn
(common-lisp:define-condition unable-to-cancel-job-id-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
unable-to-cancel-job-id-exception-message)))
(common-lisp:export
(common-lisp:list 'unable-to-cancel-job-id-exception
'unable-to-cancel-job-id-exception-message)))
(common-lisp:progn
(common-lisp:define-condition unable-to-update-job-id-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
unable-to-update-job-id-exception-message)))
(common-lisp:export
(common-lisp:list 'unable-to-update-job-id-exception
'unable-to-update-job-id-exception-message)))
(common-lisp:progn
(common-lisp:defstruct
(update-job-input (:copier common-lisp:nil)
(:conc-name "struct-shape-update-job-input-"))
(job-id (common-lisp:error ":job-id is required") :type
(common-lisp:or job-id common-lisp:null))
(manifest (common-lisp:error ":manifest is required") :type
(common-lisp:or manifest common-lisp:null))
(job-type (common-lisp:error ":job-type is required") :type
(common-lisp:or job-type common-lisp:null))
(validate-only (common-lisp:error ":validate-only is required") :type
(common-lisp:or validate-only common-lisp:null))
(apiversion common-lisp:nil :type
(common-lisp:or apiversion common-lisp:null)))
(common-lisp:export
(common-lisp:list 'update-job-input 'make-update-job-input))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input update-job-input))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input update-job-input))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-id))
(common-lisp:list
(common-lisp:cons "JobId"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'manifest))
(common-lisp:list
(common-lisp:cons "Manifest"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-type))
(common-lisp:list
(common-lisp:cons "JobType"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'validate-only))
(common-lisp:list
(common-lisp:cons "ValidateOnly"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'apiversion))
(common-lisp:list
(common-lisp:cons "APIVersion"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input update-job-input))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(update-job-output (:copier common-lisp:nil)
(:conc-name "struct-shape-update-job-output-"))
(success common-lisp:nil :type (common-lisp:or success common-lisp:null))
(warning-message common-lisp:nil :type
(common-lisp:or warning-message common-lisp:null))
(artifact-list common-lisp:nil :type
(common-lisp:or artifact-list common-lisp:null)))
(common-lisp:export
(common-lisp:list 'update-job-output 'make-update-job-output))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input update-job-output))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input update-job-output))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'success))
(common-lisp:list
(common-lisp:cons "Success"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'warning-message))
(common-lisp:list
(common-lisp:cons "WarningMessage"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'artifact-list))
(common-lisp:list
(common-lisp:cons "ArtifactList"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input update-job-output))
common-lisp:nil))
(common-lisp:deftype validate-only () 'common-lisp:boolean)
(common-lisp:deftype warning-message () 'common-lisp:string)
(common-lisp:deftype |city| () 'common-lisp:string)
(common-lisp:deftype |company| () 'common-lisp:string)
(common-lisp:deftype |country| () 'common-lisp:string)
(common-lisp:deftype |name| () 'common-lisp:string)
(common-lisp:deftype |phoneNumber| () 'common-lisp:string)
(common-lisp:deftype |postalCode| () 'common-lisp:string)
(common-lisp:deftype |stateOrProvince| () 'common-lisp:string)
(common-lisp:deftype |street1| () 'common-lisp:string)
(common-lisp:deftype |street2| () 'common-lisp:string)
(common-lisp:deftype |street3| () 'common-lisp:string)
(common-lisp:progn
(common-lisp:defun cancel-job
(
common-lisp:&rest aws-sdk/generator/operation::args
common-lisp:&key job-id apiversion)
(common-lisp:declare (common-lisp:ignorable job-id apiversion))
(common-lisp:let ((aws-sdk/generator/operation::input
(common-lisp:apply 'make-cancel-job-input
aws-sdk/generator/operation::args)))
(aws-sdk/generator/operation::parse-response
(aws-sdk/api:aws-request
(aws-sdk/generator/shape:make-request-with-input 'importexport-request
aws-sdk/generator/operation::input
"POST"
"/?Operation=CancelJob"
"CancelJob"
"2010-06-01"))
common-lisp:nil "CancelJobResult" *error-map*)))
(common-lisp:export 'cancel-job))
(common-lisp:progn
(common-lisp:defun create-job
(
common-lisp:&rest aws-sdk/generator/operation::args
common-lisp:&key job-type manifest manifest-addendum
validate-only apiversion)
(common-lisp:declare
(common-lisp:ignorable job-type manifest manifest-addendum validate-only
apiversion))
(common-lisp:let ((aws-sdk/generator/operation::input
(common-lisp:apply 'make-create-job-input
aws-sdk/generator/operation::args)))
(aws-sdk/generator/operation::parse-response
(aws-sdk/api:aws-request
(aws-sdk/generator/shape:make-request-with-input 'importexport-request
aws-sdk/generator/operation::input
"POST"
"/?Operation=CreateJob"
"CreateJob"
"2010-06-01"))
common-lisp:nil "CreateJobResult" *error-map*)))
(common-lisp:export 'create-job))
(common-lisp:progn
(common-lisp:defun get-shipping-label
(
common-lisp:&rest aws-sdk/generator/operation::args
common-lisp:&key job-ids name company phone-number country
state-or-province city postal-code street1 street2 street3
apiversion)
(common-lisp:declare
(common-lisp:ignorable job-ids name company phone-number country
state-or-province city postal-code street1 street2 street3 apiversion))
(common-lisp:let ((aws-sdk/generator/operation::input
(common-lisp:apply 'make-get-shipping-label-input
aws-sdk/generator/operation::args)))
(aws-sdk/generator/operation::parse-response
(aws-sdk/api:aws-request
(aws-sdk/generator/shape:make-request-with-input 'importexport-request
aws-sdk/generator/operation::input
"POST"
"/?Operation=GetShippingLabel"
"GetShippingLabel"
"2010-06-01"))
common-lisp:nil "GetShippingLabelResult" *error-map*)))
(common-lisp:export 'get-shipping-label))
(common-lisp:progn
(common-lisp:defun get-status
(
common-lisp:&rest aws-sdk/generator/operation::args
common-lisp:&key job-id apiversion)
(common-lisp:declare (common-lisp:ignorable job-id apiversion))
(common-lisp:let ((aws-sdk/generator/operation::input
(common-lisp:apply 'make-get-status-input
aws-sdk/generator/operation::args)))
(aws-sdk/generator/operation::parse-response
(aws-sdk/api:aws-request
(aws-sdk/generator/shape:make-request-with-input 'importexport-request
aws-sdk/generator/operation::input
"POST"
"/?Operation=GetStatus"
"GetStatus"
"2010-06-01"))
common-lisp:nil "GetStatusResult" *error-map*)))
(common-lisp:export 'get-status))
(common-lisp:progn
(common-lisp:defun list-jobs
(
common-lisp:&rest aws-sdk/generator/operation::args
common-lisp:&key max-jobs marker apiversion)
(common-lisp:declare (common-lisp:ignorable max-jobs marker apiversion))
(common-lisp:let ((aws-sdk/generator/operation::input
(common-lisp:apply 'make-list-jobs-input
aws-sdk/generator/operation::args)))
(aws-sdk/generator/operation::parse-response
(aws-sdk/api:aws-request
(aws-sdk/generator/shape:make-request-with-input 'importexport-request
aws-sdk/generator/operation::input
"POST"
"/?Operation=ListJobs"
"ListJobs"
"2010-06-01"))
common-lisp:nil "ListJobsResult" *error-map*)))
(common-lisp:export 'list-jobs))
(common-lisp:progn
(common-lisp:defun update-job
(
common-lisp:&rest aws-sdk/generator/operation::args
common-lisp:&key job-id manifest job-type validate-only
apiversion)
(common-lisp:declare
(common-lisp:ignorable job-id manifest job-type validate-only apiversion))
(common-lisp:let ((aws-sdk/generator/operation::input
(common-lisp:apply 'make-update-job-input
aws-sdk/generator/operation::args)))
(aws-sdk/generator/operation::parse-response
(aws-sdk/api:aws-request
(aws-sdk/generator/shape:make-request-with-input 'importexport-request
aws-sdk/generator/operation::input
"POST"
"/?Operation=UpdateJob"
"UpdateJob"
"2010-06-01"))
common-lisp:nil "UpdateJobResult" *error-map*)))
(common-lisp:export 'update-job))
| null | https://raw.githubusercontent.com/pokepay/aws-sdk-lisp/ad9a8f9294a9799cef5f4d85e0cd34eca418be24/services/importexport/api.lisp | lisp | DO NOT EDIT: File is generated by AWS-SDK/GENERATOR. |
(common-lisp:defpackage #:aws-sdk/services/importexport/api
(:use)
(:nicknames #:aws/importexport)
(:import-from #:aws-sdk/generator/shape)
(:import-from #:aws-sdk/generator/operation)
(:import-from #:aws-sdk/api)
(:import-from #:aws-sdk/request)
(:import-from #:aws-sdk/error))
(common-lisp:in-package #:aws-sdk/services/importexport/api)
(common-lisp:progn
(common-lisp:defclass importexport-request (aws-sdk/request:request)
common-lisp:nil
(:default-initargs :service "importexport"))
(common-lisp:export 'importexport-request))
(common-lisp:progn
(common-lisp:define-condition importexport-error
(aws-sdk/error:aws-error)
common-lisp:nil)
(common-lisp:export 'importexport-error))
(common-lisp:defvar *error-map*
'(("BucketPermissionException" . bucket-permission-exception)
("CanceledJobIdException" . canceled-job-id-exception)
("CreateJobQuotaExceededException" . create-job-quota-exceeded-exception)
("ExpiredJobIdException" . expired-job-id-exception)
("InvalidAccessKeyIdException" . invalid-access-key-id-exception)
("InvalidAddressException" . invalid-address-exception)
("InvalidCustomsException" . invalid-customs-exception)
("InvalidFileSystemException" . invalid-file-system-exception)
("InvalidJobIdException" . invalid-job-id-exception)
("InvalidManifestFieldException" . invalid-manifest-field-exception)
("InvalidParameterException" . invalid-parameter-exception)
("InvalidVersionException" . invalid-version-exception)
("MalformedManifestException" . malformed-manifest-exception)
("MissingCustomsException" . missing-customs-exception)
("MissingManifestFieldException" . missing-manifest-field-exception)
("MissingParameterException" . missing-parameter-exception)
("MultipleRegionsException" . multiple-regions-exception)
("NoSuchBucketException" . no-such-bucket-exception)
("UnableToCancelJobIdException" . unable-to-cancel-job-id-exception)
("UnableToUpdateJobIdException" . unable-to-update-job-id-exception)))
(common-lisp:deftype apiversion () 'common-lisp:string)
(common-lisp:progn
(common-lisp:defstruct
(artifact (:copier common-lisp:nil) (:conc-name "struct-shape-artifact-"))
(description common-lisp:nil :type
(common-lisp:or description common-lisp:null))
(url common-lisp:nil :type (common-lisp:or url common-lisp:null)))
(common-lisp:export (common-lisp:list 'artifact 'make-artifact))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input artifact))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input artifact))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'description))
(common-lisp:list
(common-lisp:cons "Description"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'url))
(common-lisp:list
(common-lisp:cons "URL"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input artifact))
common-lisp:nil))
(common-lisp:progn
(common-lisp:deftype artifact-list () '(trivial-types:proper-list artifact))
(common-lisp:defun |make-artifact-list|
(common-lisp:&rest aws-sdk/generator/shape::members)
(common-lisp:check-type aws-sdk/generator/shape::members
(trivial-types:proper-list artifact))
aws-sdk/generator/shape::members))
(common-lisp:progn
(common-lisp:define-condition bucket-permission-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
bucket-permission-exception-message)))
(common-lisp:export
(common-lisp:list 'bucket-permission-exception
'bucket-permission-exception-message)))
(common-lisp:progn
(common-lisp:defstruct
(cancel-job-input (:copier common-lisp:nil)
(:conc-name "struct-shape-cancel-job-input-"))
(job-id (common-lisp:error ":job-id is required") :type
(common-lisp:or job-id common-lisp:null))
(apiversion common-lisp:nil :type
(common-lisp:or apiversion common-lisp:null)))
(common-lisp:export
(common-lisp:list 'cancel-job-input 'make-cancel-job-input))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input cancel-job-input))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input cancel-job-input))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-id))
(common-lisp:list
(common-lisp:cons "JobId"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'apiversion))
(common-lisp:list
(common-lisp:cons "APIVersion"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input cancel-job-input))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(cancel-job-output (:copier common-lisp:nil)
(:conc-name "struct-shape-cancel-job-output-"))
(success common-lisp:nil :type (common-lisp:or success common-lisp:null)))
(common-lisp:export
(common-lisp:list 'cancel-job-output 'make-cancel-job-output))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input cancel-job-output))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input cancel-job-output))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'success))
(common-lisp:list
(common-lisp:cons "Success"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input cancel-job-output))
common-lisp:nil))
(common-lisp:progn
(common-lisp:define-condition canceled-job-id-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
canceled-job-id-exception-message)))
(common-lisp:export
(common-lisp:list 'canceled-job-id-exception
'canceled-job-id-exception-message)))
(common-lisp:deftype carrier () 'common-lisp:string)
(common-lisp:progn
(common-lisp:defstruct
(create-job-input (:copier common-lisp:nil)
(:conc-name "struct-shape-create-job-input-"))
(job-type (common-lisp:error ":job-type is required") :type
(common-lisp:or job-type common-lisp:null))
(manifest (common-lisp:error ":manifest is required") :type
(common-lisp:or manifest common-lisp:null))
(manifest-addendum common-lisp:nil :type
(common-lisp:or manifest-addendum common-lisp:null))
(validate-only (common-lisp:error ":validate-only is required") :type
(common-lisp:or validate-only common-lisp:null))
(apiversion common-lisp:nil :type
(common-lisp:or apiversion common-lisp:null)))
(common-lisp:export
(common-lisp:list 'create-job-input 'make-create-job-input))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input create-job-input))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input create-job-input))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-type))
(common-lisp:list
(common-lisp:cons "JobType"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'manifest))
(common-lisp:list
(common-lisp:cons "Manifest"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'manifest-addendum))
(common-lisp:list
(common-lisp:cons "ManifestAddendum"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'validate-only))
(common-lisp:list
(common-lisp:cons "ValidateOnly"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'apiversion))
(common-lisp:list
(common-lisp:cons "APIVersion"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input create-job-input))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(create-job-output (:copier common-lisp:nil)
(:conc-name "struct-shape-create-job-output-"))
(job-id common-lisp:nil :type (common-lisp:or job-id common-lisp:null))
(job-type common-lisp:nil :type (common-lisp:or job-type common-lisp:null))
(signature common-lisp:nil :type
(common-lisp:or signature common-lisp:null))
(signature-file-contents common-lisp:nil :type
(common-lisp:or signature-file-contents common-lisp:null))
(warning-message common-lisp:nil :type
(common-lisp:or warning-message common-lisp:null))
(artifact-list common-lisp:nil :type
(common-lisp:or artifact-list common-lisp:null)))
(common-lisp:export
(common-lisp:list 'create-job-output 'make-create-job-output))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input create-job-output))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input create-job-output))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-id))
(common-lisp:list
(common-lisp:cons "JobId"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-type))
(common-lisp:list
(common-lisp:cons "JobType"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'signature))
(common-lisp:list
(common-lisp:cons "Signature"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input
'signature-file-contents))
(common-lisp:list
(common-lisp:cons "SignatureFileContents"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'warning-message))
(common-lisp:list
(common-lisp:cons "WarningMessage"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'artifact-list))
(common-lisp:list
(common-lisp:cons "ArtifactList"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input create-job-output))
common-lisp:nil))
(common-lisp:progn
(common-lisp:define-condition create-job-quota-exceeded-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
create-job-quota-exceeded-exception-message)))
(common-lisp:export
(common-lisp:list 'create-job-quota-exceeded-exception
'create-job-quota-exceeded-exception-message)))
(common-lisp:deftype creation-date () 'common-lisp:string)
(common-lisp:deftype current-manifest () 'common-lisp:string)
(common-lisp:deftype description () 'common-lisp:string)
(common-lisp:deftype error-count () 'common-lisp:integer)
(common-lisp:deftype error-message () 'common-lisp:string)
(common-lisp:progn
(common-lisp:define-condition expired-job-id-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
expired-job-id-exception-message)))
(common-lisp:export
(common-lisp:list 'expired-job-id-exception
'expired-job-id-exception-message)))
(common-lisp:deftype generic-string () 'common-lisp:string)
(common-lisp:progn
(common-lisp:defstruct
(get-shipping-label-input (:copier common-lisp:nil)
(:conc-name "struct-shape-get-shipping-label-input-"))
(job-ids (common-lisp:error ":jobids is required") :type
(common-lisp:or job-id-list common-lisp:null))
(name common-lisp:nil :type (common-lisp:or |name| common-lisp:null))
(company common-lisp:nil :type (common-lisp:or |company| common-lisp:null))
(phone-number common-lisp:nil :type
(common-lisp:or |phoneNumber| common-lisp:null))
(country common-lisp:nil :type (common-lisp:or |country| common-lisp:null))
(state-or-province common-lisp:nil :type
(common-lisp:or |stateOrProvince| common-lisp:null))
(city common-lisp:nil :type (common-lisp:or |city| common-lisp:null))
(postal-code common-lisp:nil :type
(common-lisp:or |postalCode| common-lisp:null))
(street1 common-lisp:nil :type (common-lisp:or |street1| common-lisp:null))
(street2 common-lisp:nil :type (common-lisp:or |street2| common-lisp:null))
(street3 common-lisp:nil :type (common-lisp:or |street3| common-lisp:null))
(apiversion common-lisp:nil :type
(common-lisp:or apiversion common-lisp:null)))
(common-lisp:export
(common-lisp:list 'get-shipping-label-input 'make-get-shipping-label-input))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
(
(aws-sdk/generator/shape::input
get-shipping-label-input))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
(
(aws-sdk/generator/shape::input
get-shipping-label-input))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-ids))
(common-lisp:list
(common-lisp:cons "jobIds"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'name))
(common-lisp:list
(common-lisp:cons "name"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'company))
(common-lisp:list
(common-lisp:cons "company"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'phone-number))
(common-lisp:list
(common-lisp:cons "phoneNumber"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'country))
(common-lisp:list
(common-lisp:cons "country"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'state-or-province))
(common-lisp:list
(common-lisp:cons "stateOrProvince"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'city))
(common-lisp:list
(common-lisp:cons "city"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'postal-code))
(common-lisp:list
(common-lisp:cons "postalCode"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'street1))
(common-lisp:list
(common-lisp:cons "street1"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'street2))
(common-lisp:list
(common-lisp:cons "street2"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'street3))
(common-lisp:list
(common-lisp:cons "street3"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'apiversion))
(common-lisp:list
(common-lisp:cons "APIVersion"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
(
(aws-sdk/generator/shape::input
get-shipping-label-input))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(get-shipping-label-output (:copier common-lisp:nil)
(:conc-name "struct-shape-get-shipping-label-output-"))
(shipping-label-url common-lisp:nil :type
(common-lisp:or generic-string common-lisp:null))
(warning common-lisp:nil :type
(common-lisp:or generic-string common-lisp:null)))
(common-lisp:export
(common-lisp:list 'get-shipping-label-output
'make-get-shipping-label-output))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
(
(aws-sdk/generator/shape::input
get-shipping-label-output))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
(
(aws-sdk/generator/shape::input
get-shipping-label-output))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'shipping-label-url))
(common-lisp:list
(common-lisp:cons "ShippingLabelURL"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'warning))
(common-lisp:list
(common-lisp:cons "Warning"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
(
(aws-sdk/generator/shape::input
get-shipping-label-output))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(get-status-input (:copier common-lisp:nil)
(:conc-name "struct-shape-get-status-input-"))
(job-id (common-lisp:error ":job-id is required") :type
(common-lisp:or job-id common-lisp:null))
(apiversion common-lisp:nil :type
(common-lisp:or apiversion common-lisp:null)))
(common-lisp:export
(common-lisp:list 'get-status-input 'make-get-status-input))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input get-status-input))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input get-status-input))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-id))
(common-lisp:list
(common-lisp:cons "JobId"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'apiversion))
(common-lisp:list
(common-lisp:cons "APIVersion"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input get-status-input))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(get-status-output (:copier common-lisp:nil)
(:conc-name "struct-shape-get-status-output-"))
(job-id common-lisp:nil :type (common-lisp:or job-id common-lisp:null))
(job-type common-lisp:nil :type (common-lisp:or job-type common-lisp:null))
(location-code common-lisp:nil :type
(common-lisp:or location-code common-lisp:null))
(location-message common-lisp:nil :type
(common-lisp:or location-message common-lisp:null))
(progress-code common-lisp:nil :type
(common-lisp:or progress-code common-lisp:null))
(progress-message common-lisp:nil :type
(common-lisp:or progress-message common-lisp:null))
(carrier common-lisp:nil :type (common-lisp:or carrier common-lisp:null))
(tracking-number common-lisp:nil :type
(common-lisp:or tracking-number common-lisp:null))
(log-bucket common-lisp:nil :type
(common-lisp:or log-bucket common-lisp:null))
(log-key common-lisp:nil :type (common-lisp:or log-key common-lisp:null))
(error-count common-lisp:nil :type
(common-lisp:or error-count common-lisp:null))
(signature common-lisp:nil :type
(common-lisp:or signature common-lisp:null))
(signature-file-contents common-lisp:nil :type
(common-lisp:or signature common-lisp:null))
(current-manifest common-lisp:nil :type
(common-lisp:or current-manifest common-lisp:null))
(creation-date common-lisp:nil :type
(common-lisp:or creation-date common-lisp:null))
(artifact-list common-lisp:nil :type
(common-lisp:or artifact-list common-lisp:null)))
(common-lisp:export
(common-lisp:list 'get-status-output 'make-get-status-output))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input get-status-output))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input get-status-output))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-id))
(common-lisp:list
(common-lisp:cons "JobId"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-type))
(common-lisp:list
(common-lisp:cons "JobType"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'location-code))
(common-lisp:list
(common-lisp:cons "LocationCode"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'location-message))
(common-lisp:list
(common-lisp:cons "LocationMessage"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'progress-code))
(common-lisp:list
(common-lisp:cons "ProgressCode"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'progress-message))
(common-lisp:list
(common-lisp:cons "ProgressMessage"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'carrier))
(common-lisp:list
(common-lisp:cons "Carrier"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'tracking-number))
(common-lisp:list
(common-lisp:cons "TrackingNumber"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'log-bucket))
(common-lisp:list
(common-lisp:cons "LogBucket"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'log-key))
(common-lisp:list
(common-lisp:cons "LogKey"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'error-count))
(common-lisp:list
(common-lisp:cons "ErrorCount"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'signature))
(common-lisp:list
(common-lisp:cons "Signature"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input
'signature-file-contents))
(common-lisp:list
(common-lisp:cons "SignatureFileContents"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'current-manifest))
(common-lisp:list
(common-lisp:cons "CurrentManifest"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'creation-date))
(common-lisp:list
(common-lisp:cons "CreationDate"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'artifact-list))
(common-lisp:list
(common-lisp:cons "ArtifactList"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input get-status-output))
common-lisp:nil))
(common-lisp:progn
(common-lisp:define-condition invalid-access-key-id-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-access-key-id-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-access-key-id-exception
'invalid-access-key-id-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-address-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-address-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-address-exception
'invalid-address-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-customs-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-customs-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-customs-exception
'invalid-customs-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-file-system-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-file-system-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-file-system-exception
'invalid-file-system-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-job-id-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-job-id-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-job-id-exception
'invalid-job-id-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-manifest-field-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-manifest-field-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-manifest-field-exception
'invalid-manifest-field-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-parameter-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-parameter-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-parameter-exception
'invalid-parameter-exception-message)))
(common-lisp:progn
(common-lisp:define-condition invalid-version-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
invalid-version-exception-message)))
(common-lisp:export
(common-lisp:list 'invalid-version-exception
'invalid-version-exception-message)))
(common-lisp:deftype is-canceled () 'common-lisp:boolean)
(common-lisp:deftype is-truncated () 'common-lisp:boolean)
(common-lisp:progn
(common-lisp:defstruct
(job (:copier common-lisp:nil) (:conc-name "struct-shape-job-"))
(job-id common-lisp:nil :type (common-lisp:or job-id common-lisp:null))
(creation-date common-lisp:nil :type
(common-lisp:or creation-date common-lisp:null))
(is-canceled common-lisp:nil :type
(common-lisp:or is-canceled common-lisp:null))
(job-type common-lisp:nil :type (common-lisp:or job-type common-lisp:null)))
(common-lisp:export (common-lisp:list 'job 'make-job))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input job))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input job))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-id))
(common-lisp:list
(common-lisp:cons "JobId"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'creation-date))
(common-lisp:list
(common-lisp:cons "CreationDate"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'is-canceled))
(common-lisp:list
(common-lisp:cons "IsCanceled"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-type))
(common-lisp:list
(common-lisp:cons "JobType"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input job))
common-lisp:nil))
(common-lisp:deftype job-id () 'common-lisp:string)
(common-lisp:progn
(common-lisp:deftype job-id-list ()
'(trivial-types:proper-list generic-string))
(common-lisp:defun |make-job-id-list|
(common-lisp:&rest aws-sdk/generator/shape::members)
(common-lisp:check-type aws-sdk/generator/shape::members
(trivial-types:proper-list generic-string))
aws-sdk/generator/shape::members))
(common-lisp:deftype job-type () 'common-lisp:string)
(common-lisp:progn
(common-lisp:deftype jobs-list () '(trivial-types:proper-list job))
(common-lisp:defun |make-jobs-list|
(common-lisp:&rest aws-sdk/generator/shape::members)
(common-lisp:check-type aws-sdk/generator/shape::members
(trivial-types:proper-list job))
aws-sdk/generator/shape::members))
(common-lisp:progn
(common-lisp:defstruct
(list-jobs-input (:copier common-lisp:nil)
(:conc-name "struct-shape-list-jobs-input-"))
(max-jobs common-lisp:nil :type (common-lisp:or max-jobs common-lisp:null))
(marker common-lisp:nil :type (common-lisp:or marker common-lisp:null))
(apiversion common-lisp:nil :type
(common-lisp:or apiversion common-lisp:null)))
(common-lisp:export (common-lisp:list 'list-jobs-input 'make-list-jobs-input))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input list-jobs-input))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input list-jobs-input))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'max-jobs))
(common-lisp:list
(common-lisp:cons "MaxJobs"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'marker))
(common-lisp:list
(common-lisp:cons "Marker"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'apiversion))
(common-lisp:list
(common-lisp:cons "APIVersion"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input list-jobs-input))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(list-jobs-output (:copier common-lisp:nil)
(:conc-name "struct-shape-list-jobs-output-"))
(jobs common-lisp:nil :type (common-lisp:or jobs-list common-lisp:null))
(is-truncated common-lisp:nil :type
(common-lisp:or is-truncated common-lisp:null)))
(common-lisp:export
(common-lisp:list 'list-jobs-output 'make-list-jobs-output))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input list-jobs-output))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input list-jobs-output))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'jobs))
(common-lisp:list
(common-lisp:cons "Jobs"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'is-truncated))
(common-lisp:list
(common-lisp:cons "IsTruncated"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input list-jobs-output))
common-lisp:nil))
(common-lisp:deftype location-code () 'common-lisp:string)
(common-lisp:deftype location-message () 'common-lisp:string)
(common-lisp:deftype log-bucket () 'common-lisp:string)
(common-lisp:deftype log-key () 'common-lisp:string)
(common-lisp:progn
(common-lisp:define-condition malformed-manifest-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
malformed-manifest-exception-message)))
(common-lisp:export
(common-lisp:list 'malformed-manifest-exception
'malformed-manifest-exception-message)))
(common-lisp:deftype manifest () 'common-lisp:string)
(common-lisp:deftype manifest-addendum () 'common-lisp:string)
(common-lisp:deftype marker () 'common-lisp:string)
(common-lisp:deftype max-jobs () 'common-lisp:integer)
(common-lisp:progn
(common-lisp:define-condition missing-customs-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
missing-customs-exception-message)))
(common-lisp:export
(common-lisp:list 'missing-customs-exception
'missing-customs-exception-message)))
(common-lisp:progn
(common-lisp:define-condition missing-manifest-field-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
missing-manifest-field-exception-message)))
(common-lisp:export
(common-lisp:list 'missing-manifest-field-exception
'missing-manifest-field-exception-message)))
(common-lisp:progn
(common-lisp:define-condition missing-parameter-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
missing-parameter-exception-message)))
(common-lisp:export
(common-lisp:list 'missing-parameter-exception
'missing-parameter-exception-message)))
(common-lisp:progn
(common-lisp:define-condition multiple-regions-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
multiple-regions-exception-message)))
(common-lisp:export
(common-lisp:list 'multiple-regions-exception
'multiple-regions-exception-message)))
(common-lisp:progn
(common-lisp:define-condition no-such-bucket-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
no-such-bucket-exception-message)))
(common-lisp:export
(common-lisp:list 'no-such-bucket-exception
'no-such-bucket-exception-message)))
(common-lisp:deftype progress-code () 'common-lisp:string)
(common-lisp:deftype progress-message () 'common-lisp:string)
(common-lisp:deftype signature () 'common-lisp:string)
(common-lisp:deftype signature-file-contents () 'common-lisp:string)
(common-lisp:deftype success () 'common-lisp:boolean)
(common-lisp:deftype tracking-number () 'common-lisp:string)
(common-lisp:deftype url () 'common-lisp:string)
(common-lisp:progn
(common-lisp:define-condition unable-to-cancel-job-id-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
unable-to-cancel-job-id-exception-message)))
(common-lisp:export
(common-lisp:list 'unable-to-cancel-job-id-exception
'unable-to-cancel-job-id-exception-message)))
(common-lisp:progn
(common-lisp:define-condition unable-to-update-job-id-exception
(importexport-error)
((message :initarg :message :initform common-lisp:nil :reader
unable-to-update-job-id-exception-message)))
(common-lisp:export
(common-lisp:list 'unable-to-update-job-id-exception
'unable-to-update-job-id-exception-message)))
(common-lisp:progn
(common-lisp:defstruct
(update-job-input (:copier common-lisp:nil)
(:conc-name "struct-shape-update-job-input-"))
(job-id (common-lisp:error ":job-id is required") :type
(common-lisp:or job-id common-lisp:null))
(manifest (common-lisp:error ":manifest is required") :type
(common-lisp:or manifest common-lisp:null))
(job-type (common-lisp:error ":job-type is required") :type
(common-lisp:or job-type common-lisp:null))
(validate-only (common-lisp:error ":validate-only is required") :type
(common-lisp:or validate-only common-lisp:null))
(apiversion common-lisp:nil :type
(common-lisp:or apiversion common-lisp:null)))
(common-lisp:export
(common-lisp:list 'update-job-input 'make-update-job-input))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input update-job-input))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input update-job-input))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-id))
(common-lisp:list
(common-lisp:cons "JobId"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'manifest))
(common-lisp:list
(common-lisp:cons "Manifest"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'job-type))
(common-lisp:list
(common-lisp:cons "JobType"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'validate-only))
(common-lisp:list
(common-lisp:cons "ValidateOnly"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'apiversion))
(common-lisp:list
(common-lisp:cons "APIVersion"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input update-job-input))
common-lisp:nil))
(common-lisp:progn
(common-lisp:defstruct
(update-job-output (:copier common-lisp:nil)
(:conc-name "struct-shape-update-job-output-"))
(success common-lisp:nil :type (common-lisp:or success common-lisp:null))
(warning-message common-lisp:nil :type
(common-lisp:or warning-message common-lisp:null))
(artifact-list common-lisp:nil :type
(common-lisp:or artifact-list common-lisp:null)))
(common-lisp:export
(common-lisp:list 'update-job-output 'make-update-job-output))
(common-lisp:defmethod aws-sdk/generator/shape::input-headers
((aws-sdk/generator/shape::input update-job-output))
(common-lisp:append))
(common-lisp:defmethod aws-sdk/generator/shape::input-params
((aws-sdk/generator/shape::input update-job-output))
(common-lisp:append
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'success))
(common-lisp:list
(common-lisp:cons "Success"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'warning-message))
(common-lisp:list
(common-lisp:cons "WarningMessage"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))
(alexandria:when-let (aws-sdk/generator/shape::value
(common-lisp:slot-value
aws-sdk/generator/shape::input 'artifact-list))
(common-lisp:list
(common-lisp:cons "ArtifactList"
(aws-sdk/generator/shape::input-params
aws-sdk/generator/shape::value))))))
(common-lisp:defmethod aws-sdk/generator/shape::input-payload
((aws-sdk/generator/shape::input update-job-output))
common-lisp:nil))
(common-lisp:deftype validate-only () 'common-lisp:boolean)
(common-lisp:deftype warning-message () 'common-lisp:string)
(common-lisp:deftype |city| () 'common-lisp:string)
(common-lisp:deftype |company| () 'common-lisp:string)
(common-lisp:deftype |country| () 'common-lisp:string)
(common-lisp:deftype |name| () 'common-lisp:string)
(common-lisp:deftype |phoneNumber| () 'common-lisp:string)
(common-lisp:deftype |postalCode| () 'common-lisp:string)
(common-lisp:deftype |stateOrProvince| () 'common-lisp:string)
(common-lisp:deftype |street1| () 'common-lisp:string)
(common-lisp:deftype |street2| () 'common-lisp:string)
(common-lisp:deftype |street3| () 'common-lisp:string)
(common-lisp:progn
(common-lisp:defun cancel-job
(
common-lisp:&rest aws-sdk/generator/operation::args
common-lisp:&key job-id apiversion)
(common-lisp:declare (common-lisp:ignorable job-id apiversion))
(common-lisp:let ((aws-sdk/generator/operation::input
(common-lisp:apply 'make-cancel-job-input
aws-sdk/generator/operation::args)))
(aws-sdk/generator/operation::parse-response
(aws-sdk/api:aws-request
(aws-sdk/generator/shape:make-request-with-input 'importexport-request
aws-sdk/generator/operation::input
"POST"
"/?Operation=CancelJob"
"CancelJob"
"2010-06-01"))
common-lisp:nil "CancelJobResult" *error-map*)))
(common-lisp:export 'cancel-job))
(common-lisp:progn
(common-lisp:defun create-job
(
common-lisp:&rest aws-sdk/generator/operation::args
common-lisp:&key job-type manifest manifest-addendum
validate-only apiversion)
(common-lisp:declare
(common-lisp:ignorable job-type manifest manifest-addendum validate-only
apiversion))
(common-lisp:let ((aws-sdk/generator/operation::input
(common-lisp:apply 'make-create-job-input
aws-sdk/generator/operation::args)))
(aws-sdk/generator/operation::parse-response
(aws-sdk/api:aws-request
(aws-sdk/generator/shape:make-request-with-input 'importexport-request
aws-sdk/generator/operation::input
"POST"
"/?Operation=CreateJob"
"CreateJob"
"2010-06-01"))
common-lisp:nil "CreateJobResult" *error-map*)))
(common-lisp:export 'create-job))
(common-lisp:progn
(common-lisp:defun get-shipping-label
(
common-lisp:&rest aws-sdk/generator/operation::args
common-lisp:&key job-ids name company phone-number country
state-or-province city postal-code street1 street2 street3
apiversion)
(common-lisp:declare
(common-lisp:ignorable job-ids name company phone-number country
state-or-province city postal-code street1 street2 street3 apiversion))
(common-lisp:let ((aws-sdk/generator/operation::input
(common-lisp:apply 'make-get-shipping-label-input
aws-sdk/generator/operation::args)))
(aws-sdk/generator/operation::parse-response
(aws-sdk/api:aws-request
(aws-sdk/generator/shape:make-request-with-input 'importexport-request
aws-sdk/generator/operation::input
"POST"
"/?Operation=GetShippingLabel"
"GetShippingLabel"
"2010-06-01"))
common-lisp:nil "GetShippingLabelResult" *error-map*)))
(common-lisp:export 'get-shipping-label))
(common-lisp:progn
(common-lisp:defun get-status
(
common-lisp:&rest aws-sdk/generator/operation::args
common-lisp:&key job-id apiversion)
(common-lisp:declare (common-lisp:ignorable job-id apiversion))
(common-lisp:let ((aws-sdk/generator/operation::input
(common-lisp:apply 'make-get-status-input
aws-sdk/generator/operation::args)))
(aws-sdk/generator/operation::parse-response
(aws-sdk/api:aws-request
(aws-sdk/generator/shape:make-request-with-input 'importexport-request
aws-sdk/generator/operation::input
"POST"
"/?Operation=GetStatus"
"GetStatus"
"2010-06-01"))
common-lisp:nil "GetStatusResult" *error-map*)))
(common-lisp:export 'get-status))
(common-lisp:progn
(common-lisp:defun list-jobs
(
common-lisp:&rest aws-sdk/generator/operation::args
common-lisp:&key max-jobs marker apiversion)
(common-lisp:declare (common-lisp:ignorable max-jobs marker apiversion))
(common-lisp:let ((aws-sdk/generator/operation::input
(common-lisp:apply 'make-list-jobs-input
aws-sdk/generator/operation::args)))
(aws-sdk/generator/operation::parse-response
(aws-sdk/api:aws-request
(aws-sdk/generator/shape:make-request-with-input 'importexport-request
aws-sdk/generator/operation::input
"POST"
"/?Operation=ListJobs"
"ListJobs"
"2010-06-01"))
common-lisp:nil "ListJobsResult" *error-map*)))
(common-lisp:export 'list-jobs))
(common-lisp:progn
(common-lisp:defun update-job
(
common-lisp:&rest aws-sdk/generator/operation::args
common-lisp:&key job-id manifest job-type validate-only
apiversion)
(common-lisp:declare
(common-lisp:ignorable job-id manifest job-type validate-only apiversion))
(common-lisp:let ((aws-sdk/generator/operation::input
(common-lisp:apply 'make-update-job-input
aws-sdk/generator/operation::args)))
(aws-sdk/generator/operation::parse-response
(aws-sdk/api:aws-request
(aws-sdk/generator/shape:make-request-with-input 'importexport-request
aws-sdk/generator/operation::input
"POST"
"/?Operation=UpdateJob"
"UpdateJob"
"2010-06-01"))
common-lisp:nil "UpdateJobResult" *error-map*)))
(common-lisp:export 'update-job))
|
94343fff8434cd1c5de6c7f9022ad488151881320142463d455f5343404aea35 | well-typed/optics | Optics.hs | -- |
-- Module: Numeric.Optics
-- Description: Optics for working with numeric types.
--
module Numeric.Optics
( base
, integral
-- * Predefined bases
, binary
, octal
, decimal
, hex
-- * Arithmetic lenses
, adding
, subtracting
, multiplying
, dividing
, exponentiating
, negated
, pattern Integral
) where
import Data.Char (chr, ord, isAsciiLower, isAsciiUpper, isDigit)
import Data.Maybe (fromMaybe)
import GHC.Stack
import Numeric (readInt, showIntAtBase)
import Data.Tuple.Optics
import Optics.AffineFold
import Optics.Iso
import Optics.Optic
import Optics.Prism
import Optics.Review
import Optics.Setter
| This ' Prism ' can be used to model the fact that every ' Prelude . Integral '
type is a subset of ' Integer ' .
--
Embedding through the ' Prism ' only succeeds if the ' Integer ' would pass
-- through unmodified when re-extracted.
integral :: (Integral a, Integral b) => Prism Integer Integer a b
integral = prism toInteger $ \i -> let a = fromInteger i in
if toInteger a == i
then Right a
else Left i
# INLINE integral #
-- | Pattern synonym that can be used to construct or pattern match on an
' Integer ' as if it were of any ' Prelude . Integral ' type .
pattern Integral :: forall a. Integral a => a -> Integer
pattern Integral a <- (preview integral -> Just a) where
Integral a = review integral a
| A prism that shows and reads integers in base-2 through base-36
--
Note : This is an improper prism , since leading 0s are stripped when reading .
--
> > > " 100 " ^ ? base 16
-- Just 256
--
> > > 1767707668033969 ^. re ( base 36 )
-- "helloworld"
base :: (HasCallStack, Integral a) => Int -> Prism' String a
base b
| b < 2 || b > 36 = error ("base: Invalid base " ++ show b)
| otherwise = prism intShow intRead
where
intShow n = showSigned' (showIntAtBase (toInteger b) intToDigit') (toInteger n) ""
intRead s =
case readSigned' (readInt (fromIntegral b) (isDigit' b) digitToInt') s of
[(n,"")] -> Right n
_ -> Left s
# INLINE base #
| Like ' Data . Char.intToDigit ' , but handles up to base-36
intToDigit' :: HasCallStack => Int -> Char
intToDigit' i
| i >= 0 && i < 10 = chr (ord '0' + i)
| i >= 10 && i < 36 = chr (ord 'a' + i - 10)
| otherwise = error ("intToDigit': Invalid int " ++ show i)
# INLINE intToDigit ' #
| Like ' Data . Char.digitToInt ' , but handles up to base-36
digitToInt' :: HasCallStack => Char -> Int
digitToInt' c = fromMaybe (error ("digitToInt': Invalid digit " ++ show c))
(digitToIntMay c)
# INLINE digitToInt ' #
-- | A safe variant of 'digitToInt''
digitToIntMay :: Char -> Maybe Int
digitToIntMay c
| isDigit c = Just (ord c - ord '0')
| isAsciiLower c = Just (ord c - ord 'a' + 10)
| isAsciiUpper c = Just (ord c - ord 'A' + 10)
| otherwise = Nothing
# INLINE digitToIntMay #
-- | Select digits that fall into the given base
isDigit' :: Int -> Char -> Bool
isDigit' b c = case digitToIntMay c of
Just i -> i < b
_ -> False
{-# INLINE isDigit' #-}
| A simpler variant of ' Numeric.showSigned ' that only prepends a dash and
-- doesn't know about parentheses
showSigned' :: Real a => (a -> ShowS) -> a -> ShowS
showSigned' f n
| n < 0 = showChar '-' . f (negate n)
| otherwise = f n
{-# INLINE showSigned' #-}
-- | A simpler variant of 'Numeric.readSigned' that supports any base, only
-- recognizes an initial dash and doesn't know about parentheses
readSigned' :: Real a => ReadS a -> ReadS a
readSigned' f ('-':xs) = f xs <&> over _1 negate
readSigned' f xs = f xs
{-# INLINE readSigned' #-}
| @'binary ' = ' base ' 2@
binary :: Integral a => Prism' String a
binary = base 2
# INLINE binary #
| @'octal ' = ' base ' 8@
octal :: Integral a => Prism' String a
octal = base 8
# INLINE octal #
| @'decimal ' = ' base ' 10@
decimal :: Integral a => Prism' String a
decimal = base 10
# INLINE decimal #
| @'hex ' = ' base ' 16@
hex :: Integral a => Prism' String a
hex = base 16
# INLINE hex #
-- | @'adding' n = 'iso' (+n) (subtract n)@
--
> > > [ 1 .. 3 ] ^ .. traversed % adding 1000
-- [1001,1002,1003]
adding :: Num a => a -> Iso' a a
adding n = iso (+n) (subtract n)
# INLINE adding #
-- | @
-- 'subtracting' n = 'iso' (subtract n) ((+n)
-- 'subtracting' n = 'Optics.Re.re' ('adding' n)
-- @
subtracting :: Num a => a -> Iso' a a
subtracting n = iso (subtract n) (+n)
# INLINE subtracting #
-- | @'multiplying' n = iso (*n) (/n)@
--
Note : This errors for n = 0
--
> > > 5 & multiplying 1000 % ~ ( +3 )
5.003
--
> > > let = multiplying ( 9/5 ) % adding 32 in 230 ^. re fahrenheit
110.0
multiplying :: (Fractional a, Eq a) => a -> Iso' a a
multiplying 0 = error "Numeric.Optics.multiplying: factor 0"
multiplying n = iso (*n) (/n)
# INLINE multiplying #
-- | @
-- 'dividing' n = 'iso' (/n) (*n)
-- 'dividing' n = 'Optics.Re.re' ('multiplying' n)@
--
Note : This errors for n = 0
dividing :: (Fractional a, Eq a) => a -> Iso' a a
dividing 0 = error "Numeric.Optics.dividing: divisor 0"
dividing n = iso (/n) (*n)
# INLINE dividing #
| @'exponentiating ' n = ' iso ' ( * * n ) ( * * recip
--
Note : This errors for n = 0
--
> > > au ( coerced1 @Sum % re ( exponentiating 2 ) ) ( foldMapOf each ) ( 3,4 ) = = 5
-- True
exponentiating :: (Floating a, Eq a) => a -> Iso' a a
exponentiating 0 = error "Numeric.Optics.exponentiating: exponent 0"
exponentiating n = iso (**n) (**recip n)
# INLINE exponentiating #
| @'negated ' = ' iso ' ' negate ' ' negate'@
--
> > > au ( coerced1 @Sum % negated ) ( foldMapOf each ) ( 3,4 ) = = 7
-- True
--
> > > au ( @Sum ) ( foldMapOf ( each % negated ) ) ( 3,4 ) = = -7
-- True
negated :: Num a => Iso' a a
negated = iso negate negate
# INLINE negated #
-- $setup
> > > import Data . Monoid
> > > import Optics . Core
| null | https://raw.githubusercontent.com/well-typed/optics/ba3c5a4d2f110c82238bc2fe7bb187023ab516f5/optics-core/src/Numeric/Optics.hs | haskell | |
Module: Numeric.Optics
Description: Optics for working with numeric types.
* Predefined bases
* Arithmetic lenses
through unmodified when re-extracted.
| Pattern synonym that can be used to construct or pattern match on an
Just 256
"helloworld"
| A safe variant of 'digitToInt''
| Select digits that fall into the given base
# INLINE isDigit' #
doesn't know about parentheses
# INLINE showSigned' #
| A simpler variant of 'Numeric.readSigned' that supports any base, only
recognizes an initial dash and doesn't know about parentheses
# INLINE readSigned' #
| @'adding' n = 'iso' (+n) (subtract n)@
[1001,1002,1003]
| @
'subtracting' n = 'iso' (subtract n) ((+n)
'subtracting' n = 'Optics.Re.re' ('adding' n)
@
| @'multiplying' n = iso (*n) (/n)@
| @
'dividing' n = 'iso' (/n) (*n)
'dividing' n = 'Optics.Re.re' ('multiplying' n)@
True
True
True
$setup | module Numeric.Optics
( base
, integral
, binary
, octal
, decimal
, hex
, adding
, subtracting
, multiplying
, dividing
, exponentiating
, negated
, pattern Integral
) where
import Data.Char (chr, ord, isAsciiLower, isAsciiUpper, isDigit)
import Data.Maybe (fromMaybe)
import GHC.Stack
import Numeric (readInt, showIntAtBase)
import Data.Tuple.Optics
import Optics.AffineFold
import Optics.Iso
import Optics.Optic
import Optics.Prism
import Optics.Review
import Optics.Setter
| This ' Prism ' can be used to model the fact that every ' Prelude . Integral '
type is a subset of ' Integer ' .
Embedding through the ' Prism ' only succeeds if the ' Integer ' would pass
integral :: (Integral a, Integral b) => Prism Integer Integer a b
integral = prism toInteger $ \i -> let a = fromInteger i in
if toInteger a == i
then Right a
else Left i
# INLINE integral #
' Integer ' as if it were of any ' Prelude . Integral ' type .
pattern Integral :: forall a. Integral a => a -> Integer
pattern Integral a <- (preview integral -> Just a) where
Integral a = review integral a
| A prism that shows and reads integers in base-2 through base-36
Note : This is an improper prism , since leading 0s are stripped when reading .
> > > " 100 " ^ ? base 16
> > > 1767707668033969 ^. re ( base 36 )
base :: (HasCallStack, Integral a) => Int -> Prism' String a
base b
| b < 2 || b > 36 = error ("base: Invalid base " ++ show b)
| otherwise = prism intShow intRead
where
intShow n = showSigned' (showIntAtBase (toInteger b) intToDigit') (toInteger n) ""
intRead s =
case readSigned' (readInt (fromIntegral b) (isDigit' b) digitToInt') s of
[(n,"")] -> Right n
_ -> Left s
# INLINE base #
| Like ' Data . Char.intToDigit ' , but handles up to base-36
intToDigit' :: HasCallStack => Int -> Char
intToDigit' i
| i >= 0 && i < 10 = chr (ord '0' + i)
| i >= 10 && i < 36 = chr (ord 'a' + i - 10)
| otherwise = error ("intToDigit': Invalid int " ++ show i)
# INLINE intToDigit ' #
| Like ' Data . Char.digitToInt ' , but handles up to base-36
digitToInt' :: HasCallStack => Char -> Int
digitToInt' c = fromMaybe (error ("digitToInt': Invalid digit " ++ show c))
(digitToIntMay c)
# INLINE digitToInt ' #
digitToIntMay :: Char -> Maybe Int
digitToIntMay c
| isDigit c = Just (ord c - ord '0')
| isAsciiLower c = Just (ord c - ord 'a' + 10)
| isAsciiUpper c = Just (ord c - ord 'A' + 10)
| otherwise = Nothing
# INLINE digitToIntMay #
isDigit' :: Int -> Char -> Bool
isDigit' b c = case digitToIntMay c of
Just i -> i < b
_ -> False
| A simpler variant of ' Numeric.showSigned ' that only prepends a dash and
showSigned' :: Real a => (a -> ShowS) -> a -> ShowS
showSigned' f n
| n < 0 = showChar '-' . f (negate n)
| otherwise = f n
readSigned' :: Real a => ReadS a -> ReadS a
readSigned' f ('-':xs) = f xs <&> over _1 negate
readSigned' f xs = f xs
| @'binary ' = ' base ' 2@
binary :: Integral a => Prism' String a
binary = base 2
# INLINE binary #
| @'octal ' = ' base ' 8@
octal :: Integral a => Prism' String a
octal = base 8
# INLINE octal #
| @'decimal ' = ' base ' 10@
decimal :: Integral a => Prism' String a
decimal = base 10
# INLINE decimal #
| @'hex ' = ' base ' 16@
hex :: Integral a => Prism' String a
hex = base 16
# INLINE hex #
> > > [ 1 .. 3 ] ^ .. traversed % adding 1000
adding :: Num a => a -> Iso' a a
adding n = iso (+n) (subtract n)
# INLINE adding #
subtracting :: Num a => a -> Iso' a a
subtracting n = iso (subtract n) (+n)
# INLINE subtracting #
Note : This errors for n = 0
> > > 5 & multiplying 1000 % ~ ( +3 )
5.003
> > > let = multiplying ( 9/5 ) % adding 32 in 230 ^. re fahrenheit
110.0
multiplying :: (Fractional a, Eq a) => a -> Iso' a a
multiplying 0 = error "Numeric.Optics.multiplying: factor 0"
multiplying n = iso (*n) (/n)
# INLINE multiplying #
Note : This errors for n = 0
dividing :: (Fractional a, Eq a) => a -> Iso' a a
dividing 0 = error "Numeric.Optics.dividing: divisor 0"
dividing n = iso (/n) (*n)
# INLINE dividing #
| @'exponentiating ' n = ' iso ' ( * * n ) ( * * recip
Note : This errors for n = 0
> > > au ( coerced1 @Sum % re ( exponentiating 2 ) ) ( foldMapOf each ) ( 3,4 ) = = 5
exponentiating :: (Floating a, Eq a) => a -> Iso' a a
exponentiating 0 = error "Numeric.Optics.exponentiating: exponent 0"
exponentiating n = iso (**n) (**recip n)
# INLINE exponentiating #
| @'negated ' = ' iso ' ' negate ' ' negate'@
> > > au ( coerced1 @Sum % negated ) ( foldMapOf each ) ( 3,4 ) = = 7
> > > au ( @Sum ) ( foldMapOf ( each % negated ) ) ( 3,4 ) = = -7
negated :: Num a => Iso' a a
negated = iso negate negate
# INLINE negated #
> > > import Data . Monoid
> > > import Optics . Core
|
5de21bd59346c464392fcfc97b046331690baeae2ef8aa1a150906b3d5945d03 | inhabitedtype/ocaml-aws | describeDBProxyTargetGroups.ml | open Types
open Aws
type input = DescribeDBProxyTargetGroupsRequest.t
type output = DescribeDBProxyTargetGroupsResponse.t
type error = Errors_internal.t
let service = "rds"
let signature_version = Request.V4
let to_http service region req =
let uri =
Uri.add_query_params
(Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region)))
(List.append
[ "Version", [ "2014-10-31" ]; "Action", [ "DescribeDBProxyTargetGroups" ] ]
(Util.drop_empty
(Uri.query_of_encoded
(Query.render (DescribeDBProxyTargetGroupsRequest.to_query req)))))
in
`POST, uri, []
let of_http body =
try
let xml = Ezxmlm.from_string body in
let resp =
Util.option_bind
(Xml.member "DescribeDBProxyTargetGroupsResponse" (snd xml))
(Xml.member "DescribeDBProxyTargetGroupsResult")
in
try
Util.or_error
(Util.option_bind resp DescribeDBProxyTargetGroupsResponse.parse)
(let open Error in
BadResponse
{ body
; message = "Could not find well formed DescribeDBProxyTargetGroupsResponse."
})
with Xml.RequiredFieldMissing msg ->
let open Error in
`Error
(BadResponse
{ body
; message =
"Error parsing DescribeDBProxyTargetGroupsResponse - missing field in \
body or children: "
^ msg
})
with Failure msg ->
`Error
(let open Error in
BadResponse { body; message = "Error parsing xml: " ^ msg })
let parse_error code err =
let errors = [] @ Errors_internal.common in
match Errors_internal.of_string err with
| Some var ->
if List.mem var errors
&&
match Errors_internal.to_http_code var with
| Some var -> var = code
| None -> true
then Some var
else None
| None -> None
| null | https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/rds/lib/describeDBProxyTargetGroups.ml | ocaml | open Types
open Aws
type input = DescribeDBProxyTargetGroupsRequest.t
type output = DescribeDBProxyTargetGroupsResponse.t
type error = Errors_internal.t
let service = "rds"
let signature_version = Request.V4
let to_http service region req =
let uri =
Uri.add_query_params
(Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region)))
(List.append
[ "Version", [ "2014-10-31" ]; "Action", [ "DescribeDBProxyTargetGroups" ] ]
(Util.drop_empty
(Uri.query_of_encoded
(Query.render (DescribeDBProxyTargetGroupsRequest.to_query req)))))
in
`POST, uri, []
let of_http body =
try
let xml = Ezxmlm.from_string body in
let resp =
Util.option_bind
(Xml.member "DescribeDBProxyTargetGroupsResponse" (snd xml))
(Xml.member "DescribeDBProxyTargetGroupsResult")
in
try
Util.or_error
(Util.option_bind resp DescribeDBProxyTargetGroupsResponse.parse)
(let open Error in
BadResponse
{ body
; message = "Could not find well formed DescribeDBProxyTargetGroupsResponse."
})
with Xml.RequiredFieldMissing msg ->
let open Error in
`Error
(BadResponse
{ body
; message =
"Error parsing DescribeDBProxyTargetGroupsResponse - missing field in \
body or children: "
^ msg
})
with Failure msg ->
`Error
(let open Error in
BadResponse { body; message = "Error parsing xml: " ^ msg })
let parse_error code err =
let errors = [] @ Errors_internal.common in
match Errors_internal.of_string err with
| Some var ->
if List.mem var errors
&&
match Errors_internal.to_http_code var with
| Some var -> var = code
| None -> true
then Some var
else None
| None -> None
| |
36a866aae57276a94b113881618bbeeaeb360d9ae9c5e7af9ebc12fa2d004047 | grin-compiler/ghc-grin | Main.hs | # LANGUAGE ScopedTypeVariables #
import Control.Monad
import Data.Maybe
import Data.List (sortBy)
import Data.Monoid
import Data.Ord
import Options.Applicative
import Text.PrettyPrint.ANSI.Leijen hiding ((<$>), (<>))
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import qualified Data.ByteString.Char8 as BS8
import Stg.Syntax
import Stg.Pretty
import Stg.Util
modes :: Parser (IO ())
modes = subparser
( mode "show" showMode (progDesc "print Stg")
<> mode "show-prep-core" showPCoreMode (progDesc "print prep Core")
<> mode "show-core" showCoreMode (progDesc "print Core")
<> mode "show-ghc-stg" showGHCStgMode (progDesc "print GHC Stg")
)
where
mode :: String -> Parser a -> InfoMod a -> Mod CommandFields a
mode name f opts = command name (info (helper <*> f) opts)
dumpFile :: Parser FilePath
dumpFile = argument str (metavar "DUMP FILE" <> help "STGBIN dump file")
showMode :: Parser (IO ())
showMode =
run <$> dumpFile
where
run fname = do
dump <- Stg.Util.readStgbin fname
print $ pprModule dump
showPCoreMode :: Parser (IO ())
showPCoreMode =
run <$> dumpFile
where
run fname = do
dump <- Stg.Util.readStgbin fname
putStrLn . BS8.unpack . modulePrepCoreSrc $ dump
showCoreMode :: Parser (IO ())
showCoreMode =
run <$> dumpFile
where
run fname = do
dump <- Stg.Util.readStgbin fname
putStrLn . BS8.unpack . moduleCoreSrc $ dump
showGHCStgMode :: Parser (IO ())
showGHCStgMode =
run <$> dumpFile
where
run fname = do
dump <- Stg.Util.readStgbin fname
putStrLn . BS8.unpack . moduleStgSrc $ dump
main :: IO ()
main = join $ execParser $ info (helper <*> modes) mempty
| null | https://raw.githubusercontent.com/grin-compiler/ghc-grin/ebc4dca2e1f5b3581d4b84726730564ce909d786/external-stg-util/app/Main.hs | haskell | # LANGUAGE ScopedTypeVariables #
import Control.Monad
import Data.Maybe
import Data.List (sortBy)
import Data.Monoid
import Data.Ord
import Options.Applicative
import Text.PrettyPrint.ANSI.Leijen hiding ((<$>), (<>))
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import qualified Data.ByteString.Char8 as BS8
import Stg.Syntax
import Stg.Pretty
import Stg.Util
modes :: Parser (IO ())
modes = subparser
( mode "show" showMode (progDesc "print Stg")
<> mode "show-prep-core" showPCoreMode (progDesc "print prep Core")
<> mode "show-core" showCoreMode (progDesc "print Core")
<> mode "show-ghc-stg" showGHCStgMode (progDesc "print GHC Stg")
)
where
mode :: String -> Parser a -> InfoMod a -> Mod CommandFields a
mode name f opts = command name (info (helper <*> f) opts)
dumpFile :: Parser FilePath
dumpFile = argument str (metavar "DUMP FILE" <> help "STGBIN dump file")
showMode :: Parser (IO ())
showMode =
run <$> dumpFile
where
run fname = do
dump <- Stg.Util.readStgbin fname
print $ pprModule dump
showPCoreMode :: Parser (IO ())
showPCoreMode =
run <$> dumpFile
where
run fname = do
dump <- Stg.Util.readStgbin fname
putStrLn . BS8.unpack . modulePrepCoreSrc $ dump
showCoreMode :: Parser (IO ())
showCoreMode =
run <$> dumpFile
where
run fname = do
dump <- Stg.Util.readStgbin fname
putStrLn . BS8.unpack . moduleCoreSrc $ dump
showGHCStgMode :: Parser (IO ())
showGHCStgMode =
run <$> dumpFile
where
run fname = do
dump <- Stg.Util.readStgbin fname
putStrLn . BS8.unpack . moduleStgSrc $ dump
main :: IO ()
main = join $ execParser $ info (helper <*> modes) mempty
| |
7eb1377b9969ff603c9990a1585d93e0269296353aff850ac9939a7ec6bf7066 | tsloughter/kuberl | kuberl_v1beta1_event.erl | -module(kuberl_v1beta1_event).
-export([encode/1]).
-export_type([kuberl_v1beta1_event/0]).
-type kuberl_v1beta1_event() ::
#{ 'action' => binary(),
'apiVersion' => binary(),
'deprecatedCount' => integer(),
'deprecatedFirstTimestamp' => kuberl_date_time:kuberl_date_time(),
'deprecatedLastTimestamp' => kuberl_date_time:kuberl_date_time(),
'deprecatedSource' => kuberl_v1_event_source:kuberl_v1_event_source(),
'eventTime' := kuberl_date_time:kuberl_date_time(),
'kind' => binary(),
'metadata' => kuberl_v1_object_meta:kuberl_v1_object_meta(),
'note' => binary(),
'reason' => binary(),
'regarding' => kuberl_v1_object_reference:kuberl_v1_object_reference(),
'related' => kuberl_v1_object_reference:kuberl_v1_object_reference(),
'reportingController' => binary(),
'reportingInstance' => binary(),
'series' => kuberl_v1beta1_event_series:kuberl_v1beta1_event_series(),
'type' => binary()
}.
encode(#{ 'action' := Action,
'apiVersion' := ApiVersion,
'deprecatedCount' := DeprecatedCount,
'deprecatedFirstTimestamp' := DeprecatedFirstTimestamp,
'deprecatedLastTimestamp' := DeprecatedLastTimestamp,
'deprecatedSource' := DeprecatedSource,
'eventTime' := EventTime,
'kind' := Kind,
'metadata' := Metadata,
'note' := Note,
'reason' := Reason,
'regarding' := Regarding,
'related' := Related,
'reportingController' := ReportingController,
'reportingInstance' := ReportingInstance,
'series' := Series,
'type' := Type
}) ->
#{ 'action' => Action,
'apiVersion' => ApiVersion,
'deprecatedCount' => DeprecatedCount,
'deprecatedFirstTimestamp' => DeprecatedFirstTimestamp,
'deprecatedLastTimestamp' => DeprecatedLastTimestamp,
'deprecatedSource' => DeprecatedSource,
'eventTime' => EventTime,
'kind' => Kind,
'metadata' => Metadata,
'note' => Note,
'reason' => Reason,
'regarding' => Regarding,
'related' => Related,
'reportingController' => ReportingController,
'reportingInstance' => ReportingInstance,
'series' => Series,
'type' => Type
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1beta1_event.erl | erlang | -module(kuberl_v1beta1_event).
-export([encode/1]).
-export_type([kuberl_v1beta1_event/0]).
-type kuberl_v1beta1_event() ::
#{ 'action' => binary(),
'apiVersion' => binary(),
'deprecatedCount' => integer(),
'deprecatedFirstTimestamp' => kuberl_date_time:kuberl_date_time(),
'deprecatedLastTimestamp' => kuberl_date_time:kuberl_date_time(),
'deprecatedSource' => kuberl_v1_event_source:kuberl_v1_event_source(),
'eventTime' := kuberl_date_time:kuberl_date_time(),
'kind' => binary(),
'metadata' => kuberl_v1_object_meta:kuberl_v1_object_meta(),
'note' => binary(),
'reason' => binary(),
'regarding' => kuberl_v1_object_reference:kuberl_v1_object_reference(),
'related' => kuberl_v1_object_reference:kuberl_v1_object_reference(),
'reportingController' => binary(),
'reportingInstance' => binary(),
'series' => kuberl_v1beta1_event_series:kuberl_v1beta1_event_series(),
'type' => binary()
}.
encode(#{ 'action' := Action,
'apiVersion' := ApiVersion,
'deprecatedCount' := DeprecatedCount,
'deprecatedFirstTimestamp' := DeprecatedFirstTimestamp,
'deprecatedLastTimestamp' := DeprecatedLastTimestamp,
'deprecatedSource' := DeprecatedSource,
'eventTime' := EventTime,
'kind' := Kind,
'metadata' := Metadata,
'note' := Note,
'reason' := Reason,
'regarding' := Regarding,
'related' := Related,
'reportingController' := ReportingController,
'reportingInstance' := ReportingInstance,
'series' := Series,
'type' := Type
}) ->
#{ 'action' => Action,
'apiVersion' => ApiVersion,
'deprecatedCount' => DeprecatedCount,
'deprecatedFirstTimestamp' => DeprecatedFirstTimestamp,
'deprecatedLastTimestamp' => DeprecatedLastTimestamp,
'deprecatedSource' => DeprecatedSource,
'eventTime' => EventTime,
'kind' => Kind,
'metadata' => Metadata,
'note' => Note,
'reason' => Reason,
'regarding' => Regarding,
'related' => Related,
'reportingController' => ReportingController,
'reportingInstance' => ReportingInstance,
'series' => Series,
'type' => Type
}.
| |
e77c56d8f2f54f99fed2aa3f7895d18bd92cda6ecfe1fba75f12d3eb9873face | byorgey/AoC | 17.hs | #!/usr/bin/env stack
stack --resolver lts-19.28 script --package containers --package split --package lens --package mtl --package array
# LANGUAGE FlexibleContexts #
{-# LANGUAGE LambdaCase #-}
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
import Control.Arrow (first, (***), (>>>))
import Control.Lens (imap, makeLenses, use, (%=), (+=), (-=),
(.=), (<-=), (^.))
import Control.Monad.State
import Data.Array
import Data.List (foldl')
import Data.List.Split (splitOn)
import Data.Maybe (fromMaybe)
import Data.Set (Set)
import qualified Data.Set as S
------------------------------------------------------------
type Coord = (Int,Int)
above, below, left, right :: Coord -> Coord
above (r,c) = (r-1,c)
below (r,c) = (r+1,c)
left (r,c) = (r,c-1)
right (r,c) = (r,c+1)
applyAll :: [a -> b] -> a -> [b]
applyAll fs a = map ($ a) fs
infixr 0 >$>
(>$>) = flip ($)
------------------------------------------------------------
type Jet = Char
type Jets = [Jet]
type Rock = [Coord]
readRocks :: FilePath -> IO [Rock]
readRocks rocksFile = do
f <- readFile rocksFile
return $ f >$> lines >>> splitOn [""] >>> map readRock
readRock :: [String] -> Rock
readRock = imap (\r -> imap (\c -> ((r,c),))) >>> concat >>> filter (snd >>> (=='#')) >>> map fst
data Board = Board { _topRow :: Int, _filled :: Set Coord } deriving (Eq, Show)
makeLenses ''Board
showBoard :: Jet -> Maybe Rock -> Maybe Int -> Board -> String
showBoard j mr mt (Board tr cs) = unlines $
[ show tr ]
++
[ lt : [ showCell (r,c) | c <- [1..7]] ++ [rt] | r <- [tr', tr'+1 .. maybe (-1) (tr'+) mt] ]
++
["+-------+"]
where
rock = fromMaybe [] mr
tr' = case rock of { [] -> tr; _ -> min tr (minimum . map fst $ rock) }
lt = if j == '>' then j else '|'
rt = if j == '<' then j else '|'
showCell p
| p `elem` rock = '@'
| p `S.member` cs = '#'
| otherwise = '.'
emptyBoard :: Board
emptyBoard = Board 0 S.empty
initRockPosition :: Board -> Rock -> Rock
initRockPosition b r = map ((+ (b ^. topRow - 4 - maxRow)) *** (+3)) r
where
maxRow = maximum . map fst $ r
------------------------------------------------------------
data St = St
{ _curJets :: Jets
, _curBoard :: Board
, _rockArray :: Array Int Rock
, _rockIndex :: Int
, _rocksLeft :: Int
, _jetCycle :: Int
, _rockCount :: Int
, _prevCycleRockCount :: Int
, _prevCycleHeight :: Int
, _savedHeight :: Int
}
deriving (Eq, Show)
makeLenses ''St
initSt :: Jets -> Int -> [Rock] -> St
initSt js n rocks =
St js emptyBoard (listArray (0,length rocks - 1) rocks) 0 n (-1) 0 0 0 0
showSt :: Maybe Int -> Maybe Rock -> St -> String
showSt mt mr st = showBoard (head (st ^. curJets)) mr mt (st ^. curBoard)
nextJet :: State St (Coord -> Coord)
nextJet = do
js <- use curJets
curJets %= tail
case head js of
' ' -> do
jetCycle += 1
nextJet
'<' -> return left
_ -> return right
sim :: Int -> [Rock] -> Jets -> St
sim n rocks js = execState runSim (initSt js n rocks)
runSim :: State St ()
runSim = do
b <- use curBoard
i <- use rockIndex
rs <- use rockArray
let r = rs!i
fall (initRockPosition b r)
rockCount += 1
rockIndex += 1
rockIndex %= (`mod` (snd (bounds rs) + 1))
rl <- rocksLeft <-= 1
case rl > 0 of
True -> runSim
False -> do
p <- use prevCycleHeight
h <- height
savedHeight += (h - p)
height :: State St Int
height = negate <$> use (curBoard . topRow)
fall :: Rock -> State St ()
fall r0 = do
js <- use curJets
when (head js == ' ') $ do
st <- get
prevR <- use prevCycleRockCount
traceM ( showSt ( Just 10 ) ( Just r0 ) st )
case prevR == 0 of
If this is just the first cycle , record the rock count + height
True -> do
rc <- use rockCount
prevCycleRockCount .= rc
h <- height
prevCycleHeight .= h
Otherwise , it 's going to repeat . Ascertained by hand that it
repeats after the first jet cycle for my real input , although
-- that's not true for the sample input so this doesn't work in
-- general! Spent a long time trying to debug on the sample
-- input before realizing this.
False -> do
h <- height
ph <- use prevCycleHeight
prevCycleHeight .= h
let heightPeriod = h - ph
n <- use rockCount
pn <- use prevCycleRockCount
prevCycleRockCount .= n
let rockPeriod = n - pn
l <- use rocksLeft
savedHeight .= h + (l `div` rockPeriod) * heightPeriod
rocksLeft .= l `mod` rockPeriod
b <- use (curBoard . filled)
j <- nextJet
let r1 = fromMaybe r0 $ moveRock b j r0
case moveRock b below r1 of
Just r2 -> fall r2
Nothing -> freeze r1
moveRock :: Set Coord -> (Coord -> Coord) -> Rock -> Maybe Rock
moveRock b m r0
| rockOK b r1 = Just r1
| otherwise = Nothing
where
r1 = map m r0
rockOK :: Set Coord -> Rock -> Bool
rockOK b = all unblocked
where
unblocked p@(r,c) = r < 0 && c > 0 && c < 8 && p `S.notMember` b
freeze :: Rock -> State St ()
freeze r = do
curBoard . topRow %= min (minimum . map fst $ r)
curBoard . filled %= (\cs -> foldl' (flip S.insert) cs r)
------------------------------------------------------------
main = do
rocks <- readRocks "rocks.txt"
interact $
init >>> applyAll [solveA rocks, solveB rocks] >>> map show >>> unlines
solveA, solveB :: [Rock] -> Jets -> Int
solveA rocks jets = sim 2022 rocks (cycle jets) >$> (^. curBoard . topRow) >>> negate
solveB rocks jets = sim (10^12) rocks (cycle (' ':jets)) >$> (^. savedHeight)
| null | https://raw.githubusercontent.com/byorgey/AoC/03f250a121a8214e12fe9708908fe41704c5d1bc/2022/17/17.hs | haskell | resolver lts-19.28 script --package containers --package split --package lens --package mtl --package array
# LANGUAGE LambdaCase #
----------------------------------------------------------
----------------------------------------------------------
----------------------------------------------------------
that's not true for the sample input so this doesn't work in
general! Spent a long time trying to debug on the sample
input before realizing this.
---------------------------------------------------------- | #!/usr/bin/env stack
# LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
import Control.Arrow (first, (***), (>>>))
import Control.Lens (imap, makeLenses, use, (%=), (+=), (-=),
(.=), (<-=), (^.))
import Control.Monad.State
import Data.Array
import Data.List (foldl')
import Data.List.Split (splitOn)
import Data.Maybe (fromMaybe)
import Data.Set (Set)
import qualified Data.Set as S
type Coord = (Int,Int)
above, below, left, right :: Coord -> Coord
above (r,c) = (r-1,c)
below (r,c) = (r+1,c)
left (r,c) = (r,c-1)
right (r,c) = (r,c+1)
applyAll :: [a -> b] -> a -> [b]
applyAll fs a = map ($ a) fs
infixr 0 >$>
(>$>) = flip ($)
type Jet = Char
type Jets = [Jet]
type Rock = [Coord]
readRocks :: FilePath -> IO [Rock]
readRocks rocksFile = do
f <- readFile rocksFile
return $ f >$> lines >>> splitOn [""] >>> map readRock
readRock :: [String] -> Rock
readRock = imap (\r -> imap (\c -> ((r,c),))) >>> concat >>> filter (snd >>> (=='#')) >>> map fst
data Board = Board { _topRow :: Int, _filled :: Set Coord } deriving (Eq, Show)
makeLenses ''Board
showBoard :: Jet -> Maybe Rock -> Maybe Int -> Board -> String
showBoard j mr mt (Board tr cs) = unlines $
[ show tr ]
++
[ lt : [ showCell (r,c) | c <- [1..7]] ++ [rt] | r <- [tr', tr'+1 .. maybe (-1) (tr'+) mt] ]
++
["+-------+"]
where
rock = fromMaybe [] mr
tr' = case rock of { [] -> tr; _ -> min tr (minimum . map fst $ rock) }
lt = if j == '>' then j else '|'
rt = if j == '<' then j else '|'
showCell p
| p `elem` rock = '@'
| p `S.member` cs = '#'
| otherwise = '.'
emptyBoard :: Board
emptyBoard = Board 0 S.empty
initRockPosition :: Board -> Rock -> Rock
initRockPosition b r = map ((+ (b ^. topRow - 4 - maxRow)) *** (+3)) r
where
maxRow = maximum . map fst $ r
data St = St
{ _curJets :: Jets
, _curBoard :: Board
, _rockArray :: Array Int Rock
, _rockIndex :: Int
, _rocksLeft :: Int
, _jetCycle :: Int
, _rockCount :: Int
, _prevCycleRockCount :: Int
, _prevCycleHeight :: Int
, _savedHeight :: Int
}
deriving (Eq, Show)
makeLenses ''St
initSt :: Jets -> Int -> [Rock] -> St
initSt js n rocks =
St js emptyBoard (listArray (0,length rocks - 1) rocks) 0 n (-1) 0 0 0 0
showSt :: Maybe Int -> Maybe Rock -> St -> String
showSt mt mr st = showBoard (head (st ^. curJets)) mr mt (st ^. curBoard)
nextJet :: State St (Coord -> Coord)
nextJet = do
js <- use curJets
curJets %= tail
case head js of
' ' -> do
jetCycle += 1
nextJet
'<' -> return left
_ -> return right
sim :: Int -> [Rock] -> Jets -> St
sim n rocks js = execState runSim (initSt js n rocks)
runSim :: State St ()
runSim = do
b <- use curBoard
i <- use rockIndex
rs <- use rockArray
let r = rs!i
fall (initRockPosition b r)
rockCount += 1
rockIndex += 1
rockIndex %= (`mod` (snd (bounds rs) + 1))
rl <- rocksLeft <-= 1
case rl > 0 of
True -> runSim
False -> do
p <- use prevCycleHeight
h <- height
savedHeight += (h - p)
height :: State St Int
height = negate <$> use (curBoard . topRow)
fall :: Rock -> State St ()
fall r0 = do
js <- use curJets
when (head js == ' ') $ do
st <- get
prevR <- use prevCycleRockCount
traceM ( showSt ( Just 10 ) ( Just r0 ) st )
case prevR == 0 of
If this is just the first cycle , record the rock count + height
True -> do
rc <- use rockCount
prevCycleRockCount .= rc
h <- height
prevCycleHeight .= h
Otherwise , it 's going to repeat . Ascertained by hand that it
repeats after the first jet cycle for my real input , although
False -> do
h <- height
ph <- use prevCycleHeight
prevCycleHeight .= h
let heightPeriod = h - ph
n <- use rockCount
pn <- use prevCycleRockCount
prevCycleRockCount .= n
let rockPeriod = n - pn
l <- use rocksLeft
savedHeight .= h + (l `div` rockPeriod) * heightPeriod
rocksLeft .= l `mod` rockPeriod
b <- use (curBoard . filled)
j <- nextJet
let r1 = fromMaybe r0 $ moveRock b j r0
case moveRock b below r1 of
Just r2 -> fall r2
Nothing -> freeze r1
moveRock :: Set Coord -> (Coord -> Coord) -> Rock -> Maybe Rock
moveRock b m r0
| rockOK b r1 = Just r1
| otherwise = Nothing
where
r1 = map m r0
rockOK :: Set Coord -> Rock -> Bool
rockOK b = all unblocked
where
unblocked p@(r,c) = r < 0 && c > 0 && c < 8 && p `S.notMember` b
freeze :: Rock -> State St ()
freeze r = do
curBoard . topRow %= min (minimum . map fst $ r)
curBoard . filled %= (\cs -> foldl' (flip S.insert) cs r)
main = do
rocks <- readRocks "rocks.txt"
interact $
init >>> applyAll [solveA rocks, solveB rocks] >>> map show >>> unlines
solveA, solveB :: [Rock] -> Jets -> Int
solveA rocks jets = sim 2022 rocks (cycle jets) >$> (^. curBoard . topRow) >>> negate
solveB rocks jets = sim (10^12) rocks (cycle (' ':jets)) >$> (^. savedHeight)
|
6ba593886c1a4f06732c93907730769cd1b1467f709b7f0d82256380c5148319 | blindglobe/clocc | clex.lisp | -*- Mode : Lisp ; Syntax : Common - Lisp ; Package : CLEX ; -*-
;;; --------------------------------------------------------------------------------------
;;; Title: A flex like scanner generator for Common LISP
Created : 1997 - 10 - 12
Author : < >
;;; License: LGPL (See file COPYING for details).
;;; --------------------------------------------------------------------------------------
( c ) copyright 1997 - 1999 by
;;; This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation ; either
version 2 of the License , or ( at your option ) any later version .
;;;
;;; This library 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
Library General Public License for more details .
;;;
You should have received a copy of the GNU Library General Public
;;; License along with this library; if not, write to the
Free Software Foundation , Inc. , 59 Temple Place - Suite 330 ,
Boston , MA 02111 - 1307 USA .
(defpackage :clex
(:use :common-lisp)
(:export
#:deflexer #:backup #:begin #:initial #:bag))
(in-package :CLEX)
;; This code should burn!
( declaim ( optimize ( space 1 ) ( speed 3 ) ) )
NOTE -- It turns out that this code is a magintude slower under CMUCL
compared to CLISP or ACL . Probably they do not have a good implementation of
;;; bit vectors.
We encode our FSA 's directly as linked datastructures ; A state is represented by :
(defstruct (state (:type vector))
(final 0)
transitions ;simple alist of (sigma . next-state)
id ;numeric id of state
eps-transitions) ;list of all states reached by epsilon (empty transitions)
(defun state-add-link (this char that)
"Add a transition to state `this'; reading `char' proceeds to `that'."
(cond ((eq char 'eps)
(pushnew that (state-eps-transitions this)))
(t
(dolist (k (state-transitions this)
(push (cons (list char) that) (state-transitions this)))
(when (eq (cdr k) that)
(pushnew char (car k))
(return nil))) )))
When constructing FSA 's from regular expressions we abstract by the notation
of FSA 's as boxen with an entry and an exit state .
(defstruct fsa
start ;entry state
end) ;exit state
(defun fsa-empty ()
"Accepts the empty word."
(let ((q (make-state)))
(make-fsa :start q :end q)))
(defun fsa-trivial (char)
"Accepts the trivial word consisting out of exactly one `char'."
(let ((q0 (make-state))
(q1 (make-state)))
(state-add-link q0 char q1)
(make-fsa :start q0 :end q1)))
(defun fsa-concat (a1 a2)
"Concatenation of `a1' and `a2'. Hence `a1 a2'."
(state-add-link (fsa-end a1) 'eps (fsa-start a2))
(make-fsa :start (fsa-start a1)
:end (fsa-end a2)))
(defun fsa-iterate (a)
"Iteration of `a'. Hence `a*'"
(let ((q0 (make-state))
(q1 (make-state)))
(state-add-link q0 'eps (fsa-start a))
(state-add-link q0 'eps q1)
(state-add-link q1 'eps q0)
(state-add-link (fsa-end a) 'eps q1)
(make-fsa :start q0 :end q1)))
(defun fsa-branch (&rest as)
"Alternation of a0..an; Hence `a0 | a1 | ... | an'."
(let ((q0 (make-state))
(q1 (make-state)))
(dolist (a as)
(state-add-link q0 'eps (fsa-start a))
(state-add-link (fsa-end a) 'eps q1))
(make-fsa :start q0 :end q1)))
;;;; ----------------------------------------------------------------------------------------------------
;;;; Converting regular expressions to (ND)FSA
;;;;
However we choose here a syntax for regular expressions :
;;; a singelton
;;; (and a0 .. an) concatation
;;; (or a0 .. an) alternation
;;; (* a) iteration
;;; Further the abbrevs.:
;;; (+ a) == (and a (* a))
;;; (? a) == (or a (and))
;;; (a0 ... an) == (and a0 ... an)
;;; When a string embeded into a regular expression is seen, the list
;;; of characters is spliced in. So formally:
( a0 .. ai " xyz " aj .. an ) = = ( a0 .. ai # \x # \y # \z aj .. an )
;;;
;;; This is useful for matching words:
" foo " -- > ( and " foo " ) -- > ( and # \f # \o # \o ) = = The word ' foo '
;;; or for denoting small sets:
( or " + - " ) -- > ( or # \+ # \- ) = = One of ' + ' or ' - '
(defun loose-eq (x y)
(cond ((eq x y))
((and (symbolp x) (symbolp y))
(string= (symbol-name x) (symbol-name y)))))
(defun regexp->fsa (term)
(setf term (regexp-expand-splicing term))
(cond ((and (atom term) (not (stringp term)))
(fsa-trivial term))
((loose-eq (car term) 'AND) (regexp/and->fsa term))
((loose-eq (car term) 'OR) (regexp/or->fsa term))
((loose-eq (car term) '*) (fsa-iterate (regexp->fsa (cadr term))))
((loose-eq (car term) '+) (regexp->fsa `(AND ,(cadr term) (* ,(cadr term)))))
((loose-eq (car term) '?) (regexp->fsa `(OR (AND) ,(cadr term))))
((loose-eq (car term) 'RANGE)
(regexp->fsa `(OR .,(loop for i from (char-code (cadr term)) to (char-code (caddr term))
collect (code-char i)))))
(t
(regexp->fsa `(AND .,term))) ))
(defun regexp/or->fsa (term)
;; I optimize here a bit: I recognized, that ORs are mainly just
;; (large) sets of characters. The extra epsilon transitions are not
;; neccessary on single atoms, so I omit them here. -- This reduces the
number of states quite a bit in the first place .
(let ((q0 (make-state))
(q1 (make-state)))
(dolist (a (cdr term))
(cond ((atom a)
(state-add-link q0 a q1))
((let ((a (regexp->fsa a)))
(state-add-link q0 'eps (fsa-start a))
(state-add-link (fsa-end a) 'eps q1)))))
(make-fsa :start q0 :end q1)))
(defun regexp/and->fsa (term)
(cond ((null (cdr term)) (fsa-empty))
((null (cddr term)) (regexp->fsa (cadr term)))
((fsa-concat (regexp->fsa (cadr term)) (regexp->fsa `(and .,(cddr term)))))))
(defun regexp-expand-splicing (term)
(cond ((consp term)
(mapcan #'(lambda (x)
(cond ((stringp x) (coerce x 'list))
((list x))))
term))
(t term)))
;;;; ----------------------------------------------------------------------------------------------------
Converting a ND - FSA to a D - FSA
;;;;
Since we have to compare and unionfy sets of states a lot , I use bit - vectors
;;; to represent these sets for speed. However let me abstract that a bit:
( All these are defined as macros simply for speed . would be an
;;; option here, when it would be reliable. With defining macros I enforce
;;; inlining).
(defmacro make-empty-set (n)
"Create the empty set on the domain [0,n)."
`(make-array ,n :element-type 'bit :initial-element 0))
(defmacro nset-put (bag new)
"Destructively calculate bag = bag U {new}."
`(setf (sbit (the (simple-array bit (*)) ,bag) (the fixnum ,new)) 1))
(defmacro element-of-set-p (elm set)
"Determine whether `elm' is element of the set `set'."
`(eq 1 (sbit (the (simple-array bit (*)) ,set) (the fixnum ,elm))))
(defmacro set-size (set)
"Return the upper bound of the domain of `set'."
`(length ,set))
(defmacro do-bits ((var set &optional result) &body body)
"Iterate body with `var' over all elements of `set'."
(let ((g/set (gensym)))
`(let ((,g/set ,set))
(dotimes (,var (set-size ,g/set) ,result)
(when (element-of-set-p ,var ,g/set)
,@body)))))
;;; Since the sets we defined above only take non-negative integers, we have to
;;; number our states. This is done once by NUMBER-STATES.
(defun number-states (starts)
"Number all state reachable form `starts', continuosly from 0. Each state got
it's number stuck into the `id' slot.
Returns two values: `n' the number of states and `tab' a table to lookup a
state given the number it got attached to."
(let ((n 0)
(tab (make-array 0 :adjustable t :fill-pointer 0 :initial-element nil)))
(labels ((walk (x)
(unless (state-id x)
(vector-push-extend x tab 300)
(setf (state-id x) (prog1 n (incf n)))
(dolist (tr (state-transitions x))
(walk (cdr tr)))
(dolist (y (state-eps-transitions x))
(walk y)))))
(dolist (s starts) (walk s))
(values n tab))))
;;; We need to calculate the epsilon closure of a given state. Due to the
;;; precise workings of our algorithm below, we only need this augmenting
;;; version.
(defun fsa-epsilon-closure/set (x state-set)
"Augment the epsilon closure of the state `state' into `state-set'."
(unless (element-of-set-p (state-id x) state-set)
(nset-put state-set (state-id x))
(dolist (k (state-eps-transitions x))
(fsa-epsilon-closure/set k state-set))))
(defun ndfsa->dfsa (starts)
(let ((batch nil)
(known nil))
(multiple-value-bind (n tab) (number-states starts)
(labels ((name-state-set (state-set)
(or (cdr (assoc state-set known :test #'equal))
(let ((new (make-state)))
(push (cons state-set new) known)
(push state-set batch)
new)))
(add-state-set (state-set)
(let ((new-tr nil)
(new-tr-real nil)
(name (name-state-set state-set))
(new-final 0))
(do-bits (s0 state-set)
(let ((s (aref tab s0)))
(setf new-final (max new-final (state-final s)))
(dolist (tr (state-transitions s))
(let ((to (cdr tr)))
(dolist (z (car tr))
(let ((looked (getf new-tr z nil)))
(if looked
(fsa-epsilon-closure/set to looked)
(let ((sts (make-empty-set n)))
(fsa-epsilon-closure/set to sts)
(setf (getf new-tr z) sts) ))))))))
(setq new-tr (frob2 new-tr))
(do ((q new-tr (cddr q)))
((null q))
(let ((z (car q))
(to (cadr q)))
(push (cons z (name-state-set to)) new-tr-real)))
(setf (state-transitions name) new-tr-real
(state-final name) new-final))))
(prog1
(mapcar #'(lambda (s)
(name-state-set (let ((sts (make-empty-set n)))
(fsa-epsilon-closure/set s sts)
sts)))
starts)
(do ()
((null batch))
(add-state-set (pop batch)))) ))))
(defun frob2 (res &aux res2)
(do ((q res (cddr q)))
((null q) res2)
(do ((p res2 (cddr p)))
((null p)
(setf res2 (list* (list (car q)) (cadr q) res2)))
(when (equal (cadr q) (cadr p))
(setf (car p) (cons (car q) (car p)))
(return)))))
;;;; ----------------------------------------------------------------------------------------------------
;;;; API
;;;;
;;; Features to think about:
;;; - case insensitive scanner
;;; - compression of tables
;;; - debugging aids
;;; - non-interactive high speed scanning?
;;; - make BAG a macro? So that non used bags are not considered?
;;; - REJECT?
;;; - support for include?
;;; - support for putting back input?
;;; - count lines/columns? Track source?
;;; - richer set of regexp primitives e.g. "[a-z]" style sets
;;; - could we offer complement regexp?
;;; - trailing context
;;; - sub-state stacks?
;;; - user variables to include ['global' / 'lexical']
- identifing sub - expression of regexps ( ala \( .. \ ) and )
;;;
#-(OR CMU GCL)
(defun loadable-states-form (starts)
`',starts)
#+(OR CMU GCL)
so dumm , dass es scheinbar nicht faehig ist die
selbstbezuegliche ' , starts in ein FASL file ; - (
Deswegen hier dieser read - from - string Hack .
(defun loadable-states-form (starts)
`(LET ((*PACKAGE* (FIND-PACKAGE ',(package-name *package*))))
(READ-FROM-STRING ',(let ((*print-circle* t)
(*print-readably* t)
(*print-pretty* nil))
(prin1-to-string starts)))))
(defmacro old/deflexer (name macro-defs &rest rule-defs)
(let ((macros nil) starts clauses (n-fin 0))
(dolist (k macro-defs)
(push (cons (car k) (sublis macros (cadr k))) macros))
;;canon clauses -- each element of rule-defs becomes (start expr end action)
(setq rule-defs
(mapcar #'(lambda (x)
(cond ((and (consp (car x)) (eq (caar x) 'in))
(list (cadar x) (sublis macros (caddar x)) (progn (incf n-fin) n-fin) (cdr x)))
((list 'initial (sublis macros (car x)) (progn (incf n-fin) n-fin) (cdr x)))))
(reverse rule-defs)))
;;collect all start states in alist (<name> . <state>)
(setq starts (mapcar #'(lambda (name)
(cons name (make-state)))
(remove-duplicates (mapcar #'car rule-defs))))
build the nd - fsa 's
(dolist (r rule-defs)
(destructuring-bind (start expr end action) r
(let ((q0 (cdr (assoc start starts)))
(fsa (regexp->fsa `(and ,expr))))
;;link start state
(state-add-link q0 'eps (fsa-start fsa))
;;mark final state
(setf (state-final (fsa-end fsa)) end)
;; build a clause for CASE
(push `((,end) .,action) clauses))))
;; hmm... we have to sort the final states after building the dfsa
;; or introduce fixnum identifier and instead of union take the minimum
above in ndfsa->dfsa .
(progn
(mapcar #'(lambda (x y) (setf (cdr x) y))
starts (ndfsa->dfsa (mapcar #'cdr starts))))
;; (print (number-states starts))
`(DEFUN ,(intern (format nil "MAKE-~A-LEXER" name)) (INPUT)
(LET* ((STARTS ,(loadable-states-form starts))
(SUB-STATE 'INITIAL)
(STATE NIL)
(LOOK-AHEAD NIL)
(BAGG/CH (MAKE-ARRAY 100 :FILL-POINTER 0 :ADJUSTABLE T :ELEMENT-TYPE ',(ARRAY-ELEMENT-TYPE "")))
(BAGG/STATE (MAKE-ARRAY 100 :FILL-POINTER 0 :ADJUSTABLE T))
(CH NIL))
#'(LAMBDA ()
(BLOCK NIL
(LABELS ((BEGIN (X)
(SETQ SUB-STATE X))
(BACKUP (CH)
(COND ((STRINGP CH)
(WHEN (> (LENGTH CH) 0)
(PUSH (CONS 0 CH) LOOK-AHEAD)))
(T (PUSH CH LOOK-AHEAD))))
(PUSH* (CH STATE)
(VECTOR-PUSH-EXTEND CH BAGG/CH 10)
(VECTOR-PUSH-EXTEND STATE BAGG/STATE 10) )
(POP*/CH ()
(LET ((FP (LENGTH BAGG/CH)))
(PROG1 (AREF BAGG/CH (1- FP))
(SETF (FILL-POINTER BAGG/STATE) (1- FP))
(SETF (FILL-POINTER BAGG/CH) (1- FP)))))
(TOS*/STATE ()
(AREF BAGG/STATE (1- (LENGTH BAGG/STATE))) )
(EMPTY*? ()
(= (LENGTH BAGG/CH) 0))
(REWIND* ()
(SETF (FILL-POINTER BAGG/CH) 0)
(SETF (FILL-POINTER BAGG/STATE) 0) )
(STRING* ()
(COPY-SEQ BAGG/CH))
#+(OR)
(FIND-NEXT-STATE (CH STATE)
(DOLIST (K (STATE-TRANSITIONS STATE))
(WHEN (MEMBER CH (CAR K))
(RETURN (CDR K)))))
(GETCH ()
(COND ((NULL LOOK-AHEAD) (READ-CHAR INPUT NIL NIL))
((CONSP (CAR LOOK-AHEAD))
(LET ((S (CDAR LOOK-AHEAD)))
(PROG1
(AREF S (CAAR LOOK-AHEAD))
(INCF (CAAR LOOK-AHEAD))
(WHEN (= (CAAR LOOK-AHEAD) (LENGTH S))
(POP LOOK-AHEAD)))))
(T (POP LOOK-AHEAD)) )))
(DECLARE (INLINE BACKUP GETCH))
(TAGBODY
START (SETQ STATE (CDR (ASSOC SUB-STATE STARTS)))
(WHEN (NULL STATE)
(ERROR "Sub-state ~S is not defined." SUB-STATE))
(REWIND*)
LOOP (SETQ CH (GETCH))
(LET ((NEXT-STATE
(BLOCK FOO
(DOLIST (K (STATE-TRANSITIONS STATE))
(DOLIST (Q (CAR K))
(WHEN (EQL CH Q)
(RETURN-FROM FOO (CDR K)))))) ))
(COND ((NULL NEXT-STATE)
(BACKUP CH)
(DO ()
((OR (EMPTY*?) (NOT (EQ 0 (TOS*/STATE)))))
(BACKUP (POP*/CH)))
(COND ((AND (EMPTY*?) (NULL CH))
(RETURN :EOF))
((EMPTY*?)
(ERROR "oops ~S ~S" ch (mapcar #'car (state-transitions state))))
(T
(LET ((HALTING-STATE (TOS*/STATE)))
(LET ((BAG* NIL))
(SYMBOL-MACROLET ((BAG (IF BAG*
BAG*
(SETF BAG* (STRING*)))))
(CASE HALTING-STATE
,@clauses)))
(GO START)))))
(T
(PUSH* CH (STATE-FINAL NEXT-STATE))
(SETQ STATE NEXT-STATE)
(GO LOOP))))))))))))
;;;; ----------------------------------------------------------------------------------------------------
;;;;
(defun parse-char-set (string i)
(let ((res nil)
(complement-p nil))
(incf i) ;skip '['
the first char is special
(cond ((char= (char string i) #\]) (incf i) (push #\] res))
((char= (char string i) #\^) (incf i) (setq complement-p t))
((char= (char string i) #\-) (incf i) (push #\- res)))
(do ()
((char= (char string i) #\])
(values (if complement-p (cons 'cset res) (cons 'set res)) (+ i 1)))
(cond ((char= (char string (+ i 1)) #\-)
;;it's a range
(push (cons (char string i) (char string (+ i 2))) res)
(incf i 3))
(t
;;singleton
(push (char string i) res)
(incf i))))))
;;;; ------------------------------------------------------------------------------------------
(defparameter *full-table-p* t)
(defun mungle-transitions (trs)
(if *full-table-p*
(let ((res (make-array 256 :initial-element nil)))
(dolist (tr trs)
(dolist (ch (car tr))
(setf (aref res (char-code ch)) (cdr tr))))
res)
trs))
(defun over-all-states (fun starts)
;; Apply `fun' to each state reachable from starts.
(let ((yet nil))
(labels ((walk (q)
(unless (member q yet)
(push q yet)
(let ((trs (state-transitions q)))
(funcall fun q)
(dolist (tr trs)
(walk (cdr tr)))))))
(mapc #'walk starts))))
(defmacro deflexer (name macro-defs &rest rule-defs)
(let ((macros nil) starts clauses (n-fin 0))
(dolist (k macro-defs)
(push (cons (car k) (sublis macros (cadr k))) macros))
;;canon clauses -- each element of rule-defs becomes (start expr end action)
(setq rule-defs
(mapcar #'(lambda (x)
(cond ((and (consp (car x)) (eq (caar x) 'in))
(list (cadar x) (sublis macros (caddar x)) (progn (incf n-fin) n-fin) (cdr x)))
((list 'initial (sublis macros (car x)) (progn (incf n-fin) n-fin) (cdr x)))))
(reverse rule-defs)))
;;collect all start states in alist (<name> . <state>)
(setq starts (mapcar #'(lambda (name)
(cons name (make-state)))
(remove-duplicates (mapcar #'car rule-defs))))
build the nd - fsa 's
(dolist (r rule-defs)
(destructuring-bind (start expr end action) r
(let ((q0 (cdr (assoc start starts)))
(fsa (regexp->fsa `(and ,expr))))
;;link start state
(state-add-link q0 'eps (fsa-start fsa))
;;mark final state
(setf (state-final (fsa-end fsa)) end)
;; build a clause for CASE
(push `((,end) .,action) clauses))))
;; hmm... we have to sort the final states after building the dfsa
;; or introduce fixnum identifier and instead of union take the minimum
above in ndfsa->dfsa .
(progn
(mapcar #'(lambda (x y) (setf (cdr x) y))
starts (ndfsa->dfsa (mapcar #'cdr starts))))
;;(terpri)(princ `(,(number-states starts) states))(finish-output)
(let ((n 0))
(over-all-states (lambda (state)
(incf n)
(setf (state-transitions state)
(mungle-transitions (state-transitions state))))
(mapcar #'cdr starts))
(format T "~&~D states." n))
`(DEFUN ,(intern (format nil "MAKE-~A-LEXER" name)) (INPUT)
(LET* ((STARTS ,(loadable-states-form starts))
(SUB-STATE 'INITIAL)
(STATE NIL)
(LOOK-AHEAD NIL)
(BAGG/CH (MAKE-ARRAY 100 :FILL-POINTER 0 :ADJUSTABLE T :ELEMENT-TYPE ',(ARRAY-ELEMENT-TYPE "")))
(BAGG/STATE (MAKE-ARRAY 100 :FILL-POINTER 0 :ADJUSTABLE T))
(CH NIL))
#'(LAMBDA ()
(BLOCK NIL
(LABELS ((BEGIN (X)
(SETQ SUB-STATE X))
(BACKUP (CH)
(COND ((STRINGP CH)
(WHEN (> (LENGTH CH) 0)
(PUSH (CONS 0 CH) LOOK-AHEAD)))
(T (PUSH CH LOOK-AHEAD))))
(PUSH* (CH STATE)
(VECTOR-PUSH-EXTEND CH BAGG/CH 10)
(VECTOR-PUSH-EXTEND STATE BAGG/STATE 10) )
(POP*/CH ()
(LET ((FP (LENGTH BAGG/CH)))
(PROG1 (CHAR BAGG/CH (1- FP))
(SETF (FILL-POINTER BAGG/STATE) (1- FP))
(SETF (FILL-POINTER BAGG/CH) (1- FP)))))
(TOS*/STATE ()
(AREF BAGG/STATE (1- (LENGTH BAGG/STATE))) )
(EMPTY*? ()
(= (LENGTH BAGG/CH) 0))
(REWIND* ()
(SETF (FILL-POINTER BAGG/CH) 0)
(SETF (FILL-POINTER BAGG/STATE) 0) )
(STRING* ()
(COPY-SEQ BAGG/CH))
(GETCH ()
(COND ((NULL LOOK-AHEAD) (READ-CHAR INPUT NIL NIL))
((CONSP (CAR LOOK-AHEAD))
(LET ((S (CDAR LOOK-AHEAD)))
(PROG1
(CHAR S (CAAR LOOK-AHEAD))
(INCF (CAAR LOOK-AHEAD))
(WHEN (= (CAAR LOOK-AHEAD) (LENGTH S))
(POP LOOK-AHEAD)))))
(T (POP LOOK-AHEAD)) ))
,(if *full-table-p*
`(FIND-NEXT-STATE (STATE CH)
(IF (CHARACTERP CH)
(SVREF (STATE-TRANSITIONS STATE) (CHAR-CODE CH))
NIL))
`(FIND-NEXT-STATE (STATE CH)
(BLOCK FOO
(DOLIST (K (STATE-TRANSITIONS STATE))
(DOLIST (Q (CAR K))
(WHEN (CHAR= CH Q)
(RETURN-FROM FOO (CDR K)))))))) )
(DECLARE (INLINE BACKUP GETCH FIND-NEXT-STATE))
(TAGBODY
START (SETQ STATE (CDR (ASSOC SUB-STATE STARTS)))
(WHEN (NULL STATE)
(ERROR "Sub-state ~S is not defined." SUB-STATE))
(REWIND*)
LOOP (SETQ CH (GETCH))
(LET ((NEXT-STATE (FIND-NEXT-STATE STATE CH)) )
(COND ((NULL NEXT-STATE)
(BACKUP CH)
(DO ()
((OR (EMPTY*?) (NOT (EQ 0 (TOS*/STATE)))))
(BACKUP (POP*/CH)))
(COND ((AND (EMPTY*?) (NULL CH))
(RETURN :EOF))
((EMPTY*?)
(ERROR "oops ~S ~S" ch (mapcar #'car (state-transitions state))))
(T
(LET ((HALTING-STATE (TOS*/STATE)))
(LET ((BAG* NIL))
(SYMBOL-MACROLET ((BAG (IF BAG*
BAG*
(SETF BAG* (STRING*)))))
(CASE HALTING-STATE
,@clauses)))
(GO START)))))
(T
(PUSH* CH (STATE-FINAL NEXT-STATE))
(SETQ STATE NEXT-STATE)
(GO LOOP))))))))))))
| null | https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/gui/clx/docs/clex.lisp | lisp | Syntax : Common - Lisp ; Package : CLEX ; -*-
--------------------------------------------------------------------------------------
Title: A flex like scanner generator for Common LISP
License: LGPL (See file COPYING for details).
--------------------------------------------------------------------------------------
This library is free software; you can redistribute it and/or
either
This library 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
License along with this library; if not, write to the
This code should burn!
bit vectors.
A state is represented by :
simple alist of (sigma . next-state)
numeric id of state
list of all states reached by epsilon (empty transitions)
entry state
exit state
----------------------------------------------------------------------------------------------------
Converting regular expressions to (ND)FSA
a singelton
(and a0 .. an) concatation
(or a0 .. an) alternation
(* a) iteration
Further the abbrevs.:
(+ a) == (and a (* a))
(? a) == (or a (and))
(a0 ... an) == (and a0 ... an)
When a string embeded into a regular expression is seen, the list
of characters is spliced in. So formally:
This is useful for matching words:
or for denoting small sets:
I optimize here a bit: I recognized, that ORs are mainly just
(large) sets of characters. The extra epsilon transitions are not
neccessary on single atoms, so I omit them here. -- This reduces the
----------------------------------------------------------------------------------------------------
to represent these sets for speed. However let me abstract that a bit:
option here, when it would be reliable. With defining macros I enforce
inlining).
Since the sets we defined above only take non-negative integers, we have to
number our states. This is done once by NUMBER-STATES.
We need to calculate the epsilon closure of a given state. Due to the
precise workings of our algorithm below, we only need this augmenting
version.
----------------------------------------------------------------------------------------------------
API
Features to think about:
- case insensitive scanner
- compression of tables
- debugging aids
- non-interactive high speed scanning?
- make BAG a macro? So that non used bags are not considered?
- REJECT?
- support for include?
- support for putting back input?
- count lines/columns? Track source?
- richer set of regexp primitives e.g. "[a-z]" style sets
- could we offer complement regexp?
- trailing context
- sub-state stacks?
- user variables to include ['global' / 'lexical']
- (
canon clauses -- each element of rule-defs becomes (start expr end action)
collect all start states in alist (<name> . <state>)
link start state
mark final state
build a clause for CASE
hmm... we have to sort the final states after building the dfsa
or introduce fixnum identifier and instead of union take the minimum
(print (number-states starts))
----------------------------------------------------------------------------------------------------
skip '['
it's a range
singleton
------------------------------------------------------------------------------------------
Apply `fun' to each state reachable from starts.
canon clauses -- each element of rule-defs becomes (start expr end action)
collect all start states in alist (<name> . <state>)
link start state
mark final state
build a clause for CASE
hmm... we have to sort the final states after building the dfsa
or introduce fixnum identifier and instead of union take the minimum
(terpri)(princ `(,(number-states starts) states))(finish-output) | Created : 1997 - 10 - 12
Author : < >
( c ) copyright 1997 - 1999 by
modify it under the terms of the GNU Library General Public
version 2 of the License , or ( at your option ) any later version .
Library General Public License for more details .
You should have received a copy of the GNU Library General Public
Free Software Foundation , Inc. , 59 Temple Place - Suite 330 ,
Boston , MA 02111 - 1307 USA .
(defpackage :clex
(:use :common-lisp)
(:export
#:deflexer #:backup #:begin #:initial #:bag))
(in-package :CLEX)
( declaim ( optimize ( space 1 ) ( speed 3 ) ) )
NOTE -- It turns out that this code is a magintude slower under CMUCL
compared to CLISP or ACL . Probably they do not have a good implementation of
(defstruct (state (:type vector))
(final 0)
(defun state-add-link (this char that)
"Add a transition to state `this'; reading `char' proceeds to `that'."
(cond ((eq char 'eps)
(pushnew that (state-eps-transitions this)))
(t
(dolist (k (state-transitions this)
(push (cons (list char) that) (state-transitions this)))
(when (eq (cdr k) that)
(pushnew char (car k))
(return nil))) )))
When constructing FSA 's from regular expressions we abstract by the notation
of FSA 's as boxen with an entry and an exit state .
(defstruct fsa
(defun fsa-empty ()
"Accepts the empty word."
(let ((q (make-state)))
(make-fsa :start q :end q)))
(defun fsa-trivial (char)
"Accepts the trivial word consisting out of exactly one `char'."
(let ((q0 (make-state))
(q1 (make-state)))
(state-add-link q0 char q1)
(make-fsa :start q0 :end q1)))
(defun fsa-concat (a1 a2)
"Concatenation of `a1' and `a2'. Hence `a1 a2'."
(state-add-link (fsa-end a1) 'eps (fsa-start a2))
(make-fsa :start (fsa-start a1)
:end (fsa-end a2)))
(defun fsa-iterate (a)
"Iteration of `a'. Hence `a*'"
(let ((q0 (make-state))
(q1 (make-state)))
(state-add-link q0 'eps (fsa-start a))
(state-add-link q0 'eps q1)
(state-add-link q1 'eps q0)
(state-add-link (fsa-end a) 'eps q1)
(make-fsa :start q0 :end q1)))
(defun fsa-branch (&rest as)
"Alternation of a0..an; Hence `a0 | a1 | ... | an'."
(let ((q0 (make-state))
(q1 (make-state)))
(dolist (a as)
(state-add-link q0 'eps (fsa-start a))
(state-add-link (fsa-end a) 'eps q1))
(make-fsa :start q0 :end q1)))
However we choose here a syntax for regular expressions :
( a0 .. ai " xyz " aj .. an ) = = ( a0 .. ai # \x # \y # \z aj .. an )
" foo " -- > ( and " foo " ) -- > ( and # \f # \o # \o ) = = The word ' foo '
( or " + - " ) -- > ( or # \+ # \- ) = = One of ' + ' or ' - '
(defun loose-eq (x y)
(cond ((eq x y))
((and (symbolp x) (symbolp y))
(string= (symbol-name x) (symbol-name y)))))
(defun regexp->fsa (term)
(setf term (regexp-expand-splicing term))
(cond ((and (atom term) (not (stringp term)))
(fsa-trivial term))
((loose-eq (car term) 'AND) (regexp/and->fsa term))
((loose-eq (car term) 'OR) (regexp/or->fsa term))
((loose-eq (car term) '*) (fsa-iterate (regexp->fsa (cadr term))))
((loose-eq (car term) '+) (regexp->fsa `(AND ,(cadr term) (* ,(cadr term)))))
((loose-eq (car term) '?) (regexp->fsa `(OR (AND) ,(cadr term))))
((loose-eq (car term) 'RANGE)
(regexp->fsa `(OR .,(loop for i from (char-code (cadr term)) to (char-code (caddr term))
collect (code-char i)))))
(t
(regexp->fsa `(AND .,term))) ))
(defun regexp/or->fsa (term)
number of states quite a bit in the first place .
(let ((q0 (make-state))
(q1 (make-state)))
(dolist (a (cdr term))
(cond ((atom a)
(state-add-link q0 a q1))
((let ((a (regexp->fsa a)))
(state-add-link q0 'eps (fsa-start a))
(state-add-link (fsa-end a) 'eps q1)))))
(make-fsa :start q0 :end q1)))
(defun regexp/and->fsa (term)
(cond ((null (cdr term)) (fsa-empty))
((null (cddr term)) (regexp->fsa (cadr term)))
((fsa-concat (regexp->fsa (cadr term)) (regexp->fsa `(and .,(cddr term)))))))
(defun regexp-expand-splicing (term)
(cond ((consp term)
(mapcan #'(lambda (x)
(cond ((stringp x) (coerce x 'list))
((list x))))
term))
(t term)))
Converting a ND - FSA to a D - FSA
Since we have to compare and unionfy sets of states a lot , I use bit - vectors
( All these are defined as macros simply for speed . would be an
(defmacro make-empty-set (n)
"Create the empty set on the domain [0,n)."
`(make-array ,n :element-type 'bit :initial-element 0))
(defmacro nset-put (bag new)
"Destructively calculate bag = bag U {new}."
`(setf (sbit (the (simple-array bit (*)) ,bag) (the fixnum ,new)) 1))
(defmacro element-of-set-p (elm set)
"Determine whether `elm' is element of the set `set'."
`(eq 1 (sbit (the (simple-array bit (*)) ,set) (the fixnum ,elm))))
(defmacro set-size (set)
"Return the upper bound of the domain of `set'."
`(length ,set))
(defmacro do-bits ((var set &optional result) &body body)
"Iterate body with `var' over all elements of `set'."
(let ((g/set (gensym)))
`(let ((,g/set ,set))
(dotimes (,var (set-size ,g/set) ,result)
(when (element-of-set-p ,var ,g/set)
,@body)))))
(defun number-states (starts)
"Number all state reachable form `starts', continuosly from 0. Each state got
it's number stuck into the `id' slot.
Returns two values: `n' the number of states and `tab' a table to lookup a
state given the number it got attached to."
(let ((n 0)
(tab (make-array 0 :adjustable t :fill-pointer 0 :initial-element nil)))
(labels ((walk (x)
(unless (state-id x)
(vector-push-extend x tab 300)
(setf (state-id x) (prog1 n (incf n)))
(dolist (tr (state-transitions x))
(walk (cdr tr)))
(dolist (y (state-eps-transitions x))
(walk y)))))
(dolist (s starts) (walk s))
(values n tab))))
(defun fsa-epsilon-closure/set (x state-set)
"Augment the epsilon closure of the state `state' into `state-set'."
(unless (element-of-set-p (state-id x) state-set)
(nset-put state-set (state-id x))
(dolist (k (state-eps-transitions x))
(fsa-epsilon-closure/set k state-set))))
(defun ndfsa->dfsa (starts)
(let ((batch nil)
(known nil))
(multiple-value-bind (n tab) (number-states starts)
(labels ((name-state-set (state-set)
(or (cdr (assoc state-set known :test #'equal))
(let ((new (make-state)))
(push (cons state-set new) known)
(push state-set batch)
new)))
(add-state-set (state-set)
(let ((new-tr nil)
(new-tr-real nil)
(name (name-state-set state-set))
(new-final 0))
(do-bits (s0 state-set)
(let ((s (aref tab s0)))
(setf new-final (max new-final (state-final s)))
(dolist (tr (state-transitions s))
(let ((to (cdr tr)))
(dolist (z (car tr))
(let ((looked (getf new-tr z nil)))
(if looked
(fsa-epsilon-closure/set to looked)
(let ((sts (make-empty-set n)))
(fsa-epsilon-closure/set to sts)
(setf (getf new-tr z) sts) ))))))))
(setq new-tr (frob2 new-tr))
(do ((q new-tr (cddr q)))
((null q))
(let ((z (car q))
(to (cadr q)))
(push (cons z (name-state-set to)) new-tr-real)))
(setf (state-transitions name) new-tr-real
(state-final name) new-final))))
(prog1
(mapcar #'(lambda (s)
(name-state-set (let ((sts (make-empty-set n)))
(fsa-epsilon-closure/set s sts)
sts)))
starts)
(do ()
((null batch))
(add-state-set (pop batch)))) ))))
(defun frob2 (res &aux res2)
(do ((q res (cddr q)))
((null q) res2)
(do ((p res2 (cddr p)))
((null p)
(setf res2 (list* (list (car q)) (cadr q) res2)))
(when (equal (cadr q) (cadr p))
(setf (car p) (cons (car q) (car p)))
(return)))))
- identifing sub - expression of regexps ( ala \( .. \ ) and )
#-(OR CMU GCL)
(defun loadable-states-form (starts)
`',starts)
#+(OR CMU GCL)
so dumm , dass es scheinbar nicht faehig ist die
Deswegen hier dieser read - from - string Hack .
(defun loadable-states-form (starts)
`(LET ((*PACKAGE* (FIND-PACKAGE ',(package-name *package*))))
(READ-FROM-STRING ',(let ((*print-circle* t)
(*print-readably* t)
(*print-pretty* nil))
(prin1-to-string starts)))))
(defmacro old/deflexer (name macro-defs &rest rule-defs)
(let ((macros nil) starts clauses (n-fin 0))
(dolist (k macro-defs)
(push (cons (car k) (sublis macros (cadr k))) macros))
(setq rule-defs
(mapcar #'(lambda (x)
(cond ((and (consp (car x)) (eq (caar x) 'in))
(list (cadar x) (sublis macros (caddar x)) (progn (incf n-fin) n-fin) (cdr x)))
((list 'initial (sublis macros (car x)) (progn (incf n-fin) n-fin) (cdr x)))))
(reverse rule-defs)))
(setq starts (mapcar #'(lambda (name)
(cons name (make-state)))
(remove-duplicates (mapcar #'car rule-defs))))
build the nd - fsa 's
(dolist (r rule-defs)
(destructuring-bind (start expr end action) r
(let ((q0 (cdr (assoc start starts)))
(fsa (regexp->fsa `(and ,expr))))
(state-add-link q0 'eps (fsa-start fsa))
(setf (state-final (fsa-end fsa)) end)
(push `((,end) .,action) clauses))))
above in ndfsa->dfsa .
(progn
(mapcar #'(lambda (x y) (setf (cdr x) y))
starts (ndfsa->dfsa (mapcar #'cdr starts))))
`(DEFUN ,(intern (format nil "MAKE-~A-LEXER" name)) (INPUT)
(LET* ((STARTS ,(loadable-states-form starts))
(SUB-STATE 'INITIAL)
(STATE NIL)
(LOOK-AHEAD NIL)
(BAGG/CH (MAKE-ARRAY 100 :FILL-POINTER 0 :ADJUSTABLE T :ELEMENT-TYPE ',(ARRAY-ELEMENT-TYPE "")))
(BAGG/STATE (MAKE-ARRAY 100 :FILL-POINTER 0 :ADJUSTABLE T))
(CH NIL))
#'(LAMBDA ()
(BLOCK NIL
(LABELS ((BEGIN (X)
(SETQ SUB-STATE X))
(BACKUP (CH)
(COND ((STRINGP CH)
(WHEN (> (LENGTH CH) 0)
(PUSH (CONS 0 CH) LOOK-AHEAD)))
(T (PUSH CH LOOK-AHEAD))))
(PUSH* (CH STATE)
(VECTOR-PUSH-EXTEND CH BAGG/CH 10)
(VECTOR-PUSH-EXTEND STATE BAGG/STATE 10) )
(POP*/CH ()
(LET ((FP (LENGTH BAGG/CH)))
(PROG1 (AREF BAGG/CH (1- FP))
(SETF (FILL-POINTER BAGG/STATE) (1- FP))
(SETF (FILL-POINTER BAGG/CH) (1- FP)))))
(TOS*/STATE ()
(AREF BAGG/STATE (1- (LENGTH BAGG/STATE))) )
(EMPTY*? ()
(= (LENGTH BAGG/CH) 0))
(REWIND* ()
(SETF (FILL-POINTER BAGG/CH) 0)
(SETF (FILL-POINTER BAGG/STATE) 0) )
(STRING* ()
(COPY-SEQ BAGG/CH))
#+(OR)
(FIND-NEXT-STATE (CH STATE)
(DOLIST (K (STATE-TRANSITIONS STATE))
(WHEN (MEMBER CH (CAR K))
(RETURN (CDR K)))))
(GETCH ()
(COND ((NULL LOOK-AHEAD) (READ-CHAR INPUT NIL NIL))
((CONSP (CAR LOOK-AHEAD))
(LET ((S (CDAR LOOK-AHEAD)))
(PROG1
(AREF S (CAAR LOOK-AHEAD))
(INCF (CAAR LOOK-AHEAD))
(WHEN (= (CAAR LOOK-AHEAD) (LENGTH S))
(POP LOOK-AHEAD)))))
(T (POP LOOK-AHEAD)) )))
(DECLARE (INLINE BACKUP GETCH))
(TAGBODY
START (SETQ STATE (CDR (ASSOC SUB-STATE STARTS)))
(WHEN (NULL STATE)
(ERROR "Sub-state ~S is not defined." SUB-STATE))
(REWIND*)
LOOP (SETQ CH (GETCH))
(LET ((NEXT-STATE
(BLOCK FOO
(DOLIST (K (STATE-TRANSITIONS STATE))
(DOLIST (Q (CAR K))
(WHEN (EQL CH Q)
(RETURN-FROM FOO (CDR K)))))) ))
(COND ((NULL NEXT-STATE)
(BACKUP CH)
(DO ()
((OR (EMPTY*?) (NOT (EQ 0 (TOS*/STATE)))))
(BACKUP (POP*/CH)))
(COND ((AND (EMPTY*?) (NULL CH))
(RETURN :EOF))
((EMPTY*?)
(ERROR "oops ~S ~S" ch (mapcar #'car (state-transitions state))))
(T
(LET ((HALTING-STATE (TOS*/STATE)))
(LET ((BAG* NIL))
(SYMBOL-MACROLET ((BAG (IF BAG*
BAG*
(SETF BAG* (STRING*)))))
(CASE HALTING-STATE
,@clauses)))
(GO START)))))
(T
(PUSH* CH (STATE-FINAL NEXT-STATE))
(SETQ STATE NEXT-STATE)
(GO LOOP))))))))))))
(defun parse-char-set (string i)
(let ((res nil)
(complement-p nil))
the first char is special
(cond ((char= (char string i) #\]) (incf i) (push #\] res))
((char= (char string i) #\^) (incf i) (setq complement-p t))
((char= (char string i) #\-) (incf i) (push #\- res)))
(do ()
((char= (char string i) #\])
(values (if complement-p (cons 'cset res) (cons 'set res)) (+ i 1)))
(cond ((char= (char string (+ i 1)) #\-)
(push (cons (char string i) (char string (+ i 2))) res)
(incf i 3))
(t
(push (char string i) res)
(incf i))))))
(defparameter *full-table-p* t)
(defun mungle-transitions (trs)
(if *full-table-p*
(let ((res (make-array 256 :initial-element nil)))
(dolist (tr trs)
(dolist (ch (car tr))
(setf (aref res (char-code ch)) (cdr tr))))
res)
trs))
(defun over-all-states (fun starts)
(let ((yet nil))
(labels ((walk (q)
(unless (member q yet)
(push q yet)
(let ((trs (state-transitions q)))
(funcall fun q)
(dolist (tr trs)
(walk (cdr tr)))))))
(mapc #'walk starts))))
(defmacro deflexer (name macro-defs &rest rule-defs)
(let ((macros nil) starts clauses (n-fin 0))
(dolist (k macro-defs)
(push (cons (car k) (sublis macros (cadr k))) macros))
(setq rule-defs
(mapcar #'(lambda (x)
(cond ((and (consp (car x)) (eq (caar x) 'in))
(list (cadar x) (sublis macros (caddar x)) (progn (incf n-fin) n-fin) (cdr x)))
((list 'initial (sublis macros (car x)) (progn (incf n-fin) n-fin) (cdr x)))))
(reverse rule-defs)))
(setq starts (mapcar #'(lambda (name)
(cons name (make-state)))
(remove-duplicates (mapcar #'car rule-defs))))
build the nd - fsa 's
(dolist (r rule-defs)
(destructuring-bind (start expr end action) r
(let ((q0 (cdr (assoc start starts)))
(fsa (regexp->fsa `(and ,expr))))
(state-add-link q0 'eps (fsa-start fsa))
(setf (state-final (fsa-end fsa)) end)
(push `((,end) .,action) clauses))))
above in ndfsa->dfsa .
(progn
(mapcar #'(lambda (x y) (setf (cdr x) y))
starts (ndfsa->dfsa (mapcar #'cdr starts))))
(let ((n 0))
(over-all-states (lambda (state)
(incf n)
(setf (state-transitions state)
(mungle-transitions (state-transitions state))))
(mapcar #'cdr starts))
(format T "~&~D states." n))
`(DEFUN ,(intern (format nil "MAKE-~A-LEXER" name)) (INPUT)
(LET* ((STARTS ,(loadable-states-form starts))
(SUB-STATE 'INITIAL)
(STATE NIL)
(LOOK-AHEAD NIL)
(BAGG/CH (MAKE-ARRAY 100 :FILL-POINTER 0 :ADJUSTABLE T :ELEMENT-TYPE ',(ARRAY-ELEMENT-TYPE "")))
(BAGG/STATE (MAKE-ARRAY 100 :FILL-POINTER 0 :ADJUSTABLE T))
(CH NIL))
#'(LAMBDA ()
(BLOCK NIL
(LABELS ((BEGIN (X)
(SETQ SUB-STATE X))
(BACKUP (CH)
(COND ((STRINGP CH)
(WHEN (> (LENGTH CH) 0)
(PUSH (CONS 0 CH) LOOK-AHEAD)))
(T (PUSH CH LOOK-AHEAD))))
(PUSH* (CH STATE)
(VECTOR-PUSH-EXTEND CH BAGG/CH 10)
(VECTOR-PUSH-EXTEND STATE BAGG/STATE 10) )
(POP*/CH ()
(LET ((FP (LENGTH BAGG/CH)))
(PROG1 (CHAR BAGG/CH (1- FP))
(SETF (FILL-POINTER BAGG/STATE) (1- FP))
(SETF (FILL-POINTER BAGG/CH) (1- FP)))))
(TOS*/STATE ()
(AREF BAGG/STATE (1- (LENGTH BAGG/STATE))) )
(EMPTY*? ()
(= (LENGTH BAGG/CH) 0))
(REWIND* ()
(SETF (FILL-POINTER BAGG/CH) 0)
(SETF (FILL-POINTER BAGG/STATE) 0) )
(STRING* ()
(COPY-SEQ BAGG/CH))
(GETCH ()
(COND ((NULL LOOK-AHEAD) (READ-CHAR INPUT NIL NIL))
((CONSP (CAR LOOK-AHEAD))
(LET ((S (CDAR LOOK-AHEAD)))
(PROG1
(CHAR S (CAAR LOOK-AHEAD))
(INCF (CAAR LOOK-AHEAD))
(WHEN (= (CAAR LOOK-AHEAD) (LENGTH S))
(POP LOOK-AHEAD)))))
(T (POP LOOK-AHEAD)) ))
,(if *full-table-p*
`(FIND-NEXT-STATE (STATE CH)
(IF (CHARACTERP CH)
(SVREF (STATE-TRANSITIONS STATE) (CHAR-CODE CH))
NIL))
`(FIND-NEXT-STATE (STATE CH)
(BLOCK FOO
(DOLIST (K (STATE-TRANSITIONS STATE))
(DOLIST (Q (CAR K))
(WHEN (CHAR= CH Q)
(RETURN-FROM FOO (CDR K)))))))) )
(DECLARE (INLINE BACKUP GETCH FIND-NEXT-STATE))
(TAGBODY
START (SETQ STATE (CDR (ASSOC SUB-STATE STARTS)))
(WHEN (NULL STATE)
(ERROR "Sub-state ~S is not defined." SUB-STATE))
(REWIND*)
LOOP (SETQ CH (GETCH))
(LET ((NEXT-STATE (FIND-NEXT-STATE STATE CH)) )
(COND ((NULL NEXT-STATE)
(BACKUP CH)
(DO ()
((OR (EMPTY*?) (NOT (EQ 0 (TOS*/STATE)))))
(BACKUP (POP*/CH)))
(COND ((AND (EMPTY*?) (NULL CH))
(RETURN :EOF))
((EMPTY*?)
(ERROR "oops ~S ~S" ch (mapcar #'car (state-transitions state))))
(T
(LET ((HALTING-STATE (TOS*/STATE)))
(LET ((BAG* NIL))
(SYMBOL-MACROLET ((BAG (IF BAG*
BAG*
(SETF BAG* (STRING*)))))
(CASE HALTING-STATE
,@clauses)))
(GO START)))))
(T
(PUSH* CH (STATE-FINAL NEXT-STATE))
(SETQ STATE NEXT-STATE)
(GO LOOP))))))))))))
|
bc59c3449bfceefe941349729c56424618aa10c88ccf28c64ca2d6fe77dff6c0 | haskell-effectful/effectful | Utils.hs | module Utils
( runShallow
, runDeep
) where
import Effectful
import Effectful.State.Dynamic
runShallow :: Eff '[IOE] a -> IO a
runShallow = runEff
runDeep
:: Eff '[ State (), State (), State (), State (), State ()
, State (), State (), State (), State (), State ()
, IOE
] a
-> IO a
runDeep = runEff
. evalStateLocal () . evalStateLocal () . evalStateLocal () . evalStateLocal ()
. evalStateLocal () . evalStateLocal () . evalStateLocal () . evalStateLocal ()
. evalStateLocal () . evalStateLocal ()
| null | https://raw.githubusercontent.com/haskell-effectful/effectful/20848432bd29f648dbbae671da5dff3216b60e44/effectful/bench/Utils.hs | haskell | module Utils
( runShallow
, runDeep
) where
import Effectful
import Effectful.State.Dynamic
runShallow :: Eff '[IOE] a -> IO a
runShallow = runEff
runDeep
:: Eff '[ State (), State (), State (), State (), State ()
, State (), State (), State (), State (), State ()
, IOE
] a
-> IO a
runDeep = runEff
. evalStateLocal () . evalStateLocal () . evalStateLocal () . evalStateLocal ()
. evalStateLocal () . evalStateLocal () . evalStateLocal () . evalStateLocal ()
. evalStateLocal () . evalStateLocal ()
| |
4777e0ceb3edcbb9d3799eb93166bde57cc5a92da0e89919e0a74c377212aab9 | chrisdone/lucid | RunHtmlBenchmarks.hs | | This is a module which runs the ' HtmlBenchmarks ' module using the different
-- renderers available.
--
module RunHtmlBenchmarks where
import Criterion.Main
import qualified Data.ByteString.Lazy as LB
import qualified Data.Text.Lazy.Encoding as LT
import qualified Data.Text.Lazy as LT
import qualified Text.Blaze.Renderer.Utf8 as Utf8
import qualified Text.Blaze.Renderer.String as String
import qualified Text.Blaze.Renderer.Text as Text
import HtmlBenchmarks (HtmlBenchmark (..), benchmarks)
import qualified Blaze.ByteString.Builder.Char.Utf8 as Blaze
import qualified Blaze.ByteString.Builder as Blaze
import Lucid (renderBS)
-- | Function to run the benchmarks using criterion
--
main :: IO ()
main = defaultMain $ map benchHtml benchmarks
where
benchHtml (HtmlBenchmark name f x _) = bgroup name $
[bench "ByteString" $ nf (LB.length . renderBS . f) x
]
| null | https://raw.githubusercontent.com/chrisdone/lucid/cc7b2e77c65fc87d5729fabd942486d5729789de/lucid1/benchmarks/RunHtmlBenchmarks.hs | haskell | renderers available.
| Function to run the benchmarks using criterion
| | This is a module which runs the ' HtmlBenchmarks ' module using the different
module RunHtmlBenchmarks where
import Criterion.Main
import qualified Data.ByteString.Lazy as LB
import qualified Data.Text.Lazy.Encoding as LT
import qualified Data.Text.Lazy as LT
import qualified Text.Blaze.Renderer.Utf8 as Utf8
import qualified Text.Blaze.Renderer.String as String
import qualified Text.Blaze.Renderer.Text as Text
import HtmlBenchmarks (HtmlBenchmark (..), benchmarks)
import qualified Blaze.ByteString.Builder.Char.Utf8 as Blaze
import qualified Blaze.ByteString.Builder as Blaze
import Lucid (renderBS)
main :: IO ()
main = defaultMain $ map benchHtml benchmarks
where
benchHtml (HtmlBenchmark name f x _) = bgroup name $
[bench "ByteString" $ nf (LB.length . renderBS . f) x
]
|
ea797b2fbcd166b04b35e22763ccbdd136863578888ea624b7b22ffc8e1a6568 | eeng/shevek | save.cljs | (ns shevek.pages.reports.save
(:require [reagent.core :as r]
[shevek.rpc :as rpc]
[shevek.i18n :refer [t]]
[shevek.reflow.core :refer [dispatch] :refer-macros [defevh]]
[shevek.components.modal :refer [show-modal close-modal]]
[shevek.components.form :refer [input-field]]
[shevek.components.shortcuts :refer [shortcuts]]
[shevek.components.notification :refer [notify]]))
(defevh :reports/saved [db {:keys [name] :as report} after-save]
(notify (t :reports/saved name))
(after-save report)
(close-modal)
(rpc/loaded db :saving-report))
(defevh :reports/save [db report after-save]
(rpc/call "reports/save" :args [report] :handler #(dispatch :reports/saved % after-save))
(rpc/loading db :saving-report))
(defn- save-as-dialog [{:keys [report after-save]}]
(r/with-let [form-data (r/atom (select-keys report [:name :description]))
valid? #(seq (:name @form-data))
save #(when (valid?)
(dispatch :reports/save (merge report @form-data) after-save))]
[shortcuts {:enter save}
[:div.ui.tiny.modal
[:div.header (t :actions/save-as)]
[:div.content
[:div.ui.form
[input-field form-data :name {:label (t :reports/name) :auto-focus true :on-focus #(-> % .-target .select)}]
[input-field form-data :description {:label (t :reports/description) :as :textarea :rows 2}]]]
[:div.actions
[:button.ui.green.button
{:on-click save
:class [(when-not (valid?) "disabled")
(when (rpc/loading? :saving-report) "loading disabled")]}
(t :actions/save)]
[:button.ui.cancel.button
(t :actions/cancel)]]]]))
(defn open-save-as-dialog [props]
(show-modal [save-as-dialog props]))
| null | https://raw.githubusercontent.com/eeng/shevek/7783b8037303b8dd5f320f35edee3bfbb2b41c02/src/cljs/shevek/pages/reports/save.cljs | clojure | (ns shevek.pages.reports.save
(:require [reagent.core :as r]
[shevek.rpc :as rpc]
[shevek.i18n :refer [t]]
[shevek.reflow.core :refer [dispatch] :refer-macros [defevh]]
[shevek.components.modal :refer [show-modal close-modal]]
[shevek.components.form :refer [input-field]]
[shevek.components.shortcuts :refer [shortcuts]]
[shevek.components.notification :refer [notify]]))
(defevh :reports/saved [db {:keys [name] :as report} after-save]
(notify (t :reports/saved name))
(after-save report)
(close-modal)
(rpc/loaded db :saving-report))
(defevh :reports/save [db report after-save]
(rpc/call "reports/save" :args [report] :handler #(dispatch :reports/saved % after-save))
(rpc/loading db :saving-report))
(defn- save-as-dialog [{:keys [report after-save]}]
(r/with-let [form-data (r/atom (select-keys report [:name :description]))
valid? #(seq (:name @form-data))
save #(when (valid?)
(dispatch :reports/save (merge report @form-data) after-save))]
[shortcuts {:enter save}
[:div.ui.tiny.modal
[:div.header (t :actions/save-as)]
[:div.content
[:div.ui.form
[input-field form-data :name {:label (t :reports/name) :auto-focus true :on-focus #(-> % .-target .select)}]
[input-field form-data :description {:label (t :reports/description) :as :textarea :rows 2}]]]
[:div.actions
[:button.ui.green.button
{:on-click save
:class [(when-not (valid?) "disabled")
(when (rpc/loading? :saving-report) "loading disabled")]}
(t :actions/save)]
[:button.ui.cancel.button
(t :actions/cancel)]]]]))
(defn open-save-as-dialog [props]
(show-modal [save-as-dialog props]))
| |
18d0174e93a718da74a8a9fd4d4f42d8cdcd8407ed1af021a69a6778374a6f00 | Gbury/dolmen | value.mli |
(* This file is free software, part of dolmen. See file "LICENSE" for more information *)
* { 2 Type definitions }
(** ************************************************************************ *)
type t
type 'a ops
type any_ops = Ops : _ ops -> any_ops
exception Extraction_failed of t * any_ops
(* Creating/extracting values *)
(* ************************************************************************* *)
val mk : ops:'a ops -> 'a -> t
val extract : ops:'a ops -> t -> 'a option
val extract_exn : ops:'a ops -> t -> 'a
val abstract_cst : Dolmen.Std.Expr.Term.Const.t -> t
* { 2 Custom operations }
(** ************************************************************************ *)
val ops :
?abstract:'a ->
compare:('a -> 'a -> int) ->
print:(Format.formatter -> 'a -> unit) ->
unit -> 'a ops
val print : Format.formatter -> t -> unit
val compare : t -> t -> int
* { 2 Sets and Maps }
(** ************************************************************************ *)
module Set : Set.S with type elt = t
module Map : Map.S with type key = t
| null | https://raw.githubusercontent.com/Gbury/dolmen/12bf280df3d886ddc0faa110effbafb71bffef7e/src/model/value.mli | ocaml | This file is free software, part of dolmen. See file "LICENSE" for more information
* ************************************************************************
Creating/extracting values
*************************************************************************
* ************************************************************************
* ************************************************************************ |
* { 2 Type definitions }
type t
type 'a ops
type any_ops = Ops : _ ops -> any_ops
exception Extraction_failed of t * any_ops
val mk : ops:'a ops -> 'a -> t
val extract : ops:'a ops -> t -> 'a option
val extract_exn : ops:'a ops -> t -> 'a
val abstract_cst : Dolmen.Std.Expr.Term.Const.t -> t
* { 2 Custom operations }
val ops :
?abstract:'a ->
compare:('a -> 'a -> int) ->
print:(Format.formatter -> 'a -> unit) ->
unit -> 'a ops
val print : Format.formatter -> t -> unit
val compare : t -> t -> int
* { 2 Sets and Maps }
module Set : Set.S with type elt = t
module Map : Map.S with type key = t
|
9c73d1173dbde4d236a4de48fdcf100cf0f3116bae1551a19df0506d1972b9ce | metosin/kekkonen | client.clj | (ns example.client)
(require '[kekkonen.core :as k])
(require '[schema.core :as s])
(require '[plumbing.core :as p])
;;
;; Handlers
;;
; simplest thing that works
(def hello-world
(k/handler
{:name "hello-world"
:handle (fn [_]
"hello world.")}))
(hello-world {})
; with more stuff
(def echo
(k/handler
{:description "this is a handler for echoing data"
:name :echo
:summary "echoes data"
:handle (fn [{:keys [data]}]
data)}))
(echo {:data {:name "tommi"}})
fnks
(def ^:handler plus
(k/handler
{:description "fnk echo"
:name :fnkecho
:summery "echoes data"
:handle (p/fnk [[:data x :- s/Int, y :- s/Int]]
(+ x y))}))
(plus {:data {:x 1, :y 2}})
; defnk
(p/defnk ^:handler multiply
"multiply x with y"
[[:data x :- s/Int, y :- s/Int]]
{:result (* x y)})
(multiply {:data {:x 4, :y 7}})
; stateful inc!
(p/defnk ^:handler inc!
"adds a global counter"
[[:components counter]]
(swap! counter inc))
(inc! {:components {:counter (atom 10)}})
;;
;; Dispatcher
;;
; create
(def d (k/dispatcher
{:handlers {:api {:calculator [#'multiply #'plus]
:stateful #'inc!
:others [echo
hello-world]
:public (k/handler
{:name :ping
:handle (p/fnk [] :pong)})}}
:context {:components {:counter (atom 0)}}}))
; get a handler
(k/some-handler d :api/nill)
(k/some-handler d :api.stateful/inc!)
; invoke a handler
(k/invoke d :api.stateful/inc!)
multi - tenant SAAS ftw ?
(k/invoke d :api.stateful/inc! {:components {:counter (atom 99)}})
; can i call it?
(k/validate d :api.stateful/inc!)
| null | https://raw.githubusercontent.com/metosin/kekkonen/5a38c52af34a0eb0f19d87e9f549e93e6d87885f/dev-src/example/client.clj | clojure |
Handlers
simplest thing that works
with more stuff
defnk
stateful inc!
Dispatcher
create
get a handler
invoke a handler
can i call it? | (ns example.client)
(require '[kekkonen.core :as k])
(require '[schema.core :as s])
(require '[plumbing.core :as p])
(def hello-world
(k/handler
{:name "hello-world"
:handle (fn [_]
"hello world.")}))
(hello-world {})
(def echo
(k/handler
{:description "this is a handler for echoing data"
:name :echo
:summary "echoes data"
:handle (fn [{:keys [data]}]
data)}))
(echo {:data {:name "tommi"}})
fnks
(def ^:handler plus
(k/handler
{:description "fnk echo"
:name :fnkecho
:summery "echoes data"
:handle (p/fnk [[:data x :- s/Int, y :- s/Int]]
(+ x y))}))
(plus {:data {:x 1, :y 2}})
(p/defnk ^:handler multiply
"multiply x with y"
[[:data x :- s/Int, y :- s/Int]]
{:result (* x y)})
(multiply {:data {:x 4, :y 7}})
(p/defnk ^:handler inc!
"adds a global counter"
[[:components counter]]
(swap! counter inc))
(inc! {:components {:counter (atom 10)}})
(def d (k/dispatcher
{:handlers {:api {:calculator [#'multiply #'plus]
:stateful #'inc!
:others [echo
hello-world]
:public (k/handler
{:name :ping
:handle (p/fnk [] :pong)})}}
:context {:components {:counter (atom 0)}}}))
(k/some-handler d :api/nill)
(k/some-handler d :api.stateful/inc!)
(k/invoke d :api.stateful/inc!)
multi - tenant SAAS ftw ?
(k/invoke d :api.stateful/inc! {:components {:counter (atom 99)}})
(k/validate d :api.stateful/inc!)
|
b27d3da12ee10c3cd2bc55d1b0fed302af15e58c95edef6817bb94996f57fc1d | omcljs/om | next.cljc | (ns om.next
(:refer-clojure :exclude #?(:clj [deftype replace var? force]
:cljs [var? key replace force]))
#?(:cljs (:require-macros [om.next :refer [defui invariant]]))
(:require #?@(:clj [clojure.main
[cljs.core :refer [deftype specify! this-as js-arguments]]
[clojure.reflect :as reflect]
[cljs.util]]
:cljs [[goog.string :as gstring]
[goog.object :as gobj]
[goog.log :as glog]
[om.next.cache :as c]])
[om.next.impl.parser :as parser]
[om.tempid :as tempid]
[om.transit :as transit]
[om.util :as util]
[clojure.zip :as zip]
[om.next.protocols :as p]
[cljs.analyzer :as ana]
[cljs.analyzer.api :as ana-api]
[clojure.string :as str])
#?(:clj (:import [java.io Writer])
:cljs (:import [goog.debug Console])))
(defn collect-statics [dt]
(letfn [(split-on-static [forms]
(split-with (complement '#{static}) forms))
(split-on-symbol [forms]
(split-with (complement symbol?) forms))]
(loop [dt (seq dt) dt' [] statics {:fields {} :protocols []}]
(if dt
(let [[pre [_ sym & remaining :as post]] (split-on-static dt)
dt' (into dt' pre)]
(if (seq post)
(cond
(= sym 'field)
(let [[field-info dt] (split-at 2 remaining)]
(recur (seq dt) dt'
(update-in statics [:fields] conj (vec field-info))))
(symbol? sym)
(let [[protocol-info dt] (split-on-symbol remaining)]
(recur (seq dt) dt'
(update-in statics [:protocols]
into (concat [sym] protocol-info))))
:else (throw #?(:clj (IllegalArgumentException. "Malformed static")
:cljs (js/Error. "Malformed static"))))
(recur nil dt' statics)))
{:dt dt' :statics statics}))))
(defn- validate-statics [dt]
(when-let [invalid (some #{"Ident" "IQuery" "IQueryParams"}
(map #(-> % str (str/split #"/") last)
(filter symbol? dt)))]
(throw
#?(:clj (IllegalArgumentException.
(str invalid " protocol declaration must appear with `static`."))
:cljs (js/Error.
(str invalid " protocol declaration must appear with `static`."))))))
(def lifecycle-sigs
'{initLocalState [this]
shouldComponentUpdate [this next-props next-state]
componentWillReceiveProps [this next-props]
componentWillUpdate [this next-props next-state]
componentDidUpdate [this prev-props prev-state]
componentWillMount [this]
componentDidMount [this]
componentWillUnmount [this]
render [this]})
(defn validate-sig [[name sig :as method]]
(let [sig' (get lifecycle-sigs name)]
(assert (= (count sig') (count sig))
(str "Invalid signature for " name " got " sig ", need " sig'))))
#?(:clj
(def reshape-map-clj
{:reshape
{'render
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#]
(binding [om.next/*reconciler* (om.next/get-reconciler this#)
om.next/*depth* (inc (om.next/depth this#))
om.next/*shared* (om.next/shared this#)
om.next/*instrument* (om.next/instrument this#)
om.next/*parent* this#]
(let [ret# (do ~@body)
props# (:props this#)]
(when-not @(:omcljs$mounted? props#)
(swap! (:omcljs$mounted? props#) not))
ret#)))))
'componentWillMount
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#
indexer# (get-in (om.next/get-reconciler this#) [:config :indexer])]
(when-not (nil? indexer#)
(om.next.protocols/index-component! indexer# this#))
~@body)))}
:defaults
`{~'initLocalState
([this#])
~'componentWillMount
([this#]
(let [indexer# (get-in (om.next/get-reconciler this#) [:config :indexer])]
(when-not (nil? indexer#)
(om.next.protocols/index-component! indexer# this#))))
~'render
([this#])}}))
(def reshape-map
{:reshape
{'initLocalState
(fn [[name [this :as args] & body]]
`(~name ~args
(let [ret# (do ~@body)]
(cljs.core/js-obj "omcljs$state" ret#))))
'componentWillReceiveProps
(fn [[name [this next-props :as args] & body]]
`(~name [this# next-props#]
(let [~this this#
~next-props (om.next/-next-props next-props# this#)]
~@body)))
'componentWillUpdate
(fn [[name [this next-props next-state :as args] & body]]
`(~name [this# next-props# next-state#]
(let [~this this#
~next-props (om.next/-next-props next-props# this#)
~next-state (or (goog.object/get next-state# "omcljs$pendingState")
(goog.object/get next-state# "omcljs$state"))
ret# (do ~@body)]
(when (cljs.core/implements? om.next/Ident this#)
(let [ident# (om.next/ident this# (om.next/props this#))
next-ident# (om.next/ident this# ~next-props)]
(when (not= ident# next-ident#)
(let [idxr# (get-in (om.next/get-reconciler this#) [:config :indexer])]
(when-not (nil? idxr#)
(swap! (:indexes idxr#)
(fn [indexes#]
(-> indexes#
(update-in [:ref->components ident#] disj this#)
(update-in [:ref->components next-ident#] (fnil conj #{}) this#)))))))))
(om.next/merge-pending-props! this#)
(om.next/merge-pending-state! this#)
ret#)))
'componentDidUpdate
(fn [[name [this prev-props prev-state :as args] & body]]
`(~name [this# prev-props# prev-state#]
(let [~this this#
~prev-props (om.next/-prev-props prev-props# this#)
~prev-state (goog.object/get prev-state# "omcljs$previousState")]
~@body
(om.next/clear-prev-props! this#))))
'componentWillMount
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#
indexer# (get-in (om.next/get-reconciler this#) [:config :indexer])]
(when-not (nil? indexer#)
(om.next.protocols/index-component! indexer# this#))
~@body)))
'componentWillUnmount
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#
r# (om.next/get-reconciler this#)
cfg# (:config r#)
st# (:state cfg#)
indexer# (:indexer cfg#)]
(when (and (not (nil? st#))
(get-in @st# [:om.next/queries this#]))
(swap! st# update-in [:om.next/queries] dissoc this#))
(when-not (nil? indexer#)
(om.next.protocols/drop-component! indexer# this#))
~@body)))
'render
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#]
(binding [om.next/*reconciler* (om.next/get-reconciler this#)
om.next/*depth* (inc (om.next/depth this#))
om.next/*shared* (om.next/shared this#)
om.next/*instrument* (om.next/instrument this#)
om.next/*parent* this#]
~@body))))}
:defaults
`{~'isMounted
([this#]
(boolean
(or (some-> this# .-_reactInternalFiber .-stateNode)
Pre React 16 support . Remove when we do n't wish to support
React < 16 anymore - Antonio
(some-> this# .-_reactInternalInstance .-_renderedComponent))))
~'shouldComponentUpdate
([this# next-props# next-state#]
(let [next-children# (. next-props# -children)
next-props# (goog.object/get next-props# "omcljs$value")
next-props# (cond-> next-props#
(instance? om.next/OmProps next-props#) om.next/unwrap)]
(or (not= (om.next/props this#)
next-props#)
(and (.. this# ~'-state)
(not= (goog.object/get (. this# ~'-state) "omcljs$state")
(goog.object/get next-state# "omcljs$state")))
(not= (.. this# -props -children)
next-children#))))
~'componentWillUpdate
([this# next-props# next-state#]
(when (cljs.core/implements? om.next/Ident this#)
(let [ident# (om.next/ident this# (om.next/props this#))
next-ident# (om.next/ident this# (om.next/-next-props next-props# this#))]
(when (not= ident# next-ident#)
(let [idxr# (get-in (om.next/get-reconciler this#) [:config :indexer])]
(when-not (nil? idxr#)
(swap! (:indexes idxr#)
(fn [indexes#]
(-> indexes#
(update-in [:ref->components ident#] disj this#)
(update-in [:ref->components next-ident#] (fnil conj #{}) this#)))))))))
(om.next/merge-pending-props! this#)
(om.next/merge-pending-state! this#))
~'componentDidUpdate
([this# prev-props# prev-state#]
(om.next/clear-prev-props! this#))
~'componentWillMount
([this#]
(let [indexer# (get-in (om.next/get-reconciler this#) [:config :indexer])]
(when-not (nil? indexer#)
(om.next.protocols/index-component! indexer# this#))))
~'componentWillUnmount
([this#]
(let [r# (om.next/get-reconciler this#)
cfg# (:config r#)
st# (:state cfg#)
indexer# (:indexer cfg#)]
(when (and (not (nil? st#))
(get-in @st# [:om.next/queries this#]))
(swap! st# update-in [:om.next/queries] dissoc this#))
(when-not (nil? indexer#)
(om.next.protocols/drop-component! indexer# this#))))}})
(defn reshape [dt {:keys [reshape defaults]}]
(letfn [(reshape* [x]
(if (and (sequential? x)
(contains? reshape (first x)))
(let [reshapef (get reshape (first x))]
(validate-sig x)
(reshapef x))
x))
(add-defaults-step [ret [name impl]]
(if-not (some #{name} (map first (filter seq? ret)))
(let [[before [p & after]] (split-with (complement '#{Object}) ret)]
(into (conj (vec before) p (cons name impl)) after))
ret))
(add-defaults [dt]
(reduce add-defaults-step dt defaults))
(add-object-protocol [dt]
(if-not (some '#{Object} dt)
(conj dt 'Object)
dt))]
(->> dt (map reshape*) vec add-object-protocol add-defaults)))
#?(:clj
(defn- add-proto-methods* [pprefix type type-sym [f & meths :as form]]
(let [pf (str pprefix (name f))
emit-static (when (-> type-sym meta :static)
`(~'js* "/** @nocollapse */"))]
(if (vector? (first meths))
;; single method case
(let [meth meths]
[`(do
~emit-static
(set! ~(#'cljs.core/extend-prefix type-sym (str pf "$arity$" (count (first meth))))
~(with-meta `(fn ~@(#'cljs.core/adapt-proto-params type meth)) (meta form))))])
(map (fn [[sig & body :as meth]]
`(do
~emit-static
(set! ~(#'cljs.core/extend-prefix type-sym (str pf "$arity$" (count sig)))
~(with-meta `(fn ~(#'cljs.core/adapt-proto-params type meth)) (meta form)))))
meths)))))
#?(:clj (intern 'cljs.core 'add-proto-methods* add-proto-methods*))
#?(:clj
(defn- proto-assign-impls [env resolve type-sym type [p sigs]]
(#'cljs.core/warn-and-update-protocol p type env)
(let [psym (resolve p)
pprefix (#'cljs.core/protocol-prefix psym)
skip-flag (set (-> type-sym meta :skip-protocol-flag))
static? (-> p meta :static)
type-sym (cond-> type-sym
static? (vary-meta assoc :static true))
emit-static (when static?
`(~'js* "/** @nocollapse */"))]
(if (= p 'Object)
(#'cljs.core/add-obj-methods type type-sym sigs)
(concat
(when-not (skip-flag psym)
(let [{:keys [major minor qualifier]} cljs.util/*clojurescript-version*]
(if (or (> major 1)
(and (== major 1) (> minor 9))
(and (== major 1) (== minor 9) (>= qualifier 293)))
[`(do
~emit-static
(set! ~(#'cljs.core/extend-prefix type-sym pprefix) cljs.core/PROTOCOL_SENTINEL))]
[`(do
~emit-static
(set! ~(#'cljs.core/extend-prefix type-sym pprefix) true))])))
(mapcat
(fn [sig]
(if (= psym 'cljs.core/IFn)
(#'cljs.core/add-ifn-methods type type-sym sig)
(#'cljs.core/add-proto-methods* pprefix type type-sym sig)))
sigs))))))
#?(:clj (intern 'cljs.core 'proto-assign-impls proto-assign-impls))
#?(:clj (defn- extract-static-methods [protocols]
(letfn [(add-protocol-method [existing-methods method]
(let [nm (first method)
new-arity (rest method)
k (keyword nm)
existing-method (get existing-methods k)]
(if existing-method
(let [single-arity? (vector? (second existing-method))
existing-arities (if single-arity?
(list (rest existing-method))
(rest existing-method))]
(assoc existing-methods k (conj existing-arities new-arity 'fn)))
(assoc existing-methods k (list 'fn new-arity)))))]
(when-not (empty? protocols)
(let [result (->> protocols
(filter #(not (symbol? %)))
(reduce
(fn [r impl] (add-protocol-method r impl))
{}))]
(if (contains? result :params)
result
(assoc result :params '(fn [this]))))))))
#?(:clj
(defn defui*-clj [name forms]
(let [docstring (when (string? (first forms))
(first forms))
forms (cond-> forms
docstring rest)
{:keys [dt statics]} (collect-statics forms)
[other-protocols obj-dt] (split-with (complement '#{Object}) dt)
klass-name (symbol (str name "_klass"))
lifecycle-method-names (set (keys lifecycle-sigs))
{obj-dt false non-lifecycle-dt true} (group-by
(fn [x]
(and (sequential? x)
(not (lifecycle-method-names (first x)))))
obj-dt)
class-methods (extract-static-methods (:protocols statics))]
`(do
~(when-not (empty? non-lifecycle-dt)
`(defprotocol ~(symbol (str name "_proto"))
~@(map (fn [[m-name args]] (list m-name args)) non-lifecycle-dt)))
(declare ~name)
(defrecord ~klass-name [~'state ~'refs ~'props ~'children]
TODO : non - lifecycle methods defined in the JS prototype - António
om.next.protocols/IReactLifecycle
~@(rest (reshape obj-dt reshape-map-clj))
~@other-protocols
~@(:protocols statics)
~@(when-not (empty? non-lifecycle-dt)
(list* (symbol (str name "_proto"))
non-lifecycle-dt))
om.next.protocols/IReactComponent
(~'-render [this#]
(p/componentWillMount this#)
(p/render this#)))
(defmethod clojure.core/print-method ~(symbol (str (munge *ns*) "." klass-name))
[o# ^Writer w#]
(.write w# (str "#object[" (ns-name *ns*) "/" ~(str name) "]")))
(let [c# (fn ~name [state# refs# props# children#]
(~(symbol (str (munge *ns*) "." klass-name ".")) state# refs# props# children#))]
(def ~(with-meta name
(merge (meta name)
(when docstring
{:doc docstring})))
(with-meta c#
(merge {:component c#
:component-ns (ns-name *ns*)
:component-name ~(str name)}
~class-methods))))))))
(defn defui*
([name form] (defui* name form nil))
([name forms env]
(letfn [(field-set! [obj [field value]]
`(set! (. ~obj ~(symbol (str "-" field))) ~value))]
(let [docstring (when (string? (first forms))
(first forms))
forms (cond-> forms
docstring rest)
{:keys [dt statics]} (collect-statics forms)
_ (validate-statics dt)
rname (if env
(:name (ana/resolve-var (dissoc env :locals) name))
name)
ctor `(defn ~(with-meta name
(merge {:jsdoc ["@constructor"]}
(meta name)
(when docstring
{:doc docstring})))
[]
(this-as this#
(.apply js/React.Component this# (js-arguments))
(if-not (nil? (.-initLocalState this#))
(set! (.-state this#) (.initLocalState this#))
(set! (.-state this#) (cljs.core/js-obj)))
this#))
set-react-proto! `(set! (.-prototype ~name)
(goog.object/clone js/React.Component.prototype))
ctor (if (-> name meta :once)
`(when-not (cljs.core/exists? ~name)
~ctor
~set-react-proto!)
`(do
~ctor
~set-react-proto!))
display-name (if env
(str (-> env :ns :name) "/" name)
'js/undefined)]
`(do
~ctor
(specify! (.-prototype ~name) ~@(reshape dt reshape-map))
(set! (.. ~name -prototype -constructor) ~name)
(set! (.. ~name -prototype -constructor -displayName) ~display-name)
(set! (.. ~name -prototype -om$isComponent) true)
~@(map #(field-set! name %) (:fields statics))
(specify! ~name
~@(mapv #(cond-> %
(symbol? %) (vary-meta assoc :static true)) (:protocols statics)))
(specify! (. ~name ~'-prototype) ~@(:protocols statics))
(set! (.-cljs$lang$type ~rname) true)
(set! (.-cljs$lang$ctorStr ~rname) ~(str rname))
(set! (.-cljs$lang$ctorPrWriter ~rname)
(fn [this# writer# opt#]
(cljs.core/-write writer# ~(str rname)))))))))
(defmacro defui [name & forms]
(if (boolean (:ns &env))
(defui* name forms &env)
#?(:clj (defui*-clj name forms))))
(defmacro ui
[& forms]
(let [t (with-meta (gensym "ui_") {:anonymous true})]
`(do (defui ~t ~@forms) ~t)))
;; TODO: #?:clj invariant - António
(defn invariant*
[condition message env]
(let [opts (ana-api/get-options)
fn-scope (:fn-scope env)
fn-name (some-> fn-scope first :name str)]
(when-not (:elide-asserts opts)
`(let [l# om.next/*logger*]
(when-not ~condition
(goog.log/error l#
(str "Invariant Violation"
(when-not (nil? ~fn-name)
(str " (in function: `" ~fn-name "`)"))
": " ~message)))))))
(defmacro invariant
[condition message]
(when (boolean (:ns &env))
(invariant* condition message &env)))
#?(:clj
(defmethod print-method clojure.lang.AFunction
[o ^Writer w]
(let [obj-ns (-> o meta :component-ns)
obj-name (-> o meta :component-name)]
(if obj-name
(.write w (str obj-ns "/" obj-name))
(#'clojure.core/print-object o w)))))
;; =============================================================================
;; CLJS
#?(:cljs
(defonce *logger*
(when ^boolean goog.DEBUG
(.setCapturing (Console.) true)
(glog/getLogger "om.next"))))
;; =============================================================================
;; Globals & Dynamics
(def ^:private roots (atom {}))
(def ^{:dynamic true} *raf* nil)
(def ^{:dynamic true :private true} *reconciler* nil)
(def ^{:dynamic true :private true} *parent* nil)
(def ^{:dynamic true :private true} *shared* nil)
(def ^{:dynamic true :private true} *instrument* nil)
(def ^{:dynamic true :private true} *depth* 0)
;; =============================================================================
Utilities
(defn nil-or-map?
#?(:cljs {:tag boolean})
[x]
(or (nil? x) (map? x)))
(defn- expr->key
"Given a query expression return its key."
[expr]
(cond
(keyword? expr) expr
(map? expr) (ffirst expr)
(seq? expr) (let [expr' (first expr)]
(when (map? expr')
(ffirst expr')))
(util/ident? expr) (cond-> expr (= '_ (second expr)) first)
:else
(throw
(ex-info (str "Invalid query expr " expr)
{:type :error/invalid-expression}))))
(defn- query-zip
"Return a zipper on a query expression."
[root]
(zip/zipper
#(or (vector? %) (map? %) (seq? %))
seq
(fn [node children]
(let [ret (cond
(vector? node) (vec children)
(map? node) (into {} children)
(seq? node) children)]
(with-meta ret (meta node))))
root))
(defn- move-to-key
"Move from the current zipper location to the specified key. loc must be a
hash map node."
[loc k]
(loop [loc (zip/down loc)]
(let [node (zip/node loc)]
(if (= k (first node))
(-> loc zip/down zip/right)
(recur (zip/right loc))))))
(defn- query-template
"Given a query and a path into a query return a zipper focused at the location
specified by the path. This location can be replaced to customize / alter
the query."
[query path]
(letfn [(query-template* [loc path]
(if (empty? path)
loc
(let [node (zip/node loc)]
(if (vector? node) ;; SUBQUERY
(recur (zip/down loc) path)
(let [[k & ks] path
k' (expr->key node)]
(if (= k k')
(if (or (map? node)
(and (seq? node) (map? (first node))))
(let [loc' (move-to-key (cond-> loc (seq? node) zip/down) k)
node' (zip/node loc')]
(if (map? node') ;; UNION
(if (seq ks)
(recur
(zip/replace loc'
(zip/node (move-to-key loc' (first ks))))
(next ks))
loc')
(recur loc' ks))) ;; JOIN
(recur (-> loc zip/down zip/down zip/down zip/right) ks)) ;; CALL
(recur (zip/right loc) path)))))))]
(query-template* (query-zip query) path)))
(defn- replace [template new-query]
(-> template (zip/replace new-query) zip/root))
(declare focus-query*)
(defn- focused-join [expr ks full-expr union-expr]
(let [expr-meta (meta expr)
expr' (cond
(map? expr)
(let [join-value (-> expr first second)
join-value (if (and (util/recursion? join-value)
(seq ks))
(if-not (nil? union-expr)
union-expr
full-expr)
join-value)]
{(ffirst expr) (focus-query* join-value ks nil)})
(seq? expr) (list (focused-join (first expr) ks nil nil) (second expr))
:else expr)]
(cond-> expr'
(some? expr-meta) (with-meta expr-meta))))
(defn- focus-query*
[query path union-expr]
(if (empty? path)
query
(let [[k & ks] path]
(letfn [(match [x]
(= k (util/join-key x)))
(value [x]
(focused-join x ks query union-expr))]
(if (map? query) ;; UNION
{k (focus-query* (get query k) ks query)}
(into [] (comp (filter match) (map value) (take 1)) query))))))
(defn focus-query
"Given a query, focus it along the specified path.
Examples:
(om.next/focus-query [:foo :bar :baz] [:foo])
=> [:foo]
(om.next/focus-query [{:foo [:bar :baz]} :woz] [:foo :bar])
=> [{:foo [:bar]}]"
[query path]
(focus-query* query path nil))
;; this function assumes focus is actually in fact
;; already focused!
(defn- focus->path
"Given a focused query return the path represented by the query.
Examples:
(om.next/focus->path [{:foo [{:bar {:baz []}]}])
=> [:foo :bar :baz]"
([focus]
(focus->path focus '* []))
([focus bound]
(focus->path focus bound []))
([focus bound path]
(if (and (or (= bound '*)
(and (not= path bound)
(< (count path) (count bound))))
(some util/join? focus)
(== 1 (count focus)))
(let [[k focus'] (util/join-entry (first focus))
focus' (if (util/recursion? focus')
focus
focus')]
(recur focus' bound (conj path k)))
path)))
;; =============================================================================
;; Query Protocols & Helpers
(defprotocol Ident
(ident [this props] "Return the ident for this component"))
(defprotocol IQueryParams
(params [this] "Return the query parameters"))
#?(:clj (extend-type Object
IQueryParams
(params [this]
(when-let [ps (-> this meta :params)]
(ps this))))
:cljs (extend-type default
IQueryParams
(params [_])))
(defprotocol IQuery
(query [this] "Return the component's unbound query"))
(defprotocol ILocalState
(-set-state! [this new-state] "Set the component's local state")
(-get-state [this] "Get the component's local state")
(-get-rendered-state [this] "Get the component's rendered local state")
(-merge-pending-state! [this] "Get the component's pending local state"))
(defn- var? [x]
(and (symbol? x)
#?(:clj (.startsWith (str x) "?")
:cljs (gstring/startsWith (str x) "?"))))
(defn- var->keyword [x]
(keyword (.substring (str x) 1)))
(defn- replace-var [expr params]
(if (var? expr)
(get params (var->keyword expr) expr)
expr))
(defn- bind-query [query params]
(let [qm (meta query)
tr (map #(bind-query % params))
ret (cond
(seq? query) (apply list (into [] tr query))
#?@(:cljs [(and (exists? cljs.core/IMapEntry)
(implements? ^:cljs.analyzer/no-resolve cljs.core/IMapEntry query))
(into [] tr query)])
#?@(:clj [(instance? clojure.lang.IMapEntry query) (into [] tr query)])
(coll? query) (into (empty query) tr query)
:else (replace-var query params))]
(cond-> ret
(and qm #?(:clj (instance? clojure.lang.IObj ret)
:cljs (satisfies? IMeta ret)))
(with-meta qm))))
(declare component? get-reconciler props class-path get-indexer path react-type)
(defn- component->query-data [component]
(some-> (get-reconciler component)
:config :state deref ::queries (get component)))
(defn get-unbound-query
"Return the unbound query for a component."
[component]
(:query (component->query-data component) (query component)))
(defn get-params
"Return the query params for a component."
[component]
(:params (component->query-data component) (params component)))
(defn- get-component-query
([component]
(get-component-query component (component->query-data component)))
([component query-data]
(let [q (:query query-data (query component))
c' (-> q meta :component)]
(assert (nil? c')
(str "Query violation, " component " reuses " c' " query"))
(with-meta
(bind-query q (:params query-data (params component)))
{:component (react-type component)}))))
(defn iquery?
#?(:cljs {:tag boolean})
[x]
#?(:clj (if (fn? x)
(some? (-> x meta :query))
(let [class (cond-> x (component? x) class)]
(extends? IQuery class)))
:cljs (implements? IQuery x)))
(defn- get-class-or-instance-query
"Return a IQuery/IParams local bound query. Works for component classes
and component instances. Does not use the indexer."
[x]
(if (component? x)
(get-component-query x)
(let [q #?(:clj ((-> x meta :query) x)
:cljs (query x))
c (-> q meta :component)]
(assert (nil? c) (str "Query violation, " x , " reuses " c " query"))
(with-meta (bind-query q (params x)) {:component x}))))
(defn- get-indexed-query
"Get a component's static query from the indexer. For recursive queries, recurses
up the data path. Falls back to `get-class-or-instance-query` if nothing is
found in the indexer."
[component class-path-query-data data-path]
(let [qs (filter #(= data-path (-> % zip/root (focus->path data-path)))
class-path-query-data)
qs (if (empty? qs) class-path-query-data qs)]
(if-not (empty? qs)
(let [q (first qs)
node (zip/node q)]
(if-not (util/recursion? node)
node
(recur component class-path-query-data (pop data-path))))
(get-class-or-instance-query component))))
(defn get-query
"Return a IQuery/IParams instance bound query. Works for component classes
and component instances. See also om.next/full-query."
[x]
(when #?(:clj (iquery? x)
:cljs (implements? IQuery x))
(if (component? x)
(if-let [query-data (component->query-data x)]
(get-component-query x query-data)
(let [cp (class-path x)
r (get-reconciler x)
data-path (into [] (remove number?) (path x))
class-path-query-data (get (:class-path->query @(get-indexer r)) cp)]
(get-indexed-query x class-path-query-data data-path)))
(get-class-or-instance-query x))))
(defn tag [x class]
(vary-meta x assoc :component class))
;; =============================================================================
React Bridging
#?(:cljs (deftype ^:private OmProps [props basis-t]))
#?(:cljs
(defn- om-props [props basis-t]
(OmProps. props basis-t)))
#?(:cljs
(defn- om-props-basis [om-props]
(.-basis-t om-props)))
#?(:cljs (def ^:private nil-props (om-props nil -1)))
#?(:cljs
(defn- unwrap [om-props]
(.-props om-props)))
#?(:clj
(defn- munge-component-name [x]
(let [ns-name (-> x meta :component-ns)
cl-name (-> x meta :component-name)]
(munge
(str (str/replace (str ns-name) "." "$") "$" cl-name)))))
#?(:clj
(defn- compute-react-key [cl props]
(when-let [idx (-> props meta :om-path)]
(str (munge-component-name cl) "_" idx))))
#?(:cljs
(defn- compute-react-key [cl props]
(if-let [rk (:react-key props)]
rk
(if-let [idx (-> props meta :om-path)]
(str (. cl -name) "_" idx)
js/undefined))))
#?(:clj
(defn factory
"Create a factory constructor from a component class created with
om.next/defui."
([class]
(factory class nil))
([class {:keys [validator keyfn instrument?]
:or {instrument? true} :as opts}]
{:pre [(fn? class)]}
(fn self
([] (self nil))
([props & children]
(when-not (nil? validator)
(assert (validator props)))
(if (and *instrument* instrument?)
(*instrument*
{:props props
:children children
:class class
:factory (factory class (assoc opts :instrument? false))})
(let [react-key (cond
(some? keyfn) (keyfn props)
(some? (:react-key props)) (:react-key props)
:else (compute-react-key class props))
ctor class
ref (:ref props)
props {:omcljs$reactRef ref
:omcljs$reactKey react-key
:omcljs$value (cond-> props
(map? props) (dissoc :ref))
:omcljs$mounted? (atom false)
:omcljs$path (-> props meta :om-path)
:omcljs$reconciler *reconciler*
:omcljs$parent *parent*
:omcljs$shared *shared*
:omcljs$instrument *instrument*
:omcljs$depth *depth*}
component (ctor (atom nil) (atom nil) props children)]
(when ref
(assert (some? *parent*))
(swap! (:refs *parent*) assoc ref component))
(reset! (:state component) (.initLocalState component))
component)))))))
#?(:cljs
(defn factory
"Create a factory constructor from a component class created with
om.next/defui."
([class] (factory class nil))
([class {:keys [validator keyfn instrument?]
:or {instrument? true} :as opts}]
{:pre [(fn? class)]}
(fn self [props & children]
(when-not (nil? validator)
(assert (validator props)))
(if (and *instrument* instrument?)
(*instrument*
{:props props
:children children
:class class
:factory (factory class (assoc opts :instrument? false))})
(let [key (if-not (nil? keyfn)
(keyfn props)
(compute-react-key class props))
ref (:ref props)
ref (cond-> ref (keyword? ref) str)
t (if-not (nil? *reconciler*)
(p/basis-t *reconciler*)
0)]
(js/React.createElement class
#js {:key key
:ref ref
:omcljs$reactKey key
:omcljs$value (om-props props t)
:omcljs$path (-> props meta :om-path)
:omcljs$reconciler *reconciler*
:omcljs$parent *parent*
:omcljs$shared *shared*
:omcljs$instrument *instrument*
:omcljs$depth *depth*}
(util/force-children children))))))))
(defn component?
"Returns true if the argument is an Om component."
#?(:cljs {:tag boolean})
[x]
(if-not (nil? x)
#?(:clj (or (instance? om.next.protocols.IReactComponent x)
(satisfies? p/IReactComponent x))
:cljs (true? (. x -om$isComponent)))
false))
(defn- state [c]
{:pre [(component? c)]}
(.-state c))
(defn- get-prop
"PRIVATE: Do not use"
[c k]
#?(:clj (get (:props c) k)
:cljs (gobj/get (.-props c) k)))
#?(:cljs
(defn- get-props*
[x k]
(if (nil? x)
nil-props
(let [y (gobj/get x k)]
(if (nil? y)
nil-props
y)))))
#?(:cljs
(defn- get-prev-props [x]
(get-props* x "omcljs$prev$value")))
#?(:cljs
(defn- get-next-props [x]
(get-props* x "omcljs$next$value")))
#?(:cljs
(defn- get-props [x]
(get-props* x "omcljs$value")))
#?(:cljs
(defn- set-prop!
"PRIVATE: Do not use"
[c k v]
(gobj/set (.-props c) k v)))
(defn get-reconciler
[c]
{:pre [(component? c)]}
(get-prop c #?(:clj :omcljs$reconciler
:cljs "omcljs$reconciler")))
#?(:cljs
(defn- props*
([x y]
(max-key om-props-basis x y))
([x y z]
(max-key om-props-basis x (props* y z)))))
#?(:cljs
(defn- prev-props*
([x y]
(min-key om-props-basis x y))
([x y z]
(min-key om-props-basis
(props* x y) (props* y z)))))
#?(:cljs
(defn -prev-props [prev-props component]
(let [cst (.-state component)
props (.-props component)]
(unwrap
(prev-props*
(props* (get-props prev-props) (get-prev-props cst))
(props* (get-props cst) (get-props props)))))))
#?(:cljs
(defn -next-props [next-props component]
(unwrap
(props*
(-> component .-props get-props)
(get-props next-props)
(-> component .-state get-next-props)))))
#?(:cljs
(defn- merge-pending-props! [c]
{:pre [(component? c)]}
(let [cst (. c -state)
props (.-props c)
pending (gobj/get cst "omcljs$next$value")
prev (props* (get-props cst) (get-props props))]
(gobj/set cst "omcljs$prev$value" prev)
(when-not (nil? pending)
(gobj/remove cst "omcljs$next$value")
(gobj/set cst "omcljs$value" pending)))))
#?(:cljs
(defn- clear-prev-props! [c]
(gobj/remove (.-state c) "omcljs$prev$value")))
#?(:cljs
(defn- t
"Get basis t value for when the component last read its props from
the global state."
[c]
(om-props-basis
(props*
(-> c .-props get-props)
(-> c .-state get-props)))))
(defn- parent
"Returns the parent Om component."
[component]
(get-prop component #?(:clj :omcljs$parent
:cljs "omcljs$parent")))
(defn depth
"PRIVATE: Returns the render depth (a integer) of the component relative to
the mount root."
[component]
(when (component? component)
(get-prop component #?(:clj :omcljs$depth
:cljs "omcljs$depth"))))
(defn react-key
"Returns the components React key."
[component]
(get-prop component #?(:clj :omcljs$reactKey
:cljs "omcljs$reactKey")))
#?(:clj
(defn react-type
"Returns the component type, regardless of whether the component has been
mounted"
[component]
{:pre [(component? component)]}
(let [[klass-name] (str/split (reflect/typename (type component)) #"_klass")
last-idx-dot (.lastIndexOf klass-name ".")
ns (clojure.main/demunge (subs klass-name 0 last-idx-dot))
c (subs klass-name (inc last-idx-dot))]
@(or (find-var (symbol ns c))
(find-var (symbol ns (clojure.main/demunge c)))))))
#?(:cljs
(defn react-type
"Returns the component type, regardless of whether the component has been
mounted"
[x]
(or (gobj/get x "type") (type x))))
(defn- path
"Returns the component's Om data path."
[c]
(get-prop c #?(:clj :omcljs$path
:cljs "omcljs$path")))
(defn shared
"Return the global shared properties of the Om Next root. See :shared and
:shared-fn reconciler options."
([component]
(shared component []))
([component k-or-ks]
{:pre [(component? component)]}
(let [shared #?(:clj (get-prop component :omcljs$shared)
:cljs (gobj/get (. component -props) "omcljs$shared"))
ks (cond-> k-or-ks
(not (sequential? k-or-ks)) vector)]
(cond-> shared
(not (empty? ks)) (get-in ks)))))
(defn instrument [component]
{:pre [(component? component)]}
(get-prop component #?(:clj :omcljs$instrument
:cljs "omcljs$instrument")))
#?(:cljs
(defn- update-props! [c next-props]
{:pre [(component? c)]}
We can not write directly to props , React will complain
(doto (.-state c)
(gobj/set "omcljs$next$value"
(om-props next-props (p/basis-t (get-reconciler c)))))))
#?(:clj
(defn props [component]
{:pre [(component? component)]}
(:omcljs$value (:props component))))
#?(:cljs
(defn props
"Return a components props."
[component]
{:pre [(component? component)]}
;; When force updating we write temporarily props into state to avoid bogus
complaints from React . We record the basis T of the reconciler to determine
;; if the props recorded into state are more recent - props will get updated
;; when React actually re-renders the component.
(unwrap
(props*
(-> component .-props get-props)
(-> component .-state get-props)))))
(defn computed
"Add computed properties to props. Note will replace any pre-existing
computed properties."
[props computed-map]
(when-not (nil? props)
(if (vector? props)
(cond-> props
(not (empty? computed-map)) (vary-meta assoc :om.next/computed computed-map))
(cond-> props
(not (empty? computed-map)) (assoc :om.next/computed computed-map)))))
(defn get-computed
"Return the computed properties on a component or its props."
([x]
(get-computed x []))
([x k-or-ks]
(when-not (nil? x)
(let [props (cond-> x (component? x) props)
ks (into [:om.next/computed]
(cond-> k-or-ks
(not (sequential? k-or-ks)) vector))]
(if (vector? props)
(-> props meta (get-in ks))
(get-in props ks))))))
(declare schedule-render!)
#?(:clj
(defn set-state!
[component new-state]
{:pre [(component? component)]}
(if (satisfies? ILocalState component)
(-set-state! component new-state)
(reset! (:state component) new-state))))
#?(:cljs
(defn set-state!
"Set the component local state of the component. Analogous to React's
setState."
[component new-state]
{:pre [(component? component)]}
(if (implements? ILocalState component)
(-set-state! component new-state)
(gobj/set (.-state component) "omcljs$pendingState" new-state))
(if-let [r (get-reconciler component)]
(do
(p/queue! r [component])
(schedule-render! r))
(.forceUpdate component))))
(defn get-state
"Get a component's local state. May provide a single key or a sequential
collection of keys for indexed access into the component's local state."
([component]
(get-state component []))
([component k-or-ks]
{:pre [(component? component)]}
(let [cst (if #?(:clj (satisfies? ILocalState component)
:cljs (implements? ILocalState component))
(-get-state component)
#?(:clj @(:state component)
:cljs (when-let [state (. component -state)]
(or (gobj/get state "omcljs$pendingState")
(gobj/get state "omcljs$state")))))]
(get-in cst (if (sequential? k-or-ks) k-or-ks [k-or-ks])))))
(defn update-state!
"Update a component's local state. Similar to Clojure(Script)'s swap!"
([component f]
(set-state! component (f (get-state component))))
([component f arg0]
(set-state! component (f (get-state component) arg0)))
([component f arg0 arg1]
(set-state! component (f (get-state component) arg0 arg1)))
([component f arg0 arg1 arg2]
(set-state! component (f (get-state component) arg0 arg1 arg2)))
([component f arg0 arg1 arg2 arg3]
(set-state! component (f (get-state component) arg0 arg1 arg2 arg3)))
([component f arg0 arg1 arg2 arg3 & arg-rest]
(set-state! component
(apply f (get-state component) arg0 arg1 arg2 arg3 arg-rest))))
(defn get-rendered-state
"Get the rendered state of component. om.next/get-state always returns the
up-to-date state."
([component]
(get-rendered-state component []))
([component k-or-ks]
{:pre [(component? component)]}
(let [cst (if #?(:clj (satisfies? ILocalState component)
:cljs (implements? ILocalState component))
(-get-rendered-state component)
#?(:clj (get-state component)
:cljs (some-> component .-state (gobj/get "omcljs$state"))))]
(get-in cst (if (sequential? k-or-ks) k-or-ks [k-or-ks])))))
#?(:cljs
(defn- merge-pending-state! [c]
(if (implements? ILocalState c)
(-merge-pending-state! c)
(when-let [pending (some-> c .-state (gobj/get "omcljs$pendingState"))]
(let [state (.-state c)
previous (gobj/get state "omcljs$state")]
(gobj/remove state "omcljs$pendingState")
(gobj/set state "omcljs$previousState" previous)
(gobj/set state "omcljs$state" pending))))))
(defn react-set-state!
([component new-state]
(react-set-state! component new-state nil))
([component new-state cb]
{:pre [(component? component)]}
#?(:clj (do
(set-state! component new-state)
(cb))
:cljs (.setState component #js {:omcljs$state new-state} cb))))
(declare full-query to-env schedule-sends! reconciler? ref->components force)
(defn gather-sends
"Given an environment, a query and a set of remotes return a hash map of remotes
mapped to the query specific to that remote."
[{:keys [parser] :as env} q remotes]
(into {}
(comp
(map #(vector % (parser env q %)))
(filter (fn [[_ v]] (pos? (count v)))))
remotes))
(defn transform-reads
"Given r (a reconciler) and a query expression including a mutation and
any simple reads, return the equivalent query expression where the simple
reads have been replaced by the full query for each component that cares about
the specified read."
[r tx]
(if (-> r :config :easy-reads)
(letfn [(with-target [target q]
(if-not (nil? target)
[(force (first q) target)]
q))
(add-focused-query [k target tx c]
(let [transformed (->> (focus-query (get-query c) [k])
(with-target target)
(full-query c))]
(into tx (remove (set tx)) transformed)))]
(loop [exprs (seq tx) tx' []]
(if-not (nil? exprs)
(let [expr (first exprs)
ast (parser/expr->ast expr)
key (:key ast)
tgt (:target ast)]
(if (keyword? key)
(let [cs (ref->components r key)]
(recur (next exprs)
(reduce #(add-focused-query key tgt %1 %2)
(cond-> tx'
(empty? cs) (conj expr)) cs)))
(recur (next exprs) (conj tx' expr))))
tx')))
tx))
(defn set-query!
"Change the query of a component. Takes a map containing :params and/or
:query. :params should be a map of new bindings and :query should be a query
expression. Will schedule a re-render as well as remote re-sends if
necessary."
([x params&query]
(set-query! x params&query nil))
([x {:keys [params query]} reads]
{:pre [(or (reconciler? x)
(component? x))
(or (not (nil? params))
(not (nil? query)))
(or (nil? reads)
(vector? reads))]}
(let [r (if (component? x)
(get-reconciler x)
x)
c (when (component? x) x)
xs (if-not (nil? c) [c] [])
root (:root @(:state r))
cfg (:config r)
st (:state cfg)
id #?(:clj (java.util.UUID/randomUUID)
:cljs (random-uuid))]
#?(:cljs (.add (:history cfg) id @st))
#?(:cljs
(when-let [l (:logger cfg)]
(glog/info l
(cond-> (str (when-let [ident (when (implements? Ident c)
(ident c (props c)))]
(str (pr-str ident) " ")))
(reconciler? x) (str "reconciler ")
query (str "changed query '" query ", ")
params (str "changed params " params " ")
true (str (pr-str id))))))
(swap! st update-in [:om.next/queries (or c root)] merge
(merge (when query {:query query}) (when params {:params params})))
(when (and (not (nil? c)) (nil? reads))
(p/queue! r [c]))
(when-not (nil? reads)
(p/queue! r reads))
(p/reindex! r)
(let [rootq (if (not (nil? c))
(full-query c)
(when (nil? reads)
(get-query root)))
sends (gather-sends (to-env cfg)
(into (or rootq []) (transform-reads r reads)) (:remotes cfg))]
(when-not (empty? sends)
(doseq [[remote _] sends]
(p/queue! r xs remote))
(p/queue-sends! r sends)
(schedule-sends! r)))
nil)))
(defn update-query!
"Update a component's query and query parameters with a function."
([component f]
(set-query! component
(f {:query (get-unbound-query component)
:params (get-params component)})))
([component f arg0]
(set-query! component
(f {:query (get-unbound-query component)
:params (get-params component)}
arg0)))
([component f arg0 arg1]
(set-query! component
(f {:query (get-unbound-query component)
:params (get-params component)}
arg0 arg1)))
([component f arg0 arg1 arg2]
(set-query! component
(f {:query (get-unbound-query component)
:params (get-params component)}
arg0 arg1 arg2)))
([component f arg0 arg1 arg2 arg3 & arg-rest]
(set-query! component
(apply f {:query (get-unbound-query component)
:params (get-params component)}
arg0 arg1 arg2 arg3 arg-rest))))
(defn mounted?
"Returns true if the component is mounted."
#?(:cljs {:tag boolean})
[x]
#?(:clj (and (component? x) @(get-prop x :omcljs$mounted?))
:cljs (and (component? x) ^boolean (.isMounted x))))
(defn react-ref
"Returns the component associated with a component's React ref."
[component name]
#?(:clj (some-> @(:refs component) (get name))
:cljs (some-> (.-refs component) (gobj/get name))))
(defn children
"Returns the component's children."
[component]
#?(:clj (:children component)
:cljs (.. component -props -children)))
#?(:cljs
(defn- update-component! [c next-props]
{:pre [(component? c)]}
(update-props! c next-props)
(.forceUpdate c)))
#?(:cljs
(defn should-update?
([c next-props]
(should-update? c next-props nil))
([c next-props next-state]
{:pre [(component? c)]}
(.shouldComponentUpdate c
#js {:omcljs$value next-props}
#js {:omcljs$state next-state}))))
(defn- raw-class-path
"Return the raw component class path associated with a component. Contains
duplicates for recursive component trees."
[c]
(loop [c c ret (list (react-type c))]
(if-let [p (parent c)]
(if (iquery? p)
(recur p (cons (react-type p) ret))
(recur p ret))
ret)))
(defn class-path
"Return the component class path associated with a component."
[c]
{:pre [(component? c)]}
(let [raw-cp (raw-class-path c)]
(loop [cp (seq raw-cp) ret [] seen #{}]
(if cp
(let [c (first cp)]
(if (contains? seen c)
(recur (next cp) ret seen)
(recur (next cp) (conj ret c) (conj seen c))))
(seq ret)))))
(defn- recursive-class-path?
"Returns true if a component's classpath is recursive"
#?(:cljs {:tag boolean})
[c]
{:pre [(component? c)]}
(not (apply distinct? (raw-class-path c))))
(defn subquery
"Given a class or mounted component x and a ref to an instantiated component
or class that defines a subquery, pick the most specific subquery. If the
component is mounted subquery-ref will be used, subquery-class otherwise."
[x subquery-ref subquery-class]
{:pre [(or (keyword? subquery-ref) (string? subquery-ref))
(fn? subquery-class)]}
(let [ref (cond-> subquery-ref (keyword? subquery-ref) str)]
(if (and (component? x) (mounted? x))
(get-query (react-ref x ref))
(get-query subquery-class))))
(defn get-ident
"Given a mounted component with assigned props, return the ident for the
component."
[x]
{:pre [(component? x)]}
(let [m (props x)]
(assert (not (nil? m)) "get-ident invoked on component with nil props")
(ident x m)))
;; =============================================================================
;; Reconciler API
(declare reconciler?)
(defn- basis-t [reconciler]
(p/basis-t reconciler))
#?(:cljs
(defn- queue-render! [f]
(cond
(fn? *raf*) (*raf* f)
(not (exists? js/requestAnimationFrame))
(js/setTimeout f 16)
:else
(js/requestAnimationFrame f))))
#?(:cljs
(defn schedule-render! [reconciler]
(when (p/schedule-render! reconciler)
(queue-render! #(p/reconcile! reconciler)))))
(defn schedule-sends! [reconciler]
(when (p/schedule-sends! reconciler)
#?(:clj (p/send! reconciler)
:cljs (js/setTimeout #(p/send! reconciler) 0))))
(declare remove-root!)
(defn add-root!
"Given a root component class and a target root DOM node, instantiate and
render the root class using the reconciler's :state property. The reconciler
will continue to observe changes to :state and keep the target node in sync.
Note a reconciler may have only one root. If invoked on a reconciler with an
existing root, the new root will replace the old one."
([reconciler root-class target]
(add-root! reconciler root-class target nil))
([reconciler root-class target options]
{:pre [(reconciler? reconciler) (fn? root-class)]}
(when-let [old-reconciler (get @roots target)]
(remove-root! old-reconciler target))
(swap! roots assoc target reconciler)
(p/add-root! reconciler root-class target options)))
(defn remove-root!
"Remove a root target (a DOM element) from a reconciler. The reconciler will
no longer attempt to reconcile application state with the specified root."
[reconciler target]
(p/remove-root! reconciler target))
;; =============================================================================
;; Transactions
(defprotocol ITxIntercept
(tx-intercept [c tx]
"An optional protocol that component may implement to intercept child
transactions."))
(defn- to-env [x]
(let [config (if (reconciler? x) (:config x) x)]
(select-keys config [:state :shared :parser :logger :pathopt])))
(defn transact* [r c ref tx]
(let [cfg (:config r)
ref (if (and c #?(:clj (satisfies? Ident c)
:cljs (implements? Ident c)) (not ref))
(ident c (props c))
ref)
env (merge
(to-env cfg)
{:reconciler r :component c}
(when ref
{:ref ref}))
id #?(:clj (java.util.UUID/randomUUID)
:cljs (random-uuid))
#?@(:cljs
[_ (.add (:history cfg) id @(:state cfg))
_ (when-let [l (:logger cfg)]
(glog/info l
(str (when ref (str (pr-str ref) " "))
"transacted '" tx ", " (pr-str id))))])
old-state @(:state cfg)
v ((:parser cfg) env tx)
snds (gather-sends env tx (:remotes cfg))
xs (cond-> []
(not (nil? c)) (conj c)
(not (nil? ref)) (conj ref))]
(p/queue! r (into xs (remove symbol?) (keys v)))
(when-not (empty? snds)
(doseq [[remote _] snds]
(p/queue! r xs remote))
(p/queue-sends! r snds)
(schedule-sends! r))
(when-let [f (:tx-listen cfg)]
(let [tx-data (merge env
{:old-state old-state
:new-state @(:state cfg)})]
(f tx-data {:tx tx
:ret v
:sends snds})))
v))
(defn annotate-mutations
"Given a query expression annotate all mutations by adding a :mutator -> ident
entry to the metadata of each mutation expression in the query."
[tx ident]
(letfn [(annotate [expr ident]
(cond-> expr
(util/mutation? expr) (vary-meta assoc :mutator ident)))]
(into [] (map #(annotate % ident)) tx)))
(defn some-iquery? [c]
(loop [c c]
(cond
(nil? c) false
(iquery? c) true
:else (recur (parent c)))))
(defn transact!
"Given a reconciler or component run a transaction. tx is a parse expression
that should include mutations followed by any necessary read. The reads will
be used to trigger component re-rendering.
Example:
(om/transact! widget
'[(do/this!) (do/that!)
:read/this :read/that])"
([x tx]
{:pre [(or (component? x)
(reconciler? x))
(vector? tx)]}
(let [tx (cond-> tx
(and (component? x) (satisfies? Ident x))
(annotate-mutations (get-ident x)))]
(cond
(reconciler? x) (transact* x nil nil tx)
(not (iquery? x)) (do
(invariant (some-iquery? x)
(str "transact! should be called on a component"
"that implements IQuery or has a parent that"
"implements IQuery"))
(transact* (get-reconciler x) nil nil tx))
:else (do
(loop [p (parent x) x x tx tx]
(if (nil? p)
(let [r (get-reconciler x)]
(transact* r x nil (transform-reads r tx)))
(let [[x' tx] (if #?(:clj (satisfies? ITxIntercept p)
:cljs (implements? ITxIntercept p))
[p (tx-intercept p tx)]
[x tx])]
(recur (parent p) x' tx))))))))
([r ref tx]
(transact* r nil ref tx)))
;; =============================================================================
Parser
(defn parser
"Create a parser. The argument is a map of two keys, :read and :mutate. Both
functions should have the signature (Env -> Key -> Params -> ParseResult)."
[{:keys [read mutate] :as opts}]
{:pre [(map? opts)]}
(parser/parser opts))
(defn dispatch
"Helper function for implementing :read and :mutate as multimethods. Use this
as the dispatch-fn."
[_ key _] key)
(defn query->ast
"Given a query expression convert it into an AST."
[query-expr]
(parser/query->ast query-expr))
(defn ast->query [query-ast]
"Given an AST convert it back into a query expression."
(parser/ast->expr query-ast true))
(defn- get-dispatch-key [prop]
(cond-> prop
(or (not (util/ident? prop))
(= (second prop) '_))
((comp :dispatch-key parser/expr->ast))))
;; =============================================================================
;; Indexer
(defn- cascade-query
"Cascades a query up the classpath. class-path->query is a map of classpaths
to their queries. classpath is the classpath where we start cascading (typically
the direct parent's classpath of the component changing query). data-path is
the data path in the classpath's query to the new query. new-query is the
query to be applied to the classpaths. union-keys are any keys into union
queries found during index building; they are used to access union queries
when cascading the classpath, and to generate the classpaths' rendered-paths,
which skip these keys."
[class-path->query classpath data-path new-query union-keys]
(loop [cp classpath
data-path data-path
new-query new-query
ret {}]
(if-not (empty? cp)
(let [rendered-data-path (into [] (remove (set union-keys)) data-path)
filter-data-path (cond-> rendered-data-path
(not (empty? rendered-data-path)) pop)
qs (filter #(= filter-data-path
(-> % zip/root (focus->path filter-data-path)))
(get class-path->query cp))
qs' (into #{}
(map (fn [q]
(let [new-query (if (or (map? (zip/node q))
(some #{(peek data-path)} union-keys))
(let [union-key (peek data-path)]
(-> (query-template (zip/root q)
rendered-data-path)
zip/node
(assoc union-key new-query)))
new-query)]
(-> (zip/root q)
(query-template rendered-data-path)
(replace new-query)
(focus-query filter-data-path)
(query-template filter-data-path)))))
qs)]
(recur (pop cp) (pop data-path)
(-> qs' first zip/node) (assoc ret cp qs')))
ret)))
(defrecord Indexer [indexes extfs]
#?(:clj clojure.lang.IDeref
:cljs IDeref)
#?(:clj (deref [_] @indexes)
:cljs (-deref [_] @indexes))
p/IIndexer
(index-root [_ x]
(let [prop->classes (atom {})
class-path->query (atom {})
rootq (get-query x)
root-class (cond-> x (component? x) react-type)]
(letfn [(build-index* [class query path classpath union-expr union-keys]
(invariant (or (not (iquery? class))
(and (iquery? class)
(not (empty? query))))
(str "`IQuery` implementation must return a non-empty query."
" Check the `IQuery` implementation of component `"
(if (component? class)
(.. class -constructor -displayName)
(.. class -prototype -constructor -displayName)) "`."))
(let [recursive? (some #{class} classpath)
classpath (cond-> classpath
(and (not (nil? class))
(not recursive?))
(conj class))
dp->cs (get-in @indexes [:data-path->components])]
(when class
;; path could have changed when setting queries, so we only use
rootq on the first call ( when there 's no class - path->query
;; information) - António
(let [root-query (if (empty? path)
rootq
(-> @class-path->query
(get [root-class]) first zip/root))]
(swap! class-path->query update-in [classpath] (fnil conj #{})
(query-template (focus-query root-query path) path))))
(let [recursive-join? (and recursive?
(some (fn [e]
(and (util/join? e)
(not (util/recursion?
(util/join-value e)))))
query)
(= (distinct path) path))
recursive-union? (and recursive?
union-expr
(= (distinct path) path))]
(when (or (not recursive?)
recursive-join?
recursive-union?)
(cond
(vector? query)
(let [{props false joins true} (group-by util/join? query)]
(swap! prop->classes
#(merge-with into %
(zipmap
(map get-dispatch-key props)
(repeat #{class}))))
(doseq [join joins]
(let [[prop query'] (util/join-entry join)
prop-dispatch-key (get-dispatch-key prop)
recursion? (util/recursion? query')
union-recursion? (and recursion? union-expr)
query' (if recursion?
(if-not (nil? union-expr)
union-expr
query)
query')
path' (conj path prop)
rendered-path' (into []
(remove
(set union-keys)
(conj path
prop-dispatch-key)))
cs (get dp->cs rendered-path')
cascade-query? (and (= (count cs) 1)
(= (-> query' meta :component)
(react-type (first cs)))
(not (map? query')))
query'' (if cascade-query?
(get-query (first cs))
query')]
(swap! prop->classes
#(merge-with into % {prop-dispatch-key #{class}}))
(when (and cascade-query? (not= query' query''))
(let [cp->q' (cascade-query @class-path->query classpath
path' query'' union-keys)]
(swap! class-path->query merge cp->q')))
(let [class' (-> query'' meta :component)]
(when-not (and recursion? (nil? class'))
(build-index* class' query''
path' classpath (if recursion? union-expr nil) union-keys))))))
;; Union query case
(map? query)
(doseq [[prop query'] query]
(let [path' (conj path prop)
class' (-> query' meta :component)
cs (filter #(= class' (react-type %))
(get dp->cs path))
cascade-query? (and class' (= (count cs) 1))
query'' (if cascade-query?
(get-query (first cs))
query')]
(when (and cascade-query? (not= query' query''))
(let [qs (get @class-path->query classpath)
q (first qs)
qnode (zip/node
(cond-> q
(nil? class) (query-template path)))
new-query (assoc qnode
prop query'')
q' (cond-> (zip/replace
(query-template (zip/root q) path)
new-query)
(nil? class)
(-> zip/root
(focus-query (pop path))
(query-template (pop path))))
qs' (into #{q'} (remove #{q}) qs)
cp->q' (merge {classpath qs'}
(cascade-query @class-path->query
(pop classpath) path
(zip/node q') union-keys))]
(swap! class-path->query merge cp->q')))
(build-index* class' query'' path' classpath query (conj union-keys prop)))))))))]
(build-index* root-class rootq [] [] nil [])
(swap! indexes merge
{:prop->classes @prop->classes
:class-path->query @class-path->query}))))
(index-component! [_ c]
(swap! indexes
(fn [indexes]
(let [indexes (update-in ((:index-component extfs) indexes c)
[:class->components (react-type c)]
(fnil conj #{}) c)
data-path (into [] (remove number?) (path c))
indexes (update-in ((:index-component extfs) indexes c)
[:data-path->components data-path]
(fnil conj #{}) c)
ident (when #?(:clj (satisfies? Ident c)
:cljs (implements? Ident c))
(let [ident (ident c (props c))]
(invariant (util/ident? ident)
(str "malformed Ident. An ident must be a vector of "
"two elements (a keyword and an EDN value). Check "
"the Ident implementation of component `"
(.. c -constructor -displayName) "`."))
(invariant (some? (second ident))
(str "component " (.. c -constructor -displayName)
"'s ident (" ident ") has a `nil` second element."
" This warning can be safely ignored if that is intended."))
ident))]
(if-not (nil? ident)
(cond-> indexes
ident (update-in [:ref->components ident] (fnil conj #{}) c))
indexes)))))
(drop-component! [_ c]
(swap! indexes
(fn [indexes]
(let [indexes (update-in ((:drop-component extfs) indexes c)
[:class->components (react-type c)]
disj c)
data-path (into [] (remove number?) (path c))
indexes (update-in ((:drop-component extfs) indexes c)
[:data-path->components data-path]
disj c)
ident (when #?(:clj (satisfies? Ident c)
:cljs (implements? Ident c))
(ident c (props c)))]
(if-not (nil? ident)
(cond-> indexes
ident (update-in [:ref->components ident] disj c))
indexes)))))
(key->components [_ k]
(let [indexes @indexes]
(if (component? k)
#{k}
(if-let [cs ((:ref->components extfs) indexes k)]
cs
(transduce (map #(get-in indexes [:class->components %]))
(completing into)
(get-in indexes [:ref->components k] #{})
(get-in indexes [:prop->classes k])))))))
(defn indexer
"Given a function (Component -> Ref), return an indexer."
([]
(indexer
{:index-component (fn [indexes component] indexes)
:drop-component (fn [indexes component] indexes)
:ref->components (fn [indexes ref] nil)}))
([extfs]
(Indexer.
(atom
{:class->components {}
:data-path->components {}
:ref->components {}})
extfs)))
(defn get-indexer
"PRIVATE: Get the indexer associated with the reconciler."
[reconciler]
{:pre [(reconciler? reconciler)]}
(-> reconciler :config :indexer))
(defn ref->components
"Return all components for a given ref."
[x ref]
(when-not (nil? ref)
(let [indexer (if (reconciler? x) (get-indexer x) x)]
(p/key->components indexer ref))))
(defn ref->any
"Get any component from the indexer that matches the ref."
[x ref]
(let [indexer (if (reconciler? x) (get-indexer x) x)]
(first (p/key->components indexer ref))))
(defn class->any
"Get any component from the indexer that matches the component class."
[x class]
(let [indexer (if (reconciler? x) (get-indexer x) x)]
(first (get-in @indexer [:class->components class]))))
(defn class-path->queries
"Given x (a reconciler or indexer) and y (a component or component class
path), return the queries for that path."
[x y]
(let [indexer (if (reconciler? x) (get-indexer x) x)
cp (if (component? y) (class-path y) y)]
(into #{} (map zip/root)
(get-in @indexer [:class-path->query cp]))))
(defn full-query
"Returns the absolute query for a given component, not relative like
om.next/get-query."
([component]
(when (iquery? component)
(if (nil? (path component))
(replace
(first
(get-in @(-> component get-reconciler get-indexer)
[:class-path->query (class-path component)]))
(get-query component))
(full-query component (get-query component)))))
([component query]
(when (iquery? component)
(let [xf (cond->> (remove number?)
(recursive-class-path? component) (comp (distinct)))
path' (into [] xf (path component))
cp (class-path component)
qs (get-in @(-> component get-reconciler get-indexer)
[:class-path->query cp])]
(if-not (empty? qs)
;; handle case where child appears multiple times at same class-path
;; but with different queries
(let [q (->> qs
(filter #(= path'
(mapv get-dispatch-key
(-> % zip/root (focus->path path')))))
first)]
(if-not (nil? q)
(replace q query)
(throw
(ex-info (str "No queries exist at the intersection of component path " cp " and data path " path')
{:type :om.next/no-queries}))))
(throw
(ex-info (str "No queries exist for component path " cp)
{:type :om.next/no-queries})))))))
(defn- normalize* [query data refs union-seen]
(cond
(= '[*] query) data
;; union case
(map? query)
(let [class (-> query meta :component)
ident #?(:clj (when-let [ident (-> class meta :ident)]
(ident class data))
:cljs (when (implements? Ident class)
(ident class data)))]
(if-not (nil? ident)
(vary-meta (normalize* (get query (first ident)) data refs union-seen)
assoc :om/tag (first ident))
(throw #?(:clj (IllegalArgumentException. "Union components must implement Ident")
:cljs (js/Error. "Union components must implement Ident")))))
(vector? data) data ;; already normalized
:else
(loop [q (seq query) ret data]
(if-not (nil? q)
(let [expr (first q)]
(if (util/join? expr)
(let [[k sel] (util/join-entry expr)
recursive? (util/recursion? sel)
union-entry (if (util/union? expr) sel union-seen)
sel (if recursive?
(if-not (nil? union-seen)
union-seen
query)
sel)
class (-> sel meta :component)
v (get data k)]
(cond
graph loop : db->tree leaves ident in place
(and recursive? (util/ident? v)) (recur (next q) ret)
normalize one
(map? v)
(let [x (normalize* sel v refs union-entry)]
(if-not (or (nil? class) (not #?(:clj (-> class meta :ident)
:cljs (implements? Ident class))))
(let [i #?(:clj ((-> class meta :ident) class v)
:cljs (ident class v))]
(swap! refs update-in [(first i) (second i)] merge x)
(recur (next q) (assoc ret k i)))
(recur (next q) (assoc ret k x))))
;; normalize many
(vector? v)
(let [xs (into [] (map #(normalize* sel % refs union-entry)) v)]
(if-not (or (nil? class) (not #?(:clj (-> class meta :ident)
:cljs (implements? Ident class))))
(let [is (into [] (map #?(:clj #((-> class meta :ident) class %)
:cljs #(ident class %))) xs)]
(if (vector? sel)
(when-not (empty? is)
(swap! refs
(fn [refs]
(reduce (fn [m [i x]]
(update-in m i merge x))
refs (zipmap is xs)))))
;; union case
(swap! refs
(fn [refs']
(reduce
(fn [ret [i x]]
(update-in ret i merge x))
refs' (map vector is xs)))))
(recur (next q) (assoc ret k is)))
(recur (next q) (assoc ret k xs))))
;; missing key
(nil? v)
(recur (next q) ret)
;; can't handle
:else (recur (next q) (assoc ret k v))))
(let [k (if (seq? expr) (first expr) expr)
v (get data k)]
(if (nil? v)
(recur (next q) ret)
(recur (next q) (assoc ret k v))))))
ret))))
(defn tree->db
"Given a Om component class or instance and a tree of data, use the component's
query to transform the tree into the default database format. All nodes that
can be mapped via Ident implementations wil be replaced with ident links. The
original node data will be moved into tables indexed by ident. If merge-idents
option is true, will return these tables in the result instead of as metadata."
([x data]
(tree->db x data false))
([x data #?(:clj merge-idents :cljs ^boolean merge-idents) ]
(let [refs (atom {})
x (if (vector? x) x (get-query x))
ret (normalize* x data refs nil)]
(if merge-idents
(let [refs' @refs]
(assoc (merge ret refs')
::tables (into #{} (keys refs'))))
(with-meta ret @refs)))))
(defn- sift-idents [res]
(let [{idents true rest false} (group-by #(vector? (first %)) res)]
[(into {} idents) (into {} rest)]))
(defn reduce-query-depth
"Changes a join on key k with depth limit from [:a {:k n}] to [:a {:k (dec n)}]"
[q k]
(if-not (empty? (focus-query q [k]))
(let [pos (query-template q [k])
node (zip/node pos)
node' (cond-> node (number? node) dec)]
(replace pos node'))
q))
(defn- reduce-union-recursion-depth
"Given a union expression decrement each of the query roots by one if it
is recursive."
[union-expr recursion-key]
(->> union-expr
(map (fn [[k q]] [k (reduce-query-depth q recursion-key)]))
(into {})))
(defn- mappable-ident? [refs ident]
(and (util/ident? ident)
(contains? refs (first ident))))
;; TODO: easy to optimize
(defn- denormalize*
"Denormalize a data based on query. refs is a data structure which maps idents
to their values. map-ident is a function taking a ident to another ident,
used during tempid transition. idents-seen is the set of idents encountered,
used to limit recursion. union-expr is the current union expression being
evaluated. recurse-key is key representing the current recursive query being
evaluted."
[query data refs map-ident idents-seen union-expr recurse-key]
;; support taking ident for data param
(let [union-recur? (and union-expr recurse-key)
recur-ident (when union-recur?
data)
data (loop [data data]
(if (mappable-ident? refs data)
(recur (get-in refs (map-ident data)))
data))]
(cond
(vector? data)
;; join
(let [step (fn [ident]
(if-not (mappable-ident? refs ident)
(if (= query '[*])
ident
(let [{props false joins true} (group-by util/join? query)
props (mapv #(cond-> % (seq? %) first) props)]
(loop [joins (seq joins) ret {}]
(if-not (nil? joins)
(let [join (first joins)
[key sel] (util/join-entry join)
v (get ident key)]
(recur (next joins)
(assoc ret
key (denormalize* sel v refs map-ident
idents-seen union-expr recurse-key))))
(merge (select-keys ident props) ret)))))
(let [ident' (get-in refs (map-ident ident))
query (cond-> query
union-recur? (reduce-union-recursion-depth recurse-key))
;; also reduce query depth of union-seen, there can
;; be more union recursions inside
union-seen' (cond-> union-expr
union-recur? (reduce-union-recursion-depth recurse-key))
query' (cond-> query
(map? query) (get (first ident)))] ;; UNION
(denormalize* query' ident' refs map-ident idents-seen union-seen' nil))))]
(into [] (map step) data))
(and (map? query) union-recur?)
(denormalize* (get query (first recur-ident)) data refs map-ident
idents-seen union-expr recurse-key)
:else
;; map case
(if (= '[*] query)
data
(let [{props false joins true} (group-by #(or (util/join? %)
(util/ident? %)
(and (seq? %)
(util/ident? (first %))))
query)
props (mapv #(cond-> % (seq? %) first) props)]
(loop [joins (seq joins) ret {}]
(if-not (nil? joins)
(let [join (first joins)
join (cond-> join
(seq? join) first)
join (cond-> join
(util/ident? join) (hash-map '[*]))
[key sel] (util/join-entry join)
recurse? (util/recursion? sel)
recurse-key (when recurse? key)
v (if (util/ident? key)
(if (= '_ (second key))
(get refs (first key))
(get-in refs (map-ident key)))
(get data key))
key (cond-> key (util/unique-ident? key) first)
v (if (mappable-ident? refs v)
(loop [v v]
(let [next (get-in refs (map-ident v))]
(if (mappable-ident? refs next)
(recur next)
(map-ident v))))
v)
limit (if (number? sel) sel :none)
union-entry (if (util/union? join)
sel
(when recurse?
union-expr))
sel (cond
recurse?
(if-not (nil? union-expr)
union-entry
(reduce-query-depth query key))
(and (mappable-ident? refs v)
(util/union? join))
(get sel (first v))
(and (util/ident? key)
(util/union? join))
(get sel (first key))
:else sel)
graph-loop? (and recurse?
(contains? (set (get idents-seen key)) v)
(= :none limit))
idents-seen (if (and (mappable-ident? refs v) recurse?)
(-> idents-seen
(update-in [key] (fnil conj #{}) v)
(assoc-in [:last-ident key] v)) idents-seen)]
(cond
(= 0 limit) (recur (next joins) ret)
graph-loop? (recur (next joins) ret)
(nil? v) (recur (next joins) ret)
:else (recur (next joins)
(assoc ret
key (denormalize* sel v refs map-ident
idents-seen union-entry recurse-key)))))
(if-let [looped-key (some
(fn [[k identset]]
(if (contains? identset (get data k))
(get-in idents-seen [:last-ident k])
nil))
(dissoc idents-seen :last-ident))]
looped-key
(merge (select-keys data props) ret)))))))))
(defn db->tree
"Given a query, some data in the default database format, and the entire
application state in the default database format, return the tree where all
ident links have been replaced with their original node values."
([query data refs]
{:pre [(map? refs)]}
(denormalize* query data refs identity {} nil nil))
([query data refs map-ident]
{:pre [(map? refs)]}
(denormalize* query data refs map-ident {} nil nil)))
;; =============================================================================
;; Reconciler
(defn rewrite [rewrite-map result]
(letfn [(step [res [k orig-paths]]
(let [to-move (get result k)
res' (reduce #(assoc-in %1 (conj %2 k) to-move)
res orig-paths)]
(dissoc res' k)))]
(reduce step result rewrite-map)))
(defn- move-roots
"When given a join `{:join selector-vector}`, roots found so far, and a `path` prefix:
returns a (possibly empty) sequence of [re-rooted-join prefix] results.
Does NOT support sub-roots. Each re-rooted join will share only
one common parent (their common branching point).
"
[join result-roots path]
(letfn [(query-root? [join] (true? (-> join meta :query-root)))]
(if (util/join? join)
(if (query-root? join)
(conj result-roots [join path])
(let [joinvalue (util/join-value join)]
(if (vector? joinvalue)
(mapcat
#(move-roots % result-roots
(conj path (util/join-key join)))
joinvalue)
result-roots)))
result-roots)))
(defn- merge-joins
"Searches a query for duplicate joins and deep-merges them into a new query."
[query]
(letfn [(step [res expr]
(if (contains? (:elements-seen res) expr)
res ; eliminate exact duplicates
(update-in
(if (and (util/join? expr)
(not (util/union? expr))
(not (list? expr)))
(let [jk (util/join-key expr)
jv (util/join-value expr)
q (or (-> res :query-by-join (get jk)) [])
nq (cond
(util/recursion? q) q
(util/recursion? jv) jv
:else (merge-joins (into [] (concat q jv))))]
(update-in res [:query-by-join] assoc jk nq))
(update-in res [:not-mergeable] conj expr))
[:elements-seen] conj expr)))]
(let [init {:query-by-join {}
:elements-seen #{}
:not-mergeable []}
res (reduce step init query)]
(->> (:query-by-join res)
(mapv (fn [[jkey jsel]] {jkey jsel}))
(concat (:not-mergeable res))
(into [])))))
(defn process-roots [query]
"A send helper for rewriting the query to remove client local keys that
don't need server side processing. Give a query this function will
return a map with two keys, :query and :rewrite. :query is the
actual query you should send. Upon receiving the response you should invoke
:rewrite on the response before invoking the send callback."
(letfn [(retain [expr] [[expr []]]) ; emulate an alternate-root element
(reroot [expr]
(let [roots (move-roots expr [] [])]
(if (empty? roots)
(retain expr)
roots)))
(rewrite-map-step [rewrites [expr path]]
(if (empty? path)
rewrites
(update-in rewrites [(util/join-key expr)] conj path)))]
(let [reroots (mapcat reroot query)
query (merge-joins (mapv first reroots))
rewrite-map (reduce rewrite-map-step {} reroots)]
{:query query
:rewrite (partial rewrite rewrite-map)})))
(defn- merge-idents [tree config refs query]
(let [{:keys [merge-ident indexer]} config
ident-joins (into {} (comp
(map #(cond-> % (seq? %) first))
(filter #(and (util/join? %)
(util/ident? (util/join-key %)))))
query)]
(letfn [ (step [tree' [ident props]]
(if (:normalize config)
(let [c-or-q (or (get ident-joins ident) (ref->any indexer ident))
props' (tree->db c-or-q props)
refs (meta props')]
((:merge-tree config)
(merge-ident config tree' ident props') refs))
(merge-ident config tree' ident props)))]
(reduce step tree refs))))
(defn- merge-novelty!
[reconciler state res query]
(let [config (:config reconciler)
[idts res'] (sift-idents res)
res' (if (:normalize config)
(tree->db
(or query (:root @(:state reconciler)))
res' true)
res')]
(-> state
(merge-idents config idts query)
((:merge-tree config) res'))))
(defn default-merge [reconciler state res query]
{:keys (into [] (remove symbol?) (keys res))
:next (merge-novelty! reconciler state res query)
:tempids (->> (filter (comp symbol? first) res)
(map (comp :tempids second))
(reduce merge {}))})
(defn merge!
"Merge a state delta into the application state. Affected components managed
by the reconciler will re-render."
([reconciler delta]
(merge! reconciler delta nil))
([reconciler delta query]
(merge! reconciler delta query nil))
([reconciler delta query remote]
(let [config (:config reconciler)
state (:state config)
merge* (:merge config)
{:keys [keys next tempids]} (merge* reconciler @state delta query)]
(when (nil? remote)
(p/queue! reconciler keys))
(reset! state
(if-let [migrate (:migrate config)]
(merge (select-keys next [:om.next/queries])
(migrate next
(or query (get-query (:root @(:state reconciler))))
tempids (:id-key config)))
next)))))
(defrecord Reconciler [config state]
#?(:clj clojure.lang.IDeref
:cljs IDeref)
#?(:clj (deref [this] @(:state config))
:cljs (-deref [_] @(:state config)))
p/IReconciler
(basis-t [_] (:t @state))
(add-root! [this root-class target options]
(let [ret (atom nil)
rctor (factory root-class)
guid #?(:clj (java.util.UUID/randomUUID)
:cljs (random-uuid))]
(when (iquery? root-class)
(p/index-root (:indexer config) root-class))
(when (and (:normalize config)
(not (:normalized @state)))
(let [new-state (tree->db root-class @(:state config))
refs (meta new-state)]
(reset! (:state config) (merge new-state refs))
(swap! state assoc :normalized true)))
(let [renderf (fn [data]
(binding [*reconciler* this
*shared* (merge
(:shared config)
(when (:shared-fn config)
((:shared-fn config) data)))
*instrument* (:instrument config)]
(let [c (cond
#?@(:cljs [(not (nil? target)) ((:root-render config) (rctor data) target)])
(nil? @ret) (rctor data)
:else (when-let [c' @ret]
#?(:clj (do
(reset! ret nil)
(rctor data))
:cljs (when (mounted? c')
(.forceUpdate c' data)))))]
(when (and (nil? @ret) (not (nil? c)))
(swap! state assoc :root c)
(reset! ret c)))))
parsef (fn []
(let [sel (get-query (or @ret root-class))]
(assert (or (nil? sel) (vector? sel))
"Application root query must be a vector")
(if-not (nil? sel)
(let [env (to-env config)
v ((:parser config) env sel)]
(when-not (empty? v)
(renderf v)))
(renderf @(:state config)))))]
(swap! state merge
{:target target :render parsef :root root-class
:remove (fn []
(remove-watch (:state config) (or target guid))
(swap! state
#(-> %
(dissoc :target) (dissoc :render) (dissoc :root)
(dissoc :remove)))
(when-not (nil? target)
((:root-unmount config) target)))})
(add-watch (:state config) (or target guid)
(fn [_ _ _ _]
(swap! state update-in [:t] inc)
#?(:cljs
(if-not (iquery? root-class)
(queue-render! parsef)
(schedule-render! this)))))
(parsef)
(when-let [sel (get-query (or (and target @ret) root-class))]
(let [env (to-env config)
snds (gather-sends env sel (:remotes config))]
(when-not (empty? snds)
(when-let [send (:send config)]
(send snds
(fn send-cb
([resp]
(merge! this resp nil)
(renderf ((:parser config) env sel)))
([resp query]
(merge! this resp query)
(renderf ((:parser config) env sel)))
([resp query remote]
(when-not (nil? remote)
(p/queue! this (keys resp) remote))
(merge! this resp query remote)
(p/reconcile! this remote))))))))
@ret)))
(remove-root! [_ target]
(when-let [remove (:remove @state)]
(remove)))
(reindex! [this]
(let [root (get @state :root)]
(when (iquery? root)
(let [indexer (:indexer config)
c (first (get-in @indexer [:class->components root]))]
(p/index-root indexer (or c root))))))
(queue! [this ks]
(p/queue! this ks nil))
(queue! [_ ks remote]
(if-not (nil? remote)
(swap! state update-in [:remote-queue remote] into ks)
(swap! state update-in [:queue] into ks)))
(queue-sends! [_ sends]
(swap! state update-in [:queued-sends]
(:merge-sends config) sends))
(schedule-render! [_]
(if-not (:queued @state)
(do
(swap! state assoc :queued true)
true)
false))
(schedule-sends! [_]
(if-not (:sends-queued @state)
(do
(swap! state assoc :sends-queued true)
true)
false))
(reconcile! [this]
(p/reconcile! this nil))
;; TODO: need to reindex roots after reconcilation
(reconcile! [this remote]
(let [st @state
q (if-not (nil? remote)
(get-in st [:remote-queue remote])
(:queue st))]
(swap! state update-in [:queued] not)
(if (not (nil? remote))
(swap! state assoc-in [:remote-queue remote] [])
(swap! state assoc :queue []))
(if (empty? q)
;; TODO: need to move root re-render logic outside of batching logic
((:render st))
(let [cs (transduce
(map #(p/key->components (:indexer config) %))
#(into %1 %2) #{} q)
{:keys [ui->props]} config
env (to-env config)
root (:root @state)]
#?(:cljs
(doseq [c ((:optimize config) cs)]
(let [props-change? (> (p/basis-t this) (t c))]
(when (mounted? c)
(let [computed (get-computed (props c))
next-raw-props (ui->props env c)
next-props (om.next/computed next-raw-props computed)]
(when (and
(some? (.-componentWillReceiveProps c))
(iquery? root)
props-change?)
(let [next-props (if (nil? next-props)
(when-let [props (props c)]
props)
next-props)]
;; `componentWilReceiveProps` is always called before `shouldComponentUpdate`
(.componentWillReceiveProps c
#js {:omcljs$value (om-props next-props (p/basis-t this))})))
(when (should-update? c next-props (get-state c))
(if-not (nil? next-props)
(update-component! c next-props)
(.forceUpdate c))
;; Only applies if we're doing incremental rendering, not
;; the case in applications without queries
(when (and (iquery? root)
(not= c root)
props-change?)
(when-let [update-path (path c)]
(loop [p (parent c)]
(when (some? p)
(let [update-path' (subvec update-path (count (path p)))]
(update-props! p (assoc-in (props p) update-path' next-raw-props))
(merge-pending-props! p)
(recur (parent p)))))))))))))))))
(send! [this]
(let [sends (:queued-sends @state)]
(when-not (empty? sends)
(swap! state
(fn [state]
(-> state
(assoc :queued-sends {})
(assoc :sends-queued false))))
((:send config) sends
(fn send-cb
([resp]
(merge! this resp nil))
([resp query]
(merge! this resp query))
([resp query remote]
(when-not (nil? remote)
(p/queue! this (keys resp) remote))
(merge! this resp query remote)
(p/reconcile! this remote))))))))
(defn default-ui->props
[{:keys [parser #?(:clj pathopt :cljs ^boolean pathopt)] :as env} c]
(let [ui (when (and pathopt #?(:clj (satisfies? Ident c)
:cljs (implements? Ident c)) (iquery? c))
(let [id (ident c (props c))]
(get (parser env [{id (get-query c)}]) id)))]
(if-not (nil? ui)
ui
(let [fq (full-query c)]
(when-not (nil? fq)
(let [s #?(:clj (System/currentTimeMillis)
:cljs (system-time))
ui (parser env fq)
e #?(:clj (System/currentTimeMillis)
:cljs (system-time))]
#?(:cljs
(when-let [l (:logger env)]
(let [dt (- e s)
component-name (.. c -constructor -displayName)]
(when (< 16 dt)
(glog/warning l (str component-name " query took " dt " msecs"))))))
(get-in ui (path c))))))))
(defn default-merge-ident
[_ tree ref props]
(update-in tree ref merge props))
(defn default-merge-tree
[a b]
(if (map? a)
(merge a b)
b))
(defn default-migrate
"Given app-state-pure (the application state as an immutable value), a query,
tempids (a hash map from tempid to stable id), and an optional id-key
keyword, return a new application state value with the tempids replaced by
the stable ids."
([app-state-pure query tempids]
(default-migrate app-state-pure query tempids nil))
([app-state-pure query tempids id-key]
(letfn [(dissoc-in [pure [table id]]
(assoc pure table (dissoc (get pure table) id)))
(step [pure [old [_ id :as new]]]
(-> pure
(dissoc-in old)
(assoc-in new
(cond-> (merge (get-in pure old) (get-in pure new))
(not (nil? id-key)) (assoc id-key id)))))]
(if-not (empty? tempids)
(let [pure' (reduce step app-state-pure tempids)]
(tree->db query
(db->tree query pure' pure'
(fn [ident] (get tempids ident ident))) true))
app-state-pure))))
(defn- has-error?
#?(:cljs {:tag boolean})
[x]
(and (map? x) (contains? x ::error)))
(defn default-extract-errors [reconciler res query]
(letfn [(extract* [query res errs]
(let [class (-> query meta :component)
top-error? (when (and (not (nil? class)) (has-error? res))
(swap! errs
#(update-in % [#?(:clj ((-> class meta :ident) class res)
:cljs (ident class res))]
(fnil conj #{}) (::error res))))
ret (when (nil? top-error?) {})]
(cond
;; query root
(vector? query)
(if (vector? res)
(into [] (map #(extract* query % errs)) res)
(loop [exprs (seq query) ret ret]
(if-not (nil? exprs)
(let [expr (first exprs)
k (as-> (expr->key expr) k
(cond-> k
(util/unique-ident? k) first))
data (get res k)]
(cond
(util/mutation? expr)
(let [mk (util/mutation-key expr)
ret' (get res mk)]
(if (has-error? ret')
(let [x (-> expr meta :mutator)]
(swap! errs
#(update-in % [x]
(fnil conj #{}) (::error ret')))
(recur (next exprs) ret))
(recur (next exprs)
(when-not (nil? ret)
(assoc ret mk ret')))))
(util/union? expr)
(let [jk (util/join-key expr)
jv (util/join-value expr)
class' (-> jv meta :component)]
(if (not (vector? data))
(let [ret' (extract*
(get jv (first #?(:clj ((-> class' meta :ident) class' data)
:cljs (ident class' data))))
data errs)]
(recur (next exprs)
(when-not (nil? ret)
(assoc ret jk ret'))))
(let [ret' (into []
(map #(extract*
(get jv
(first #?(:clj ((-> class' meta :ident) class' %)
:cljs (ident class' %))))
% errs))
data)]
(recur (next exprs)
(when-not (nil? ret)
(assoc ret jk ret'))))))
(util/join? expr)
(let [jk (util/join-key expr)
jv (util/join-value expr)
ret' (extract* jv data errs)]
(recur (next exprs)
(when-not (nil? ret)
(assoc ret jk ret'))))
(and (map? data) (has-error? data))
(do
(swap! errs
#(update-in %
[(or (when-not (nil? class)
#?(:clj ((-> class meta :ident) class res)
:cljs (ident class res)))
k)]
(fnil conj #{}) (::error data)))
(recur (next exprs) nil))
:else
(recur (next exprs)
(when-not (nil? ret)
(assoc ret k data)))))
ret))))))]
(let [errs (atom {})
ret (extract* query res errs)]
{:tree ret :errors @errs})))
(defn reconciler
"Construct a reconciler from a configuration map.
Required parameters:
:state - the application state. If IAtom value is not supplied the
data will be normalized into the default database format
using the root query. This can be disabled by explicitly
setting the optional :normalize parameter to false.
:parser - the parser to be used
Optional parameters:
:shared - a map of global shared properties for the component tree.
:shared-fn - a function to compute global shared properties from the root props.
the result is merged with :shared.
:send - required only if the parser will return a non-empty value when
run against the supplied :remotes. send is a function of two
arguments, the map of remote expressions keyed by remote target
and a callback which should be invoked with the result from each
remote target. Note this means the callback can be invoked
multiple times to support parallel fetching and incremental
loading if desired. The callback should take the response as the
first argument and the the query that was sent as the second
argument.
:normalize - whether the state should be normalized. If true it is assumed
all novelty introduced into the system will also need
normalization.
:remotes - a vector of keywords representing remote services which can
evaluate query expressions. Defaults to [:remote]
:root-render - the root render function. Defaults to ReactDOM.render
:root-unmount - the root unmount function. Defaults to
ReactDOM.unmountComponentAtNode
:logger - supply a goog.log compatible logger
:tx-listen - a function of 2 arguments that will listen to transactions.
The first argument is the parser's env map also containing
the old and new state. The second argument is a map containing
the transaction, its result and the remote sends that the
transaction originated."
[{:keys [state shared shared-fn
parser indexer
ui->props normalize
send merge-sends remotes
merge merge-tree merge-ident
prune-tree
optimize
history
root-render root-unmount
pathopt
migrate id-key
instrument tx-listen
easy-reads]
:or {ui->props default-ui->props
indexer om.next/indexer
merge-sends #(merge-with into %1 %2)
remotes [:remote]
merge default-merge
merge-tree default-merge-tree
merge-ident default-merge-ident
prune-tree default-extract-errors
optimize (fn [cs] (sort-by depth cs))
history 100
root-render #?(:clj (fn [c target] c)
:cljs #(js/ReactDOM.render %1 %2))
root-unmount #?(:clj (fn [x])
:cljs #(js/ReactDOM.unmountComponentAtNode %))
pathopt false
migrate default-migrate
easy-reads true}
:as config}]
{:pre [(map? config)]}
(let [idxr (indexer)
norm? #?(:clj (instance? clojure.lang.Atom state)
:cljs (satisfies? IAtom state))
state' (if norm? state (atom state))
logger (if (contains? config :logger)
(:logger config)
#?(:cljs *logger*))
ret (Reconciler.
{:state state' :shared shared :shared-fn shared-fn
:parser parser :indexer idxr
:ui->props ui->props
:send send :merge-sends merge-sends :remotes remotes
:merge merge :merge-tree merge-tree :merge-ident merge-ident
:prune-tree prune-tree
:optimize optimize
:normalize (or (not norm?) normalize)
:history #?(:clj []
:cljs (c/cache history))
:root-render root-render :root-unmount root-unmount
:logger logger :pathopt pathopt
:migrate migrate :id-key id-key
:instrument instrument :tx-listen tx-listen
:easy-reads easy-reads}
(atom {:queue []
:remote-queue {}
:queued false :queued-sends {}
:sends-queued false
:target nil :root nil :render nil :remove nil
:t 0 :normalized norm?}))]
ret))
(defn reconciler?
"Returns true if x is a reconciler."
#?(:cljs {:tag boolean})
[x]
#?(:cljs (implements? p/IReconciler x)
:clj (or (instance? om.next.protocols.IReconciler x)
(satisfies? p/IReconciler x))))
(defn app-state
"Return the reconciler's application state atom. Useful when the reconciler
was initialized via denormalized data."
[reconciler]
{:pre [(reconciler? reconciler)]}
(-> reconciler :config :state))
(defn app-root
"Return the application's root component."
[reconciler]
{:pre [(reconciler? reconciler)]}
(get @(:state reconciler) :root))
(defn force-root-render!
"Force a re-render of the root. Not recommended for anything except
recomputing :shared."
[reconciler]
{:pre [(reconciler? reconciler)]}
((get @(:state reconciler) :render)))
(defn from-history
"Given a reconciler and UUID return the application state snapshost
from history associated with the UUID. The size of the reconciler history
may be configured by the :history option when constructing the reconciler."
[reconciler uuid]
{:pre [(reconciler? reconciler)]}
(.get (-> reconciler :config :history) uuid))
(defn tempid
"Return a temporary id."
([] (tempid/tempid))
([id] (tempid/tempid id)))
(defn tempid?
"Return true if x is a tempid, false otherwise"
#?(:cljs {:tag boolean})
[x]
(tempid/tempid? x))
(defn reader
"Create a Om Next transit reader. This reader can handler the tempid type.
Can pass transit reader customization opts map."
([] (transit/reader))
([opts] (transit/reader opts)))
(defn writer
"Create a Om Next transit writer. This writer can handler the tempid type.
Can pass transit writer customization opts map."
([] (transit/writer))
([opts] (transit/writer opts)))
(defn force
"Given a query expression return an equivalent query expression that can be
spliced into a transaction that will force a read of that key from the
specified remote target."
([expr]
(force expr :remote))
([expr target]
(with-meta (list 'quote expr) {:target target})))
| null | https://raw.githubusercontent.com/omcljs/om/3a1fbe9c0e282646fc58550139b491ff9869f96d/src/main/om/next.cljc | clojure | single method case
TODO: #?:clj invariant - António
=============================================================================
CLJS
=============================================================================
Globals & Dynamics
=============================================================================
SUBQUERY
UNION
JOIN
CALL
UNION
this function assumes focus is actually in fact
already focused!
=============================================================================
Query Protocols & Helpers
=============================================================================
When force updating we write temporarily props into state to avoid bogus
if the props recorded into state are more recent - props will get updated
when React actually re-renders the component.
=============================================================================
Reconciler API
=============================================================================
Transactions
=============================================================================
=============================================================================
Indexer
they are used to access union queries
path could have changed when setting queries, so we only use
information) - António
Union query case
handle case where child appears multiple times at same class-path
but with different queries
union case
already normalized
normalize many
union case
missing key
can't handle
TODO: easy to optimize
support taking ident for data param
join
also reduce query depth of union-seen, there can
be more union recursions inside
UNION
map case
=============================================================================
Reconciler
eliminate exact duplicates
emulate an alternate-root element
TODO: need to reindex roots after reconcilation
TODO: need to move root re-render logic outside of batching logic
`componentWilReceiveProps` is always called before `shouldComponentUpdate`
Only applies if we're doing incremental rendering, not
the case in applications without queries
query root | (ns om.next
(:refer-clojure :exclude #?(:clj [deftype replace var? force]
:cljs [var? key replace force]))
#?(:cljs (:require-macros [om.next :refer [defui invariant]]))
(:require #?@(:clj [clojure.main
[cljs.core :refer [deftype specify! this-as js-arguments]]
[clojure.reflect :as reflect]
[cljs.util]]
:cljs [[goog.string :as gstring]
[goog.object :as gobj]
[goog.log :as glog]
[om.next.cache :as c]])
[om.next.impl.parser :as parser]
[om.tempid :as tempid]
[om.transit :as transit]
[om.util :as util]
[clojure.zip :as zip]
[om.next.protocols :as p]
[cljs.analyzer :as ana]
[cljs.analyzer.api :as ana-api]
[clojure.string :as str])
#?(:clj (:import [java.io Writer])
:cljs (:import [goog.debug Console])))
(defn collect-statics [dt]
(letfn [(split-on-static [forms]
(split-with (complement '#{static}) forms))
(split-on-symbol [forms]
(split-with (complement symbol?) forms))]
(loop [dt (seq dt) dt' [] statics {:fields {} :protocols []}]
(if dt
(let [[pre [_ sym & remaining :as post]] (split-on-static dt)
dt' (into dt' pre)]
(if (seq post)
(cond
(= sym 'field)
(let [[field-info dt] (split-at 2 remaining)]
(recur (seq dt) dt'
(update-in statics [:fields] conj (vec field-info))))
(symbol? sym)
(let [[protocol-info dt] (split-on-symbol remaining)]
(recur (seq dt) dt'
(update-in statics [:protocols]
into (concat [sym] protocol-info))))
:else (throw #?(:clj (IllegalArgumentException. "Malformed static")
:cljs (js/Error. "Malformed static"))))
(recur nil dt' statics)))
{:dt dt' :statics statics}))))
(defn- validate-statics [dt]
(when-let [invalid (some #{"Ident" "IQuery" "IQueryParams"}
(map #(-> % str (str/split #"/") last)
(filter symbol? dt)))]
(throw
#?(:clj (IllegalArgumentException.
(str invalid " protocol declaration must appear with `static`."))
:cljs (js/Error.
(str invalid " protocol declaration must appear with `static`."))))))
(def lifecycle-sigs
'{initLocalState [this]
shouldComponentUpdate [this next-props next-state]
componentWillReceiveProps [this next-props]
componentWillUpdate [this next-props next-state]
componentDidUpdate [this prev-props prev-state]
componentWillMount [this]
componentDidMount [this]
componentWillUnmount [this]
render [this]})
(defn validate-sig [[name sig :as method]]
(let [sig' (get lifecycle-sigs name)]
(assert (= (count sig') (count sig))
(str "Invalid signature for " name " got " sig ", need " sig'))))
#?(:clj
(def reshape-map-clj
{:reshape
{'render
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#]
(binding [om.next/*reconciler* (om.next/get-reconciler this#)
om.next/*depth* (inc (om.next/depth this#))
om.next/*shared* (om.next/shared this#)
om.next/*instrument* (om.next/instrument this#)
om.next/*parent* this#]
(let [ret# (do ~@body)
props# (:props this#)]
(when-not @(:omcljs$mounted? props#)
(swap! (:omcljs$mounted? props#) not))
ret#)))))
'componentWillMount
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#
indexer# (get-in (om.next/get-reconciler this#) [:config :indexer])]
(when-not (nil? indexer#)
(om.next.protocols/index-component! indexer# this#))
~@body)))}
:defaults
`{~'initLocalState
([this#])
~'componentWillMount
([this#]
(let [indexer# (get-in (om.next/get-reconciler this#) [:config :indexer])]
(when-not (nil? indexer#)
(om.next.protocols/index-component! indexer# this#))))
~'render
([this#])}}))
(def reshape-map
{:reshape
{'initLocalState
(fn [[name [this :as args] & body]]
`(~name ~args
(let [ret# (do ~@body)]
(cljs.core/js-obj "omcljs$state" ret#))))
'componentWillReceiveProps
(fn [[name [this next-props :as args] & body]]
`(~name [this# next-props#]
(let [~this this#
~next-props (om.next/-next-props next-props# this#)]
~@body)))
'componentWillUpdate
(fn [[name [this next-props next-state :as args] & body]]
`(~name [this# next-props# next-state#]
(let [~this this#
~next-props (om.next/-next-props next-props# this#)
~next-state (or (goog.object/get next-state# "omcljs$pendingState")
(goog.object/get next-state# "omcljs$state"))
ret# (do ~@body)]
(when (cljs.core/implements? om.next/Ident this#)
(let [ident# (om.next/ident this# (om.next/props this#))
next-ident# (om.next/ident this# ~next-props)]
(when (not= ident# next-ident#)
(let [idxr# (get-in (om.next/get-reconciler this#) [:config :indexer])]
(when-not (nil? idxr#)
(swap! (:indexes idxr#)
(fn [indexes#]
(-> indexes#
(update-in [:ref->components ident#] disj this#)
(update-in [:ref->components next-ident#] (fnil conj #{}) this#)))))))))
(om.next/merge-pending-props! this#)
(om.next/merge-pending-state! this#)
ret#)))
'componentDidUpdate
(fn [[name [this prev-props prev-state :as args] & body]]
`(~name [this# prev-props# prev-state#]
(let [~this this#
~prev-props (om.next/-prev-props prev-props# this#)
~prev-state (goog.object/get prev-state# "omcljs$previousState")]
~@body
(om.next/clear-prev-props! this#))))
'componentWillMount
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#
indexer# (get-in (om.next/get-reconciler this#) [:config :indexer])]
(when-not (nil? indexer#)
(om.next.protocols/index-component! indexer# this#))
~@body)))
'componentWillUnmount
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#
r# (om.next/get-reconciler this#)
cfg# (:config r#)
st# (:state cfg#)
indexer# (:indexer cfg#)]
(when (and (not (nil? st#))
(get-in @st# [:om.next/queries this#]))
(swap! st# update-in [:om.next/queries] dissoc this#))
(when-not (nil? indexer#)
(om.next.protocols/drop-component! indexer# this#))
~@body)))
'render
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#]
(binding [om.next/*reconciler* (om.next/get-reconciler this#)
om.next/*depth* (inc (om.next/depth this#))
om.next/*shared* (om.next/shared this#)
om.next/*instrument* (om.next/instrument this#)
om.next/*parent* this#]
~@body))))}
:defaults
`{~'isMounted
([this#]
(boolean
(or (some-> this# .-_reactInternalFiber .-stateNode)
Pre React 16 support . Remove when we do n't wish to support
React < 16 anymore - Antonio
(some-> this# .-_reactInternalInstance .-_renderedComponent))))
~'shouldComponentUpdate
([this# next-props# next-state#]
(let [next-children# (. next-props# -children)
next-props# (goog.object/get next-props# "omcljs$value")
next-props# (cond-> next-props#
(instance? om.next/OmProps next-props#) om.next/unwrap)]
(or (not= (om.next/props this#)
next-props#)
(and (.. this# ~'-state)
(not= (goog.object/get (. this# ~'-state) "omcljs$state")
(goog.object/get next-state# "omcljs$state")))
(not= (.. this# -props -children)
next-children#))))
~'componentWillUpdate
([this# next-props# next-state#]
(when (cljs.core/implements? om.next/Ident this#)
(let [ident# (om.next/ident this# (om.next/props this#))
next-ident# (om.next/ident this# (om.next/-next-props next-props# this#))]
(when (not= ident# next-ident#)
(let [idxr# (get-in (om.next/get-reconciler this#) [:config :indexer])]
(when-not (nil? idxr#)
(swap! (:indexes idxr#)
(fn [indexes#]
(-> indexes#
(update-in [:ref->components ident#] disj this#)
(update-in [:ref->components next-ident#] (fnil conj #{}) this#)))))))))
(om.next/merge-pending-props! this#)
(om.next/merge-pending-state! this#))
~'componentDidUpdate
([this# prev-props# prev-state#]
(om.next/clear-prev-props! this#))
~'componentWillMount
([this#]
(let [indexer# (get-in (om.next/get-reconciler this#) [:config :indexer])]
(when-not (nil? indexer#)
(om.next.protocols/index-component! indexer# this#))))
~'componentWillUnmount
([this#]
(let [r# (om.next/get-reconciler this#)
cfg# (:config r#)
st# (:state cfg#)
indexer# (:indexer cfg#)]
(when (and (not (nil? st#))
(get-in @st# [:om.next/queries this#]))
(swap! st# update-in [:om.next/queries] dissoc this#))
(when-not (nil? indexer#)
(om.next.protocols/drop-component! indexer# this#))))}})
(defn reshape [dt {:keys [reshape defaults]}]
(letfn [(reshape* [x]
(if (and (sequential? x)
(contains? reshape (first x)))
(let [reshapef (get reshape (first x))]
(validate-sig x)
(reshapef x))
x))
(add-defaults-step [ret [name impl]]
(if-not (some #{name} (map first (filter seq? ret)))
(let [[before [p & after]] (split-with (complement '#{Object}) ret)]
(into (conj (vec before) p (cons name impl)) after))
ret))
(add-defaults [dt]
(reduce add-defaults-step dt defaults))
(add-object-protocol [dt]
(if-not (some '#{Object} dt)
(conj dt 'Object)
dt))]
(->> dt (map reshape*) vec add-object-protocol add-defaults)))
#?(:clj
(defn- add-proto-methods* [pprefix type type-sym [f & meths :as form]]
(let [pf (str pprefix (name f))
emit-static (when (-> type-sym meta :static)
`(~'js* "/** @nocollapse */"))]
(if (vector? (first meths))
(let [meth meths]
[`(do
~emit-static
(set! ~(#'cljs.core/extend-prefix type-sym (str pf "$arity$" (count (first meth))))
~(with-meta `(fn ~@(#'cljs.core/adapt-proto-params type meth)) (meta form))))])
(map (fn [[sig & body :as meth]]
`(do
~emit-static
(set! ~(#'cljs.core/extend-prefix type-sym (str pf "$arity$" (count sig)))
~(with-meta `(fn ~(#'cljs.core/adapt-proto-params type meth)) (meta form)))))
meths)))))
#?(:clj (intern 'cljs.core 'add-proto-methods* add-proto-methods*))
#?(:clj
(defn- proto-assign-impls [env resolve type-sym type [p sigs]]
(#'cljs.core/warn-and-update-protocol p type env)
(let [psym (resolve p)
pprefix (#'cljs.core/protocol-prefix psym)
skip-flag (set (-> type-sym meta :skip-protocol-flag))
static? (-> p meta :static)
type-sym (cond-> type-sym
static? (vary-meta assoc :static true))
emit-static (when static?
`(~'js* "/** @nocollapse */"))]
(if (= p 'Object)
(#'cljs.core/add-obj-methods type type-sym sigs)
(concat
(when-not (skip-flag psym)
(let [{:keys [major minor qualifier]} cljs.util/*clojurescript-version*]
(if (or (> major 1)
(and (== major 1) (> minor 9))
(and (== major 1) (== minor 9) (>= qualifier 293)))
[`(do
~emit-static
(set! ~(#'cljs.core/extend-prefix type-sym pprefix) cljs.core/PROTOCOL_SENTINEL))]
[`(do
~emit-static
(set! ~(#'cljs.core/extend-prefix type-sym pprefix) true))])))
(mapcat
(fn [sig]
(if (= psym 'cljs.core/IFn)
(#'cljs.core/add-ifn-methods type type-sym sig)
(#'cljs.core/add-proto-methods* pprefix type type-sym sig)))
sigs))))))
#?(:clj (intern 'cljs.core 'proto-assign-impls proto-assign-impls))
#?(:clj (defn- extract-static-methods [protocols]
(letfn [(add-protocol-method [existing-methods method]
(let [nm (first method)
new-arity (rest method)
k (keyword nm)
existing-method (get existing-methods k)]
(if existing-method
(let [single-arity? (vector? (second existing-method))
existing-arities (if single-arity?
(list (rest existing-method))
(rest existing-method))]
(assoc existing-methods k (conj existing-arities new-arity 'fn)))
(assoc existing-methods k (list 'fn new-arity)))))]
(when-not (empty? protocols)
(let [result (->> protocols
(filter #(not (symbol? %)))
(reduce
(fn [r impl] (add-protocol-method r impl))
{}))]
(if (contains? result :params)
result
(assoc result :params '(fn [this]))))))))
#?(:clj
(defn defui*-clj [name forms]
(let [docstring (when (string? (first forms))
(first forms))
forms (cond-> forms
docstring rest)
{:keys [dt statics]} (collect-statics forms)
[other-protocols obj-dt] (split-with (complement '#{Object}) dt)
klass-name (symbol (str name "_klass"))
lifecycle-method-names (set (keys lifecycle-sigs))
{obj-dt false non-lifecycle-dt true} (group-by
(fn [x]
(and (sequential? x)
(not (lifecycle-method-names (first x)))))
obj-dt)
class-methods (extract-static-methods (:protocols statics))]
`(do
~(when-not (empty? non-lifecycle-dt)
`(defprotocol ~(symbol (str name "_proto"))
~@(map (fn [[m-name args]] (list m-name args)) non-lifecycle-dt)))
(declare ~name)
(defrecord ~klass-name [~'state ~'refs ~'props ~'children]
TODO : non - lifecycle methods defined in the JS prototype - António
om.next.protocols/IReactLifecycle
~@(rest (reshape obj-dt reshape-map-clj))
~@other-protocols
~@(:protocols statics)
~@(when-not (empty? non-lifecycle-dt)
(list* (symbol (str name "_proto"))
non-lifecycle-dt))
om.next.protocols/IReactComponent
(~'-render [this#]
(p/componentWillMount this#)
(p/render this#)))
(defmethod clojure.core/print-method ~(symbol (str (munge *ns*) "." klass-name))
[o# ^Writer w#]
(.write w# (str "#object[" (ns-name *ns*) "/" ~(str name) "]")))
(let [c# (fn ~name [state# refs# props# children#]
(~(symbol (str (munge *ns*) "." klass-name ".")) state# refs# props# children#))]
(def ~(with-meta name
(merge (meta name)
(when docstring
{:doc docstring})))
(with-meta c#
(merge {:component c#
:component-ns (ns-name *ns*)
:component-name ~(str name)}
~class-methods))))))))
(defn defui*
([name form] (defui* name form nil))
([name forms env]
(letfn [(field-set! [obj [field value]]
`(set! (. ~obj ~(symbol (str "-" field))) ~value))]
(let [docstring (when (string? (first forms))
(first forms))
forms (cond-> forms
docstring rest)
{:keys [dt statics]} (collect-statics forms)
_ (validate-statics dt)
rname (if env
(:name (ana/resolve-var (dissoc env :locals) name))
name)
ctor `(defn ~(with-meta name
(merge {:jsdoc ["@constructor"]}
(meta name)
(when docstring
{:doc docstring})))
[]
(this-as this#
(.apply js/React.Component this# (js-arguments))
(if-not (nil? (.-initLocalState this#))
(set! (.-state this#) (.initLocalState this#))
(set! (.-state this#) (cljs.core/js-obj)))
this#))
set-react-proto! `(set! (.-prototype ~name)
(goog.object/clone js/React.Component.prototype))
ctor (if (-> name meta :once)
`(when-not (cljs.core/exists? ~name)
~ctor
~set-react-proto!)
`(do
~ctor
~set-react-proto!))
display-name (if env
(str (-> env :ns :name) "/" name)
'js/undefined)]
`(do
~ctor
(specify! (.-prototype ~name) ~@(reshape dt reshape-map))
(set! (.. ~name -prototype -constructor) ~name)
(set! (.. ~name -prototype -constructor -displayName) ~display-name)
(set! (.. ~name -prototype -om$isComponent) true)
~@(map #(field-set! name %) (:fields statics))
(specify! ~name
~@(mapv #(cond-> %
(symbol? %) (vary-meta assoc :static true)) (:protocols statics)))
(specify! (. ~name ~'-prototype) ~@(:protocols statics))
(set! (.-cljs$lang$type ~rname) true)
(set! (.-cljs$lang$ctorStr ~rname) ~(str rname))
(set! (.-cljs$lang$ctorPrWriter ~rname)
(fn [this# writer# opt#]
(cljs.core/-write writer# ~(str rname)))))))))
(defmacro defui [name & forms]
(if (boolean (:ns &env))
(defui* name forms &env)
#?(:clj (defui*-clj name forms))))
(defmacro ui
[& forms]
(let [t (with-meta (gensym "ui_") {:anonymous true})]
`(do (defui ~t ~@forms) ~t)))
(defn invariant*
[condition message env]
(let [opts (ana-api/get-options)
fn-scope (:fn-scope env)
fn-name (some-> fn-scope first :name str)]
(when-not (:elide-asserts opts)
`(let [l# om.next/*logger*]
(when-not ~condition
(goog.log/error l#
(str "Invariant Violation"
(when-not (nil? ~fn-name)
(str " (in function: `" ~fn-name "`)"))
": " ~message)))))))
(defmacro invariant
[condition message]
(when (boolean (:ns &env))
(invariant* condition message &env)))
#?(:clj
(defmethod print-method clojure.lang.AFunction
[o ^Writer w]
(let [obj-ns (-> o meta :component-ns)
obj-name (-> o meta :component-name)]
(if obj-name
(.write w (str obj-ns "/" obj-name))
(#'clojure.core/print-object o w)))))
#?(:cljs
(defonce *logger*
(when ^boolean goog.DEBUG
(.setCapturing (Console.) true)
(glog/getLogger "om.next"))))
(def ^:private roots (atom {}))
(def ^{:dynamic true} *raf* nil)
(def ^{:dynamic true :private true} *reconciler* nil)
(def ^{:dynamic true :private true} *parent* nil)
(def ^{:dynamic true :private true} *shared* nil)
(def ^{:dynamic true :private true} *instrument* nil)
(def ^{:dynamic true :private true} *depth* 0)
Utilities
(defn nil-or-map?
#?(:cljs {:tag boolean})
[x]
(or (nil? x) (map? x)))
(defn- expr->key
"Given a query expression return its key."
[expr]
(cond
(keyword? expr) expr
(map? expr) (ffirst expr)
(seq? expr) (let [expr' (first expr)]
(when (map? expr')
(ffirst expr')))
(util/ident? expr) (cond-> expr (= '_ (second expr)) first)
:else
(throw
(ex-info (str "Invalid query expr " expr)
{:type :error/invalid-expression}))))
(defn- query-zip
"Return a zipper on a query expression."
[root]
(zip/zipper
#(or (vector? %) (map? %) (seq? %))
seq
(fn [node children]
(let [ret (cond
(vector? node) (vec children)
(map? node) (into {} children)
(seq? node) children)]
(with-meta ret (meta node))))
root))
(defn- move-to-key
"Move from the current zipper location to the specified key. loc must be a
hash map node."
[loc k]
(loop [loc (zip/down loc)]
(let [node (zip/node loc)]
(if (= k (first node))
(-> loc zip/down zip/right)
(recur (zip/right loc))))))
(defn- query-template
"Given a query and a path into a query return a zipper focused at the location
specified by the path. This location can be replaced to customize / alter
the query."
[query path]
(letfn [(query-template* [loc path]
(if (empty? path)
loc
(let [node (zip/node loc)]
(recur (zip/down loc) path)
(let [[k & ks] path
k' (expr->key node)]
(if (= k k')
(if (or (map? node)
(and (seq? node) (map? (first node))))
(let [loc' (move-to-key (cond-> loc (seq? node) zip/down) k)
node' (zip/node loc')]
(if (seq ks)
(recur
(zip/replace loc'
(zip/node (move-to-key loc' (first ks))))
(next ks))
loc')
(recur (zip/right loc) path)))))))]
(query-template* (query-zip query) path)))
(defn- replace [template new-query]
(-> template (zip/replace new-query) zip/root))
(declare focus-query*)
(defn- focused-join [expr ks full-expr union-expr]
(let [expr-meta (meta expr)
expr' (cond
(map? expr)
(let [join-value (-> expr first second)
join-value (if (and (util/recursion? join-value)
(seq ks))
(if-not (nil? union-expr)
union-expr
full-expr)
join-value)]
{(ffirst expr) (focus-query* join-value ks nil)})
(seq? expr) (list (focused-join (first expr) ks nil nil) (second expr))
:else expr)]
(cond-> expr'
(some? expr-meta) (with-meta expr-meta))))
(defn- focus-query*
[query path union-expr]
(if (empty? path)
query
(let [[k & ks] path]
(letfn [(match [x]
(= k (util/join-key x)))
(value [x]
(focused-join x ks query union-expr))]
{k (focus-query* (get query k) ks query)}
(into [] (comp (filter match) (map value) (take 1)) query))))))
(defn focus-query
"Given a query, focus it along the specified path.
Examples:
(om.next/focus-query [:foo :bar :baz] [:foo])
=> [:foo]
(om.next/focus-query [{:foo [:bar :baz]} :woz] [:foo :bar])
=> [{:foo [:bar]}]"
[query path]
(focus-query* query path nil))
(defn- focus->path
"Given a focused query return the path represented by the query.
Examples:
(om.next/focus->path [{:foo [{:bar {:baz []}]}])
=> [:foo :bar :baz]"
([focus]
(focus->path focus '* []))
([focus bound]
(focus->path focus bound []))
([focus bound path]
(if (and (or (= bound '*)
(and (not= path bound)
(< (count path) (count bound))))
(some util/join? focus)
(== 1 (count focus)))
(let [[k focus'] (util/join-entry (first focus))
focus' (if (util/recursion? focus')
focus
focus')]
(recur focus' bound (conj path k)))
path)))
(defprotocol Ident
(ident [this props] "Return the ident for this component"))
(defprotocol IQueryParams
(params [this] "Return the query parameters"))
#?(:clj (extend-type Object
IQueryParams
(params [this]
(when-let [ps (-> this meta :params)]
(ps this))))
:cljs (extend-type default
IQueryParams
(params [_])))
(defprotocol IQuery
(query [this] "Return the component's unbound query"))
(defprotocol ILocalState
(-set-state! [this new-state] "Set the component's local state")
(-get-state [this] "Get the component's local state")
(-get-rendered-state [this] "Get the component's rendered local state")
(-merge-pending-state! [this] "Get the component's pending local state"))
(defn- var? [x]
(and (symbol? x)
#?(:clj (.startsWith (str x) "?")
:cljs (gstring/startsWith (str x) "?"))))
(defn- var->keyword [x]
(keyword (.substring (str x) 1)))
(defn- replace-var [expr params]
(if (var? expr)
(get params (var->keyword expr) expr)
expr))
(defn- bind-query [query params]
(let [qm (meta query)
tr (map #(bind-query % params))
ret (cond
(seq? query) (apply list (into [] tr query))
#?@(:cljs [(and (exists? cljs.core/IMapEntry)
(implements? ^:cljs.analyzer/no-resolve cljs.core/IMapEntry query))
(into [] tr query)])
#?@(:clj [(instance? clojure.lang.IMapEntry query) (into [] tr query)])
(coll? query) (into (empty query) tr query)
:else (replace-var query params))]
(cond-> ret
(and qm #?(:clj (instance? clojure.lang.IObj ret)
:cljs (satisfies? IMeta ret)))
(with-meta qm))))
(declare component? get-reconciler props class-path get-indexer path react-type)
(defn- component->query-data [component]
(some-> (get-reconciler component)
:config :state deref ::queries (get component)))
(defn get-unbound-query
"Return the unbound query for a component."
[component]
(:query (component->query-data component) (query component)))
(defn get-params
"Return the query params for a component."
[component]
(:params (component->query-data component) (params component)))
(defn- get-component-query
([component]
(get-component-query component (component->query-data component)))
([component query-data]
(let [q (:query query-data (query component))
c' (-> q meta :component)]
(assert (nil? c')
(str "Query violation, " component " reuses " c' " query"))
(with-meta
(bind-query q (:params query-data (params component)))
{:component (react-type component)}))))
(defn iquery?
#?(:cljs {:tag boolean})
[x]
#?(:clj (if (fn? x)
(some? (-> x meta :query))
(let [class (cond-> x (component? x) class)]
(extends? IQuery class)))
:cljs (implements? IQuery x)))
(defn- get-class-or-instance-query
"Return a IQuery/IParams local bound query. Works for component classes
and component instances. Does not use the indexer."
[x]
(if (component? x)
(get-component-query x)
(let [q #?(:clj ((-> x meta :query) x)
:cljs (query x))
c (-> q meta :component)]
(assert (nil? c) (str "Query violation, " x , " reuses " c " query"))
(with-meta (bind-query q (params x)) {:component x}))))
(defn- get-indexed-query
"Get a component's static query from the indexer. For recursive queries, recurses
up the data path. Falls back to `get-class-or-instance-query` if nothing is
found in the indexer."
[component class-path-query-data data-path]
(let [qs (filter #(= data-path (-> % zip/root (focus->path data-path)))
class-path-query-data)
qs (if (empty? qs) class-path-query-data qs)]
(if-not (empty? qs)
(let [q (first qs)
node (zip/node q)]
(if-not (util/recursion? node)
node
(recur component class-path-query-data (pop data-path))))
(get-class-or-instance-query component))))
(defn get-query
"Return a IQuery/IParams instance bound query. Works for component classes
and component instances. See also om.next/full-query."
[x]
(when #?(:clj (iquery? x)
:cljs (implements? IQuery x))
(if (component? x)
(if-let [query-data (component->query-data x)]
(get-component-query x query-data)
(let [cp (class-path x)
r (get-reconciler x)
data-path (into [] (remove number?) (path x))
class-path-query-data (get (:class-path->query @(get-indexer r)) cp)]
(get-indexed-query x class-path-query-data data-path)))
(get-class-or-instance-query x))))
(defn tag [x class]
(vary-meta x assoc :component class))
React Bridging
#?(:cljs (deftype ^:private OmProps [props basis-t]))
#?(:cljs
(defn- om-props [props basis-t]
(OmProps. props basis-t)))
#?(:cljs
(defn- om-props-basis [om-props]
(.-basis-t om-props)))
#?(:cljs (def ^:private nil-props (om-props nil -1)))
#?(:cljs
(defn- unwrap [om-props]
(.-props om-props)))
#?(:clj
(defn- munge-component-name [x]
(let [ns-name (-> x meta :component-ns)
cl-name (-> x meta :component-name)]
(munge
(str (str/replace (str ns-name) "." "$") "$" cl-name)))))
#?(:clj
(defn- compute-react-key [cl props]
(when-let [idx (-> props meta :om-path)]
(str (munge-component-name cl) "_" idx))))
#?(:cljs
(defn- compute-react-key [cl props]
(if-let [rk (:react-key props)]
rk
(if-let [idx (-> props meta :om-path)]
(str (. cl -name) "_" idx)
js/undefined))))
#?(:clj
(defn factory
"Create a factory constructor from a component class created with
om.next/defui."
([class]
(factory class nil))
([class {:keys [validator keyfn instrument?]
:or {instrument? true} :as opts}]
{:pre [(fn? class)]}
(fn self
([] (self nil))
([props & children]
(when-not (nil? validator)
(assert (validator props)))
(if (and *instrument* instrument?)
(*instrument*
{:props props
:children children
:class class
:factory (factory class (assoc opts :instrument? false))})
(let [react-key (cond
(some? keyfn) (keyfn props)
(some? (:react-key props)) (:react-key props)
:else (compute-react-key class props))
ctor class
ref (:ref props)
props {:omcljs$reactRef ref
:omcljs$reactKey react-key
:omcljs$value (cond-> props
(map? props) (dissoc :ref))
:omcljs$mounted? (atom false)
:omcljs$path (-> props meta :om-path)
:omcljs$reconciler *reconciler*
:omcljs$parent *parent*
:omcljs$shared *shared*
:omcljs$instrument *instrument*
:omcljs$depth *depth*}
component (ctor (atom nil) (atom nil) props children)]
(when ref
(assert (some? *parent*))
(swap! (:refs *parent*) assoc ref component))
(reset! (:state component) (.initLocalState component))
component)))))))
#?(:cljs
(defn factory
"Create a factory constructor from a component class created with
om.next/defui."
([class] (factory class nil))
([class {:keys [validator keyfn instrument?]
:or {instrument? true} :as opts}]
{:pre [(fn? class)]}
(fn self [props & children]
(when-not (nil? validator)
(assert (validator props)))
(if (and *instrument* instrument?)
(*instrument*
{:props props
:children children
:class class
:factory (factory class (assoc opts :instrument? false))})
(let [key (if-not (nil? keyfn)
(keyfn props)
(compute-react-key class props))
ref (:ref props)
ref (cond-> ref (keyword? ref) str)
t (if-not (nil? *reconciler*)
(p/basis-t *reconciler*)
0)]
(js/React.createElement class
#js {:key key
:ref ref
:omcljs$reactKey key
:omcljs$value (om-props props t)
:omcljs$path (-> props meta :om-path)
:omcljs$reconciler *reconciler*
:omcljs$parent *parent*
:omcljs$shared *shared*
:omcljs$instrument *instrument*
:omcljs$depth *depth*}
(util/force-children children))))))))
(defn component?
"Returns true if the argument is an Om component."
#?(:cljs {:tag boolean})
[x]
(if-not (nil? x)
#?(:clj (or (instance? om.next.protocols.IReactComponent x)
(satisfies? p/IReactComponent x))
:cljs (true? (. x -om$isComponent)))
false))
(defn- state [c]
{:pre [(component? c)]}
(.-state c))
(defn- get-prop
"PRIVATE: Do not use"
[c k]
#?(:clj (get (:props c) k)
:cljs (gobj/get (.-props c) k)))
#?(:cljs
(defn- get-props*
[x k]
(if (nil? x)
nil-props
(let [y (gobj/get x k)]
(if (nil? y)
nil-props
y)))))
#?(:cljs
(defn- get-prev-props [x]
(get-props* x "omcljs$prev$value")))
#?(:cljs
(defn- get-next-props [x]
(get-props* x "omcljs$next$value")))
#?(:cljs
(defn- get-props [x]
(get-props* x "omcljs$value")))
#?(:cljs
(defn- set-prop!
"PRIVATE: Do not use"
[c k v]
(gobj/set (.-props c) k v)))
(defn get-reconciler
[c]
{:pre [(component? c)]}
(get-prop c #?(:clj :omcljs$reconciler
:cljs "omcljs$reconciler")))
#?(:cljs
(defn- props*
([x y]
(max-key om-props-basis x y))
([x y z]
(max-key om-props-basis x (props* y z)))))
#?(:cljs
(defn- prev-props*
([x y]
(min-key om-props-basis x y))
([x y z]
(min-key om-props-basis
(props* x y) (props* y z)))))
#?(:cljs
(defn -prev-props [prev-props component]
(let [cst (.-state component)
props (.-props component)]
(unwrap
(prev-props*
(props* (get-props prev-props) (get-prev-props cst))
(props* (get-props cst) (get-props props)))))))
#?(:cljs
(defn -next-props [next-props component]
(unwrap
(props*
(-> component .-props get-props)
(get-props next-props)
(-> component .-state get-next-props)))))
#?(:cljs
(defn- merge-pending-props! [c]
{:pre [(component? c)]}
(let [cst (. c -state)
props (.-props c)
pending (gobj/get cst "omcljs$next$value")
prev (props* (get-props cst) (get-props props))]
(gobj/set cst "omcljs$prev$value" prev)
(when-not (nil? pending)
(gobj/remove cst "omcljs$next$value")
(gobj/set cst "omcljs$value" pending)))))
#?(:cljs
(defn- clear-prev-props! [c]
(gobj/remove (.-state c) "omcljs$prev$value")))
#?(:cljs
(defn- t
"Get basis t value for when the component last read its props from
the global state."
[c]
(om-props-basis
(props*
(-> c .-props get-props)
(-> c .-state get-props)))))
(defn- parent
"Returns the parent Om component."
[component]
(get-prop component #?(:clj :omcljs$parent
:cljs "omcljs$parent")))
(defn depth
"PRIVATE: Returns the render depth (a integer) of the component relative to
the mount root."
[component]
(when (component? component)
(get-prop component #?(:clj :omcljs$depth
:cljs "omcljs$depth"))))
(defn react-key
"Returns the components React key."
[component]
(get-prop component #?(:clj :omcljs$reactKey
:cljs "omcljs$reactKey")))
#?(:clj
(defn react-type
"Returns the component type, regardless of whether the component has been
mounted"
[component]
{:pre [(component? component)]}
(let [[klass-name] (str/split (reflect/typename (type component)) #"_klass")
last-idx-dot (.lastIndexOf klass-name ".")
ns (clojure.main/demunge (subs klass-name 0 last-idx-dot))
c (subs klass-name (inc last-idx-dot))]
@(or (find-var (symbol ns c))
(find-var (symbol ns (clojure.main/demunge c)))))))
#?(:cljs
(defn react-type
"Returns the component type, regardless of whether the component has been
mounted"
[x]
(or (gobj/get x "type") (type x))))
(defn- path
"Returns the component's Om data path."
[c]
(get-prop c #?(:clj :omcljs$path
:cljs "omcljs$path")))
(defn shared
"Return the global shared properties of the Om Next root. See :shared and
:shared-fn reconciler options."
([component]
(shared component []))
([component k-or-ks]
{:pre [(component? component)]}
(let [shared #?(:clj (get-prop component :omcljs$shared)
:cljs (gobj/get (. component -props) "omcljs$shared"))
ks (cond-> k-or-ks
(not (sequential? k-or-ks)) vector)]
(cond-> shared
(not (empty? ks)) (get-in ks)))))
(defn instrument [component]
{:pre [(component? component)]}
(get-prop component #?(:clj :omcljs$instrument
:cljs "omcljs$instrument")))
#?(:cljs
(defn- update-props! [c next-props]
{:pre [(component? c)]}
We can not write directly to props , React will complain
(doto (.-state c)
(gobj/set "omcljs$next$value"
(om-props next-props (p/basis-t (get-reconciler c)))))))
#?(:clj
(defn props [component]
{:pre [(component? component)]}
(:omcljs$value (:props component))))
#?(:cljs
(defn props
"Return a components props."
[component]
{:pre [(component? component)]}
complaints from React . We record the basis T of the reconciler to determine
(unwrap
(props*
(-> component .-props get-props)
(-> component .-state get-props)))))
(defn computed
"Add computed properties to props. Note will replace any pre-existing
computed properties."
[props computed-map]
(when-not (nil? props)
(if (vector? props)
(cond-> props
(not (empty? computed-map)) (vary-meta assoc :om.next/computed computed-map))
(cond-> props
(not (empty? computed-map)) (assoc :om.next/computed computed-map)))))
(defn get-computed
"Return the computed properties on a component or its props."
([x]
(get-computed x []))
([x k-or-ks]
(when-not (nil? x)
(let [props (cond-> x (component? x) props)
ks (into [:om.next/computed]
(cond-> k-or-ks
(not (sequential? k-or-ks)) vector))]
(if (vector? props)
(-> props meta (get-in ks))
(get-in props ks))))))
(declare schedule-render!)
#?(:clj
(defn set-state!
[component new-state]
{:pre [(component? component)]}
(if (satisfies? ILocalState component)
(-set-state! component new-state)
(reset! (:state component) new-state))))
#?(:cljs
(defn set-state!
"Set the component local state of the component. Analogous to React's
setState."
[component new-state]
{:pre [(component? component)]}
(if (implements? ILocalState component)
(-set-state! component new-state)
(gobj/set (.-state component) "omcljs$pendingState" new-state))
(if-let [r (get-reconciler component)]
(do
(p/queue! r [component])
(schedule-render! r))
(.forceUpdate component))))
(defn get-state
"Get a component's local state. May provide a single key or a sequential
collection of keys for indexed access into the component's local state."
([component]
(get-state component []))
([component k-or-ks]
{:pre [(component? component)]}
(let [cst (if #?(:clj (satisfies? ILocalState component)
:cljs (implements? ILocalState component))
(-get-state component)
#?(:clj @(:state component)
:cljs (when-let [state (. component -state)]
(or (gobj/get state "omcljs$pendingState")
(gobj/get state "omcljs$state")))))]
(get-in cst (if (sequential? k-or-ks) k-or-ks [k-or-ks])))))
(defn update-state!
"Update a component's local state. Similar to Clojure(Script)'s swap!"
([component f]
(set-state! component (f (get-state component))))
([component f arg0]
(set-state! component (f (get-state component) arg0)))
([component f arg0 arg1]
(set-state! component (f (get-state component) arg0 arg1)))
([component f arg0 arg1 arg2]
(set-state! component (f (get-state component) arg0 arg1 arg2)))
([component f arg0 arg1 arg2 arg3]
(set-state! component (f (get-state component) arg0 arg1 arg2 arg3)))
([component f arg0 arg1 arg2 arg3 & arg-rest]
(set-state! component
(apply f (get-state component) arg0 arg1 arg2 arg3 arg-rest))))
(defn get-rendered-state
"Get the rendered state of component. om.next/get-state always returns the
up-to-date state."
([component]
(get-rendered-state component []))
([component k-or-ks]
{:pre [(component? component)]}
(let [cst (if #?(:clj (satisfies? ILocalState component)
:cljs (implements? ILocalState component))
(-get-rendered-state component)
#?(:clj (get-state component)
:cljs (some-> component .-state (gobj/get "omcljs$state"))))]
(get-in cst (if (sequential? k-or-ks) k-or-ks [k-or-ks])))))
#?(:cljs
(defn- merge-pending-state! [c]
(if (implements? ILocalState c)
(-merge-pending-state! c)
(when-let [pending (some-> c .-state (gobj/get "omcljs$pendingState"))]
(let [state (.-state c)
previous (gobj/get state "omcljs$state")]
(gobj/remove state "omcljs$pendingState")
(gobj/set state "omcljs$previousState" previous)
(gobj/set state "omcljs$state" pending))))))
(defn react-set-state!
([component new-state]
(react-set-state! component new-state nil))
([component new-state cb]
{:pre [(component? component)]}
#?(:clj (do
(set-state! component new-state)
(cb))
:cljs (.setState component #js {:omcljs$state new-state} cb))))
(declare full-query to-env schedule-sends! reconciler? ref->components force)
(defn gather-sends
"Given an environment, a query and a set of remotes return a hash map of remotes
mapped to the query specific to that remote."
[{:keys [parser] :as env} q remotes]
(into {}
(comp
(map #(vector % (parser env q %)))
(filter (fn [[_ v]] (pos? (count v)))))
remotes))
(defn transform-reads
"Given r (a reconciler) and a query expression including a mutation and
any simple reads, return the equivalent query expression where the simple
reads have been replaced by the full query for each component that cares about
the specified read."
[r tx]
(if (-> r :config :easy-reads)
(letfn [(with-target [target q]
(if-not (nil? target)
[(force (first q) target)]
q))
(add-focused-query [k target tx c]
(let [transformed (->> (focus-query (get-query c) [k])
(with-target target)
(full-query c))]
(into tx (remove (set tx)) transformed)))]
(loop [exprs (seq tx) tx' []]
(if-not (nil? exprs)
(let [expr (first exprs)
ast (parser/expr->ast expr)
key (:key ast)
tgt (:target ast)]
(if (keyword? key)
(let [cs (ref->components r key)]
(recur (next exprs)
(reduce #(add-focused-query key tgt %1 %2)
(cond-> tx'
(empty? cs) (conj expr)) cs)))
(recur (next exprs) (conj tx' expr))))
tx')))
tx))
(defn set-query!
"Change the query of a component. Takes a map containing :params and/or
:query. :params should be a map of new bindings and :query should be a query
expression. Will schedule a re-render as well as remote re-sends if
necessary."
([x params&query]
(set-query! x params&query nil))
([x {:keys [params query]} reads]
{:pre [(or (reconciler? x)
(component? x))
(or (not (nil? params))
(not (nil? query)))
(or (nil? reads)
(vector? reads))]}
(let [r (if (component? x)
(get-reconciler x)
x)
c (when (component? x) x)
xs (if-not (nil? c) [c] [])
root (:root @(:state r))
cfg (:config r)
st (:state cfg)
id #?(:clj (java.util.UUID/randomUUID)
:cljs (random-uuid))]
#?(:cljs (.add (:history cfg) id @st))
#?(:cljs
(when-let [l (:logger cfg)]
(glog/info l
(cond-> (str (when-let [ident (when (implements? Ident c)
(ident c (props c)))]
(str (pr-str ident) " ")))
(reconciler? x) (str "reconciler ")
query (str "changed query '" query ", ")
params (str "changed params " params " ")
true (str (pr-str id))))))
(swap! st update-in [:om.next/queries (or c root)] merge
(merge (when query {:query query}) (when params {:params params})))
(when (and (not (nil? c)) (nil? reads))
(p/queue! r [c]))
(when-not (nil? reads)
(p/queue! r reads))
(p/reindex! r)
(let [rootq (if (not (nil? c))
(full-query c)
(when (nil? reads)
(get-query root)))
sends (gather-sends (to-env cfg)
(into (or rootq []) (transform-reads r reads)) (:remotes cfg))]
(when-not (empty? sends)
(doseq [[remote _] sends]
(p/queue! r xs remote))
(p/queue-sends! r sends)
(schedule-sends! r)))
nil)))
(defn update-query!
"Update a component's query and query parameters with a function."
([component f]
(set-query! component
(f {:query (get-unbound-query component)
:params (get-params component)})))
([component f arg0]
(set-query! component
(f {:query (get-unbound-query component)
:params (get-params component)}
arg0)))
([component f arg0 arg1]
(set-query! component
(f {:query (get-unbound-query component)
:params (get-params component)}
arg0 arg1)))
([component f arg0 arg1 arg2]
(set-query! component
(f {:query (get-unbound-query component)
:params (get-params component)}
arg0 arg1 arg2)))
([component f arg0 arg1 arg2 arg3 & arg-rest]
(set-query! component
(apply f {:query (get-unbound-query component)
:params (get-params component)}
arg0 arg1 arg2 arg3 arg-rest))))
(defn mounted?
"Returns true if the component is mounted."
#?(:cljs {:tag boolean})
[x]
#?(:clj (and (component? x) @(get-prop x :omcljs$mounted?))
:cljs (and (component? x) ^boolean (.isMounted x))))
(defn react-ref
"Returns the component associated with a component's React ref."
[component name]
#?(:clj (some-> @(:refs component) (get name))
:cljs (some-> (.-refs component) (gobj/get name))))
(defn children
"Returns the component's children."
[component]
#?(:clj (:children component)
:cljs (.. component -props -children)))
#?(:cljs
(defn- update-component! [c next-props]
{:pre [(component? c)]}
(update-props! c next-props)
(.forceUpdate c)))
#?(:cljs
(defn should-update?
([c next-props]
(should-update? c next-props nil))
([c next-props next-state]
{:pre [(component? c)]}
(.shouldComponentUpdate c
#js {:omcljs$value next-props}
#js {:omcljs$state next-state}))))
(defn- raw-class-path
"Return the raw component class path associated with a component. Contains
duplicates for recursive component trees."
[c]
(loop [c c ret (list (react-type c))]
(if-let [p (parent c)]
(if (iquery? p)
(recur p (cons (react-type p) ret))
(recur p ret))
ret)))
(defn class-path
"Return the component class path associated with a component."
[c]
{:pre [(component? c)]}
(let [raw-cp (raw-class-path c)]
(loop [cp (seq raw-cp) ret [] seen #{}]
(if cp
(let [c (first cp)]
(if (contains? seen c)
(recur (next cp) ret seen)
(recur (next cp) (conj ret c) (conj seen c))))
(seq ret)))))
(defn- recursive-class-path?
"Returns true if a component's classpath is recursive"
#?(:cljs {:tag boolean})
[c]
{:pre [(component? c)]}
(not (apply distinct? (raw-class-path c))))
(defn subquery
"Given a class or mounted component x and a ref to an instantiated component
or class that defines a subquery, pick the most specific subquery. If the
component is mounted subquery-ref will be used, subquery-class otherwise."
[x subquery-ref subquery-class]
{:pre [(or (keyword? subquery-ref) (string? subquery-ref))
(fn? subquery-class)]}
(let [ref (cond-> subquery-ref (keyword? subquery-ref) str)]
(if (and (component? x) (mounted? x))
(get-query (react-ref x ref))
(get-query subquery-class))))
(defn get-ident
"Given a mounted component with assigned props, return the ident for the
component."
[x]
{:pre [(component? x)]}
(let [m (props x)]
(assert (not (nil? m)) "get-ident invoked on component with nil props")
(ident x m)))
(declare reconciler?)
(defn- basis-t [reconciler]
(p/basis-t reconciler))
#?(:cljs
(defn- queue-render! [f]
(cond
(fn? *raf*) (*raf* f)
(not (exists? js/requestAnimationFrame))
(js/setTimeout f 16)
:else
(js/requestAnimationFrame f))))
#?(:cljs
(defn schedule-render! [reconciler]
(when (p/schedule-render! reconciler)
(queue-render! #(p/reconcile! reconciler)))))
(defn schedule-sends! [reconciler]
(when (p/schedule-sends! reconciler)
#?(:clj (p/send! reconciler)
:cljs (js/setTimeout #(p/send! reconciler) 0))))
(declare remove-root!)
(defn add-root!
"Given a root component class and a target root DOM node, instantiate and
render the root class using the reconciler's :state property. The reconciler
will continue to observe changes to :state and keep the target node in sync.
Note a reconciler may have only one root. If invoked on a reconciler with an
existing root, the new root will replace the old one."
([reconciler root-class target]
(add-root! reconciler root-class target nil))
([reconciler root-class target options]
{:pre [(reconciler? reconciler) (fn? root-class)]}
(when-let [old-reconciler (get @roots target)]
(remove-root! old-reconciler target))
(swap! roots assoc target reconciler)
(p/add-root! reconciler root-class target options)))
(defn remove-root!
"Remove a root target (a DOM element) from a reconciler. The reconciler will
no longer attempt to reconcile application state with the specified root."
[reconciler target]
(p/remove-root! reconciler target))
(defprotocol ITxIntercept
(tx-intercept [c tx]
"An optional protocol that component may implement to intercept child
transactions."))
(defn- to-env [x]
(let [config (if (reconciler? x) (:config x) x)]
(select-keys config [:state :shared :parser :logger :pathopt])))
(defn transact* [r c ref tx]
(let [cfg (:config r)
ref (if (and c #?(:clj (satisfies? Ident c)
:cljs (implements? Ident c)) (not ref))
(ident c (props c))
ref)
env (merge
(to-env cfg)
{:reconciler r :component c}
(when ref
{:ref ref}))
id #?(:clj (java.util.UUID/randomUUID)
:cljs (random-uuid))
#?@(:cljs
[_ (.add (:history cfg) id @(:state cfg))
_ (when-let [l (:logger cfg)]
(glog/info l
(str (when ref (str (pr-str ref) " "))
"transacted '" tx ", " (pr-str id))))])
old-state @(:state cfg)
v ((:parser cfg) env tx)
snds (gather-sends env tx (:remotes cfg))
xs (cond-> []
(not (nil? c)) (conj c)
(not (nil? ref)) (conj ref))]
(p/queue! r (into xs (remove symbol?) (keys v)))
(when-not (empty? snds)
(doseq [[remote _] snds]
(p/queue! r xs remote))
(p/queue-sends! r snds)
(schedule-sends! r))
(when-let [f (:tx-listen cfg)]
(let [tx-data (merge env
{:old-state old-state
:new-state @(:state cfg)})]
(f tx-data {:tx tx
:ret v
:sends snds})))
v))
(defn annotate-mutations
"Given a query expression annotate all mutations by adding a :mutator -> ident
entry to the metadata of each mutation expression in the query."
[tx ident]
(letfn [(annotate [expr ident]
(cond-> expr
(util/mutation? expr) (vary-meta assoc :mutator ident)))]
(into [] (map #(annotate % ident)) tx)))
(defn some-iquery? [c]
(loop [c c]
(cond
(nil? c) false
(iquery? c) true
:else (recur (parent c)))))
(defn transact!
"Given a reconciler or component run a transaction. tx is a parse expression
that should include mutations followed by any necessary read. The reads will
be used to trigger component re-rendering.
Example:
(om/transact! widget
'[(do/this!) (do/that!)
:read/this :read/that])"
([x tx]
{:pre [(or (component? x)
(reconciler? x))
(vector? tx)]}
(let [tx (cond-> tx
(and (component? x) (satisfies? Ident x))
(annotate-mutations (get-ident x)))]
(cond
(reconciler? x) (transact* x nil nil tx)
(not (iquery? x)) (do
(invariant (some-iquery? x)
(str "transact! should be called on a component"
"that implements IQuery or has a parent that"
"implements IQuery"))
(transact* (get-reconciler x) nil nil tx))
:else (do
(loop [p (parent x) x x tx tx]
(if (nil? p)
(let [r (get-reconciler x)]
(transact* r x nil (transform-reads r tx)))
(let [[x' tx] (if #?(:clj (satisfies? ITxIntercept p)
:cljs (implements? ITxIntercept p))
[p (tx-intercept p tx)]
[x tx])]
(recur (parent p) x' tx))))))))
([r ref tx]
(transact* r nil ref tx)))
Parser
(defn parser
"Create a parser. The argument is a map of two keys, :read and :mutate. Both
functions should have the signature (Env -> Key -> Params -> ParseResult)."
[{:keys [read mutate] :as opts}]
{:pre [(map? opts)]}
(parser/parser opts))
(defn dispatch
"Helper function for implementing :read and :mutate as multimethods. Use this
as the dispatch-fn."
[_ key _] key)
(defn query->ast
"Given a query expression convert it into an AST."
[query-expr]
(parser/query->ast query-expr))
(defn ast->query [query-ast]
"Given an AST convert it back into a query expression."
(parser/ast->expr query-ast true))
(defn- get-dispatch-key [prop]
(cond-> prop
(or (not (util/ident? prop))
(= (second prop) '_))
((comp :dispatch-key parser/expr->ast))))
(defn- cascade-query
"Cascades a query up the classpath. class-path->query is a map of classpaths
to their queries. classpath is the classpath where we start cascading (typically
the direct parent's classpath of the component changing query). data-path is
the data path in the classpath's query to the new query. new-query is the
query to be applied to the classpaths. union-keys are any keys into union
when cascading the classpath, and to generate the classpaths' rendered-paths,
which skip these keys."
[class-path->query classpath data-path new-query union-keys]
(loop [cp classpath
data-path data-path
new-query new-query
ret {}]
(if-not (empty? cp)
(let [rendered-data-path (into [] (remove (set union-keys)) data-path)
filter-data-path (cond-> rendered-data-path
(not (empty? rendered-data-path)) pop)
qs (filter #(= filter-data-path
(-> % zip/root (focus->path filter-data-path)))
(get class-path->query cp))
qs' (into #{}
(map (fn [q]
(let [new-query (if (or (map? (zip/node q))
(some #{(peek data-path)} union-keys))
(let [union-key (peek data-path)]
(-> (query-template (zip/root q)
rendered-data-path)
zip/node
(assoc union-key new-query)))
new-query)]
(-> (zip/root q)
(query-template rendered-data-path)
(replace new-query)
(focus-query filter-data-path)
(query-template filter-data-path)))))
qs)]
(recur (pop cp) (pop data-path)
(-> qs' first zip/node) (assoc ret cp qs')))
ret)))
(defrecord Indexer [indexes extfs]
#?(:clj clojure.lang.IDeref
:cljs IDeref)
#?(:clj (deref [_] @indexes)
:cljs (-deref [_] @indexes))
p/IIndexer
(index-root [_ x]
(let [prop->classes (atom {})
class-path->query (atom {})
rootq (get-query x)
root-class (cond-> x (component? x) react-type)]
(letfn [(build-index* [class query path classpath union-expr union-keys]
(invariant (or (not (iquery? class))
(and (iquery? class)
(not (empty? query))))
(str "`IQuery` implementation must return a non-empty query."
" Check the `IQuery` implementation of component `"
(if (component? class)
(.. class -constructor -displayName)
(.. class -prototype -constructor -displayName)) "`."))
(let [recursive? (some #{class} classpath)
classpath (cond-> classpath
(and (not (nil? class))
(not recursive?))
(conj class))
dp->cs (get-in @indexes [:data-path->components])]
(when class
rootq on the first call ( when there 's no class - path->query
(let [root-query (if (empty? path)
rootq
(-> @class-path->query
(get [root-class]) first zip/root))]
(swap! class-path->query update-in [classpath] (fnil conj #{})
(query-template (focus-query root-query path) path))))
(let [recursive-join? (and recursive?
(some (fn [e]
(and (util/join? e)
(not (util/recursion?
(util/join-value e)))))
query)
(= (distinct path) path))
recursive-union? (and recursive?
union-expr
(= (distinct path) path))]
(when (or (not recursive?)
recursive-join?
recursive-union?)
(cond
(vector? query)
(let [{props false joins true} (group-by util/join? query)]
(swap! prop->classes
#(merge-with into %
(zipmap
(map get-dispatch-key props)
(repeat #{class}))))
(doseq [join joins]
(let [[prop query'] (util/join-entry join)
prop-dispatch-key (get-dispatch-key prop)
recursion? (util/recursion? query')
union-recursion? (and recursion? union-expr)
query' (if recursion?
(if-not (nil? union-expr)
union-expr
query)
query')
path' (conj path prop)
rendered-path' (into []
(remove
(set union-keys)
(conj path
prop-dispatch-key)))
cs (get dp->cs rendered-path')
cascade-query? (and (= (count cs) 1)
(= (-> query' meta :component)
(react-type (first cs)))
(not (map? query')))
query'' (if cascade-query?
(get-query (first cs))
query')]
(swap! prop->classes
#(merge-with into % {prop-dispatch-key #{class}}))
(when (and cascade-query? (not= query' query''))
(let [cp->q' (cascade-query @class-path->query classpath
path' query'' union-keys)]
(swap! class-path->query merge cp->q')))
(let [class' (-> query'' meta :component)]
(when-not (and recursion? (nil? class'))
(build-index* class' query''
path' classpath (if recursion? union-expr nil) union-keys))))))
(map? query)
(doseq [[prop query'] query]
(let [path' (conj path prop)
class' (-> query' meta :component)
cs (filter #(= class' (react-type %))
(get dp->cs path))
cascade-query? (and class' (= (count cs) 1))
query'' (if cascade-query?
(get-query (first cs))
query')]
(when (and cascade-query? (not= query' query''))
(let [qs (get @class-path->query classpath)
q (first qs)
qnode (zip/node
(cond-> q
(nil? class) (query-template path)))
new-query (assoc qnode
prop query'')
q' (cond-> (zip/replace
(query-template (zip/root q) path)
new-query)
(nil? class)
(-> zip/root
(focus-query (pop path))
(query-template (pop path))))
qs' (into #{q'} (remove #{q}) qs)
cp->q' (merge {classpath qs'}
(cascade-query @class-path->query
(pop classpath) path
(zip/node q') union-keys))]
(swap! class-path->query merge cp->q')))
(build-index* class' query'' path' classpath query (conj union-keys prop)))))))))]
(build-index* root-class rootq [] [] nil [])
(swap! indexes merge
{:prop->classes @prop->classes
:class-path->query @class-path->query}))))
(index-component! [_ c]
(swap! indexes
(fn [indexes]
(let [indexes (update-in ((:index-component extfs) indexes c)
[:class->components (react-type c)]
(fnil conj #{}) c)
data-path (into [] (remove number?) (path c))
indexes (update-in ((:index-component extfs) indexes c)
[:data-path->components data-path]
(fnil conj #{}) c)
ident (when #?(:clj (satisfies? Ident c)
:cljs (implements? Ident c))
(let [ident (ident c (props c))]
(invariant (util/ident? ident)
(str "malformed Ident. An ident must be a vector of "
"two elements (a keyword and an EDN value). Check "
"the Ident implementation of component `"
(.. c -constructor -displayName) "`."))
(invariant (some? (second ident))
(str "component " (.. c -constructor -displayName)
"'s ident (" ident ") has a `nil` second element."
" This warning can be safely ignored if that is intended."))
ident))]
(if-not (nil? ident)
(cond-> indexes
ident (update-in [:ref->components ident] (fnil conj #{}) c))
indexes)))))
(drop-component! [_ c]
(swap! indexes
(fn [indexes]
(let [indexes (update-in ((:drop-component extfs) indexes c)
[:class->components (react-type c)]
disj c)
data-path (into [] (remove number?) (path c))
indexes (update-in ((:drop-component extfs) indexes c)
[:data-path->components data-path]
disj c)
ident (when #?(:clj (satisfies? Ident c)
:cljs (implements? Ident c))
(ident c (props c)))]
(if-not (nil? ident)
(cond-> indexes
ident (update-in [:ref->components ident] disj c))
indexes)))))
(key->components [_ k]
(let [indexes @indexes]
(if (component? k)
#{k}
(if-let [cs ((:ref->components extfs) indexes k)]
cs
(transduce (map #(get-in indexes [:class->components %]))
(completing into)
(get-in indexes [:ref->components k] #{})
(get-in indexes [:prop->classes k])))))))
(defn indexer
"Given a function (Component -> Ref), return an indexer."
([]
(indexer
{:index-component (fn [indexes component] indexes)
:drop-component (fn [indexes component] indexes)
:ref->components (fn [indexes ref] nil)}))
([extfs]
(Indexer.
(atom
{:class->components {}
:data-path->components {}
:ref->components {}})
extfs)))
(defn get-indexer
"PRIVATE: Get the indexer associated with the reconciler."
[reconciler]
{:pre [(reconciler? reconciler)]}
(-> reconciler :config :indexer))
(defn ref->components
"Return all components for a given ref."
[x ref]
(when-not (nil? ref)
(let [indexer (if (reconciler? x) (get-indexer x) x)]
(p/key->components indexer ref))))
(defn ref->any
"Get any component from the indexer that matches the ref."
[x ref]
(let [indexer (if (reconciler? x) (get-indexer x) x)]
(first (p/key->components indexer ref))))
(defn class->any
"Get any component from the indexer that matches the component class."
[x class]
(let [indexer (if (reconciler? x) (get-indexer x) x)]
(first (get-in @indexer [:class->components class]))))
(defn class-path->queries
"Given x (a reconciler or indexer) and y (a component or component class
path), return the queries for that path."
[x y]
(let [indexer (if (reconciler? x) (get-indexer x) x)
cp (if (component? y) (class-path y) y)]
(into #{} (map zip/root)
(get-in @indexer [:class-path->query cp]))))
(defn full-query
"Returns the absolute query for a given component, not relative like
om.next/get-query."
([component]
(when (iquery? component)
(if (nil? (path component))
(replace
(first
(get-in @(-> component get-reconciler get-indexer)
[:class-path->query (class-path component)]))
(get-query component))
(full-query component (get-query component)))))
([component query]
(when (iquery? component)
(let [xf (cond->> (remove number?)
(recursive-class-path? component) (comp (distinct)))
path' (into [] xf (path component))
cp (class-path component)
qs (get-in @(-> component get-reconciler get-indexer)
[:class-path->query cp])]
(if-not (empty? qs)
(let [q (->> qs
(filter #(= path'
(mapv get-dispatch-key
(-> % zip/root (focus->path path')))))
first)]
(if-not (nil? q)
(replace q query)
(throw
(ex-info (str "No queries exist at the intersection of component path " cp " and data path " path')
{:type :om.next/no-queries}))))
(throw
(ex-info (str "No queries exist for component path " cp)
{:type :om.next/no-queries})))))))
(defn- normalize* [query data refs union-seen]
(cond
(= '[*] query) data
(map? query)
(let [class (-> query meta :component)
ident #?(:clj (when-let [ident (-> class meta :ident)]
(ident class data))
:cljs (when (implements? Ident class)
(ident class data)))]
(if-not (nil? ident)
(vary-meta (normalize* (get query (first ident)) data refs union-seen)
assoc :om/tag (first ident))
(throw #?(:clj (IllegalArgumentException. "Union components must implement Ident")
:cljs (js/Error. "Union components must implement Ident")))))
:else
(loop [q (seq query) ret data]
(if-not (nil? q)
(let [expr (first q)]
(if (util/join? expr)
(let [[k sel] (util/join-entry expr)
recursive? (util/recursion? sel)
union-entry (if (util/union? expr) sel union-seen)
sel (if recursive?
(if-not (nil? union-seen)
union-seen
query)
sel)
class (-> sel meta :component)
v (get data k)]
(cond
graph loop : db->tree leaves ident in place
(and recursive? (util/ident? v)) (recur (next q) ret)
normalize one
(map? v)
(let [x (normalize* sel v refs union-entry)]
(if-not (or (nil? class) (not #?(:clj (-> class meta :ident)
:cljs (implements? Ident class))))
(let [i #?(:clj ((-> class meta :ident) class v)
:cljs (ident class v))]
(swap! refs update-in [(first i) (second i)] merge x)
(recur (next q) (assoc ret k i)))
(recur (next q) (assoc ret k x))))
(vector? v)
(let [xs (into [] (map #(normalize* sel % refs union-entry)) v)]
(if-not (or (nil? class) (not #?(:clj (-> class meta :ident)
:cljs (implements? Ident class))))
(let [is (into [] (map #?(:clj #((-> class meta :ident) class %)
:cljs #(ident class %))) xs)]
(if (vector? sel)
(when-not (empty? is)
(swap! refs
(fn [refs]
(reduce (fn [m [i x]]
(update-in m i merge x))
refs (zipmap is xs)))))
(swap! refs
(fn [refs']
(reduce
(fn [ret [i x]]
(update-in ret i merge x))
refs' (map vector is xs)))))
(recur (next q) (assoc ret k is)))
(recur (next q) (assoc ret k xs))))
(nil? v)
(recur (next q) ret)
:else (recur (next q) (assoc ret k v))))
(let [k (if (seq? expr) (first expr) expr)
v (get data k)]
(if (nil? v)
(recur (next q) ret)
(recur (next q) (assoc ret k v))))))
ret))))
(defn tree->db
"Given a Om component class or instance and a tree of data, use the component's
query to transform the tree into the default database format. All nodes that
can be mapped via Ident implementations wil be replaced with ident links. The
original node data will be moved into tables indexed by ident. If merge-idents
option is true, will return these tables in the result instead of as metadata."
([x data]
(tree->db x data false))
([x data #?(:clj merge-idents :cljs ^boolean merge-idents) ]
(let [refs (atom {})
x (if (vector? x) x (get-query x))
ret (normalize* x data refs nil)]
(if merge-idents
(let [refs' @refs]
(assoc (merge ret refs')
::tables (into #{} (keys refs'))))
(with-meta ret @refs)))))
(defn- sift-idents [res]
(let [{idents true rest false} (group-by #(vector? (first %)) res)]
[(into {} idents) (into {} rest)]))
(defn reduce-query-depth
"Changes a join on key k with depth limit from [:a {:k n}] to [:a {:k (dec n)}]"
[q k]
(if-not (empty? (focus-query q [k]))
(let [pos (query-template q [k])
node (zip/node pos)
node' (cond-> node (number? node) dec)]
(replace pos node'))
q))
(defn- reduce-union-recursion-depth
"Given a union expression decrement each of the query roots by one if it
is recursive."
[union-expr recursion-key]
(->> union-expr
(map (fn [[k q]] [k (reduce-query-depth q recursion-key)]))
(into {})))
(defn- mappable-ident? [refs ident]
(and (util/ident? ident)
(contains? refs (first ident))))
(defn- denormalize*
"Denormalize a data based on query. refs is a data structure which maps idents
to their values. map-ident is a function taking a ident to another ident,
used during tempid transition. idents-seen is the set of idents encountered,
used to limit recursion. union-expr is the current union expression being
evaluated. recurse-key is key representing the current recursive query being
evaluted."
[query data refs map-ident idents-seen union-expr recurse-key]
(let [union-recur? (and union-expr recurse-key)
recur-ident (when union-recur?
data)
data (loop [data data]
(if (mappable-ident? refs data)
(recur (get-in refs (map-ident data)))
data))]
(cond
(vector? data)
(let [step (fn [ident]
(if-not (mappable-ident? refs ident)
(if (= query '[*])
ident
(let [{props false joins true} (group-by util/join? query)
props (mapv #(cond-> % (seq? %) first) props)]
(loop [joins (seq joins) ret {}]
(if-not (nil? joins)
(let [join (first joins)
[key sel] (util/join-entry join)
v (get ident key)]
(recur (next joins)
(assoc ret
key (denormalize* sel v refs map-ident
idents-seen union-expr recurse-key))))
(merge (select-keys ident props) ret)))))
(let [ident' (get-in refs (map-ident ident))
query (cond-> query
union-recur? (reduce-union-recursion-depth recurse-key))
union-seen' (cond-> union-expr
union-recur? (reduce-union-recursion-depth recurse-key))
query' (cond-> query
(denormalize* query' ident' refs map-ident idents-seen union-seen' nil))))]
(into [] (map step) data))
(and (map? query) union-recur?)
(denormalize* (get query (first recur-ident)) data refs map-ident
idents-seen union-expr recurse-key)
:else
(if (= '[*] query)
data
(let [{props false joins true} (group-by #(or (util/join? %)
(util/ident? %)
(and (seq? %)
(util/ident? (first %))))
query)
props (mapv #(cond-> % (seq? %) first) props)]
(loop [joins (seq joins) ret {}]
(if-not (nil? joins)
(let [join (first joins)
join (cond-> join
(seq? join) first)
join (cond-> join
(util/ident? join) (hash-map '[*]))
[key sel] (util/join-entry join)
recurse? (util/recursion? sel)
recurse-key (when recurse? key)
v (if (util/ident? key)
(if (= '_ (second key))
(get refs (first key))
(get-in refs (map-ident key)))
(get data key))
key (cond-> key (util/unique-ident? key) first)
v (if (mappable-ident? refs v)
(loop [v v]
(let [next (get-in refs (map-ident v))]
(if (mappable-ident? refs next)
(recur next)
(map-ident v))))
v)
limit (if (number? sel) sel :none)
union-entry (if (util/union? join)
sel
(when recurse?
union-expr))
sel (cond
recurse?
(if-not (nil? union-expr)
union-entry
(reduce-query-depth query key))
(and (mappable-ident? refs v)
(util/union? join))
(get sel (first v))
(and (util/ident? key)
(util/union? join))
(get sel (first key))
:else sel)
graph-loop? (and recurse?
(contains? (set (get idents-seen key)) v)
(= :none limit))
idents-seen (if (and (mappable-ident? refs v) recurse?)
(-> idents-seen
(update-in [key] (fnil conj #{}) v)
(assoc-in [:last-ident key] v)) idents-seen)]
(cond
(= 0 limit) (recur (next joins) ret)
graph-loop? (recur (next joins) ret)
(nil? v) (recur (next joins) ret)
:else (recur (next joins)
(assoc ret
key (denormalize* sel v refs map-ident
idents-seen union-entry recurse-key)))))
(if-let [looped-key (some
(fn [[k identset]]
(if (contains? identset (get data k))
(get-in idents-seen [:last-ident k])
nil))
(dissoc idents-seen :last-ident))]
looped-key
(merge (select-keys data props) ret)))))))))
(defn db->tree
"Given a query, some data in the default database format, and the entire
application state in the default database format, return the tree where all
ident links have been replaced with their original node values."
([query data refs]
{:pre [(map? refs)]}
(denormalize* query data refs identity {} nil nil))
([query data refs map-ident]
{:pre [(map? refs)]}
(denormalize* query data refs map-ident {} nil nil)))
(defn rewrite [rewrite-map result]
(letfn [(step [res [k orig-paths]]
(let [to-move (get result k)
res' (reduce #(assoc-in %1 (conj %2 k) to-move)
res orig-paths)]
(dissoc res' k)))]
(reduce step result rewrite-map)))
(defn- move-roots
"When given a join `{:join selector-vector}`, roots found so far, and a `path` prefix:
returns a (possibly empty) sequence of [re-rooted-join prefix] results.
Does NOT support sub-roots. Each re-rooted join will share only
one common parent (their common branching point).
"
[join result-roots path]
(letfn [(query-root? [join] (true? (-> join meta :query-root)))]
(if (util/join? join)
(if (query-root? join)
(conj result-roots [join path])
(let [joinvalue (util/join-value join)]
(if (vector? joinvalue)
(mapcat
#(move-roots % result-roots
(conj path (util/join-key join)))
joinvalue)
result-roots)))
result-roots)))
(defn- merge-joins
"Searches a query for duplicate joins and deep-merges them into a new query."
[query]
(letfn [(step [res expr]
(if (contains? (:elements-seen res) expr)
(update-in
(if (and (util/join? expr)
(not (util/union? expr))
(not (list? expr)))
(let [jk (util/join-key expr)
jv (util/join-value expr)
q (or (-> res :query-by-join (get jk)) [])
nq (cond
(util/recursion? q) q
(util/recursion? jv) jv
:else (merge-joins (into [] (concat q jv))))]
(update-in res [:query-by-join] assoc jk nq))
(update-in res [:not-mergeable] conj expr))
[:elements-seen] conj expr)))]
(let [init {:query-by-join {}
:elements-seen #{}
:not-mergeable []}
res (reduce step init query)]
(->> (:query-by-join res)
(mapv (fn [[jkey jsel]] {jkey jsel}))
(concat (:not-mergeable res))
(into [])))))
(defn process-roots [query]
"A send helper for rewriting the query to remove client local keys that
don't need server side processing. Give a query this function will
return a map with two keys, :query and :rewrite. :query is the
actual query you should send. Upon receiving the response you should invoke
:rewrite on the response before invoking the send callback."
(reroot [expr]
(let [roots (move-roots expr [] [])]
(if (empty? roots)
(retain expr)
roots)))
(rewrite-map-step [rewrites [expr path]]
(if (empty? path)
rewrites
(update-in rewrites [(util/join-key expr)] conj path)))]
(let [reroots (mapcat reroot query)
query (merge-joins (mapv first reroots))
rewrite-map (reduce rewrite-map-step {} reroots)]
{:query query
:rewrite (partial rewrite rewrite-map)})))
(defn- merge-idents [tree config refs query]
(let [{:keys [merge-ident indexer]} config
ident-joins (into {} (comp
(map #(cond-> % (seq? %) first))
(filter #(and (util/join? %)
(util/ident? (util/join-key %)))))
query)]
(letfn [ (step [tree' [ident props]]
(if (:normalize config)
(let [c-or-q (or (get ident-joins ident) (ref->any indexer ident))
props' (tree->db c-or-q props)
refs (meta props')]
((:merge-tree config)
(merge-ident config tree' ident props') refs))
(merge-ident config tree' ident props)))]
(reduce step tree refs))))
(defn- merge-novelty!
[reconciler state res query]
(let [config (:config reconciler)
[idts res'] (sift-idents res)
res' (if (:normalize config)
(tree->db
(or query (:root @(:state reconciler)))
res' true)
res')]
(-> state
(merge-idents config idts query)
((:merge-tree config) res'))))
(defn default-merge [reconciler state res query]
{:keys (into [] (remove symbol?) (keys res))
:next (merge-novelty! reconciler state res query)
:tempids (->> (filter (comp symbol? first) res)
(map (comp :tempids second))
(reduce merge {}))})
(defn merge!
"Merge a state delta into the application state. Affected components managed
by the reconciler will re-render."
([reconciler delta]
(merge! reconciler delta nil))
([reconciler delta query]
(merge! reconciler delta query nil))
([reconciler delta query remote]
(let [config (:config reconciler)
state (:state config)
merge* (:merge config)
{:keys [keys next tempids]} (merge* reconciler @state delta query)]
(when (nil? remote)
(p/queue! reconciler keys))
(reset! state
(if-let [migrate (:migrate config)]
(merge (select-keys next [:om.next/queries])
(migrate next
(or query (get-query (:root @(:state reconciler))))
tempids (:id-key config)))
next)))))
(defrecord Reconciler [config state]
#?(:clj clojure.lang.IDeref
:cljs IDeref)
#?(:clj (deref [this] @(:state config))
:cljs (-deref [_] @(:state config)))
p/IReconciler
(basis-t [_] (:t @state))
(add-root! [this root-class target options]
(let [ret (atom nil)
rctor (factory root-class)
guid #?(:clj (java.util.UUID/randomUUID)
:cljs (random-uuid))]
(when (iquery? root-class)
(p/index-root (:indexer config) root-class))
(when (and (:normalize config)
(not (:normalized @state)))
(let [new-state (tree->db root-class @(:state config))
refs (meta new-state)]
(reset! (:state config) (merge new-state refs))
(swap! state assoc :normalized true)))
(let [renderf (fn [data]
(binding [*reconciler* this
*shared* (merge
(:shared config)
(when (:shared-fn config)
((:shared-fn config) data)))
*instrument* (:instrument config)]
(let [c (cond
#?@(:cljs [(not (nil? target)) ((:root-render config) (rctor data) target)])
(nil? @ret) (rctor data)
:else (when-let [c' @ret]
#?(:clj (do
(reset! ret nil)
(rctor data))
:cljs (when (mounted? c')
(.forceUpdate c' data)))))]
(when (and (nil? @ret) (not (nil? c)))
(swap! state assoc :root c)
(reset! ret c)))))
parsef (fn []
(let [sel (get-query (or @ret root-class))]
(assert (or (nil? sel) (vector? sel))
"Application root query must be a vector")
(if-not (nil? sel)
(let [env (to-env config)
v ((:parser config) env sel)]
(when-not (empty? v)
(renderf v)))
(renderf @(:state config)))))]
(swap! state merge
{:target target :render parsef :root root-class
:remove (fn []
(remove-watch (:state config) (or target guid))
(swap! state
#(-> %
(dissoc :target) (dissoc :render) (dissoc :root)
(dissoc :remove)))
(when-not (nil? target)
((:root-unmount config) target)))})
(add-watch (:state config) (or target guid)
(fn [_ _ _ _]
(swap! state update-in [:t] inc)
#?(:cljs
(if-not (iquery? root-class)
(queue-render! parsef)
(schedule-render! this)))))
(parsef)
(when-let [sel (get-query (or (and target @ret) root-class))]
(let [env (to-env config)
snds (gather-sends env sel (:remotes config))]
(when-not (empty? snds)
(when-let [send (:send config)]
(send snds
(fn send-cb
([resp]
(merge! this resp nil)
(renderf ((:parser config) env sel)))
([resp query]
(merge! this resp query)
(renderf ((:parser config) env sel)))
([resp query remote]
(when-not (nil? remote)
(p/queue! this (keys resp) remote))
(merge! this resp query remote)
(p/reconcile! this remote))))))))
@ret)))
(remove-root! [_ target]
(when-let [remove (:remove @state)]
(remove)))
(reindex! [this]
(let [root (get @state :root)]
(when (iquery? root)
(let [indexer (:indexer config)
c (first (get-in @indexer [:class->components root]))]
(p/index-root indexer (or c root))))))
(queue! [this ks]
(p/queue! this ks nil))
(queue! [_ ks remote]
(if-not (nil? remote)
(swap! state update-in [:remote-queue remote] into ks)
(swap! state update-in [:queue] into ks)))
(queue-sends! [_ sends]
(swap! state update-in [:queued-sends]
(:merge-sends config) sends))
(schedule-render! [_]
(if-not (:queued @state)
(do
(swap! state assoc :queued true)
true)
false))
(schedule-sends! [_]
(if-not (:sends-queued @state)
(do
(swap! state assoc :sends-queued true)
true)
false))
(reconcile! [this]
(p/reconcile! this nil))
(reconcile! [this remote]
(let [st @state
q (if-not (nil? remote)
(get-in st [:remote-queue remote])
(:queue st))]
(swap! state update-in [:queued] not)
(if (not (nil? remote))
(swap! state assoc-in [:remote-queue remote] [])
(swap! state assoc :queue []))
(if (empty? q)
((:render st))
(let [cs (transduce
(map #(p/key->components (:indexer config) %))
#(into %1 %2) #{} q)
{:keys [ui->props]} config
env (to-env config)
root (:root @state)]
#?(:cljs
(doseq [c ((:optimize config) cs)]
(let [props-change? (> (p/basis-t this) (t c))]
(when (mounted? c)
(let [computed (get-computed (props c))
next-raw-props (ui->props env c)
next-props (om.next/computed next-raw-props computed)]
(when (and
(some? (.-componentWillReceiveProps c))
(iquery? root)
props-change?)
(let [next-props (if (nil? next-props)
(when-let [props (props c)]
props)
next-props)]
(.componentWillReceiveProps c
#js {:omcljs$value (om-props next-props (p/basis-t this))})))
(when (should-update? c next-props (get-state c))
(if-not (nil? next-props)
(update-component! c next-props)
(.forceUpdate c))
(when (and (iquery? root)
(not= c root)
props-change?)
(when-let [update-path (path c)]
(loop [p (parent c)]
(when (some? p)
(let [update-path' (subvec update-path (count (path p)))]
(update-props! p (assoc-in (props p) update-path' next-raw-props))
(merge-pending-props! p)
(recur (parent p)))))))))))))))))
(send! [this]
(let [sends (:queued-sends @state)]
(when-not (empty? sends)
(swap! state
(fn [state]
(-> state
(assoc :queued-sends {})
(assoc :sends-queued false))))
((:send config) sends
(fn send-cb
([resp]
(merge! this resp nil))
([resp query]
(merge! this resp query))
([resp query remote]
(when-not (nil? remote)
(p/queue! this (keys resp) remote))
(merge! this resp query remote)
(p/reconcile! this remote))))))))
(defn default-ui->props
[{:keys [parser #?(:clj pathopt :cljs ^boolean pathopt)] :as env} c]
(let [ui (when (and pathopt #?(:clj (satisfies? Ident c)
:cljs (implements? Ident c)) (iquery? c))
(let [id (ident c (props c))]
(get (parser env [{id (get-query c)}]) id)))]
(if-not (nil? ui)
ui
(let [fq (full-query c)]
(when-not (nil? fq)
(let [s #?(:clj (System/currentTimeMillis)
:cljs (system-time))
ui (parser env fq)
e #?(:clj (System/currentTimeMillis)
:cljs (system-time))]
#?(:cljs
(when-let [l (:logger env)]
(let [dt (- e s)
component-name (.. c -constructor -displayName)]
(when (< 16 dt)
(glog/warning l (str component-name " query took " dt " msecs"))))))
(get-in ui (path c))))))))
(defn default-merge-ident
[_ tree ref props]
(update-in tree ref merge props))
(defn default-merge-tree
[a b]
(if (map? a)
(merge a b)
b))
(defn default-migrate
"Given app-state-pure (the application state as an immutable value), a query,
tempids (a hash map from tempid to stable id), and an optional id-key
keyword, return a new application state value with the tempids replaced by
the stable ids."
([app-state-pure query tempids]
(default-migrate app-state-pure query tempids nil))
([app-state-pure query tempids id-key]
(letfn [(dissoc-in [pure [table id]]
(assoc pure table (dissoc (get pure table) id)))
(step [pure [old [_ id :as new]]]
(-> pure
(dissoc-in old)
(assoc-in new
(cond-> (merge (get-in pure old) (get-in pure new))
(not (nil? id-key)) (assoc id-key id)))))]
(if-not (empty? tempids)
(let [pure' (reduce step app-state-pure tempids)]
(tree->db query
(db->tree query pure' pure'
(fn [ident] (get tempids ident ident))) true))
app-state-pure))))
(defn- has-error?
#?(:cljs {:tag boolean})
[x]
(and (map? x) (contains? x ::error)))
(defn default-extract-errors [reconciler res query]
(letfn [(extract* [query res errs]
(let [class (-> query meta :component)
top-error? (when (and (not (nil? class)) (has-error? res))
(swap! errs
#(update-in % [#?(:clj ((-> class meta :ident) class res)
:cljs (ident class res))]
(fnil conj #{}) (::error res))))
ret (when (nil? top-error?) {})]
(cond
(vector? query)
(if (vector? res)
(into [] (map #(extract* query % errs)) res)
(loop [exprs (seq query) ret ret]
(if-not (nil? exprs)
(let [expr (first exprs)
k (as-> (expr->key expr) k
(cond-> k
(util/unique-ident? k) first))
data (get res k)]
(cond
(util/mutation? expr)
(let [mk (util/mutation-key expr)
ret' (get res mk)]
(if (has-error? ret')
(let [x (-> expr meta :mutator)]
(swap! errs
#(update-in % [x]
(fnil conj #{}) (::error ret')))
(recur (next exprs) ret))
(recur (next exprs)
(when-not (nil? ret)
(assoc ret mk ret')))))
(util/union? expr)
(let [jk (util/join-key expr)
jv (util/join-value expr)
class' (-> jv meta :component)]
(if (not (vector? data))
(let [ret' (extract*
(get jv (first #?(:clj ((-> class' meta :ident) class' data)
:cljs (ident class' data))))
data errs)]
(recur (next exprs)
(when-not (nil? ret)
(assoc ret jk ret'))))
(let [ret' (into []
(map #(extract*
(get jv
(first #?(:clj ((-> class' meta :ident) class' %)
:cljs (ident class' %))))
% errs))
data)]
(recur (next exprs)
(when-not (nil? ret)
(assoc ret jk ret'))))))
(util/join? expr)
(let [jk (util/join-key expr)
jv (util/join-value expr)
ret' (extract* jv data errs)]
(recur (next exprs)
(when-not (nil? ret)
(assoc ret jk ret'))))
(and (map? data) (has-error? data))
(do
(swap! errs
#(update-in %
[(or (when-not (nil? class)
#?(:clj ((-> class meta :ident) class res)
:cljs (ident class res)))
k)]
(fnil conj #{}) (::error data)))
(recur (next exprs) nil))
:else
(recur (next exprs)
(when-not (nil? ret)
(assoc ret k data)))))
ret))))))]
(let [errs (atom {})
ret (extract* query res errs)]
{:tree ret :errors @errs})))
(defn reconciler
"Construct a reconciler from a configuration map.
Required parameters:
:state - the application state. If IAtom value is not supplied the
data will be normalized into the default database format
using the root query. This can be disabled by explicitly
setting the optional :normalize parameter to false.
:parser - the parser to be used
Optional parameters:
:shared - a map of global shared properties for the component tree.
:shared-fn - a function to compute global shared properties from the root props.
the result is merged with :shared.
:send - required only if the parser will return a non-empty value when
run against the supplied :remotes. send is a function of two
arguments, the map of remote expressions keyed by remote target
and a callback which should be invoked with the result from each
remote target. Note this means the callback can be invoked
multiple times to support parallel fetching and incremental
loading if desired. The callback should take the response as the
first argument and the the query that was sent as the second
argument.
:normalize - whether the state should be normalized. If true it is assumed
all novelty introduced into the system will also need
normalization.
:remotes - a vector of keywords representing remote services which can
evaluate query expressions. Defaults to [:remote]
:root-render - the root render function. Defaults to ReactDOM.render
:root-unmount - the root unmount function. Defaults to
ReactDOM.unmountComponentAtNode
:logger - supply a goog.log compatible logger
:tx-listen - a function of 2 arguments that will listen to transactions.
The first argument is the parser's env map also containing
the old and new state. The second argument is a map containing
the transaction, its result and the remote sends that the
transaction originated."
[{:keys [state shared shared-fn
parser indexer
ui->props normalize
send merge-sends remotes
merge merge-tree merge-ident
prune-tree
optimize
history
root-render root-unmount
pathopt
migrate id-key
instrument tx-listen
easy-reads]
:or {ui->props default-ui->props
indexer om.next/indexer
merge-sends #(merge-with into %1 %2)
remotes [:remote]
merge default-merge
merge-tree default-merge-tree
merge-ident default-merge-ident
prune-tree default-extract-errors
optimize (fn [cs] (sort-by depth cs))
history 100
root-render #?(:clj (fn [c target] c)
:cljs #(js/ReactDOM.render %1 %2))
root-unmount #?(:clj (fn [x])
:cljs #(js/ReactDOM.unmountComponentAtNode %))
pathopt false
migrate default-migrate
easy-reads true}
:as config}]
{:pre [(map? config)]}
(let [idxr (indexer)
norm? #?(:clj (instance? clojure.lang.Atom state)
:cljs (satisfies? IAtom state))
state' (if norm? state (atom state))
logger (if (contains? config :logger)
(:logger config)
#?(:cljs *logger*))
ret (Reconciler.
{:state state' :shared shared :shared-fn shared-fn
:parser parser :indexer idxr
:ui->props ui->props
:send send :merge-sends merge-sends :remotes remotes
:merge merge :merge-tree merge-tree :merge-ident merge-ident
:prune-tree prune-tree
:optimize optimize
:normalize (or (not norm?) normalize)
:history #?(:clj []
:cljs (c/cache history))
:root-render root-render :root-unmount root-unmount
:logger logger :pathopt pathopt
:migrate migrate :id-key id-key
:instrument instrument :tx-listen tx-listen
:easy-reads easy-reads}
(atom {:queue []
:remote-queue {}
:queued false :queued-sends {}
:sends-queued false
:target nil :root nil :render nil :remove nil
:t 0 :normalized norm?}))]
ret))
(defn reconciler?
"Returns true if x is a reconciler."
#?(:cljs {:tag boolean})
[x]
#?(:cljs (implements? p/IReconciler x)
:clj (or (instance? om.next.protocols.IReconciler x)
(satisfies? p/IReconciler x))))
(defn app-state
"Return the reconciler's application state atom. Useful when the reconciler
was initialized via denormalized data."
[reconciler]
{:pre [(reconciler? reconciler)]}
(-> reconciler :config :state))
(defn app-root
"Return the application's root component."
[reconciler]
{:pre [(reconciler? reconciler)]}
(get @(:state reconciler) :root))
(defn force-root-render!
"Force a re-render of the root. Not recommended for anything except
recomputing :shared."
[reconciler]
{:pre [(reconciler? reconciler)]}
((get @(:state reconciler) :render)))
(defn from-history
"Given a reconciler and UUID return the application state snapshost
from history associated with the UUID. The size of the reconciler history
may be configured by the :history option when constructing the reconciler."
[reconciler uuid]
{:pre [(reconciler? reconciler)]}
(.get (-> reconciler :config :history) uuid))
(defn tempid
"Return a temporary id."
([] (tempid/tempid))
([id] (tempid/tempid id)))
(defn tempid?
"Return true if x is a tempid, false otherwise"
#?(:cljs {:tag boolean})
[x]
(tempid/tempid? x))
(defn reader
"Create a Om Next transit reader. This reader can handler the tempid type.
Can pass transit reader customization opts map."
([] (transit/reader))
([opts] (transit/reader opts)))
(defn writer
"Create a Om Next transit writer. This writer can handler the tempid type.
Can pass transit writer customization opts map."
([] (transit/writer))
([opts] (transit/writer opts)))
(defn force
"Given a query expression return an equivalent query expression that can be
spliced into a transaction that will force a read of that key from the
specified remote target."
([expr]
(force expr :remote))
([expr target]
(with-meta (list 'quote expr) {:target target})))
|
bf5625f7f9a683b614944afdaf14e8f2a188ffdf799bb1d3253444a0f1df2513 | Perry961002/SICP | exe3.76-smooth.scm | smooth模块
(define (smooth s)
(stream-map (lambda (x y) (/ (+ x y) 2))
s
(stream-cdr s)))
(define (make-zero-crossings input-stream smooth)
(let ((smooth-stream (smooth input-stream)))
(stream-map sign-change-detector
smooth-stream
(stream-cons 0 smooth-stream)))) | null | https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap3/exercise/exe3.76-smooth.scm | scheme | smooth模块
(define (smooth s)
(stream-map (lambda (x y) (/ (+ x y) 2))
s
(stream-cdr s)))
(define (make-zero-crossings input-stream smooth)
(let ((smooth-stream (smooth input-stream)))
(stream-map sign-change-detector
smooth-stream
(stream-cons 0 smooth-stream)))) | |
adc9301f96f2a925e8e95a29859fcc752d9958b53f36b77cf7b42caad2f81a0c | derekslager/advent-of-code-2015 | day6.clj | (ns advent-of-code-2015.day6
(:require [clojure.java.io :as io])
(:import java.util.BitSet))
(def grid-x 1000)
(def grid-y 1000)
(def grid-size (* grid-x grid-y))
(defn translate [x y]
(+ (* x grid-x) y))
(defn run []
(let [resource (slurp (io/resource "day6.txt"))
;; lines (str/split-lines resource)
ops (re-seq #"(turn off|turn on|toggle) (\d+),(\d+) through (\d+),(\d+)" resource)
lights (BitSet. grid-size)]
part 1
(doseq [[_ op from-x from-y to-x to-y] ops]
(let [op-fn (case op
"toggle" #(.flip lights ^Integer %)
"turn on" #(.set lights ^Integer % true)
"turn off" #(.set lights ^Integer % false))]
(doseq [x (range (Integer/parseInt from-x) (+ 1 (Integer/parseInt to-x)))
y (range (Integer/parseInt from-y) (+ 1 (Integer/parseInt to-y)))]
(op-fn (translate x y)))))
(.cardinality lights)
part 2
(let [dimmers (int-array grid-size)]
(doseq [[_ op from-x from-y to-x to-y] ops]
(let [turn-knob (fn [by idx] (aset dimmers ^Integer idx ^Integer (max 0 (+ (aget dimmers idx) by))))
op-fn (case op
"toggle" (partial turn-knob 2)
"turn on" (partial turn-knob 1)
"turn off" (partial turn-knob -1))]
(doseq [x (range (Integer/parseInt from-x) (+ 1 (Integer/parseInt to-x)))
y (range (Integer/parseInt from-y) (+ 1 (Integer/parseInt to-y)))]
(op-fn (translate x y)))))
(reduce + dimmers))))
| null | https://raw.githubusercontent.com/derekslager/advent-of-code-2015/bbc589d29613c594178d9305741096f3688b05f2/src/advent_of_code_2015/day6.clj | clojure | lines (str/split-lines resource) | (ns advent-of-code-2015.day6
(:require [clojure.java.io :as io])
(:import java.util.BitSet))
(def grid-x 1000)
(def grid-y 1000)
(def grid-size (* grid-x grid-y))
(defn translate [x y]
(+ (* x grid-x) y))
(defn run []
(let [resource (slurp (io/resource "day6.txt"))
ops (re-seq #"(turn off|turn on|toggle) (\d+),(\d+) through (\d+),(\d+)" resource)
lights (BitSet. grid-size)]
part 1
(doseq [[_ op from-x from-y to-x to-y] ops]
(let [op-fn (case op
"toggle" #(.flip lights ^Integer %)
"turn on" #(.set lights ^Integer % true)
"turn off" #(.set lights ^Integer % false))]
(doseq [x (range (Integer/parseInt from-x) (+ 1 (Integer/parseInt to-x)))
y (range (Integer/parseInt from-y) (+ 1 (Integer/parseInt to-y)))]
(op-fn (translate x y)))))
(.cardinality lights)
part 2
(let [dimmers (int-array grid-size)]
(doseq [[_ op from-x from-y to-x to-y] ops]
(let [turn-knob (fn [by idx] (aset dimmers ^Integer idx ^Integer (max 0 (+ (aget dimmers idx) by))))
op-fn (case op
"toggle" (partial turn-knob 2)
"turn on" (partial turn-knob 1)
"turn off" (partial turn-knob -1))]
(doseq [x (range (Integer/parseInt from-x) (+ 1 (Integer/parseInt to-x)))
y (range (Integer/parseInt from-y) (+ 1 (Integer/parseInt to-y)))]
(op-fn (translate x y)))))
(reduce + dimmers))))
|
9b408a8c472502b076c2380a225b7d431fcda4e36bc6b428db9b1ee2c59dc369 | lispcord/lispcord | guild.lisp | (in-package :lispcord.classes)
(defclass partial-role ()
((name :initarg :name :accessor name)
(color :initarg :color :accessor color)
(hoist :initarg :hoist :accessor hoistp)
(permissions :initarg :perms :accessor permissions)
(mentionable :initarg :mention :accessor mentionablep)))
(defmethod make-role (&key
(name "new role")
(color 0)
hoist
(permissions 0)
mentionable)
(make-instance 'partial-role
:name name
:color color
:hoist (or hoist :false)
:perms permissions
:mention (or mentionable :false)))
(defmethod %to-json ((r partial-role))
(with-object
(write-key-value "name" (name r))
(write-key-value "color" (color r))
(write-key-value "hoist" (or (hoistp r) :false))
(write-key-value "permissions" (permissions r))
(write-key-value "mentionable" (or (mentionablep r) :false))))
(defclass role ()
((id :initarg :id
:type snowflake
:accessor id)
(name :initarg :name
:type string
:accessor name)
(color :initarg :color
:type fixnum
:accessor color)
(hoist :initarg :hoist
:type t
:accessor hoistp)
(position :initarg :pos
:type fixnum
:accessor position)
(permissions :initarg :perms
:type permissions
:accessor permissions)
(managed :initarg :managed
:type t
:accessor managedp)
(mentionable :initarg :mentionable
:type t
:accessor mentionablep)
(guild-id :initarg :gid
:type (or null snowflake)
:accessor guild-id)))
(defmethod guild ((r role))
(getcache-id (guild-id r) :guild))
(defmethod overwrite ((c channel) (m role))
"Returns permission overwrite for role in channel"
(find (id m) (overwrites c) :key 'id))
(defmethod from-json ((c (eql :role)) (table hash-table))
(instance-from-table (table 'role)
:id (parse-snowflake (gethash "id" table))
:name "name"
:color "color"
:hoist "hoist"
:pos "position"
:perms (make-permissions (gethash "permissions" table))
:managed "managed"
:mentionable "mentionable"))
(defmethod update ((table hash-table) (r role))
(from-table-update (table data)
("id" (id r) (parse-snowflake data))
("name" (name r) data)
("color" (color r) data)
("hoist" (hoistp r) data)
("position" (position r) data)
("permissions" (permissions r) data)
("managed" (managedp r) data)
("mentionable" (mentionablep r) data))
r)
(defmethod %to-json ((r role))
(with-object
(write-key-value "id" (id r))
(write-key-value "name" (name r))
(write-key-value "color" (color r))
(write-key-value "hoist" (hoistp r))
(write-key-value "position" (position r))
(write-key-value "permissions" (permissions r))
(write-key-value "managed" (managedp r))
(write-key-value "mentionable" (mentionablep r))))
(defclass member ()
((user :initarg :user
:type user
:accessor user)
(nick :initarg :nick
:type (or null string)
:accessor nick)
(roles :initarg :roles
:type (vector role)
:accessor roles)
(joined-at :initarg :joined-at
:type (or null string)
:accessor joined-at)
(deaf :initarg :deaf
:type t
:accessor deafp)
(mute :initarg :mute
:type t
:accessor mutep)
(guild-id :initarg :gid
:type (or null snowflake)
:accessor guild-id)))
(defmethod guild ((m member))
(getcache-id (guild-id m) :guild))
(defmethod has-permission ((m member) key &optional channel)
(let ((base-permissions (base-permissions m)))
(if channel
(has-permission (compute-overwrites base-permissions m channel) key)
(has-permission base-permissions key))))
(defmethod has-permission ((u user) key &optional channel)
(if channel
(if-let ((member (member u (guild channel))))
(has-permission member key channel)
(error "User ~S is not a member of ~S" u channel))
(error "Global users don't have permissions. Either replace the user object with member, or specify the channel.")))
(defmethod overwrite ((c channel) (m member))
"Returns permission overwrite for member in channel"
(find (id (user m)) (overwrites c) :key 'id))
;;The Modify and Add Member REST-calls can use this
(defmethod %to-json ((m member))
(with-object
(write-key-value "user" (user m))
(write-key-value "nick" (nick m))
(write-key-value "roles" (roles m))
(write-key-value "joined_at" (joined-at m))
(write-key-value "mute" (mutep m))
(write-key-value "deaf" (deafp m))))
(defmethod from-json ((c (eql :g-member)) (table hash-table))
(instance-from-table (table 'member)
:user (cache :user (gethash "user" table))
:nick "nick"
:roles (map '(vector role)
(lambda (e) (getcache-id (parse-snowflake e) :role))
(gethash "roles" table))
:joined-at "joined_at"
:mute "mute"
:deaf "deaf"
:gid (parse-snowflake (gethash "guild_id" table))))
(defmethod update ((table hash-table) (m member))
(from-table-update (table data)
("user" (user m) (cache :user data))
("nick" (nick m) data)
("roles" (roles m) (map '(vector snowflake) #'parse-snowflake data))
("joined_at" (joined-at m) data)
("mute" (mutep m) data)
("deaf" (deafp m) data)
("guild_id" (guild-id m) (parse-snowflake data)))
m)
(defclass presence ()
((user :initarg :user
:type snowflake
:accessor user-id)
(roles :initarg :roles
:type (or null (vector snowflake))
:accessor roles)
(game :initarg :game
:type (or null game)
:accessor game)
(guild-id :initarg :guild-id
:type (or null snowflake)
:accessor guild-id)
(status :initarg :status
:type (or null string)
:accessor status)))
(defmethod user ((p presence))
(getcache-id (user-id p) :user))
(defmethod from-json ((c (eql :presence)) (table hash-table))
(instance-from-table (table 'presence)
:user (parse-snowflake (gethash "id" (gethash "user" table)))
:roles (map '(vector snowflake) #'parse-snowflake (gethash "roles" table))
:game (from-json :game (gethash "game" table))
:guild-id (%maybe-sf (gethash "guild_id" table))
:status "status"))
(defmethod %to-json ((p presence))
(with-object
(write-key-value "name" (name p))
(write-key-value "roles" (roles p))
(write-key-value "game" (game p))
(write-key-value "guild_id" (guild-id p))
(write-key-value "status" (status p))))
(defclass guild ()
((id :initarg :id
:type snowflake
:accessor id)
(available :initarg :available
:type t
:accessor availablep)))
(defclass available-guild (guild)
((name :initarg :name
:type string
:accessor name)
(icon :initarg :icon
:type (or null string)
:accessor icon)
(splash :initarg :splash
:type (or null string)
:accessor splash)
(owner :initarg :owner
:type snowflake
:accessor owner-id)
(region :initarg :region
:type string
:accessor region)
(afk-id :initarg :afk-id
:type (or null snowflake)
:accessor afk-id)
(afk-to :initarg :afk-to
:type fixnum
:accessor afk-to)
(embed? :initarg :embed?
:type t
:accessor embedp)
(embed-id :initarg :embed-id
:type (or null snowflake)
:accessor embed-id)
(verification-level :initarg :verify-l
:type fixnum
:accessor verify-level)
(notification-level :initarg :notify-l
:type fixnum
:accessor notify-level)
(content-filter :initarg :content
:type fixnum
:accessor content-filter)
(roles :initarg :roles
:type (vector role)
:accessor roles)
(emojis :initarg :emojis
:type (vector emoji)
:accessor emojis)
(features :initarg :features
:type (or null (vector string))
:accessor features)
(mfa-level :initarg :mfa
:type fixnum
:accessor mfa-level)
(application-id :initarg :app-id
:type (or null snowflake)
:accessor app-id)
(widget-enabled :initarg :widget?
:type t
:accessor widgetp)
(widget-channel-id :initarg :widget-id
:type (or null snowflake)
:accessor widget-id)
(system-channel-id :initarg :system-id
:type (or null snowflake)
:accessor system-channel-id)
(joined-at :initarg :joined-at
:type (or null string)
:accessor joined-at)
(large :initarg :large
:type t
:accessor largep)
(member-count :initarg :member-cnt
:type (or null fixnum)
:accessor member-count)
(members :initarg :members
:type (vector member)
:accessor members)
(channels :initarg :channels
:type (vector channel)
:accessor channels)
(presences :initarg :presences
:type (vector presence)
:accessor presences)))
(defmethod role-everyone ((g guild))
"Returns the @everyone role of the guild"
;; It always has the same id as the guild
(getcache-id (id g) :role))
(defmethod owner ((g guild))
(getcache-id (owner-id g) :user))
(defmethod member ((u user) (g guild))
(find-if (lambda (e) (eq u (lc:user e))) (members g)))
(defmethod nick-or-name ((u user) (g guild))
"Member u of the guild g"
(if-let ((member (member u g)))
(or (nick member)
(name u))
(name u)))
(defmethod %to-json ((g available-guild))
(with-object
(write-key-value "id" (id g))
(write-key-value "name" (name g))
(write-key-value "icon" (icon g))
(write-key-value "joined_at" (joined-at g))
(write-key-value "splash" (splash g))
(write-key-value "owner_id" (owner g))
(write-key-value "region" (region g))
(write-key-value "afk_channel_id" (afk-id g))
(write-key-value "afk_timeout" (afk-to g))
(write-key-value "embed_enabled" (embedp g))
(write-key-value "embed_channel_id" (embed-id g))
(write-key-value "verification_level" (verify-level g))
(write-key-value "default_message_notification" (notify-level g))
(write-key-value "explicit_content_filter" (content-filter g))
(write-key-value "roles" (roles g))
(write-key-value "emojis" (emojis g))
(write-key-value "features" (features g))
(write-key-value "mfa_level" (mfa-level g))
(write-key-value "application_id" (app-id g))
(write-key-value "widget_enabled" (widgetp g))
(write-key-value "widget_channel_id" (widget-id g))
(write-key-value "system_channel_id" (system-channel-id g))
(write-key-value "large" (largep g))
(write-key-value "unavailable" (not (availablep g)))
(write-key-value "member_count" (member-count g))
(write-key-value "members" (members g))
(write-key-value "channels" (channels g))
(write-key-value "presences" (presences g))))
(defmethod %to-json ((g guild))
(with-object
(write-key-value "id" (id g))
(write-key-value "unvailable" (not (availablep g)))))
(defun %available-from-json (table)
(flet ((parse-with-gid (f type e)
(unless (gethash "guild_id" e)
(setf (gethash "guild_id" e) (gethash "id" table)))
(funcall f type e)))
(instance-from-table (table 'available-guild)
:id (parse-snowflake (gethash "id" table))
:name "name"
:icon "icon"
:splash "splash"
:owner (parse-snowflake (gethash "owner_id" table))
:region "region"
:afk-id (%maybe-sf (gethash "afk_channel_id" table))
:afk-to "afk_timeout"
:embed? "embed_enabled"
:embed-id (%maybe-sf (gethash "embed_channel_id" table))
:verify-l "verification_level"
:notify-l "default_message_notifications"
:content "explicit_content_filter"
:roles (map '(vector role)
(curry #'parse-with-gid #'cache :role)
(gethash "roles" table))
:emojis (map '(vector emoji)
(curry #'parse-with-gid #'cache :emoji)
(gethash "emojis" table))
:features (coerce (gethash "features" table) 'vector)
:mfa "mfa_level"
:app-id (%maybe-sf (gethash "application_id" table))
:widget? "widget_enabled"
:widget-id (%maybe-sf (gethash "widget_channel_id" table))
:system-id (%maybe-sf (gethash "sytem_channel_id" table))
:joined-at "joined_at"
:large "large"
:available (not (gethash "unavailable" table))
:member-cnt "member_count"
:members (map '(vector member)
(curry #'parse-with-gid #'from-json :g-member)
(gethash "members" table))
:channels (map '(vector channel)
(curry #'parse-with-gid #'cache :channel)
(gethash "channels" table))
:presences (map '(vector presence)
(curry #'from-json :presence)
(gethash "presences" table)))))
(defun %unavailable-from-json (table)
(make-instance 'guild
:id (parse-snowflake (gethash "id" table))
:available (not (gethash "unavailable" table))))
(defmethod update ((table hash-table) (g guild))
(cache-update (id g) :guild table))
(defmethod update ((table hash-table) (g available-guild))
(from-table-update (table data)
("id" (id g) (parse-snowflake data))
("name" (name g) data)
("icon" (icon g) data)
("splash" (splash g) data)
("owner_id" (owner-id g) (parse-snowflake data))
("region" (region g) data)
("afk_channel_id" (afk-id g) (parse-snowflake data))
("afk_timeout" (afk-to g) data)
("embed_enabled" (embedp g) data)
("embed_channel_id" (embed-id g) (parse-snowflake data))
("verification_level" (verify-level g) data)
("default_message_notification" (notify-level g) data)
("explicit_content_filter" (content-filter g) data)
("roles" (roles g) (map '(vector role) (curry #'cache :role) data))
("emojis" (emojis g) (map '(vector emoji) (curry #'cache :emoji) data))
("features" (features g) (coerce data 'vector))
("mfa_level" (mfa-level g) data)
("application_id" (app-id g) (parse-snowflake data))
("widget_enabled" (widgetp g) data)
("widget_channel_id" (widget-id g) (parse-snowflake data))
("system_channel_id" (system-channel-id g) (parse-snowflake data)))
g)
(defmethod from-json ((c (eql :guild)) (table hash-table))
(if (gethash "unavailable" table)
(%unavailable-from-json table)
(%available-from-json table)))
| null | https://raw.githubusercontent.com/lispcord/lispcord/448190cc503a0d7e59bdc0ffddb2e9dba0a706af/src/classes/guild.lisp | lisp | The Modify and Add Member REST-calls can use this
It always has the same id as the guild | (in-package :lispcord.classes)
(defclass partial-role ()
((name :initarg :name :accessor name)
(color :initarg :color :accessor color)
(hoist :initarg :hoist :accessor hoistp)
(permissions :initarg :perms :accessor permissions)
(mentionable :initarg :mention :accessor mentionablep)))
(defmethod make-role (&key
(name "new role")
(color 0)
hoist
(permissions 0)
mentionable)
(make-instance 'partial-role
:name name
:color color
:hoist (or hoist :false)
:perms permissions
:mention (or mentionable :false)))
(defmethod %to-json ((r partial-role))
(with-object
(write-key-value "name" (name r))
(write-key-value "color" (color r))
(write-key-value "hoist" (or (hoistp r) :false))
(write-key-value "permissions" (permissions r))
(write-key-value "mentionable" (or (mentionablep r) :false))))
(defclass role ()
((id :initarg :id
:type snowflake
:accessor id)
(name :initarg :name
:type string
:accessor name)
(color :initarg :color
:type fixnum
:accessor color)
(hoist :initarg :hoist
:type t
:accessor hoistp)
(position :initarg :pos
:type fixnum
:accessor position)
(permissions :initarg :perms
:type permissions
:accessor permissions)
(managed :initarg :managed
:type t
:accessor managedp)
(mentionable :initarg :mentionable
:type t
:accessor mentionablep)
(guild-id :initarg :gid
:type (or null snowflake)
:accessor guild-id)))
(defmethod guild ((r role))
(getcache-id (guild-id r) :guild))
(defmethod overwrite ((c channel) (m role))
"Returns permission overwrite for role in channel"
(find (id m) (overwrites c) :key 'id))
(defmethod from-json ((c (eql :role)) (table hash-table))
(instance-from-table (table 'role)
:id (parse-snowflake (gethash "id" table))
:name "name"
:color "color"
:hoist "hoist"
:pos "position"
:perms (make-permissions (gethash "permissions" table))
:managed "managed"
:mentionable "mentionable"))
(defmethod update ((table hash-table) (r role))
(from-table-update (table data)
("id" (id r) (parse-snowflake data))
("name" (name r) data)
("color" (color r) data)
("hoist" (hoistp r) data)
("position" (position r) data)
("permissions" (permissions r) data)
("managed" (managedp r) data)
("mentionable" (mentionablep r) data))
r)
(defmethod %to-json ((r role))
(with-object
(write-key-value "id" (id r))
(write-key-value "name" (name r))
(write-key-value "color" (color r))
(write-key-value "hoist" (hoistp r))
(write-key-value "position" (position r))
(write-key-value "permissions" (permissions r))
(write-key-value "managed" (managedp r))
(write-key-value "mentionable" (mentionablep r))))
(defclass member ()
((user :initarg :user
:type user
:accessor user)
(nick :initarg :nick
:type (or null string)
:accessor nick)
(roles :initarg :roles
:type (vector role)
:accessor roles)
(joined-at :initarg :joined-at
:type (or null string)
:accessor joined-at)
(deaf :initarg :deaf
:type t
:accessor deafp)
(mute :initarg :mute
:type t
:accessor mutep)
(guild-id :initarg :gid
:type (or null snowflake)
:accessor guild-id)))
(defmethod guild ((m member))
(getcache-id (guild-id m) :guild))
(defmethod has-permission ((m member) key &optional channel)
(let ((base-permissions (base-permissions m)))
(if channel
(has-permission (compute-overwrites base-permissions m channel) key)
(has-permission base-permissions key))))
(defmethod has-permission ((u user) key &optional channel)
(if channel
(if-let ((member (member u (guild channel))))
(has-permission member key channel)
(error "User ~S is not a member of ~S" u channel))
(error "Global users don't have permissions. Either replace the user object with member, or specify the channel.")))
(defmethod overwrite ((c channel) (m member))
"Returns permission overwrite for member in channel"
(find (id (user m)) (overwrites c) :key 'id))
(defmethod %to-json ((m member))
(with-object
(write-key-value "user" (user m))
(write-key-value "nick" (nick m))
(write-key-value "roles" (roles m))
(write-key-value "joined_at" (joined-at m))
(write-key-value "mute" (mutep m))
(write-key-value "deaf" (deafp m))))
(defmethod from-json ((c (eql :g-member)) (table hash-table))
(instance-from-table (table 'member)
:user (cache :user (gethash "user" table))
:nick "nick"
:roles (map '(vector role)
(lambda (e) (getcache-id (parse-snowflake e) :role))
(gethash "roles" table))
:joined-at "joined_at"
:mute "mute"
:deaf "deaf"
:gid (parse-snowflake (gethash "guild_id" table))))
(defmethod update ((table hash-table) (m member))
(from-table-update (table data)
("user" (user m) (cache :user data))
("nick" (nick m) data)
("roles" (roles m) (map '(vector snowflake) #'parse-snowflake data))
("joined_at" (joined-at m) data)
("mute" (mutep m) data)
("deaf" (deafp m) data)
("guild_id" (guild-id m) (parse-snowflake data)))
m)
(defclass presence ()
((user :initarg :user
:type snowflake
:accessor user-id)
(roles :initarg :roles
:type (or null (vector snowflake))
:accessor roles)
(game :initarg :game
:type (or null game)
:accessor game)
(guild-id :initarg :guild-id
:type (or null snowflake)
:accessor guild-id)
(status :initarg :status
:type (or null string)
:accessor status)))
(defmethod user ((p presence))
(getcache-id (user-id p) :user))
(defmethod from-json ((c (eql :presence)) (table hash-table))
(instance-from-table (table 'presence)
:user (parse-snowflake (gethash "id" (gethash "user" table)))
:roles (map '(vector snowflake) #'parse-snowflake (gethash "roles" table))
:game (from-json :game (gethash "game" table))
:guild-id (%maybe-sf (gethash "guild_id" table))
:status "status"))
(defmethod %to-json ((p presence))
(with-object
(write-key-value "name" (name p))
(write-key-value "roles" (roles p))
(write-key-value "game" (game p))
(write-key-value "guild_id" (guild-id p))
(write-key-value "status" (status p))))
(defclass guild ()
((id :initarg :id
:type snowflake
:accessor id)
(available :initarg :available
:type t
:accessor availablep)))
(defclass available-guild (guild)
((name :initarg :name
:type string
:accessor name)
(icon :initarg :icon
:type (or null string)
:accessor icon)
(splash :initarg :splash
:type (or null string)
:accessor splash)
(owner :initarg :owner
:type snowflake
:accessor owner-id)
(region :initarg :region
:type string
:accessor region)
(afk-id :initarg :afk-id
:type (or null snowflake)
:accessor afk-id)
(afk-to :initarg :afk-to
:type fixnum
:accessor afk-to)
(embed? :initarg :embed?
:type t
:accessor embedp)
(embed-id :initarg :embed-id
:type (or null snowflake)
:accessor embed-id)
(verification-level :initarg :verify-l
:type fixnum
:accessor verify-level)
(notification-level :initarg :notify-l
:type fixnum
:accessor notify-level)
(content-filter :initarg :content
:type fixnum
:accessor content-filter)
(roles :initarg :roles
:type (vector role)
:accessor roles)
(emojis :initarg :emojis
:type (vector emoji)
:accessor emojis)
(features :initarg :features
:type (or null (vector string))
:accessor features)
(mfa-level :initarg :mfa
:type fixnum
:accessor mfa-level)
(application-id :initarg :app-id
:type (or null snowflake)
:accessor app-id)
(widget-enabled :initarg :widget?
:type t
:accessor widgetp)
(widget-channel-id :initarg :widget-id
:type (or null snowflake)
:accessor widget-id)
(system-channel-id :initarg :system-id
:type (or null snowflake)
:accessor system-channel-id)
(joined-at :initarg :joined-at
:type (or null string)
:accessor joined-at)
(large :initarg :large
:type t
:accessor largep)
(member-count :initarg :member-cnt
:type (or null fixnum)
:accessor member-count)
(members :initarg :members
:type (vector member)
:accessor members)
(channels :initarg :channels
:type (vector channel)
:accessor channels)
(presences :initarg :presences
:type (vector presence)
:accessor presences)))
(defmethod role-everyone ((g guild))
"Returns the @everyone role of the guild"
(getcache-id (id g) :role))
(defmethod owner ((g guild))
(getcache-id (owner-id g) :user))
(defmethod member ((u user) (g guild))
(find-if (lambda (e) (eq u (lc:user e))) (members g)))
(defmethod nick-or-name ((u user) (g guild))
"Member u of the guild g"
(if-let ((member (member u g)))
(or (nick member)
(name u))
(name u)))
(defmethod %to-json ((g available-guild))
(with-object
(write-key-value "id" (id g))
(write-key-value "name" (name g))
(write-key-value "icon" (icon g))
(write-key-value "joined_at" (joined-at g))
(write-key-value "splash" (splash g))
(write-key-value "owner_id" (owner g))
(write-key-value "region" (region g))
(write-key-value "afk_channel_id" (afk-id g))
(write-key-value "afk_timeout" (afk-to g))
(write-key-value "embed_enabled" (embedp g))
(write-key-value "embed_channel_id" (embed-id g))
(write-key-value "verification_level" (verify-level g))
(write-key-value "default_message_notification" (notify-level g))
(write-key-value "explicit_content_filter" (content-filter g))
(write-key-value "roles" (roles g))
(write-key-value "emojis" (emojis g))
(write-key-value "features" (features g))
(write-key-value "mfa_level" (mfa-level g))
(write-key-value "application_id" (app-id g))
(write-key-value "widget_enabled" (widgetp g))
(write-key-value "widget_channel_id" (widget-id g))
(write-key-value "system_channel_id" (system-channel-id g))
(write-key-value "large" (largep g))
(write-key-value "unavailable" (not (availablep g)))
(write-key-value "member_count" (member-count g))
(write-key-value "members" (members g))
(write-key-value "channels" (channels g))
(write-key-value "presences" (presences g))))
(defmethod %to-json ((g guild))
(with-object
(write-key-value "id" (id g))
(write-key-value "unvailable" (not (availablep g)))))
(defun %available-from-json (table)
(flet ((parse-with-gid (f type e)
(unless (gethash "guild_id" e)
(setf (gethash "guild_id" e) (gethash "id" table)))
(funcall f type e)))
(instance-from-table (table 'available-guild)
:id (parse-snowflake (gethash "id" table))
:name "name"
:icon "icon"
:splash "splash"
:owner (parse-snowflake (gethash "owner_id" table))
:region "region"
:afk-id (%maybe-sf (gethash "afk_channel_id" table))
:afk-to "afk_timeout"
:embed? "embed_enabled"
:embed-id (%maybe-sf (gethash "embed_channel_id" table))
:verify-l "verification_level"
:notify-l "default_message_notifications"
:content "explicit_content_filter"
:roles (map '(vector role)
(curry #'parse-with-gid #'cache :role)
(gethash "roles" table))
:emojis (map '(vector emoji)
(curry #'parse-with-gid #'cache :emoji)
(gethash "emojis" table))
:features (coerce (gethash "features" table) 'vector)
:mfa "mfa_level"
:app-id (%maybe-sf (gethash "application_id" table))
:widget? "widget_enabled"
:widget-id (%maybe-sf (gethash "widget_channel_id" table))
:system-id (%maybe-sf (gethash "sytem_channel_id" table))
:joined-at "joined_at"
:large "large"
:available (not (gethash "unavailable" table))
:member-cnt "member_count"
:members (map '(vector member)
(curry #'parse-with-gid #'from-json :g-member)
(gethash "members" table))
:channels (map '(vector channel)
(curry #'parse-with-gid #'cache :channel)
(gethash "channels" table))
:presences (map '(vector presence)
(curry #'from-json :presence)
(gethash "presences" table)))))
(defun %unavailable-from-json (table)
(make-instance 'guild
:id (parse-snowflake (gethash "id" table))
:available (not (gethash "unavailable" table))))
(defmethod update ((table hash-table) (g guild))
(cache-update (id g) :guild table))
(defmethod update ((table hash-table) (g available-guild))
(from-table-update (table data)
("id" (id g) (parse-snowflake data))
("name" (name g) data)
("icon" (icon g) data)
("splash" (splash g) data)
("owner_id" (owner-id g) (parse-snowflake data))
("region" (region g) data)
("afk_channel_id" (afk-id g) (parse-snowflake data))
("afk_timeout" (afk-to g) data)
("embed_enabled" (embedp g) data)
("embed_channel_id" (embed-id g) (parse-snowflake data))
("verification_level" (verify-level g) data)
("default_message_notification" (notify-level g) data)
("explicit_content_filter" (content-filter g) data)
("roles" (roles g) (map '(vector role) (curry #'cache :role) data))
("emojis" (emojis g) (map '(vector emoji) (curry #'cache :emoji) data))
("features" (features g) (coerce data 'vector))
("mfa_level" (mfa-level g) data)
("application_id" (app-id g) (parse-snowflake data))
("widget_enabled" (widgetp g) data)
("widget_channel_id" (widget-id g) (parse-snowflake data))
("system_channel_id" (system-channel-id g) (parse-snowflake data)))
g)
(defmethod from-json ((c (eql :guild)) (table hash-table))
(if (gethash "unavailable" table)
(%unavailable-from-json table)
(%available-from-json table)))
|
2165759581cef655146b33fc2cc4d17e7b83a76cc856bd5f9c0fc4314dfbefe2 | ftovagliari/ocamleditor | dot.ml |
OCamlEditor
Copyright ( C ) 2010 - 2014
This file is part of OCamlEditor .
OCamlEditor 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 3 of the License , or
( at your option ) any later version .
OCamlEditor is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with this program . If not , see < / > .
OCamlEditor
Copyright (C) 2010-2014 Francesco Tovagliari
This file is part of OCamlEditor.
OCamlEditor 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 3 of the License, or
(at your option) any later version.
OCamlEditor is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see </>.
*)
open Printf
open Miscellanea
let round f =
int_of_float (if f < 0. then f -. 0.5 else f +. 0.5)
let ocamldoc = Ocaml_config.ocamldoc ()
(** mk_ocamldoc_cmd *)
let mk_ocamldoc_cmd ~project ?(dot_include_all=false) ?(dot_reduce=true) ?(dot_types=false) ~outfile sourcefiles =
let search_path = Project.get_search_path_i_format project in
ocamldoc, Array.concat [
[| "-dot";
"-I";
"+threads";
|];
(Array.of_list (Miscellanea.split " +" search_path));
[|
(if dot_include_all then "-dot-include-all" else "");
(if dot_reduce then "-dot-reduce" else "");
(if dot_types then "-dot-types" else "");
"-o";
outfile
|];
(Array.of_list sourcefiles);
];;
(** mk_dot_cmd *)
let mk_dot_cmd ~outlang ~outfile ?(label="") ?(rotate=0.) filename =
"dot", [|
("-T" ^ outlang);
"-o";
outfile;
"-Glabel=\"" ^ label ^ "\"";
(sprintf "-Grotate=%.2f" rotate);
Oe_config.dot_attributes;
filename
|]
;;
(** draw *)
let draw ~project ~filename ?dot_include_all ?dot_types ?packing ?on_ready_cb () =
let module Device =
(val match Oe_config.dot_viewer with
| `DEFAULT -> !Dot_viewer_plugin.device
| `PDF -> (module Dot_viewer_pdf.PDF))
in
let outlang = Device.lang in
let basename = Filename.basename filename in
let label = sprintf "Dependency graph for \xC2\xAB%s\xC2\xBB" basename in
let prefix = Filename.chop_extension basename in
let search_path = "-I " ^ String.concat " -I " (Project.get_search_path_local project) in
let dependencies =
Oebuild_dep.ocamldep_recursive ~search_path [filename] |> Oebuild_dep.sort_dependencies |> List.map Oebuild_util.replace_extension_to_ml
in
let dependants =
let path = [Filename.dirname filename] in
let modname = Miscellanea.modname_of_path filename in
Oebuild_dep.find_dependants ~path ~modname
in
let sourcefiles = dependencies @ dependants in
let dotfile = Filename.temp_file prefix ".dot" in
let outfile = dotfile ^ "." ^ outlang in
(* *)
let ocamldoc_cmd, oargs = mk_ocamldoc_cmd ?dot_include_all ?dot_types ~project ~outfile:dotfile sourcefiles in
let dot_cmd, dargs = mk_dot_cmd ~outlang ~outfile ~label dotfile in
let viewer = Device.create ?packing () in
let activity_name = "Generating module dependency graph, please wait..." in
Activity.add Activity.Other activity_name;
Spawn.async ~at_exit:begin fun _ ->
let modname = Miscellanea.modname_of_path filename in
let re = kprintf Str.regexp "\"%s\" \\[.*color=\\(.+\\).*\\]" modname in
(*let re1 = Str.regexp "\\(\".*\"\\) \\[style=filled, color=darkturquoise\\];$" in*)
map_file_lines dotfile begin fun ~lnum ~line ->
if Str.string_match re line 0 then ( sprintf " \"%s\ " [ style = filled , color = black , fontcolor = white];\n " )
if Str.string_match re line 0 then (sprintf "\"%s\" [style=filled, color=black, fillcolor=%s, fontsize=28, shape=box];\n" modname (Str.matched_group 1 line))
else if Str.string_match re1 line 0 then ( sprintf " % s;\n " ( Str.matched_group 1 line ) )
else line
end;
Spawn.async ~at_exit:begin fun _ ->
if Sys.file_exists dotfile then (Sys.remove dotfile);
Device.draw ~filename:outfile viewer;
Activity.remove activity_name;
Gaux.may on_ready_cb ~f:(fun cb -> cb viewer);
end dot_cmd dargs |> ignore;
end ocamldoc_cmd oargs |> ignore;
viewer;;
| null | https://raw.githubusercontent.com/ftovagliari/ocamleditor/53284253cf7603b96051e7425e85a731f09abcd1/src/dot.ml | ocaml | * mk_ocamldoc_cmd
* mk_dot_cmd
* draw
let re1 = Str.regexp "\\(\".*\"\\) \\[style=filled, color=darkturquoise\\];$" in |
OCamlEditor
Copyright ( C ) 2010 - 2014
This file is part of OCamlEditor .
OCamlEditor 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 3 of the License , or
( at your option ) any later version .
OCamlEditor is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with this program . If not , see < / > .
OCamlEditor
Copyright (C) 2010-2014 Francesco Tovagliari
This file is part of OCamlEditor.
OCamlEditor 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 3 of the License, or
(at your option) any later version.
OCamlEditor is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see </>.
*)
open Printf
open Miscellanea
let round f =
int_of_float (if f < 0. then f -. 0.5 else f +. 0.5)
let ocamldoc = Ocaml_config.ocamldoc ()
let mk_ocamldoc_cmd ~project ?(dot_include_all=false) ?(dot_reduce=true) ?(dot_types=false) ~outfile sourcefiles =
let search_path = Project.get_search_path_i_format project in
ocamldoc, Array.concat [
[| "-dot";
"-I";
"+threads";
|];
(Array.of_list (Miscellanea.split " +" search_path));
[|
(if dot_include_all then "-dot-include-all" else "");
(if dot_reduce then "-dot-reduce" else "");
(if dot_types then "-dot-types" else "");
"-o";
outfile
|];
(Array.of_list sourcefiles);
];;
let mk_dot_cmd ~outlang ~outfile ?(label="") ?(rotate=0.) filename =
"dot", [|
("-T" ^ outlang);
"-o";
outfile;
"-Glabel=\"" ^ label ^ "\"";
(sprintf "-Grotate=%.2f" rotate);
Oe_config.dot_attributes;
filename
|]
;;
let draw ~project ~filename ?dot_include_all ?dot_types ?packing ?on_ready_cb () =
let module Device =
(val match Oe_config.dot_viewer with
| `DEFAULT -> !Dot_viewer_plugin.device
| `PDF -> (module Dot_viewer_pdf.PDF))
in
let outlang = Device.lang in
let basename = Filename.basename filename in
let label = sprintf "Dependency graph for \xC2\xAB%s\xC2\xBB" basename in
let prefix = Filename.chop_extension basename in
let search_path = "-I " ^ String.concat " -I " (Project.get_search_path_local project) in
let dependencies =
Oebuild_dep.ocamldep_recursive ~search_path [filename] |> Oebuild_dep.sort_dependencies |> List.map Oebuild_util.replace_extension_to_ml
in
let dependants =
let path = [Filename.dirname filename] in
let modname = Miscellanea.modname_of_path filename in
Oebuild_dep.find_dependants ~path ~modname
in
let sourcefiles = dependencies @ dependants in
let dotfile = Filename.temp_file prefix ".dot" in
let outfile = dotfile ^ "." ^ outlang in
let ocamldoc_cmd, oargs = mk_ocamldoc_cmd ?dot_include_all ?dot_types ~project ~outfile:dotfile sourcefiles in
let dot_cmd, dargs = mk_dot_cmd ~outlang ~outfile ~label dotfile in
let viewer = Device.create ?packing () in
let activity_name = "Generating module dependency graph, please wait..." in
Activity.add Activity.Other activity_name;
Spawn.async ~at_exit:begin fun _ ->
let modname = Miscellanea.modname_of_path filename in
let re = kprintf Str.regexp "\"%s\" \\[.*color=\\(.+\\).*\\]" modname in
map_file_lines dotfile begin fun ~lnum ~line ->
if Str.string_match re line 0 then ( sprintf " \"%s\ " [ style = filled , color = black , fontcolor = white];\n " )
if Str.string_match re line 0 then (sprintf "\"%s\" [style=filled, color=black, fillcolor=%s, fontsize=28, shape=box];\n" modname (Str.matched_group 1 line))
else if Str.string_match re1 line 0 then ( sprintf " % s;\n " ( Str.matched_group 1 line ) )
else line
end;
Spawn.async ~at_exit:begin fun _ ->
if Sys.file_exists dotfile then (Sys.remove dotfile);
Device.draw ~filename:outfile viewer;
Activity.remove activity_name;
Gaux.may on_ready_cb ~f:(fun cb -> cb viewer);
end dot_cmd dargs |> ignore;
end ocamldoc_cmd oargs |> ignore;
viewer;;
|
a8731ee446c2938e0c9e9be38230994142dcbaf93ec0fd7c2c136c11608fd479 | dyne/freecoin-lib | core.clj | (ns freecoin-lib.test.core
(:require [midje.sweet :refer :all]
[freecoin-lib
[core :as blockchain]
[schemas :as fc]]
[freecoin-lib.db.freecoin :as db]
[clj-storage.db.mongo :as mongo]
[clj-storage.core :as storage]
[schema.core :as s]
[taoensso.timbre :as log]
[clj-time.core :as t])
(:import [freecoin_lib.core BtcRpc]))
(facts "Validate against schemas"
(fact Created Mongo stores fit the schema
(let [uri "mongodb:27017/some-db"
db (mongo/get-mongo-db uri)
stores-m (db/create-freecoin-stores db)]
(s/validate fc/StoresMap stores-m) => truthy
TODO validate
(blockchain/new-mongo "Testcoin" stores-m) => truthy
(blockchain/new-mongo nil) => (throws Exception)))
(fact Created BTC RPC record validates against the schemas
(let [conf-file (-> "sample-btc-rpc.conf"
(clojure.java.io/resource)
(.getPath))]
(blockchain/new-btc-rpc "FAIR" conf-file) => truthy
(s/validate BtcRpc (blockchain/new-btc-rpc "FAIR" conf-file)) => truthy
(blockchain/new-btc-rpc nil) => (throws Exception))))
(facts "Test internal functions"
(fact "Test the parameter composition for lib requests"
(blockchain/add-transaction-list-params
{:from (t/date-time 2016 11 30)
:to (t/date-time 2016 12 2)})
=> {:timestamp {"$lt" (t/date-time 2016 12 2)
"$gte" (t/date-time 2016 11 30)}}))
| null | https://raw.githubusercontent.com/dyne/freecoin-lib/70eca6858b3765310fdf134378a3026de9adb121/test/freecoin_lib/test/core.clj | clojure | (ns freecoin-lib.test.core
(:require [midje.sweet :refer :all]
[freecoin-lib
[core :as blockchain]
[schemas :as fc]]
[freecoin-lib.db.freecoin :as db]
[clj-storage.db.mongo :as mongo]
[clj-storage.core :as storage]
[schema.core :as s]
[taoensso.timbre :as log]
[clj-time.core :as t])
(:import [freecoin_lib.core BtcRpc]))
(facts "Validate against schemas"
(fact Created Mongo stores fit the schema
(let [uri "mongodb:27017/some-db"
db (mongo/get-mongo-db uri)
stores-m (db/create-freecoin-stores db)]
(s/validate fc/StoresMap stores-m) => truthy
TODO validate
(blockchain/new-mongo "Testcoin" stores-m) => truthy
(blockchain/new-mongo nil) => (throws Exception)))
(fact Created BTC RPC record validates against the schemas
(let [conf-file (-> "sample-btc-rpc.conf"
(clojure.java.io/resource)
(.getPath))]
(blockchain/new-btc-rpc "FAIR" conf-file) => truthy
(s/validate BtcRpc (blockchain/new-btc-rpc "FAIR" conf-file)) => truthy
(blockchain/new-btc-rpc nil) => (throws Exception))))
(facts "Test internal functions"
(fact "Test the parameter composition for lib requests"
(blockchain/add-transaction-list-params
{:from (t/date-time 2016 11 30)
:to (t/date-time 2016 12 2)})
=> {:timestamp {"$lt" (t/date-time 2016 12 2)
"$gte" (t/date-time 2016 11 30)}}))
| |
eeb34f31a6106acbca1fa465733d2aef1ea1ae6232c9be43887e2043a77e934a | janestreet/universe | test.ml | let f x = x
let g x = x
let h x = x
let _ =
(1 |> f) |> (g |> h)
type 'a t = X | F of 'a
let _constr_on_left f = X |> f
let _constr_on_right x = x |> F
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/ppx_pipebang/example/test.ml | ocaml | let f x = x
let g x = x
let h x = x
let _ =
(1 |> f) |> (g |> h)
type 'a t = X | F of 'a
let _constr_on_left f = X |> f
let _constr_on_right x = x |> F
| |
da8ba6f4b1eaef79336e461ce76239d8409a27501f668a442d14176a8845f3ae | Decentralized-Pictures/T4L3NT | delegate_services.mli | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2020 Metastate AG < >
Copyright ( c ) 2021 Nomadic Labs , < >
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
open Alpha_context
val list :
'a #RPC_context.simple ->
'a ->
?active:bool ->
?inactive:bool ->
unit ->
Signature.Public_key_hash.t list shell_tzresult Lwt.t
type info = {
full_balance : Tez.t; (** Balance + Frozen balance *)
current_frozen_deposits : Tez.t;
frozen_deposits : Tez.t;
staking_balance : Tez.t;
frozen_deposits_limit : Tez.t option;
delegated_contracts : Contract.t list;
delegated_balance : Tez.t;
deactivated : bool;
grace_period : Cycle.t;
voting_power : int32;
}
val info_encoding : info Data_encoding.t
val info :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
info shell_tzresult Lwt.t
val full_balance :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Tez.t shell_tzresult Lwt.t
val current_frozen_deposits :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Tez.t shell_tzresult Lwt.t
val frozen_deposits :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Tez.t shell_tzresult Lwt.t
val staking_balance :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Tez.t shell_tzresult Lwt.t
val frozen_deposits_limit :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Tez.t option shell_tzresult Lwt.t
val delegated_contracts :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Contract.t list shell_tzresult Lwt.t
val delegated_balance :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Tez.t shell_tzresult Lwt.t
val deactivated :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
bool shell_tzresult Lwt.t
val grace_period :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Cycle.t shell_tzresult Lwt.t
val voting_power :
'a #RPC_context.simple -> 'a -> public_key_hash -> int32 shell_tzresult Lwt.t
val participation :
'a #RPC_context.simple ->
'a ->
public_key_hash ->
Delegate.participation_info shell_tzresult Lwt.t
val register : unit -> unit
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_alpha/lib_protocol/delegate_services.mli | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
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.
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
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* Balance + Frozen balance | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2020 Metastate AG < >
Copyright ( c ) 2021 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Alpha_context
val list :
'a #RPC_context.simple ->
'a ->
?active:bool ->
?inactive:bool ->
unit ->
Signature.Public_key_hash.t list shell_tzresult Lwt.t
type info = {
current_frozen_deposits : Tez.t;
frozen_deposits : Tez.t;
staking_balance : Tez.t;
frozen_deposits_limit : Tez.t option;
delegated_contracts : Contract.t list;
delegated_balance : Tez.t;
deactivated : bool;
grace_period : Cycle.t;
voting_power : int32;
}
val info_encoding : info Data_encoding.t
val info :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
info shell_tzresult Lwt.t
val full_balance :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Tez.t shell_tzresult Lwt.t
val current_frozen_deposits :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Tez.t shell_tzresult Lwt.t
val frozen_deposits :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Tez.t shell_tzresult Lwt.t
val staking_balance :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Tez.t shell_tzresult Lwt.t
val frozen_deposits_limit :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Tez.t option shell_tzresult Lwt.t
val delegated_contracts :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Contract.t list shell_tzresult Lwt.t
val delegated_balance :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Tez.t shell_tzresult Lwt.t
val deactivated :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
bool shell_tzresult Lwt.t
val grace_period :
'a #RPC_context.simple ->
'a ->
Signature.Public_key_hash.t ->
Cycle.t shell_tzresult Lwt.t
val voting_power :
'a #RPC_context.simple -> 'a -> public_key_hash -> int32 shell_tzresult Lwt.t
val participation :
'a #RPC_context.simple ->
'a ->
public_key_hash ->
Delegate.participation_info shell_tzresult Lwt.t
val register : unit -> unit
|
06031ce5f8887b791b7a3a22dbf545fc088d7b456041386a83b555424c7dae72 | athensresearch/athens | help.cljs | (ns athens.views.help
(:require
["@chakra-ui/react" :refer [Text Heading Box Modal ModalOverlay ModalContent ModalHeader ModalBody ModalCloseButton]]
[athens.util :as util]
[clojure.string :as str]
[re-frame.core :refer [dispatch subscribe]]
[reagent.core :as r]))
;; Helpers to create the help content
;; ==========================
(defn faded-text
[text]
[:> Text {:as "span"
:color "foreground.secondary"
:fontWeight "normal"}
text])
(defn space
[]
[:> Box {:as "i"
:width "0.5em"
:display "inline-block"
:marginInline "0.125em"
:background "currentColor"
:height "1px"
:opacity "0.5"}])
(defn- add-keys
[sequence]
(doall
(for [el sequence]
^{:keys (hash el)}
el)))
(defn example
[template & args]
(let [faded-texts (map #(r/as-element [faded-text %]) args)
space-component (r/as-element [space])
insert-spaces (fn [str-or-vec]
(if (and (string? str-or-vec)
(str/includes? str-or-vec "$space"))
(into [:<>]
(-> str-or-vec
(str/split #"\$space")
(interleave (repeat space-component))
add-keys))
str-or-vec))]
[:> Text {:fontSize "85%"
:fontWeight "bold"
:userSelect "all"
:wordBreak "break-word"}
(as-> template t
(str/split t #"\$text")
(interleave t (concat faded-texts [nil]))
(map insert-spaces t)
(add-keys t)
(into [:<>] t))]))
;; Help content
;; The examples use a small template language to insert the text (opaque) in the examples.
;; $text -> placeholder that will be replaced with opaque text, there can be many. The args passed
;; passed after the template will replace the $text placeholders in order
;; $space -> small utility to render a space symbol.
;; ==========================
(def syntax-groups
[{:name "Bidirectional Link, Block References, and Tags"
:items [{:description "Bidirectional Links"
:example [example "[[$text]]" "Athens"]}
{:description "Labeled Bidirectional Link"
:example [example "[$text][[$text]]" "AS" "Alice Smith"]}
{:description "Block Reference"
:example [example "(($text))" "Block ID"]}
{:description "Labeled Block Reference"
:example [example "[$text](($text))" "Block text" "Block ID"]}
{:description "Tag"
:example [example "#$text" "Athens"]}
{:description "Tagged Link"
:example [example "#[[$text]]" "Athens"]}]}
{:name "Embeds"
:items [{:description "Block"
:example [example "{{[[embed]]:(($text))}}" "reference to a block on a page"]}
{:description "Image by URL"
:example [example "" "Athens Logo" ""]}
{:description "Youtube Video"
:example [example "{{[[youtube]]:$text]]}}" "/..."]}
{:description "Web Page"
:example [example "{{iframe:<iframe src=\"$text\"></iframe>}}" "/"]}
{:description "Checkbox"
:example [example "{{[[TODO]]}}$space$text" "Label"]}]}
{:name "Markdown Formatting"
:items [{:description "Labeled Link"
:example [example "[$text]($text)" "Athens" "/"]}
{:description "Link"
:example [example "<$text>" "/"]}
{:description "LaTeX"
:example [example "$$$text$$" "Your equation or mathematical symbol"]}
{:description "Inline code"
:example [example "`$text`" "Inline Code"]}
{:description "Highlight"
:example [example "^^$text^^" "Athens"]}
{:description "Italicize"
:example [example "__$text__" "Athens"]}
{:description "Bold"
:example [example "**$text**" "Athens"]}
{:description "Underline"
:example [example "--$text--" "Athens"]}
{:description "Strikethrough"
:example [example "~~$text~~" "Athens"]}
{:description "Heading level 1"
:example [example "#$space$text" "Athens"]}
{:description "Heading level 2"
:example [example "##$space$text" "Athens"]}
{:description "Heading level 3"
:example [example "###$space$text" "Athens"]}
{:description "Heading level 4"
:example [example "####$space$text" "Athens"]}
{:description "Heading level 5"
:example [example "#####$space$text" "Athens"]}
{:description "Heading level 6"
:example [example "######$space$text" "Athens"]}]}])
(def shortcut-groups
[{:name "App"
:items [{:description "Toggle Search"
:shortcut "mod+k"}
{:description "Toggle Left Sidebar"
:shortcut "mod+\\"}
{:description "Toggle Right Sidebar"
:shortcut "mod+shift+\\"}
{:description "Increase Text Size"
:shortcut "mod+plus"}
{:description "Decrease Text Size"
:shortcut "mod+minus"}
{:description "Reset Text Size"
:shortcut "mod+0"}]}
{:name "Input"
:items [{:description "Autocomplete Menu"
:shortcut "/"}
{:description "Indent selected block"
:shortcut "tab"}
{:description "Unindent selected block"
:shortcut "shift+tab"}
{:description "Undo"
:shortcut "mod+z"}
{:description "Redo"
:shortcut "mod+shift+z"}
{:description "Copy"
:shortcut "mod+c"}
{:description "Paste"
:shortcut "mod+v"}
{:description "Paste without formatting"
:shortcut "mod+shift+v"}
{:description "Convert to checkbox"
:shortcut "mod+enter"}]}
{:name "Navigation"
:items [{:description "Zoom into current block"
:shortcut "mod+o"}
{:description "Zoom out of current block"
:shortcut "mod+alt+o"}
{:description "Open page or block link"
:shortcut "mod+o"}
{:description "Fold block"
:shortcut "mod+up"}
{:description "Unfold block"
:shortcut "mod+down"}]}
{:name "Selection"
:items [{:description "Select previous block"
:shortcut "shift+up"}
{:description "Select next block"
:shortcut "shift+down"}
{:description "Select all blocks"
:shortcut "mod+a"}]}
{:name "Formatting"
:items [{:description "Bold"
:example [:strong "Athens"]
:shortcut "mod+b"}
{:description "Italics"
:example [:i "Athens"]
:shortcut "mod+i"}
;; Underline is currently not working. Uncomment when it does.
;; {:description "Underline"
: example [: span ( use - style { : text - decoration " underline " } ) " Athens " ]
;; :shortcut "mod+u"}
{:description "Strikethrough"
:example [:> Text {:as "span" :textDecoration "line-through"} "Athens"]
:shortcut "mod+y"}
{:description "Highlight"
:example [:> Text {:as "span"
:background "highlight"
:color "highlightContrast"
:borderRadius "0.1rem"
:padding "0 0.125em"}
"Athens"]
:shortcut "mod+h"}]}
{:name "Graph"
:items [{:description "Open Node in Sidebar"
:shortcut "shift+click"}
{:description "Move Node"
:shortcut "click+drag"}
{:description "Zoom in/out"
:shortcut "scroll up/down"}]}])
(def content
[{:name "Syntax",
:groups syntax-groups}
{:name "Keyboard Shortcuts"
:groups shortcut-groups}])
;; Components to render content
;; =============================
(def mod-key
(if (util/is-mac?) "⌘" "CTRL"))
(def alt-key
(if (util/is-mac?) "⌥" "Alt"))
(defn shortcut
[shortcut-str]
(let [key-to-display (fn [key]
(-> key
(str/replace #"mod" mod-key)
(str/replace #"alt" alt-key)
(str/replace #"shift" "⇧")
(str/replace #"minus" "-")
(str/replace #"plus" "+")))
keys (as-> shortcut-str s
(str/split s #"\+")
(map key-to-display s))]
[:> Box {:display "flex"
:alignItems "center"
:gap "0.3rem"}
(doall
(for [key keys]
^{:key key}
[:> Text {:fontFamily "inherit"
:display "inline-flex"
:gap "0.3em"
:textTransform "uppercase"
:fontSize "0.8em"
:paddingInline "0.35em"
:background "background.basement"
:borderRadius "0.25rem"
:fontWeight 600}
key]))]))
(defn help-section
[title & children]
[:> Box {:as "section"}
[:> Heading {:as "h2"
:color "foreground.primary"
:textTransform "uppercase"
:letterSpacing "0.06rem"
:margin 0
:font-weight 600
:font-size "100%"
:padding "1rem 1.5rem"}
title]
(doall
(for [child children]
^{:key (hash child)}
child))])
(defn help-section-group
[title & children]
[:> Box {:display "grid"
:padding "1.5rem"
:gridTemplateColumns "12rem 1fr"
:columnGap "1rem"
:borderTop "1px solid"
:borderColor "separator.divider"}
[:> Heading {:fontSize "1.5em"
:as "h3"
:margin 0
:font-weight "bold"}
title]
[:div
(doall
(for [child children]
^{:key (hash child)}
child))]])
(defn help-item
[item]
[:> Box {:borderRadius "0.5rem"
:alignItems "center"
:display "grid"
:gap "1rem"
:gridTemplateColumns "12rem 1fr"
:padding "0.25rem 0.5rem"
:sx {"&:nth-of-type(odd)"
{:bg "background.floor"}}}
[:> Text {:display "flex"
:justify-content "space-between"}
;; Position of the example changes if there is a shortcut or not.
(:description item)
(when (contains? item :shortcut)
(:example item))]
(when (not (contains? item :shortcut))
(:example item))
(when (contains? item :shortcut)
[shortcut (:shortcut item)])])
(defn help-popup
[]
(r/with-let [open? (subscribe [:help/open?])
close #(dispatch [:help/toggle])]
[:> Modal {:isOpen @open?
:onClose close
:scrollBehavior "outside"
:size "full"}
[:> ModalOverlay]
[:> ModalContent {:maxWidth "calc(100% - 8rem)"
:width "max-content"
:my "4rem"}
[:> ModalHeader "Help"
[:> ModalCloseButton]]
[:> ModalBody {:flexDirection "column"}
(doall
(for [section content]
^{:key section}
[help-section (:name section)
(doall
(for [group (:groups section)]
^{:key group}
[help-section-group (:name group)
(doall
(for [item (:items group)]
^{:key item}
[help-item item]))]))]))]]]))
| null | https://raw.githubusercontent.com/athensresearch/athens/73cb4fa8f88f0730e2fe7a0d38505493b96f4d4b/src/cljs/athens/views/help.cljs | clojure | Helpers to create the help content
==========================
Help content
The examples use a small template language to insert the text (opaque) in the examples.
$text -> placeholder that will be replaced with opaque text, there can be many. The args passed
passed after the template will replace the $text placeholders in order
$space -> small utility to render a space symbol.
==========================
Underline is currently not working. Uncomment when it does.
{:description "Underline"
:shortcut "mod+u"}
Components to render content
=============================
Position of the example changes if there is a shortcut or not. | (ns athens.views.help
(:require
["@chakra-ui/react" :refer [Text Heading Box Modal ModalOverlay ModalContent ModalHeader ModalBody ModalCloseButton]]
[athens.util :as util]
[clojure.string :as str]
[re-frame.core :refer [dispatch subscribe]]
[reagent.core :as r]))
(defn faded-text
[text]
[:> Text {:as "span"
:color "foreground.secondary"
:fontWeight "normal"}
text])
(defn space
[]
[:> Box {:as "i"
:width "0.5em"
:display "inline-block"
:marginInline "0.125em"
:background "currentColor"
:height "1px"
:opacity "0.5"}])
(defn- add-keys
[sequence]
(doall
(for [el sequence]
^{:keys (hash el)}
el)))
(defn example
[template & args]
(let [faded-texts (map #(r/as-element [faded-text %]) args)
space-component (r/as-element [space])
insert-spaces (fn [str-or-vec]
(if (and (string? str-or-vec)
(str/includes? str-or-vec "$space"))
(into [:<>]
(-> str-or-vec
(str/split #"\$space")
(interleave (repeat space-component))
add-keys))
str-or-vec))]
[:> Text {:fontSize "85%"
:fontWeight "bold"
:userSelect "all"
:wordBreak "break-word"}
(as-> template t
(str/split t #"\$text")
(interleave t (concat faded-texts [nil]))
(map insert-spaces t)
(add-keys t)
(into [:<>] t))]))
(def syntax-groups
[{:name "Bidirectional Link, Block References, and Tags"
:items [{:description "Bidirectional Links"
:example [example "[[$text]]" "Athens"]}
{:description "Labeled Bidirectional Link"
:example [example "[$text][[$text]]" "AS" "Alice Smith"]}
{:description "Block Reference"
:example [example "(($text))" "Block ID"]}
{:description "Labeled Block Reference"
:example [example "[$text](($text))" "Block text" "Block ID"]}
{:description "Tag"
:example [example "#$text" "Athens"]}
{:description "Tagged Link"
:example [example "#[[$text]]" "Athens"]}]}
{:name "Embeds"
:items [{:description "Block"
:example [example "{{[[embed]]:(($text))}}" "reference to a block on a page"]}
{:description "Image by URL"
:example [example "" "Athens Logo" ""]}
{:description "Youtube Video"
:example [example "{{[[youtube]]:$text]]}}" "/..."]}
{:description "Web Page"
:example [example "{{iframe:<iframe src=\"$text\"></iframe>}}" "/"]}
{:description "Checkbox"
:example [example "{{[[TODO]]}}$space$text" "Label"]}]}
{:name "Markdown Formatting"
:items [{:description "Labeled Link"
:example [example "[$text]($text)" "Athens" "/"]}
{:description "Link"
:example [example "<$text>" "/"]}
{:description "LaTeX"
:example [example "$$$text$$" "Your equation or mathematical symbol"]}
{:description "Inline code"
:example [example "`$text`" "Inline Code"]}
{:description "Highlight"
:example [example "^^$text^^" "Athens"]}
{:description "Italicize"
:example [example "__$text__" "Athens"]}
{:description "Bold"
:example [example "**$text**" "Athens"]}
{:description "Underline"
:example [example "--$text--" "Athens"]}
{:description "Strikethrough"
:example [example "~~$text~~" "Athens"]}
{:description "Heading level 1"
:example [example "#$space$text" "Athens"]}
{:description "Heading level 2"
:example [example "##$space$text" "Athens"]}
{:description "Heading level 3"
:example [example "###$space$text" "Athens"]}
{:description "Heading level 4"
:example [example "####$space$text" "Athens"]}
{:description "Heading level 5"
:example [example "#####$space$text" "Athens"]}
{:description "Heading level 6"
:example [example "######$space$text" "Athens"]}]}])
(def shortcut-groups
[{:name "App"
:items [{:description "Toggle Search"
:shortcut "mod+k"}
{:description "Toggle Left Sidebar"
:shortcut "mod+\\"}
{:description "Toggle Right Sidebar"
:shortcut "mod+shift+\\"}
{:description "Increase Text Size"
:shortcut "mod+plus"}
{:description "Decrease Text Size"
:shortcut "mod+minus"}
{:description "Reset Text Size"
:shortcut "mod+0"}]}
{:name "Input"
:items [{:description "Autocomplete Menu"
:shortcut "/"}
{:description "Indent selected block"
:shortcut "tab"}
{:description "Unindent selected block"
:shortcut "shift+tab"}
{:description "Undo"
:shortcut "mod+z"}
{:description "Redo"
:shortcut "mod+shift+z"}
{:description "Copy"
:shortcut "mod+c"}
{:description "Paste"
:shortcut "mod+v"}
{:description "Paste without formatting"
:shortcut "mod+shift+v"}
{:description "Convert to checkbox"
:shortcut "mod+enter"}]}
{:name "Navigation"
:items [{:description "Zoom into current block"
:shortcut "mod+o"}
{:description "Zoom out of current block"
:shortcut "mod+alt+o"}
{:description "Open page or block link"
:shortcut "mod+o"}
{:description "Fold block"
:shortcut "mod+up"}
{:description "Unfold block"
:shortcut "mod+down"}]}
{:name "Selection"
:items [{:description "Select previous block"
:shortcut "shift+up"}
{:description "Select next block"
:shortcut "shift+down"}
{:description "Select all blocks"
:shortcut "mod+a"}]}
{:name "Formatting"
:items [{:description "Bold"
:example [:strong "Athens"]
:shortcut "mod+b"}
{:description "Italics"
:example [:i "Athens"]
:shortcut "mod+i"}
: example [: span ( use - style { : text - decoration " underline " } ) " Athens " ]
{:description "Strikethrough"
:example [:> Text {:as "span" :textDecoration "line-through"} "Athens"]
:shortcut "mod+y"}
{:description "Highlight"
:example [:> Text {:as "span"
:background "highlight"
:color "highlightContrast"
:borderRadius "0.1rem"
:padding "0 0.125em"}
"Athens"]
:shortcut "mod+h"}]}
{:name "Graph"
:items [{:description "Open Node in Sidebar"
:shortcut "shift+click"}
{:description "Move Node"
:shortcut "click+drag"}
{:description "Zoom in/out"
:shortcut "scroll up/down"}]}])
(def content
[{:name "Syntax",
:groups syntax-groups}
{:name "Keyboard Shortcuts"
:groups shortcut-groups}])
(def mod-key
(if (util/is-mac?) "⌘" "CTRL"))
(def alt-key
(if (util/is-mac?) "⌥" "Alt"))
(defn shortcut
[shortcut-str]
(let [key-to-display (fn [key]
(-> key
(str/replace #"mod" mod-key)
(str/replace #"alt" alt-key)
(str/replace #"shift" "⇧")
(str/replace #"minus" "-")
(str/replace #"plus" "+")))
keys (as-> shortcut-str s
(str/split s #"\+")
(map key-to-display s))]
[:> Box {:display "flex"
:alignItems "center"
:gap "0.3rem"}
(doall
(for [key keys]
^{:key key}
[:> Text {:fontFamily "inherit"
:display "inline-flex"
:gap "0.3em"
:textTransform "uppercase"
:fontSize "0.8em"
:paddingInline "0.35em"
:background "background.basement"
:borderRadius "0.25rem"
:fontWeight 600}
key]))]))
(defn help-section
[title & children]
[:> Box {:as "section"}
[:> Heading {:as "h2"
:color "foreground.primary"
:textTransform "uppercase"
:letterSpacing "0.06rem"
:margin 0
:font-weight 600
:font-size "100%"
:padding "1rem 1.5rem"}
title]
(doall
(for [child children]
^{:key (hash child)}
child))])
(defn help-section-group
[title & children]
[:> Box {:display "grid"
:padding "1.5rem"
:gridTemplateColumns "12rem 1fr"
:columnGap "1rem"
:borderTop "1px solid"
:borderColor "separator.divider"}
[:> Heading {:fontSize "1.5em"
:as "h3"
:margin 0
:font-weight "bold"}
title]
[:div
(doall
(for [child children]
^{:key (hash child)}
child))]])
(defn help-item
[item]
[:> Box {:borderRadius "0.5rem"
:alignItems "center"
:display "grid"
:gap "1rem"
:gridTemplateColumns "12rem 1fr"
:padding "0.25rem 0.5rem"
:sx {"&:nth-of-type(odd)"
{:bg "background.floor"}}}
[:> Text {:display "flex"
:justify-content "space-between"}
(:description item)
(when (contains? item :shortcut)
(:example item))]
(when (not (contains? item :shortcut))
(:example item))
(when (contains? item :shortcut)
[shortcut (:shortcut item)])])
(defn help-popup
[]
(r/with-let [open? (subscribe [:help/open?])
close #(dispatch [:help/toggle])]
[:> Modal {:isOpen @open?
:onClose close
:scrollBehavior "outside"
:size "full"}
[:> ModalOverlay]
[:> ModalContent {:maxWidth "calc(100% - 8rem)"
:width "max-content"
:my "4rem"}
[:> ModalHeader "Help"
[:> ModalCloseButton]]
[:> ModalBody {:flexDirection "column"}
(doall
(for [section content]
^{:key section}
[help-section (:name section)
(doall
(for [group (:groups section)]
^{:key group}
[help-section-group (:name group)
(doall
(for [item (:items group)]
^{:key item}
[help-item item]))]))]))]]]))
|
fb911723f5e0066e14efa68ae7ee56ff7f360be86608257d2043c950ed7ff02b | BekaValentine/SimpleFP-v2 | Unification.hs | {-# OPTIONS -Wall #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE UndecidableInstances #
-- | This module defines unification of dependent types.
module OpenDefs.Unification.Unification where
import Utils.ABT
import Utils.Elaborator
import Utils.Names
import Utils.Pretty
import Utils.Telescope
import Utils.Unifier
import OpenDefs.Core.Term
import OpenDefs.Unification.Elaborator
import Control.Monad.Except
-- | Equating terms by trivial structural equations.
instance MonadUnify TermF Elaborator where
equate (Defined n1) (Defined n2) =
if n1 == n2
then return []
else throwError $ "Mismatching names "
++ showName n1 ++ " and " ++ showName n2
equate (Ann m1 t1) (Ann m2 t2) =
return [ Equation (instantiate0 m1) (instantiate0 m2)
, Equation (instantiate0 t1) (instantiate0 t2)
]
equate Type Type =
return []
equate (Fun plic1 a1 sc1) (Fun plic2 a2 sc2) =
do unless (plic1 == plic2)
$ throwError $ "Mismatching plicities when unifying "
++ pretty (In (Fun plic1 a1 sc1)) ++ " with "
++ pretty (In (Fun plic2 a2 sc2))
ns <- freshRelTo (names sc1) context
let xs = map (Var . Free) ns
return [ Equation (instantiate0 a1) (instantiate0 a2)
, Equation (instantiate sc1 xs) (instantiate sc2 xs)
]
equate (Lam plic1 sc1) (Lam plic2 sc2) =
do unless (plic1 == plic2)
$ throwError $ "Mismatching plicities when unifying "
++ pretty (In (Lam plic1 sc1)) ++ " with "
++ pretty (In (Lam plic2 sc2))
ns <- freshRelTo (names sc1) context
let xs = map (Var . Free) ns
return [ Equation (instantiate sc1 xs) (instantiate sc2 xs) ]
equate (App plic1 f1 a1) (App plic2 f2 a2) =
do unless (plic1 == plic2)
$ throwError $ "Mismatching plicities when unifying "
++ pretty (In (App plic1 f1 a1)) ++ " with "
++ pretty (In (App plic2 f2 a2))
return [ Equation (instantiate0 f1) (instantiate0 f2)
, Equation (instantiate0 a1) (instantiate0 a2)
]
equate (Con c1 as1) (Con c2 as2) =
do unless (c1 == c2)
$ throwError $ "Mismatching constructors "
++ showName c1 ++ " and " ++ showName c2
unless (length as1 == length as2)
$ throwError $ "Mismatching constructor arg lengths between "
++ pretty (In (Con c1 as1)) ++ " and "
++ pretty (In (Con c2 as1))
let (plics1,as1') = unzip as1
(plics2,as2') = unzip as2
unless (plics1 == plics2)
$ throwError $ "Mismatching plicities when unifying "
++ pretty (In (Con c1 as1)) ++ " with "
++ pretty (In (Con c2 as2))
return $ zipWith
Equation
(map instantiate0 as1')
(map instantiate0 as2')
equate (Case as1 mot1 cs1) (Case as2 mot2 cs2) =
do unless (length as1 == length as2)
$ throwError $ "Mismatching number of case arguments in "
++ pretty (In (Case as1 mot1 cs1)) ++ " and "
++ pretty (In (Case as2 mot2 cs2))
unless (length cs1 == length cs2)
$ throwError $ "Mismatching number of clauses in "
++ pretty (In (Case as1 mot1 cs1)) ++ " and "
++ pretty (In (Case as2 mot2 cs2))
let argEqs = zipWith
Equation
(map instantiate0 as1)
(map instantiate0 as2)
motEqs <- equateCaseMotive mot1 mot2
clauseEqs <- fmap concat $ zipWithM equateClause cs1 cs2
return $ argEqs ++ motEqs ++ clauseEqs
equate (RecordType fields1 tele1) (RecordType fields2 tele2) =
do unless (fields1 == fields2)
$ throwError $ "Record types have different field names: "
++ pretty (In (RecordType fields1 tele1))
++ " and "
++ pretty (In (RecordType fields2 tele2))
ns <- freshRelTo (namesTelescope tele1) context
let xs = map (Var . Free) ns
as1 = instantiateTelescope tele1 xs
as2 = instantiateTelescope tele2 xs
unless (length as1 == length as2)
$ throwError $ "Records have different number of fields: "
++ pretty (In (RecordType fields1 tele1))
++ " and "
++ pretty (In (RecordType fields2 tele2))
return $ zipWith Equation as1 as2
equate (RecordCon fields1) (RecordCon fields2) =
do unless (length fields1 == length fields2)
$ throwError $ "Records have different number of fields: "
++ pretty (In (RecordCon fields1))
++ " and "
++ pretty (In (RecordCon fields2))
let (fs1,ms1) = unzip fields1
(fs2,ms2) = unzip fields2
unless (fs1 == fs2)
$ throwError $ "Records have different field names: "
++ pretty (In (RecordCon fields1))
++ " and "
++ pretty (In (RecordCon fields2))
return $ zipWith
Equation
(map instantiate0 ms1)
(map instantiate0 ms2)
equate (RecordProj r1 x1) (RecordProj r2 x2) =
do unless (x1 == x2)
$ throwError $ "Record projections have different names: "
++ pretty (In (RecordProj r1 x1))
++ " and "
++ pretty (In (RecordProj r2 x2))
return [Equation (instantiate0 r1) (instantiate0 r2)]
equate l r =
throwError $ "Cannot unify " ++ pretty (In l) ++ " with " ++ pretty (In r)
-- | Equating case motives as a special helper for the main 'equate' method.
equateCaseMotive :: CaseMotive -> CaseMotive -> Elaborator [Equation Term]
equateCaseMotive mot1@(CaseMotive tele1) mot2@(CaseMotive tele2) =
do ns <- freshRelTo (namesBindingTelescope tele1) context
let xs = map (Var . Free) ns
(as1, b1) = instantiateBindingTelescope tele1 xs
(as2, b2) = instantiateBindingTelescope tele2 xs
unless (length as1 == length as2)
$ throwError $ "Motives not equal: " ++ pretty mot1 ++ " and "
++ pretty mot2
return $ zipWith Equation as1 as2 ++ [ Equation b1 b2 ]
-- Equating clauses as a special helper for the main 'equate' method.
equateClause :: Clause -> Clause -> Elaborator [Equation Term]
equateClause (Clause pscs1 sc1) (Clause pscs2 sc2) =
do unless (length pscs1 == length pscs2)
$ throwError "Clauses have different numbers of patterns."
unless (length (names sc1) == length (names sc2))
$ throwError "Patterns bind different numbers of arguments."
ns <- freshRelTo (names sc1) context
let xs = map (Var . Free) ns
xs' = map (Var . Free) ns
ps1 = map (\sc -> patternInstantiate sc xs xs') pscs1
ps2 = map (\sc -> patternInstantiate sc xs xs') pscs2
b1 = instantiate sc1 xs'
b2 = instantiate sc2 xs'
case sequence (zipWith zipABTF ps1 ps2) of
Nothing ->
throwError "Patterns are not equal."
Just pEqss ->
return $ [ Equation a1 a2 | (a1,a2) <- concat pEqss ]
++ [ Equation b1 b2 ] | null | https://raw.githubusercontent.com/BekaValentine/SimpleFP-v2/ae00ec809caefcd13664395b0ae2fc66145f6a74/src/OpenDefs/Unification/Unification.hs | haskell | # OPTIONS -Wall #
# LANGUAGE TypeSynonymInstances #
| This module defines unification of dependent types.
| Equating terms by trivial structural equations.
| Equating case motives as a special helper for the main 'equate' method.
Equating clauses as a special helper for the main 'equate' method. | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
module OpenDefs.Unification.Unification where
import Utils.ABT
import Utils.Elaborator
import Utils.Names
import Utils.Pretty
import Utils.Telescope
import Utils.Unifier
import OpenDefs.Core.Term
import OpenDefs.Unification.Elaborator
import Control.Monad.Except
instance MonadUnify TermF Elaborator where
equate (Defined n1) (Defined n2) =
if n1 == n2
then return []
else throwError $ "Mismatching names "
++ showName n1 ++ " and " ++ showName n2
equate (Ann m1 t1) (Ann m2 t2) =
return [ Equation (instantiate0 m1) (instantiate0 m2)
, Equation (instantiate0 t1) (instantiate0 t2)
]
equate Type Type =
return []
equate (Fun plic1 a1 sc1) (Fun plic2 a2 sc2) =
do unless (plic1 == plic2)
$ throwError $ "Mismatching plicities when unifying "
++ pretty (In (Fun plic1 a1 sc1)) ++ " with "
++ pretty (In (Fun plic2 a2 sc2))
ns <- freshRelTo (names sc1) context
let xs = map (Var . Free) ns
return [ Equation (instantiate0 a1) (instantiate0 a2)
, Equation (instantiate sc1 xs) (instantiate sc2 xs)
]
equate (Lam plic1 sc1) (Lam plic2 sc2) =
do unless (plic1 == plic2)
$ throwError $ "Mismatching plicities when unifying "
++ pretty (In (Lam plic1 sc1)) ++ " with "
++ pretty (In (Lam plic2 sc2))
ns <- freshRelTo (names sc1) context
let xs = map (Var . Free) ns
return [ Equation (instantiate sc1 xs) (instantiate sc2 xs) ]
equate (App plic1 f1 a1) (App plic2 f2 a2) =
do unless (plic1 == plic2)
$ throwError $ "Mismatching plicities when unifying "
++ pretty (In (App plic1 f1 a1)) ++ " with "
++ pretty (In (App plic2 f2 a2))
return [ Equation (instantiate0 f1) (instantiate0 f2)
, Equation (instantiate0 a1) (instantiate0 a2)
]
equate (Con c1 as1) (Con c2 as2) =
do unless (c1 == c2)
$ throwError $ "Mismatching constructors "
++ showName c1 ++ " and " ++ showName c2
unless (length as1 == length as2)
$ throwError $ "Mismatching constructor arg lengths between "
++ pretty (In (Con c1 as1)) ++ " and "
++ pretty (In (Con c2 as1))
let (plics1,as1') = unzip as1
(plics2,as2') = unzip as2
unless (plics1 == plics2)
$ throwError $ "Mismatching plicities when unifying "
++ pretty (In (Con c1 as1)) ++ " with "
++ pretty (In (Con c2 as2))
return $ zipWith
Equation
(map instantiate0 as1')
(map instantiate0 as2')
equate (Case as1 mot1 cs1) (Case as2 mot2 cs2) =
do unless (length as1 == length as2)
$ throwError $ "Mismatching number of case arguments in "
++ pretty (In (Case as1 mot1 cs1)) ++ " and "
++ pretty (In (Case as2 mot2 cs2))
unless (length cs1 == length cs2)
$ throwError $ "Mismatching number of clauses in "
++ pretty (In (Case as1 mot1 cs1)) ++ " and "
++ pretty (In (Case as2 mot2 cs2))
let argEqs = zipWith
Equation
(map instantiate0 as1)
(map instantiate0 as2)
motEqs <- equateCaseMotive mot1 mot2
clauseEqs <- fmap concat $ zipWithM equateClause cs1 cs2
return $ argEqs ++ motEqs ++ clauseEqs
equate (RecordType fields1 tele1) (RecordType fields2 tele2) =
do unless (fields1 == fields2)
$ throwError $ "Record types have different field names: "
++ pretty (In (RecordType fields1 tele1))
++ " and "
++ pretty (In (RecordType fields2 tele2))
ns <- freshRelTo (namesTelescope tele1) context
let xs = map (Var . Free) ns
as1 = instantiateTelescope tele1 xs
as2 = instantiateTelescope tele2 xs
unless (length as1 == length as2)
$ throwError $ "Records have different number of fields: "
++ pretty (In (RecordType fields1 tele1))
++ " and "
++ pretty (In (RecordType fields2 tele2))
return $ zipWith Equation as1 as2
equate (RecordCon fields1) (RecordCon fields2) =
do unless (length fields1 == length fields2)
$ throwError $ "Records have different number of fields: "
++ pretty (In (RecordCon fields1))
++ " and "
++ pretty (In (RecordCon fields2))
let (fs1,ms1) = unzip fields1
(fs2,ms2) = unzip fields2
unless (fs1 == fs2)
$ throwError $ "Records have different field names: "
++ pretty (In (RecordCon fields1))
++ " and "
++ pretty (In (RecordCon fields2))
return $ zipWith
Equation
(map instantiate0 ms1)
(map instantiate0 ms2)
equate (RecordProj r1 x1) (RecordProj r2 x2) =
do unless (x1 == x2)
$ throwError $ "Record projections have different names: "
++ pretty (In (RecordProj r1 x1))
++ " and "
++ pretty (In (RecordProj r2 x2))
return [Equation (instantiate0 r1) (instantiate0 r2)]
equate l r =
throwError $ "Cannot unify " ++ pretty (In l) ++ " with " ++ pretty (In r)
equateCaseMotive :: CaseMotive -> CaseMotive -> Elaborator [Equation Term]
equateCaseMotive mot1@(CaseMotive tele1) mot2@(CaseMotive tele2) =
do ns <- freshRelTo (namesBindingTelescope tele1) context
let xs = map (Var . Free) ns
(as1, b1) = instantiateBindingTelescope tele1 xs
(as2, b2) = instantiateBindingTelescope tele2 xs
unless (length as1 == length as2)
$ throwError $ "Motives not equal: " ++ pretty mot1 ++ " and "
++ pretty mot2
return $ zipWith Equation as1 as2 ++ [ Equation b1 b2 ]
equateClause :: Clause -> Clause -> Elaborator [Equation Term]
equateClause (Clause pscs1 sc1) (Clause pscs2 sc2) =
do unless (length pscs1 == length pscs2)
$ throwError "Clauses have different numbers of patterns."
unless (length (names sc1) == length (names sc2))
$ throwError "Patterns bind different numbers of arguments."
ns <- freshRelTo (names sc1) context
let xs = map (Var . Free) ns
xs' = map (Var . Free) ns
ps1 = map (\sc -> patternInstantiate sc xs xs') pscs1
ps2 = map (\sc -> patternInstantiate sc xs xs') pscs2
b1 = instantiate sc1 xs'
b2 = instantiate sc2 xs'
case sequence (zipWith zipABTF ps1 ps2) of
Nothing ->
throwError "Patterns are not equal."
Just pEqss ->
return $ [ Equation a1 a2 | (a1,a2) <- concat pEqss ]
++ [ Equation b1 b2 ] |
a2663195a89266780bbf035f6779d92592bec182299cba5d06e29e8eb1acb0d2 | alex-gutev/generic-cl | arithmetic.lisp | ;;;; arithmetic.lisp
;;;;
Copyright 2018 - 2021
;;;;
;;;; 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.
;;;; Unit tests for arithmetic functions
(in-package :generic-cl/test)
;;; Test Suite Definition
(def-suite arithmetic
:description "Test arithmetic functions"
:in generic-cl)
(in-suite arithmetic)
;;; Tests
(test number-add
"Test ADD on numbers"
(is (= 3 (add 1 2)))
(signals error (add 1 'x)))
(test-nary number +
(is (= 0 (+)))
(is (= 2 (+ 2)))
(is (= 10 (+ 1 2 3 4))))
(test number-subtract
"Test SUBTRACT on numbers"
(is (= -1 (subtract 3 4)))
(signals error (subtract 3 "z")))
(test-nary number -
(is (= -3 (- 3)))
(is (= -2 (- 5 4 3))))
(test number-multiply
"Test MULTIPLY on numbers"
(is (= 8 (multiply 2 4)))
(signals error (multiply 4 #\a)))
(test-nary number *
(is (= 1 (*)))
(is (= 3 (* 3)))
(is (= 120 (* 2 3 4 5))))
(test number-divide
"Test DIVIDE on numbers"
(is (= 2 (divide 6 3)))
(signals error (divide 'a 'b)))
(test-nary number /
(is (= 1/5 (/ 5)))
(is (= 1 (/ 6 3 2))))
(test number-negate
"Test NEGATE on numbers"
(is (= -4 (negate 4)))
(signals error (negate 'x)))
(test number-increments
"Test 1+, 1-, INCF and DECF on numbers"
(is (= 5 (1+ 4)))
(is (= 7 (1- 8)))
(let ((x 2))
(is (= 3 (incf x)))
(is (= 3 x))
(is (= 7 (incf x 4)))
(is (= 7 x)))
(let ((x 6))
(is (= 5 (decf x)))
(is (= 5 x))
(is (= 2 (decf x 3)))
(is (= 2 x))))
(test number-minusp
"Test MINUSP on numbers"
(is-true (minusp -5))
(is-true (minusp -1))
(is-false (minusp 0))
(is-false (minusp 3)))
(test number-plusp
"Test PLUSP on numbers"
(is-true (plusp 5))
(is-true (plusp 1))
(is-false (plusp 0))
(is-false (plusp -3)))
(test number-zerop
"Test ZEROP on numbers"
(is-true (zerop 0))
(is-false (zerop -1))
(is-false (zerop 5)))
(test number-signum
"Test SIGNUM on numbers"
(is (= 1 (signum 3)))
(is (= -1 (signum -1)))
(is (= 0 (signum 0))))
(test number-abs
"Test ABS on numbers"
(is (= 10 (abs 10)))
(is (= 0 (abs 0)))
(is (= 3 (abs -3))))
(test number-evenp
"Test EVENP on numbers"
(is-true (evenp 2))
(is-true (evenp 10))
(is-true (evenp 0))
(is-true (evenp -4))
(is-false (evenp 5))
(is-false (evenp -3)))
(test number-oddp
"Test ODDP on numbers"
(is-true (oddp 3))
(is-true (oddp 7))
(is-true (oddp -5))
(is-false (oddp 0))
(is-false (oddp 4))
(is-false (oddp -6)))
(test number-floor
"Test FLOOR on numbers"
(is (= 3 (floor 3.0222)))
(is (= -4 (floor -3.0222)))
(is (= '(3 1) (multiple-value-list (floor 10 3))))
(is (= '(-4 2) (multiple-value-list (floor -10 3)))))
(test number-ceiling
"Test CEILING on numbers"
(is (= 4 (ceiling 3.0222)))
(is (= -3 (ceiling -3.0222)))
(is (= '(4 -2) (multiple-value-list (ceiling 10 3))))
(is (= '(-3 -1) (multiple-value-list (ceiling -10 3)))))
(test number-truncate
"Test TRUNCATE on numbers"
(is (= 3 (truncate 3.0222)))
(is (= -3 (truncate -3.0222)))
(is (= '(3 1) (multiple-value-list (truncate 10 3))))
(is (= '(-3 -1) (multiple-value-list (truncate -10 3)))))
(test number-round
"Test ROUND on numbers"
(is (= 3 (round 3.0222)))
(is (= -3 (round -3.0222)))
(is (= 4 (round 3.7222)))
(is (= -4 (round -3.7222)))
(is (= 4 (round 4.5)))
(is (= -4 (round -4.5)))
(is (= 2 (round 1.5)))
(is (= -2 (round -1.5)))
(is (= '(3 1) (multiple-value-list (round 10 3))))
(is (= '(-3 -1) (multiple-value-list (round -10 3))))
(is (= '(2 1) (multiple-value-list (round 5 2))))
(is (= '(-2 -1) (multiple-value-list (round -5 2)))))
(test number-mod
"Test MOD on numbers"
(is (= 2 (mod 5 3)))
(is (= 1 (mod -5 3))))
(test number-rem
"Test REM on numbers"
(is (= 2 (rem 5 3)))
(is (= -2 (rem -5 3))))
| null | https://raw.githubusercontent.com/alex-gutev/generic-cl/1a49eb43a2212689dba292fb1ee4ddf191153fe5/test/arithmetic.lisp | lisp | arithmetic.lisp
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
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.
Unit tests for arithmetic functions
Test Suite Definition
Tests | Copyright 2018 - 2021
files ( the " Software " ) , to deal in the Software without
copies of the Software , and to permit persons to whom the
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
(in-package :generic-cl/test)
(def-suite arithmetic
:description "Test arithmetic functions"
:in generic-cl)
(in-suite arithmetic)
(test number-add
"Test ADD on numbers"
(is (= 3 (add 1 2)))
(signals error (add 1 'x)))
(test-nary number +
(is (= 0 (+)))
(is (= 2 (+ 2)))
(is (= 10 (+ 1 2 3 4))))
(test number-subtract
"Test SUBTRACT on numbers"
(is (= -1 (subtract 3 4)))
(signals error (subtract 3 "z")))
(test-nary number -
(is (= -3 (- 3)))
(is (= -2 (- 5 4 3))))
(test number-multiply
"Test MULTIPLY on numbers"
(is (= 8 (multiply 2 4)))
(signals error (multiply 4 #\a)))
(test-nary number *
(is (= 1 (*)))
(is (= 3 (* 3)))
(is (= 120 (* 2 3 4 5))))
(test number-divide
"Test DIVIDE on numbers"
(is (= 2 (divide 6 3)))
(signals error (divide 'a 'b)))
(test-nary number /
(is (= 1/5 (/ 5)))
(is (= 1 (/ 6 3 2))))
(test number-negate
"Test NEGATE on numbers"
(is (= -4 (negate 4)))
(signals error (negate 'x)))
(test number-increments
"Test 1+, 1-, INCF and DECF on numbers"
(is (= 5 (1+ 4)))
(is (= 7 (1- 8)))
(let ((x 2))
(is (= 3 (incf x)))
(is (= 3 x))
(is (= 7 (incf x 4)))
(is (= 7 x)))
(let ((x 6))
(is (= 5 (decf x)))
(is (= 5 x))
(is (= 2 (decf x 3)))
(is (= 2 x))))
(test number-minusp
"Test MINUSP on numbers"
(is-true (minusp -5))
(is-true (minusp -1))
(is-false (minusp 0))
(is-false (minusp 3)))
(test number-plusp
"Test PLUSP on numbers"
(is-true (plusp 5))
(is-true (plusp 1))
(is-false (plusp 0))
(is-false (plusp -3)))
(test number-zerop
"Test ZEROP on numbers"
(is-true (zerop 0))
(is-false (zerop -1))
(is-false (zerop 5)))
(test number-signum
"Test SIGNUM on numbers"
(is (= 1 (signum 3)))
(is (= -1 (signum -1)))
(is (= 0 (signum 0))))
(test number-abs
"Test ABS on numbers"
(is (= 10 (abs 10)))
(is (= 0 (abs 0)))
(is (= 3 (abs -3))))
(test number-evenp
"Test EVENP on numbers"
(is-true (evenp 2))
(is-true (evenp 10))
(is-true (evenp 0))
(is-true (evenp -4))
(is-false (evenp 5))
(is-false (evenp -3)))
(test number-oddp
"Test ODDP on numbers"
(is-true (oddp 3))
(is-true (oddp 7))
(is-true (oddp -5))
(is-false (oddp 0))
(is-false (oddp 4))
(is-false (oddp -6)))
(test number-floor
"Test FLOOR on numbers"
(is (= 3 (floor 3.0222)))
(is (= -4 (floor -3.0222)))
(is (= '(3 1) (multiple-value-list (floor 10 3))))
(is (= '(-4 2) (multiple-value-list (floor -10 3)))))
(test number-ceiling
"Test CEILING on numbers"
(is (= 4 (ceiling 3.0222)))
(is (= -3 (ceiling -3.0222)))
(is (= '(4 -2) (multiple-value-list (ceiling 10 3))))
(is (= '(-3 -1) (multiple-value-list (ceiling -10 3)))))
(test number-truncate
"Test TRUNCATE on numbers"
(is (= 3 (truncate 3.0222)))
(is (= -3 (truncate -3.0222)))
(is (= '(3 1) (multiple-value-list (truncate 10 3))))
(is (= '(-3 -1) (multiple-value-list (truncate -10 3)))))
(test number-round
"Test ROUND on numbers"
(is (= 3 (round 3.0222)))
(is (= -3 (round -3.0222)))
(is (= 4 (round 3.7222)))
(is (= -4 (round -3.7222)))
(is (= 4 (round 4.5)))
(is (= -4 (round -4.5)))
(is (= 2 (round 1.5)))
(is (= -2 (round -1.5)))
(is (= '(3 1) (multiple-value-list (round 10 3))))
(is (= '(-3 -1) (multiple-value-list (round -10 3))))
(is (= '(2 1) (multiple-value-list (round 5 2))))
(is (= '(-2 -1) (multiple-value-list (round -5 2)))))
(test number-mod
"Test MOD on numbers"
(is (= 2 (mod 5 3)))
(is (= 1 (mod -5 3))))
(test number-rem
"Test REM on numbers"
(is (= 2 (rem 5 3)))
(is (= -2 (rem -5 3))))
|
b00bf777661c28dbe7b9edac5a72bd9c34a16bf0c03d409dae89725664cf3e2a | alexandergunnarson/quantum | core.cljc | (ns quantum.test.db.datomic.core
(:require [quantum.db.datomic.core :as ns]))
(defn test:unhandled-type [type obj])
PREDICATES
#?(:clj (defn test:entity? [x]))
#?(:clj (defn test:tempid? [x]))
#?(:clj (defn test:dbfn? [x]))
#?(:clj (defn test:tempid-like? [x]))
#?(:clj (defn test:db? [x]))
(defn test:mdb? [x])
#?(:clj (defn test:conn? [x]))
(defn test:mconn? [x])
(defn test:->uri-string
[{:keys [type host port db-name]
:or {type :free
host "localhost"
port 4334
db-name "test"}}])
#?(:clj
(defn test:->conn [uri]))
; TRANSFORMATIONS/CONVERSIONS
(defn test:db->seq
[db])
(defn test:history->seq
[history])
(defn test:->db
([])
([arg]))
(defn test:touch [entity])
(defn test:q
([query])
([query db & args]))
(defn test:entity
([eid])
([db eid]))
(defn test:entity-db
([entity]))
(defn test:tempid
([])
([part])
([conn part]))
(defn test:pull
([selector eid])
([db selector eid]))
(defn test:pull-many
([selector eids])
([db selector eids]))\
(defn test:is-filtered
([])
([db]))
(defn test:with-
([tx-data])
([db tx-data])
([db tx-data tx-meta]))
(defn test:datoms
([db index & args]))
(defn test:seek-datoms
([db index & args]))
(defn test:index-range
([attr start end])
([db attr start end]))
(defn test:transact!
([tx-data])
([conn tx-data])
([conn tx-data tx-meta]))
#?(:clj
(defn test:transact-async!
([tx-data])
([conn tx-data])))
; ===== QUERIES =====
#?(:clj
(defn test:txns
([])
([conn])))
(defn test:schemas
([])
([db]))
(defn test:attributes
([])
([db]))
(defn test:partitions
([])
([db]))
; ==== OPERATIONS ====
(defn test:->partition
([part])
([conn part]))
(defn test:rename-schemas [mapping])
(defn test:->schema
([ident cardinality val-type])
([ident cardinality val-type {:keys [conn part] :as opts}]))
(defn test:block->schemas
[block & [opts]])
(defn test:add-schemas!
([schemas])
([conn schemas]))
(defn test:update-schema!
[schema & kvs])
(defn test:retract-from-schema! [s k v])
(defn test:new-if-not-found
[attrs])
(defn test:attribute? [x])
(defn test:dbfn-call? [x])
(defn test:transform-validated [x])
(defn test:validated->txn
[x])
(defn test:validated->new-txn
[x part])
(defn test:queried->maps [db queried])
#?(:clj
(defn test:entity->map
([m])
([m n])))
(defn test:lookup
[attr v])
(defn test:has-transform? [x])
(defn test:wrap-transform [x])
(defn test:transform [x])
(defn test:rename [old new-])
(defn test:assoc
[eid & kvs])
(defn test:assoc! [& args])
(defn test:dissoc
[arg & args])
(defn test:dissoc! [& args])
(defn test:merge
[eid props])
(defn test:merge!
([& args]))
(defn test:excise
([eid attrs])
([eid part attrs])
([conn eid part attrs]))
(defn test:conj
([x])
([part x])
([conn part no-transform? x]))
(defn test:conj!
[& args])
(defn test:disj
([eid])
([conn eid]))
(defn test:disj! [& args])
(defn test:update
([eid k f])
([conn eid k f]))
(defn test:update!
[& args])
#?(:clj
(defmacro test:dbfn
[requires arglist & body]))
#?(:clj
(defmacro test:defn!
[sym requires arglist & body]))
#?(:clj
(defn test:entity-history [e]))
#?(:clj
(defn test:entity-history-by-txn
[e]))
; ==== MORE COMPLEX OPERATIONS ====
#?(:cljs
(defn test:undo!
([])
([^Database db])))
#?(:clj
(defn test:txn-ids-affecting-eid
[entity-id]))
(defn test:ensure-conj-entities!
[txn part])
#?(:clj
(defn test:transact-if!
[txn filter-fn ex-data-pred])) | null | https://raw.githubusercontent.com/alexandergunnarson/quantum/0c655af439734709566110949f9f2f482e468509/test/quantum/test/db/datomic/core.cljc | clojure | TRANSFORMATIONS/CONVERSIONS
===== QUERIES =====
==== OPERATIONS ====
==== MORE COMPLEX OPERATIONS ==== | (ns quantum.test.db.datomic.core
(:require [quantum.db.datomic.core :as ns]))
(defn test:unhandled-type [type obj])
PREDICATES
#?(:clj (defn test:entity? [x]))
#?(:clj (defn test:tempid? [x]))
#?(:clj (defn test:dbfn? [x]))
#?(:clj (defn test:tempid-like? [x]))
#?(:clj (defn test:db? [x]))
(defn test:mdb? [x])
#?(:clj (defn test:conn? [x]))
(defn test:mconn? [x])
(defn test:->uri-string
[{:keys [type host port db-name]
:or {type :free
host "localhost"
port 4334
db-name "test"}}])
#?(:clj
(defn test:->conn [uri]))
(defn test:db->seq
[db])
(defn test:history->seq
[history])
(defn test:->db
([])
([arg]))
(defn test:touch [entity])
(defn test:q
([query])
([query db & args]))
(defn test:entity
([eid])
([db eid]))
(defn test:entity-db
([entity]))
(defn test:tempid
([])
([part])
([conn part]))
(defn test:pull
([selector eid])
([db selector eid]))
(defn test:pull-many
([selector eids])
([db selector eids]))\
(defn test:is-filtered
([])
([db]))
(defn test:with-
([tx-data])
([db tx-data])
([db tx-data tx-meta]))
(defn test:datoms
([db index & args]))
(defn test:seek-datoms
([db index & args]))
(defn test:index-range
([attr start end])
([db attr start end]))
(defn test:transact!
([tx-data])
([conn tx-data])
([conn tx-data tx-meta]))
#?(:clj
(defn test:transact-async!
([tx-data])
([conn tx-data])))
#?(:clj
(defn test:txns
([])
([conn])))
(defn test:schemas
([])
([db]))
(defn test:attributes
([])
([db]))
(defn test:partitions
([])
([db]))
(defn test:->partition
([part])
([conn part]))
(defn test:rename-schemas [mapping])
(defn test:->schema
([ident cardinality val-type])
([ident cardinality val-type {:keys [conn part] :as opts}]))
(defn test:block->schemas
[block & [opts]])
(defn test:add-schemas!
([schemas])
([conn schemas]))
(defn test:update-schema!
[schema & kvs])
(defn test:retract-from-schema! [s k v])
(defn test:new-if-not-found
[attrs])
(defn test:attribute? [x])
(defn test:dbfn-call? [x])
(defn test:transform-validated [x])
(defn test:validated->txn
[x])
(defn test:validated->new-txn
[x part])
(defn test:queried->maps [db queried])
#?(:clj
(defn test:entity->map
([m])
([m n])))
(defn test:lookup
[attr v])
(defn test:has-transform? [x])
(defn test:wrap-transform [x])
(defn test:transform [x])
(defn test:rename [old new-])
(defn test:assoc
[eid & kvs])
(defn test:assoc! [& args])
(defn test:dissoc
[arg & args])
(defn test:dissoc! [& args])
(defn test:merge
[eid props])
(defn test:merge!
([& args]))
(defn test:excise
([eid attrs])
([eid part attrs])
([conn eid part attrs]))
(defn test:conj
([x])
([part x])
([conn part no-transform? x]))
(defn test:conj!
[& args])
(defn test:disj
([eid])
([conn eid]))
(defn test:disj! [& args])
(defn test:update
([eid k f])
([conn eid k f]))
(defn test:update!
[& args])
#?(:clj
(defmacro test:dbfn
[requires arglist & body]))
#?(:clj
(defmacro test:defn!
[sym requires arglist & body]))
#?(:clj
(defn test:entity-history [e]))
#?(:clj
(defn test:entity-history-by-txn
[e]))
#?(:cljs
(defn test:undo!
([])
([^Database db])))
#?(:clj
(defn test:txn-ids-affecting-eid
[entity-id]))
(defn test:ensure-conj-entities!
[txn part])
#?(:clj
(defn test:transact-if!
[txn filter-fn ex-data-pred])) |
08a0380f4adcf89cce57c79c0f3dbe947fd07dc48173871ea57ba11cf7e5d68e | phylogeography/spread | continuous_mcc_tree.cljs | (ns ui.new-analysis.continuous-mcc-tree
(:require [re-frame.core :as re-frame]
[reagent-material-ui.core.circular-progress :refer [circular-progress]]
[reagent-material-ui.core.linear-progress :refer [linear-progress]]
[reagent.core :as r]
[shared.components :refer [button]]
[ui.component.button :refer [button-file-upload]]
[ui.component.date-picker :refer [date-picker]]
[ui.component.input :refer [amount-input loaded-input text-input]]
[ui.component.select :refer [attributes-select]]
[ui.new-analysis.file-formats :as file-formats]
[ui.subscriptions :as subs]
[ui.time :as time]
[ui.utils :as ui-utils :refer [>evt debounce]]))
(defn controls [{:keys [readable-name y-coordinate-attribute-name x-coordinate-attribute-name most-recent-sampling-date timescale-multiplier]}
{:keys [disabled?]}]
(let [paste-disabled? (nil? @(re-frame/subscribe [::subs/pastebin]))]
[:div.controls-wrapper
[:div.controls {:style {:grid-area "controls"}}
[button {:text "Start analysis"
:on-click #(>evt [:continuous-mcc-tree/start-analysis {:readable-name readable-name
:y-coordinate-attribute-name y-coordinate-attribute-name
:x-coordinate-attribute-name x-coordinate-attribute-name
:most-recent-sampling-date most-recent-sampling-date
:timescale-multiplier timescale-multiplier}])
:class "golden"
:disabled? disabled?}]
[button {:text "Paste settings"
:on-click #(>evt [:general/paste-analysis-settings])
:class "secondary"
:disabled? paste-disabled?}]
[button {:text "Reset"
:on-click #(>evt [:continuous-mcc-tree/reset])
:class "danger"
:disabled? disabled?}]]]))
(defn continuous-mcc-tree []
(let [continuous-mcc-tree (re-frame/subscribe [::subs/continuous-mcc-tree])
field-errors (r/atom #{})]
(fn []
(let [{:keys [id
readable-name
tree-file-name
tree-file-upload-progress
trees-file-upload-progress
y-coordinate-attribute-name
x-coordinate-attribute-name
most-recent-sampling-date
timescale-multiplier
attribute-names
time-slicer]
:or {timescale-multiplier 1}} @continuous-mcc-tree
y-coordinate-attribute-name (or y-coordinate-attribute-name (first attribute-names))
x-coordinate-attribute-name (or x-coordinate-attribute-name (first attribute-names))
most-recent-sampling-date (or most-recent-sampling-date (time/now))
controls-disabled? (or (not attribute-names) (not tree-file-name))
{:keys [trees-file-name]} time-slicer]
[:<>
[:div.data {}
[:section.load-tree-file
[:div
[:h4 "Load tree file"]
(if (not tree-file-name)
(if (not (pos? tree-file-upload-progress))
[button-file-upload {:id "continuous-mcc-tree-file-upload-button"
:label "Choose a file"
:on-file-accepted #(do
(swap! field-errors disj :tree-file-error)
(>evt [:continuous-mcc-tree/on-tree-file-selected %]))
:on-file-rejected (fn [] (swap! field-errors conj :tree-file-error))
:file-accept-predicate file-formats/tree-file-accept-predicate}]
[linear-progress {:value (* 100 tree-file-upload-progress)
:variant "determinate"}])
;; we have a filename
[loaded-input {:value tree-file-name
:on-click #(>evt [:continuous-mcc-tree/delete-tree-file])}])]
(cond
(contains? @field-errors :tree-file-error) [:div.field-error.button-error "Tree file incorrect format."]
(nil? tree-file-name) [:p.doc "When upload is complete all unique attributes will be automatically filled. You can then select geographical coordinates and change other settings."])]
[:section.load-trees-file
[:div
[:h4 "Load trees file"]
(if (not trees-file-name)
(if (not (pos? trees-file-upload-progress))
[button-file-upload {:id "mcc-trees-file-upload-button"
:label "Choose a file"
:on-file-accepted #(do
(swap! field-errors disj :trees-file-error)
(>evt [:continuous-mcc-tree/on-trees-file-selected %]))
:on-file-rejected (fn [] (swap! field-errors conj :trees-file-error))
:file-accept-predicate file-formats/trees-file-accept-predicate}]
[linear-progress {:value (* 100 trees-file-upload-progress)
:variant "determinate"}])
;; we have a filename
[loaded-input {:value trees-file-name
:on-click #(>evt [:continuous-mcc-tree/delete-trees-file])}])]
(cond
(contains? @field-errors :trees-file-error) [:div.field-error.button-error "Trees file incorrect format."]
(nil? trees-file-name) [:p.doc "Optional: Select a file with corresponding trees distribution. This file will be used to compute a density interval around the MCC tree."])]
[:div.upload-spinner
(when (and (= 1 tree-file-upload-progress) (nil? attribute-names))
[circular-progress {:size 100}])]
(when (and attribute-names tree-file-name)
[:div.field-table
[:div.field-line
[:div.field-card
[:h4 "File info"]
[text-input {:label "Name"
:variant :outlined
:value readable-name
:on-change (fn [value]
(>evt [:continuous-mcc-tree/set-readable-name value]))}]]]
[:div.field-line
[:div.field-card
[:h4 "Select x coordinate"]
[attributes-select {:id "select-longitude"
:value x-coordinate-attribute-name
:options attribute-names
:label "Longitude"
:on-change (fn [value]
(>evt [:continuous-mcc-tree/set-x-coordinate value]))}]]
[:div.field-card
[:h4 "Select y coordinate"]
[attributes-select {:id "select-latitude"
:value y-coordinate-attribute-name
:options attribute-names
:label "Latitude"
:on-change (fn [value]
(>evt [:continuous-mcc-tree/set-y-coordinate value]))}]]]
[:div.field-line
[:div.field-card
[:h4 "Most recent sampling date"]
[date-picker {:date-format time/date-format
:on-change (fn [value]
(>evt [:continuous-mcc-tree/set-most-recent-sampling-date value]))
:selected most-recent-sampling-date}]]
[:div.field-card
[:h4 "Time scale"]
[amount-input {:label "Multiplier"
:value timescale-multiplier
:error? (not (nil? (:time-scale-multiplier @field-errors)))
:helper-text (:time-scale-multiplier @field-errors)
:on-change (fn [value]
(debounce (>evt [:continuous-mcc-tree/set-time-scale-multiplier value]) 10))}]]]])]
[controls {:id id
:readable-name readable-name
:y-coordinate-attribute-name y-coordinate-attribute-name
:x-coordinate-attribute-name x-coordinate-attribute-name
:most-recent-sampling-date most-recent-sampling-date
:timescale-multiplier timescale-multiplier}
{:disabled? controls-disabled? }]]))))
| null | https://raw.githubusercontent.com/phylogeography/spread/56f3500e6d83e0ebd50041dc336ffa0697d7baf8/src/cljs/ui/new_analysis/continuous_mcc_tree.cljs | clojure | we have a filename
we have a filename | (ns ui.new-analysis.continuous-mcc-tree
(:require [re-frame.core :as re-frame]
[reagent-material-ui.core.circular-progress :refer [circular-progress]]
[reagent-material-ui.core.linear-progress :refer [linear-progress]]
[reagent.core :as r]
[shared.components :refer [button]]
[ui.component.button :refer [button-file-upload]]
[ui.component.date-picker :refer [date-picker]]
[ui.component.input :refer [amount-input loaded-input text-input]]
[ui.component.select :refer [attributes-select]]
[ui.new-analysis.file-formats :as file-formats]
[ui.subscriptions :as subs]
[ui.time :as time]
[ui.utils :as ui-utils :refer [>evt debounce]]))
(defn controls [{:keys [readable-name y-coordinate-attribute-name x-coordinate-attribute-name most-recent-sampling-date timescale-multiplier]}
{:keys [disabled?]}]
(let [paste-disabled? (nil? @(re-frame/subscribe [::subs/pastebin]))]
[:div.controls-wrapper
[:div.controls {:style {:grid-area "controls"}}
[button {:text "Start analysis"
:on-click #(>evt [:continuous-mcc-tree/start-analysis {:readable-name readable-name
:y-coordinate-attribute-name y-coordinate-attribute-name
:x-coordinate-attribute-name x-coordinate-attribute-name
:most-recent-sampling-date most-recent-sampling-date
:timescale-multiplier timescale-multiplier}])
:class "golden"
:disabled? disabled?}]
[button {:text "Paste settings"
:on-click #(>evt [:general/paste-analysis-settings])
:class "secondary"
:disabled? paste-disabled?}]
[button {:text "Reset"
:on-click #(>evt [:continuous-mcc-tree/reset])
:class "danger"
:disabled? disabled?}]]]))
(defn continuous-mcc-tree []
(let [continuous-mcc-tree (re-frame/subscribe [::subs/continuous-mcc-tree])
field-errors (r/atom #{})]
(fn []
(let [{:keys [id
readable-name
tree-file-name
tree-file-upload-progress
trees-file-upload-progress
y-coordinate-attribute-name
x-coordinate-attribute-name
most-recent-sampling-date
timescale-multiplier
attribute-names
time-slicer]
:or {timescale-multiplier 1}} @continuous-mcc-tree
y-coordinate-attribute-name (or y-coordinate-attribute-name (first attribute-names))
x-coordinate-attribute-name (or x-coordinate-attribute-name (first attribute-names))
most-recent-sampling-date (or most-recent-sampling-date (time/now))
controls-disabled? (or (not attribute-names) (not tree-file-name))
{:keys [trees-file-name]} time-slicer]
[:<>
[:div.data {}
[:section.load-tree-file
[:div
[:h4 "Load tree file"]
(if (not tree-file-name)
(if (not (pos? tree-file-upload-progress))
[button-file-upload {:id "continuous-mcc-tree-file-upload-button"
:label "Choose a file"
:on-file-accepted #(do
(swap! field-errors disj :tree-file-error)
(>evt [:continuous-mcc-tree/on-tree-file-selected %]))
:on-file-rejected (fn [] (swap! field-errors conj :tree-file-error))
:file-accept-predicate file-formats/tree-file-accept-predicate}]
[linear-progress {:value (* 100 tree-file-upload-progress)
:variant "determinate"}])
[loaded-input {:value tree-file-name
:on-click #(>evt [:continuous-mcc-tree/delete-tree-file])}])]
(cond
(contains? @field-errors :tree-file-error) [:div.field-error.button-error "Tree file incorrect format."]
(nil? tree-file-name) [:p.doc "When upload is complete all unique attributes will be automatically filled. You can then select geographical coordinates and change other settings."])]
[:section.load-trees-file
[:div
[:h4 "Load trees file"]
(if (not trees-file-name)
(if (not (pos? trees-file-upload-progress))
[button-file-upload {:id "mcc-trees-file-upload-button"
:label "Choose a file"
:on-file-accepted #(do
(swap! field-errors disj :trees-file-error)
(>evt [:continuous-mcc-tree/on-trees-file-selected %]))
:on-file-rejected (fn [] (swap! field-errors conj :trees-file-error))
:file-accept-predicate file-formats/trees-file-accept-predicate}]
[linear-progress {:value (* 100 trees-file-upload-progress)
:variant "determinate"}])
[loaded-input {:value trees-file-name
:on-click #(>evt [:continuous-mcc-tree/delete-trees-file])}])]
(cond
(contains? @field-errors :trees-file-error) [:div.field-error.button-error "Trees file incorrect format."]
(nil? trees-file-name) [:p.doc "Optional: Select a file with corresponding trees distribution. This file will be used to compute a density interval around the MCC tree."])]
[:div.upload-spinner
(when (and (= 1 tree-file-upload-progress) (nil? attribute-names))
[circular-progress {:size 100}])]
(when (and attribute-names tree-file-name)
[:div.field-table
[:div.field-line
[:div.field-card
[:h4 "File info"]
[text-input {:label "Name"
:variant :outlined
:value readable-name
:on-change (fn [value]
(>evt [:continuous-mcc-tree/set-readable-name value]))}]]]
[:div.field-line
[:div.field-card
[:h4 "Select x coordinate"]
[attributes-select {:id "select-longitude"
:value x-coordinate-attribute-name
:options attribute-names
:label "Longitude"
:on-change (fn [value]
(>evt [:continuous-mcc-tree/set-x-coordinate value]))}]]
[:div.field-card
[:h4 "Select y coordinate"]
[attributes-select {:id "select-latitude"
:value y-coordinate-attribute-name
:options attribute-names
:label "Latitude"
:on-change (fn [value]
(>evt [:continuous-mcc-tree/set-y-coordinate value]))}]]]
[:div.field-line
[:div.field-card
[:h4 "Most recent sampling date"]
[date-picker {:date-format time/date-format
:on-change (fn [value]
(>evt [:continuous-mcc-tree/set-most-recent-sampling-date value]))
:selected most-recent-sampling-date}]]
[:div.field-card
[:h4 "Time scale"]
[amount-input {:label "Multiplier"
:value timescale-multiplier
:error? (not (nil? (:time-scale-multiplier @field-errors)))
:helper-text (:time-scale-multiplier @field-errors)
:on-change (fn [value]
(debounce (>evt [:continuous-mcc-tree/set-time-scale-multiplier value]) 10))}]]]])]
[controls {:id id
:readable-name readable-name
:y-coordinate-attribute-name y-coordinate-attribute-name
:x-coordinate-attribute-name x-coordinate-attribute-name
:most-recent-sampling-date most-recent-sampling-date
:timescale-multiplier timescale-multiplier}
{:disabled? controls-disabled? }]]))))
|
041aafe623550c377cd01098ae3cb35556c39dd2b5ff3c700db75bb288abc2d4 | racket/typed-racket | dotted-identity2.rkt | #lang typed/racket/shallow
;; I don't believe the below should work, but it points out where that internal error is coming from.
(: f (All (a ...) ((a ... a -> Integer) -> (a ... a -> Integer))))
(define (f x) x)
(: g (All (b ...) ( -> (b ... b -> Integer))))
(define (g) (lambda xs 0))
(f (g))
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/shallow/dotted-identity2.rkt | racket | I don't believe the below should work, but it points out where that internal error is coming from. | #lang typed/racket/shallow
(: f (All (a ...) ((a ... a -> Integer) -> (a ... a -> Integer))))
(define (f x) x)
(: g (All (b ...) ( -> (b ... b -> Integer))))
(define (g) (lambda xs 0))
(f (g))
|
d76f0c5d54f65331fb4bdfe4d73a08e99948b3b97dbc7d6c3f6becbf1500baff | xh4/web-toolkit | ed448.lisp | ;;;; -*- mode: lisp; indent-tabs-mode: nil -*-
;;;; ed448.lisp -- implementation of the ed448 signature algorithm
(in-package :crypto)
;;; class definitions
(defclass ed448-public-key ()
((y :initarg :y :reader ed448-key-y :type (simple-array (unsigned-byte 8) (*)))))
(defclass ed448-private-key ()
((x :initarg :x :reader ed448-key-x :type (simple-array (unsigned-byte 8) (*)))
(y :initarg :y :reader ed448-key-y :type (simple-array (unsigned-byte 8) (*)))))
;; Internally, a point (x, y) is represented using the projective coordinates
;; (X, Y, Z), with x = X / Z and y = Y / Z.
(deftype ed448-point () '(vector integer 3))
;;; constant and function definitions
(defconstant +ed448-bits+ 456)
(defconstant +ed448-q+ 726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439)
(defconstant +ed448-l+ 181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779)
(defconstant +ed448-d+ -39081)
(declaim (type ed448-point +ed448-b+))
(defconst +ed448-b+
(vector 224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710
298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660
1))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun ed448-dom (x y)
(declare (type (unsigned-byte 8) x)
(type (simple-array (unsigned-byte 8) (*)) y)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(when (> (length y) 255)
(error 'ironclad-error
:format-control "The Y array is to big."))
(concatenate '(simple-array (unsigned-byte 8) (*))
(map 'vector #'char-code "SigEd448")
(vector x)
(vector (length y))
y)))
;; Ed448 (x = 0), no context (y = #())
(defconst +ed448-dom+ (ed448-dom 0 (make-array 0 :element-type '(unsigned-byte 8))))
(declaim (inline ed448-inv))
(defun ed448-inv (x)
(expt-mod x (- +ed448-q+ 2) +ed448-q+))
(defun ed448-recover-x (y)
"Recover the X coordinate of a point on ed448 curve from the Y coordinate."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
(type integer y))
(let* ((u (mod (1- (* y y)) +ed448-q+))
(v (mod (1- (* +ed448-d+ (1+ u))) +ed448-q+))
(uv (mod (* u v) +ed448-q+))
(u3v (mod (* u u uv) +ed448-q+))
(u5v3 (mod (* u3v uv uv) +ed448-q+))
(x (mod (* u3v (expt-mod u5v3 (/ (- +ed448-q+ 3) 4) +ed448-q+)) +ed448-q+)))
(declare (type integer u v uv u3v u5v3 x))
(unless (evenp x)
(setf x (- +ed448-q+ x)))
x))
(defun ed448-edwards-add (p q)
"Point addition on ed448 curve."
(declare (type ed448-point p q)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let* ((x1 (aref p 0))
(y1 (aref p 1))
(z1 (aref p 2))
(x2 (aref q 0))
(y2 (aref q 1))
(z2 (aref q 2))
(a (mod (* z1 z2) +ed448-q+))
(b (mod (* a a) +ed448-q+))
(c (mod (* x1 x2) +ed448-q+))
(d (mod (* y1 y2) +ed448-q+))
(k (mod (* c d) +ed448-q+))
(e (mod (* +ed448-d+ k) +ed448-q+))
(f (mod (- b e) +ed448-q+))
(g (mod (+ b e) +ed448-q+))
(h (mod (* (+ x1 y1) (+ x2 y2)) +ed448-q+))
(i (mod (* a f) +ed448-q+))
(j (mod (* a g) +ed448-q+))
(x3 (mod (* i (- h c d)) +ed448-q+))
(y3 (mod (* j (- d c)) +ed448-q+))
(z3 (mod (* f g) +ed448-q+)))
(declare (type integer x1 y1 z1 x2 y2 z2 a b c d e f g h i j k x3 y3 z3))
(vector x3 y3 z3)))
(defun ed448-edwards-double (p)
"Point doubling on ed448 curve."
(declare (type ed448-point p)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let* ((x1 (aref p 0))
(y1 (aref p 1))
(z1 (aref p 2))
(a (mod (+ x1 y1) +ed448-q+))
(b (mod (* a a) +ed448-q+))
(c (mod (* x1 x1) +ed448-q+))
(d (mod (* y1 y1) +ed448-q+))
(e (mod (+ c d) +ed448-q+))
(f (mod (* z1 z1) +ed448-q+))
(g (mod (- e (* 2 f)) +ed448-q+))
(x2 (mod (* (- b e) g) +ed448-q+))
(y2 (mod (* (- c d) e) +ed448-q+))
(z2 (mod (* e g) +ed448-q+)))
(declare (type integer x1 y1 z1 x2 y2 z2 a b c d e f g x2 y2 z2))
(vector x2 y2 z2)))
(defun ed448-scalar-mult (p e)
"Point multiplication on ed448 curve using the Montgomery ladder."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
(type ed448-point p)
(type integer e))
(do ((r0 (vector 0 1 1))
(r1 p)
(i 447 (1- i)))
((minusp i) r0)
(declare (type ed448-point r0 r1)
(type fixnum i))
(if (logbitp i e)
(setf r0 (ed448-edwards-add r0 r1)
r1 (ed448-edwards-double r1))
(setf r1 (ed448-edwards-add r0 r1)
r0 (ed448-edwards-double r0)))))
(defun ed448-on-curve-p (p)
"Check if the point P is on ed448 curve."
(declare (type ed448-point p)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let* ((x (aref p 0))
(y (aref p 1))
(z (aref p 2))
(xx (mod (* x x) +ed448-q+))
(yy (mod (* y y) +ed448-q+))
(zz (mod (* z z) +ed448-q+))
(zzzz (mod (* zz zz) +ed448-q+))
(a (mod (* zz (+ yy xx)) +ed448-q+))
(b (mod (+ zzzz (* +ed448-d+ xx yy)) +ed448-q+)))
(declare (type integer x y z xx yy zz zzzz a b))
(zerop (mod (- a b) +ed448-q+))))
(defun ed448-point-equal (p q)
"Check whether P and Q represent the same point."
(declare (type ed448-point p q)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let ((x1 (aref p 0))
(y1 (aref p 1))
(z1 (aref p 2))
(x2 (aref q 0))
(y2 (aref q 1))
(z2 (aref q 2)))
(declare (type integer x1 y1 z1 x2 y2 z2))
(and (zerop (mod (- (* x1 z2) (* x2 z1)) +ed448-q+))
(zerop (mod (- (* y1 z2) (* y2 z1)) +ed448-q+)))))
(defun ed448-encode-int (y)
"Encode an integer as a byte array (little-endian)."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0)))
(integer-to-octets y :n-bits +ed448-bits+ :big-endian nil))
(defun ed448-decode-int (octets)
"Decode a byte array to an integer (little-endian)."
(declare (type (simple-array (unsigned-byte 8) (*)) octets)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(octets-to-integer octets :big-endian nil))
(defun ed448-encode-point (p)
"Encode a point on ed448 curve as a byte array."
(declare (type ed448-point p)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let* ((z (aref p 2))
(invz (ed448-inv z))
(x (mod (* (aref p 0) invz) +ed448-q+))
(y (mod (* (aref p 1) invz) +ed448-q+)))
(setf (ldb (byte 1 (- +ed448-bits+ 1)) y) (ldb (byte 1 0) x))
(ed448-encode-int y)))
(defun ed448-decode-point (octets)
"Decode a byte array to a point on ed448 curve."
(declare (type (simple-array (unsigned-byte 8) (*)) octets)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let* ((y (ed448-decode-int octets))
(b (ldb (byte 1 (- +ed448-bits+ 1)) y)))
(setf (ldb (byte 1 (- +ed448-bits+ 1)) y) 0)
(let ((x (ed448-recover-x y)))
(unless (= (ldb (byte 1 0) x) b)
(setf x (- +ed448-q+ x)))
(let ((p (vector x y 1)))
(unless (ed448-on-curve-p p)
(error 'invalid-curve-point :kind 'ed448))
p))))
(defun ed448-hash (&rest messages)
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let ((digest (make-digest :shake256 :output-length 114)))
(dolist (m messages)
(update-digest digest m))
(produce-digest digest)))
(defun ed448-public-key (sk)
"Compute the public key associated to the private key SK."
(let ((h (ed448-hash sk)))
(setf h (subseq h 0 (ceiling +ed448-bits+ 8)))
(setf (ldb (byte 2 0) (elt h 0)) 0)
(setf (ldb (byte 1 7) (elt h (- (ceiling +ed448-bits+ 8) 2))) 1)
(setf (elt h (- (ceiling +ed448-bits+ 8) 1)) 0)
(let ((a (ed448-decode-int h)))
(ed448-encode-point (ed448-scalar-mult +ed448-b+ a)))))
(defmethod make-signature ((kind (eql :ed448)) &key r s &allow-other-keys)
(unless r
(error 'missing-signature-parameter
:kind 'ed448
:parameter 'r
:description "first signature element"))
(unless s
(error 'missing-signature-parameter
:kind 'ed448
:parameter 's
:description "second signature element"))
(concatenate '(simple-array (unsigned-byte 8) (*)) r s))
(defmethod destructure-signature ((kind (eql :ed448)) signature)
(let ((length (length signature)))
(if (/= length (/ +ed448-bits+ 4))
(error 'invalid-signature-length :kind 'ed448)
(let* ((middle (/ length 2))
(r (subseq signature 0 middle))
(s (subseq signature middle)))
(list :r r :s s)))))
(defun ed448-sign (m sk pk)
(declare (type (simple-array (unsigned-byte 8) (*)) m sk pk)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let ((h (ed448-hash sk)))
(setf (ldb (byte 2 0) (elt h 0)) 0)
(setf (ldb (byte 1 7) (elt h (- (ceiling +ed448-bits+ 8) 2))) 1)
(setf (elt h (- (ceiling +ed448-bits+ 8) 1)) 0)
(let* ((a (ed448-decode-int (subseq h 0 (ceiling +ed448-bits+ 8))))
(rh (ed448-hash +ed448-dom+ (subseq h (ceiling +ed448-bits+ 8) (ceiling +ed448-bits+ 4)) m))
(ri (mod (ed448-decode-int rh) +ed448-l+))
(r (ed448-scalar-mult +ed448-b+ ri))
(rp (ed448-encode-point r))
(k (mod (ed448-decode-int (ed448-hash +ed448-dom+ rp pk m)) +ed448-l+))
(s (mod (+ (* k a) ri) +ed448-l+)))
(make-signature :ed448 :r rp :s (ed448-encode-int s)))))
(defun ed448-verify (s m pk)
(declare (type (simple-array (unsigned-byte 8) (*)) s m pk)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(unless (= (length s) (ceiling +ed448-bits+ 4))
(error 'invalid-signature-length :kind 'ed448))
(unless (= (length pk) (ceiling +ed448-bits+ 8))
(error 'invalid-public-key-length :kind 'ed448))
(let* ((signature-elements (destructure-signature :ed448 s))
(r (getf signature-elements :r))
(rp (ed448-decode-point r))
(s (ed448-decode-int (getf signature-elements :s)))
(a (ed448-decode-point pk))
(h (mod (ed448-decode-int (ed448-hash +ed448-dom+ r pk m)) +ed448-l+))
(res1 (ed448-scalar-mult +ed448-b+ s))
(res2 (ed448-edwards-add rp (ed448-scalar-mult a h))))
(declare (type (simple-array (unsigned-byte 8) (*)) r)
(type integer s h)
(type ed448-point rp a res1 res2))
(and (< s +ed448-l+)
(ed448-point-equal res1 res2))))
(defmethod make-public-key ((kind (eql :ed448)) &key y &allow-other-keys)
(unless y
(error 'missing-key-parameter
:kind 'ed448
:parameter 'y
:description "public key"))
(make-instance 'ed448-public-key :y y))
(defmethod destructure-public-key ((public-key ed448-public-key))
(list :y (ed448-key-y public-key)))
(defmethod make-private-key ((kind (eql :ed448)) &key x y &allow-other-keys)
(unless x
(error 'missing-key-parameter
:kind 'ed448
:parameter 'x
:description "private key"))
(make-instance 'ed448-private-key :x x :y (or y (ed448-public-key x))))
(defmethod destructure-private-key ((private-key ed448-private-key))
(list :x (ed448-key-x private-key)
:y (ed448-key-y private-key)))
(defmethod sign-message ((key ed448-private-key) message &key (start 0) end &allow-other-keys)
(let ((end (or end (length message)))
(sk (ed448-key-x key))
(pk (ed448-key-y key)))
(ed448-sign (subseq message start end) sk pk)))
(defmethod verify-signature ((key ed448-public-key) message signature &key (start 0) end &allow-other-keys)
(let ((end (or end (length message)))
(pk (ed448-key-y key)))
(ed448-verify signature (subseq message start end) pk)))
(defmethod generate-key-pair ((kind (eql :ed448)) &key &allow-other-keys)
(let* ((sk (random-data (ceiling +ed448-bits+ 8)))
(pk (ed448-public-key sk)))
(values (make-private-key :ed448 :x sk :y pk)
(make-public-key :ed448 :y pk))))
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/ironclad-v0.47/src/public-key/ed448.lisp | lisp | -*- mode: lisp; indent-tabs-mode: nil -*-
ed448.lisp -- implementation of the ed448 signature algorithm
class definitions
Internally, a point (x, y) is represented using the projective coordinates
(X, Y, Z), with x = X / Z and y = Y / Z.
constant and function definitions
Ed448 (x = 0), no context (y = #()) |
(in-package :crypto)
(defclass ed448-public-key ()
((y :initarg :y :reader ed448-key-y :type (simple-array (unsigned-byte 8) (*)))))
(defclass ed448-private-key ()
((x :initarg :x :reader ed448-key-x :type (simple-array (unsigned-byte 8) (*)))
(y :initarg :y :reader ed448-key-y :type (simple-array (unsigned-byte 8) (*)))))
(deftype ed448-point () '(vector integer 3))
(defconstant +ed448-bits+ 456)
(defconstant +ed448-q+ 726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439)
(defconstant +ed448-l+ 181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779)
(defconstant +ed448-d+ -39081)
(declaim (type ed448-point +ed448-b+))
(defconst +ed448-b+
(vector 224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710
298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660
1))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun ed448-dom (x y)
(declare (type (unsigned-byte 8) x)
(type (simple-array (unsigned-byte 8) (*)) y)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(when (> (length y) 255)
(error 'ironclad-error
:format-control "The Y array is to big."))
(concatenate '(simple-array (unsigned-byte 8) (*))
(map 'vector #'char-code "SigEd448")
(vector x)
(vector (length y))
y)))
(defconst +ed448-dom+ (ed448-dom 0 (make-array 0 :element-type '(unsigned-byte 8))))
(declaim (inline ed448-inv))
(defun ed448-inv (x)
(expt-mod x (- +ed448-q+ 2) +ed448-q+))
(defun ed448-recover-x (y)
"Recover the X coordinate of a point on ed448 curve from the Y coordinate."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
(type integer y))
(let* ((u (mod (1- (* y y)) +ed448-q+))
(v (mod (1- (* +ed448-d+ (1+ u))) +ed448-q+))
(uv (mod (* u v) +ed448-q+))
(u3v (mod (* u u uv) +ed448-q+))
(u5v3 (mod (* u3v uv uv) +ed448-q+))
(x (mod (* u3v (expt-mod u5v3 (/ (- +ed448-q+ 3) 4) +ed448-q+)) +ed448-q+)))
(declare (type integer u v uv u3v u5v3 x))
(unless (evenp x)
(setf x (- +ed448-q+ x)))
x))
(defun ed448-edwards-add (p q)
"Point addition on ed448 curve."
(declare (type ed448-point p q)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let* ((x1 (aref p 0))
(y1 (aref p 1))
(z1 (aref p 2))
(x2 (aref q 0))
(y2 (aref q 1))
(z2 (aref q 2))
(a (mod (* z1 z2) +ed448-q+))
(b (mod (* a a) +ed448-q+))
(c (mod (* x1 x2) +ed448-q+))
(d (mod (* y1 y2) +ed448-q+))
(k (mod (* c d) +ed448-q+))
(e (mod (* +ed448-d+ k) +ed448-q+))
(f (mod (- b e) +ed448-q+))
(g (mod (+ b e) +ed448-q+))
(h (mod (* (+ x1 y1) (+ x2 y2)) +ed448-q+))
(i (mod (* a f) +ed448-q+))
(j (mod (* a g) +ed448-q+))
(x3 (mod (* i (- h c d)) +ed448-q+))
(y3 (mod (* j (- d c)) +ed448-q+))
(z3 (mod (* f g) +ed448-q+)))
(declare (type integer x1 y1 z1 x2 y2 z2 a b c d e f g h i j k x3 y3 z3))
(vector x3 y3 z3)))
(defun ed448-edwards-double (p)
"Point doubling on ed448 curve."
(declare (type ed448-point p)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let* ((x1 (aref p 0))
(y1 (aref p 1))
(z1 (aref p 2))
(a (mod (+ x1 y1) +ed448-q+))
(b (mod (* a a) +ed448-q+))
(c (mod (* x1 x1) +ed448-q+))
(d (mod (* y1 y1) +ed448-q+))
(e (mod (+ c d) +ed448-q+))
(f (mod (* z1 z1) +ed448-q+))
(g (mod (- e (* 2 f)) +ed448-q+))
(x2 (mod (* (- b e) g) +ed448-q+))
(y2 (mod (* (- c d) e) +ed448-q+))
(z2 (mod (* e g) +ed448-q+)))
(declare (type integer x1 y1 z1 x2 y2 z2 a b c d e f g x2 y2 z2))
(vector x2 y2 z2)))
(defun ed448-scalar-mult (p e)
"Point multiplication on ed448 curve using the Montgomery ladder."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
(type ed448-point p)
(type integer e))
(do ((r0 (vector 0 1 1))
(r1 p)
(i 447 (1- i)))
((minusp i) r0)
(declare (type ed448-point r0 r1)
(type fixnum i))
(if (logbitp i e)
(setf r0 (ed448-edwards-add r0 r1)
r1 (ed448-edwards-double r1))
(setf r1 (ed448-edwards-add r0 r1)
r0 (ed448-edwards-double r0)))))
(defun ed448-on-curve-p (p)
"Check if the point P is on ed448 curve."
(declare (type ed448-point p)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let* ((x (aref p 0))
(y (aref p 1))
(z (aref p 2))
(xx (mod (* x x) +ed448-q+))
(yy (mod (* y y) +ed448-q+))
(zz (mod (* z z) +ed448-q+))
(zzzz (mod (* zz zz) +ed448-q+))
(a (mod (* zz (+ yy xx)) +ed448-q+))
(b (mod (+ zzzz (* +ed448-d+ xx yy)) +ed448-q+)))
(declare (type integer x y z xx yy zz zzzz a b))
(zerop (mod (- a b) +ed448-q+))))
(defun ed448-point-equal (p q)
"Check whether P and Q represent the same point."
(declare (type ed448-point p q)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let ((x1 (aref p 0))
(y1 (aref p 1))
(z1 (aref p 2))
(x2 (aref q 0))
(y2 (aref q 1))
(z2 (aref q 2)))
(declare (type integer x1 y1 z1 x2 y2 z2))
(and (zerop (mod (- (* x1 z2) (* x2 z1)) +ed448-q+))
(zerop (mod (- (* y1 z2) (* y2 z1)) +ed448-q+)))))
(defun ed448-encode-int (y)
"Encode an integer as a byte array (little-endian)."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0)))
(integer-to-octets y :n-bits +ed448-bits+ :big-endian nil))
(defun ed448-decode-int (octets)
"Decode a byte array to an integer (little-endian)."
(declare (type (simple-array (unsigned-byte 8) (*)) octets)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(octets-to-integer octets :big-endian nil))
(defun ed448-encode-point (p)
"Encode a point on ed448 curve as a byte array."
(declare (type ed448-point p)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let* ((z (aref p 2))
(invz (ed448-inv z))
(x (mod (* (aref p 0) invz) +ed448-q+))
(y (mod (* (aref p 1) invz) +ed448-q+)))
(setf (ldb (byte 1 (- +ed448-bits+ 1)) y) (ldb (byte 1 0) x))
(ed448-encode-int y)))
(defun ed448-decode-point (octets)
"Decode a byte array to a point on ed448 curve."
(declare (type (simple-array (unsigned-byte 8) (*)) octets)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let* ((y (ed448-decode-int octets))
(b (ldb (byte 1 (- +ed448-bits+ 1)) y)))
(setf (ldb (byte 1 (- +ed448-bits+ 1)) y) 0)
(let ((x (ed448-recover-x y)))
(unless (= (ldb (byte 1 0) x) b)
(setf x (- +ed448-q+ x)))
(let ((p (vector x y 1)))
(unless (ed448-on-curve-p p)
(error 'invalid-curve-point :kind 'ed448))
p))))
(defun ed448-hash (&rest messages)
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let ((digest (make-digest :shake256 :output-length 114)))
(dolist (m messages)
(update-digest digest m))
(produce-digest digest)))
(defun ed448-public-key (sk)
"Compute the public key associated to the private key SK."
(let ((h (ed448-hash sk)))
(setf h (subseq h 0 (ceiling +ed448-bits+ 8)))
(setf (ldb (byte 2 0) (elt h 0)) 0)
(setf (ldb (byte 1 7) (elt h (- (ceiling +ed448-bits+ 8) 2))) 1)
(setf (elt h (- (ceiling +ed448-bits+ 8) 1)) 0)
(let ((a (ed448-decode-int h)))
(ed448-encode-point (ed448-scalar-mult +ed448-b+ a)))))
(defmethod make-signature ((kind (eql :ed448)) &key r s &allow-other-keys)
(unless r
(error 'missing-signature-parameter
:kind 'ed448
:parameter 'r
:description "first signature element"))
(unless s
(error 'missing-signature-parameter
:kind 'ed448
:parameter 's
:description "second signature element"))
(concatenate '(simple-array (unsigned-byte 8) (*)) r s))
(defmethod destructure-signature ((kind (eql :ed448)) signature)
(let ((length (length signature)))
(if (/= length (/ +ed448-bits+ 4))
(error 'invalid-signature-length :kind 'ed448)
(let* ((middle (/ length 2))
(r (subseq signature 0 middle))
(s (subseq signature middle)))
(list :r r :s s)))))
(defun ed448-sign (m sk pk)
(declare (type (simple-array (unsigned-byte 8) (*)) m sk pk)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(let ((h (ed448-hash sk)))
(setf (ldb (byte 2 0) (elt h 0)) 0)
(setf (ldb (byte 1 7) (elt h (- (ceiling +ed448-bits+ 8) 2))) 1)
(setf (elt h (- (ceiling +ed448-bits+ 8) 1)) 0)
(let* ((a (ed448-decode-int (subseq h 0 (ceiling +ed448-bits+ 8))))
(rh (ed448-hash +ed448-dom+ (subseq h (ceiling +ed448-bits+ 8) (ceiling +ed448-bits+ 4)) m))
(ri (mod (ed448-decode-int rh) +ed448-l+))
(r (ed448-scalar-mult +ed448-b+ ri))
(rp (ed448-encode-point r))
(k (mod (ed448-decode-int (ed448-hash +ed448-dom+ rp pk m)) +ed448-l+))
(s (mod (+ (* k a) ri) +ed448-l+)))
(make-signature :ed448 :r rp :s (ed448-encode-int s)))))
(defun ed448-verify (s m pk)
(declare (type (simple-array (unsigned-byte 8) (*)) s m pk)
(optimize (speed 3) (safety 0) (space 0) (debug 0)))
(unless (= (length s) (ceiling +ed448-bits+ 4))
(error 'invalid-signature-length :kind 'ed448))
(unless (= (length pk) (ceiling +ed448-bits+ 8))
(error 'invalid-public-key-length :kind 'ed448))
(let* ((signature-elements (destructure-signature :ed448 s))
(r (getf signature-elements :r))
(rp (ed448-decode-point r))
(s (ed448-decode-int (getf signature-elements :s)))
(a (ed448-decode-point pk))
(h (mod (ed448-decode-int (ed448-hash +ed448-dom+ r pk m)) +ed448-l+))
(res1 (ed448-scalar-mult +ed448-b+ s))
(res2 (ed448-edwards-add rp (ed448-scalar-mult a h))))
(declare (type (simple-array (unsigned-byte 8) (*)) r)
(type integer s h)
(type ed448-point rp a res1 res2))
(and (< s +ed448-l+)
(ed448-point-equal res1 res2))))
(defmethod make-public-key ((kind (eql :ed448)) &key y &allow-other-keys)
(unless y
(error 'missing-key-parameter
:kind 'ed448
:parameter 'y
:description "public key"))
(make-instance 'ed448-public-key :y y))
(defmethod destructure-public-key ((public-key ed448-public-key))
(list :y (ed448-key-y public-key)))
(defmethod make-private-key ((kind (eql :ed448)) &key x y &allow-other-keys)
(unless x
(error 'missing-key-parameter
:kind 'ed448
:parameter 'x
:description "private key"))
(make-instance 'ed448-private-key :x x :y (or y (ed448-public-key x))))
(defmethod destructure-private-key ((private-key ed448-private-key))
(list :x (ed448-key-x private-key)
:y (ed448-key-y private-key)))
(defmethod sign-message ((key ed448-private-key) message &key (start 0) end &allow-other-keys)
(let ((end (or end (length message)))
(sk (ed448-key-x key))
(pk (ed448-key-y key)))
(ed448-sign (subseq message start end) sk pk)))
(defmethod verify-signature ((key ed448-public-key) message signature &key (start 0) end &allow-other-keys)
(let ((end (or end (length message)))
(pk (ed448-key-y key)))
(ed448-verify signature (subseq message start end) pk)))
(defmethod generate-key-pair ((kind (eql :ed448)) &key &allow-other-keys)
(let* ((sk (random-data (ceiling +ed448-bits+ 8)))
(pk (ed448-public-key sk)))
(values (make-private-key :ed448 :x sk :y pk)
(make-public-key :ed448 :y pk))))
|
def75a2bd4fff692e3e45925d858710e223416468239a0baca6f6686eccad0f3 | afronski/wolves-and-rabbits-world-simulation | carrot_protocol_SUITE.erl | -module(carrot_protocol_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("../include/simulation_records.hrl").
-export([ all/0, init_per_testcase/2, end_per_testcase/2 ]).
-export([ carrot_entity_should_have_world_state_applied/1,
carrot_entity_should_notify_about_state_changes/1,
carrot_entity_can_be_asked_about_its_position/1,
carrot_entity_can_be_bitten/1,
carrot_entity_when_eaten_should_be_stopped/1 ]).
all() ->
[ carrot_entity_should_have_world_state_applied,
carrot_entity_should_notify_about_state_changes,
carrot_entity_can_be_asked_about_its_position,
carrot_entity_can_be_bitten,
carrot_entity_when_eaten_should_be_stopped ].
init_per_testcase(_TestCase, Config) ->
WorldParameters = #world_parameters{carrots = 1, rabbits = 1, wolves = 1, width = 5, height = 5},
simulation_event_stream:start_link(),
simulation_event_stream:attach_handler(common_test_event_handler),
{ok, Pid} = simulation_entity_carrot:start_link(WorldParameters),
[ {carrot_entity_pid, Pid}, {world_parameters, WorldParameters} | Config ].
end_per_testcase(_TestCase, Config) ->
Pid = proplists:get_value(carrot_entity_pid, Config),
exit(Pid, normal).
carrot_entity_should_have_world_state_applied(Config) ->
WorldParameters = proplists:get_value(world_parameters, Config),
Pid = proplists:get_value(carrot_entity_pid, Config),
{carrot, planted, EntityState} = common_test_event_handler:last_event_of(carrot, planted),
Pid = EntityState#carrot.pid,
WorldParameters = EntityState#carrot.world.
carrot_entity_should_notify_about_state_changes(Config) ->
Pid = proplists:get_value(carrot_entity_pid, Config),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
4 = length(common_test_event_handler:all_events()).
carrot_entity_can_be_asked_about_its_position(Config) ->
Pid = proplists:get_value(carrot_entity_pid, Config),
{carrot, planted, EntityState} = common_test_event_handler:last_event_of(carrot, planted),
GoodPosition = EntityState#carrot.position,
BadPosition = #position{x = 0, y = 0},
true = gen_server:call(Pid, {are_you_at, GoodPosition}),
false = gen_server:call(Pid, {are_you_at, BadPosition}).
carrot_entity_can_be_bitten(Config) ->
Pid = proplists:get_value(carrot_entity_pid, Config),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
{carrot, bite, EntityState} = common_test_event_handler:last_event_of(carrot, bite),
2 = EntityState#carrot.quantity.
carrot_entity_when_eaten_should_be_stopped(Config) ->
Pid = proplists:get_value(carrot_entity_pid, Config),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
undefined = process_info(Pid).
| null | https://raw.githubusercontent.com/afronski/wolves-and-rabbits-world-simulation/245cbff5a87f3cae0f4cc7bc422e0a4d139fcecc/test/carrot_protocol_SUITE.erl | erlang | -module(carrot_protocol_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("../include/simulation_records.hrl").
-export([ all/0, init_per_testcase/2, end_per_testcase/2 ]).
-export([ carrot_entity_should_have_world_state_applied/1,
carrot_entity_should_notify_about_state_changes/1,
carrot_entity_can_be_asked_about_its_position/1,
carrot_entity_can_be_bitten/1,
carrot_entity_when_eaten_should_be_stopped/1 ]).
all() ->
[ carrot_entity_should_have_world_state_applied,
carrot_entity_should_notify_about_state_changes,
carrot_entity_can_be_asked_about_its_position,
carrot_entity_can_be_bitten,
carrot_entity_when_eaten_should_be_stopped ].
init_per_testcase(_TestCase, Config) ->
WorldParameters = #world_parameters{carrots = 1, rabbits = 1, wolves = 1, width = 5, height = 5},
simulation_event_stream:start_link(),
simulation_event_stream:attach_handler(common_test_event_handler),
{ok, Pid} = simulation_entity_carrot:start_link(WorldParameters),
[ {carrot_entity_pid, Pid}, {world_parameters, WorldParameters} | Config ].
end_per_testcase(_TestCase, Config) ->
Pid = proplists:get_value(carrot_entity_pid, Config),
exit(Pid, normal).
carrot_entity_should_have_world_state_applied(Config) ->
WorldParameters = proplists:get_value(world_parameters, Config),
Pid = proplists:get_value(carrot_entity_pid, Config),
{carrot, planted, EntityState} = common_test_event_handler:last_event_of(carrot, planted),
Pid = EntityState#carrot.pid,
WorldParameters = EntityState#carrot.world.
carrot_entity_should_notify_about_state_changes(Config) ->
Pid = proplists:get_value(carrot_entity_pid, Config),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
4 = length(common_test_event_handler:all_events()).
carrot_entity_can_be_asked_about_its_position(Config) ->
Pid = proplists:get_value(carrot_entity_pid, Config),
{carrot, planted, EntityState} = common_test_event_handler:last_event_of(carrot, planted),
GoodPosition = EntityState#carrot.position,
BadPosition = #position{x = 0, y = 0},
true = gen_server:call(Pid, {are_you_at, GoodPosition}),
false = gen_server:call(Pid, {are_you_at, BadPosition}).
carrot_entity_can_be_bitten(Config) ->
Pid = proplists:get_value(carrot_entity_pid, Config),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
{carrot, bite, EntityState} = common_test_event_handler:last_event_of(carrot, bite),
2 = EntityState#carrot.quantity.
carrot_entity_when_eaten_should_be_stopped(Config) ->
Pid = proplists:get_value(carrot_entity_pid, Config),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
gen_server:call(Pid, eat),
undefined = process_info(Pid).
| |
15ee3cd0f503ffdc520c8cd8f117ac687433fe96966d026112f3bb0969758616 | achesnais/clj-jupyter | heartbeat.clj | (ns clj-jupyter.heartbeat
(:require [taoensso.timbre :as log])
(:import zmq.ZMQ))
(set! *warn-on-reflection* true)
(defn start [{:keys [transport ip hb-port]} shutdown-signal]
(future
(log/info "Starting hearbeat...")
(let [ctx (ZMQ/createContext)
hb-socket (ZMQ/socket ctx ZMQ/ZMQ_REP)]
(ZMQ/bind hb-socket (str transport "://" ip ":" hb-port))
(ZMQ/setSocketOption hb-socket ZMQ/ZMQ_RCVTIMEO (int 250))
(log/debug "Heartbeat started!")
(while (not (realized? shutdown-signal))
(when-let [msg (ZMQ/recv hb-socket 0)]
(ZMQ/send hb-socket msg ZMQ/ZMQ_DONTWAIT)))
(log/debug "Stopping heartbeat...")
(ZMQ/close hb-socket)
(ZMQ/term ctx)
(log/info "Hearbeat stopped!")
:shutdown-success)))
| null | https://raw.githubusercontent.com/achesnais/clj-jupyter/3e90a87d5025e4d908c9b6baf75ef20b7c3618ce/src/clj_jupyter/heartbeat.clj | clojure | (ns clj-jupyter.heartbeat
(:require [taoensso.timbre :as log])
(:import zmq.ZMQ))
(set! *warn-on-reflection* true)
(defn start [{:keys [transport ip hb-port]} shutdown-signal]
(future
(log/info "Starting hearbeat...")
(let [ctx (ZMQ/createContext)
hb-socket (ZMQ/socket ctx ZMQ/ZMQ_REP)]
(ZMQ/bind hb-socket (str transport "://" ip ":" hb-port))
(ZMQ/setSocketOption hb-socket ZMQ/ZMQ_RCVTIMEO (int 250))
(log/debug "Heartbeat started!")
(while (not (realized? shutdown-signal))
(when-let [msg (ZMQ/recv hb-socket 0)]
(ZMQ/send hb-socket msg ZMQ/ZMQ_DONTWAIT)))
(log/debug "Stopping heartbeat...")
(ZMQ/close hb-socket)
(ZMQ/term ctx)
(log/info "Hearbeat stopped!")
:shutdown-success)))
| |
1a4afd19869ffa0b4fe824d4a0719662bb1eb8bf019ea8409ce54563e099f6b2 | abrantesasf/sicp-abrantes-study-guide | exercise-1.5.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Structure and Interpretation of Computer Programs , 2 . ed . ; ; ; ; ;
Section 1.1 , Exercise 1.5 ; ; ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Student : ; ; ; ; ;
Date : 2019 - 02 - 11 ; ; ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; QUESTION:
has invented a test to determine whether the
;;;; interpreter he is faced with is using applicative-order
;;;; evaluation or normal-order evaluation. He defines the following
two procedures :
(define (p) (p))
(define (test x y)
(if (= x 0)
0
y))
;;;; Then he evaluates the expression
(test 0 (p))
What behavior will observe with an interpreter that uses
;;;; applicative-order evaluation? What behavior will he observe with
;;;; an interpreter that uses normal-order evaluation? Explain your
;;;; answer. (Assume that the evaluation rule for the special form if
;;;; is the same whether the interpreter is using normal or applicative
order : The predicate expression is evaluated first , and the result
;;;; determines whether to evaluate the consequent or the alternative
;;;; expression.)
;;;; WRITE YOUR ANSWER HERE:
;
The first DEFINE it 's used to create a procedure " p " without any
; parameters. This procedure just return the value of procedure "p",
that is , procedure p is " recursivelly " returning the value of " p "
; itself.
(define (p) (p))
p
; compound procedure
The second DEFINE it 's used to create a procedure " test " with 2
; arguments, "x" and "y". If the value of x is 0, return 0, else
; return y value.
(define (test x y)
(if (= x 0)
0
y))
(test 0 1)
0
(test 1 1)
1
The " magic " is on the third expression :
(test 0 (p))
; The result of this expression it's dependent on the type of
; substitution model used by the interpreter: applicative-order or
; normal-order.
;
; a) If applicative-order, the interpreter FIRST EVALUATES the
; parameters, replacing it by the value of the subexpressions. But
; evaluating (p) just return "p" itself, so the interpreter
; continues to evaluate and ends in an infinite loop:
1 ) Evaluate ( test 0 ( p ) )
2 ) Evaluate subexpression 0 , and return 0 . Now we have :
( test 0 ( p ) )
3 ) Now evaluate subexpression ( p ): this return the value of
procedure p , which is p itself . Now we have :
( test 0 ( p ) )
4 ) Woops ! It 's need to evaluate the ( p ) subexpression again
; because of applicative-order. Evaluating (p) again, we have:
( test 0 ( p ) )
5 ) And so on ... we have an infinite loop . The problem was the
; applicative-order: THE ARGUMENTS ARE EVALUATED FIRST AND THEN
; THESE VALUES ARE SUBSTITUTED IN FURTHER EXPRESSION. The
; important point to note is this:
;
APPLICATIVE - ORDER : the arguments are evaluated first , and only
; after obtaining the value of the subexpression, the
; substitution continues.
;
; b) If normal-order: the interpreter FIRST EXPAND the procedures and
; the subexpressions are NOT EVALUATED until it's needed. We have:
1 ) Evaluate ( test 0 ( p ) )
2 ) Expand to : ( if (= 0 0 ) 0 ( p ) )
3 ) Now the interpreter evaluates (= 0 0 ) , which is # t , and so the
; procedure return 0:
0
4 ) The important point is :
;
; NORMAL-ORDER: the interpreter FIRST EXPAND the procedures and
; DO NOT EVALUATE subexpression until when it's needed.
| null | https://raw.githubusercontent.com/abrantesasf/sicp-abrantes-study-guide/c8d41093ed3d9944f003e88b7e1b7b29fbb6874a/1/1.1/sicp/exercise-1.5.scm | scheme |
; ; ; ;
; ; ; ;
; ; ; ;
; ; ; ;
QUESTION:
interpreter he is faced with is using applicative-order
evaluation or normal-order evaluation. He defines the following
Then he evaluates the expression
applicative-order evaluation? What behavior will he observe with
an interpreter that uses normal-order evaluation? Explain your
answer. (Assume that the evaluation rule for the special form if
is the same whether the interpreter is using normal or applicative
determines whether to evaluate the consequent or the alternative
expression.)
WRITE YOUR ANSWER HERE:
parameters. This procedure just return the value of procedure "p",
itself.
compound procedure
arguments, "x" and "y". If the value of x is 0, return 0, else
return y value.
The result of this expression it's dependent on the type of
substitution model used by the interpreter: applicative-order or
normal-order.
a) If applicative-order, the interpreter FIRST EVALUATES the
parameters, replacing it by the value of the subexpressions. But
evaluating (p) just return "p" itself, so the interpreter
continues to evaluate and ends in an infinite loop:
because of applicative-order. Evaluating (p) again, we have:
applicative-order: THE ARGUMENTS ARE EVALUATED FIRST AND THEN
THESE VALUES ARE SUBSTITUTED IN FURTHER EXPRESSION. The
important point to note is this:
after obtaining the value of the subexpression, the
substitution continues.
b) If normal-order: the interpreter FIRST EXPAND the procedures and
the subexpressions are NOT EVALUATED until it's needed. We have:
procedure return 0:
NORMAL-ORDER: the interpreter FIRST EXPAND the procedures and
DO NOT EVALUATE subexpression until when it's needed. |
has invented a test to determine whether the
two procedures :
(define (p) (p))
(define (test x y)
(if (= x 0)
0
y))
(test 0 (p))
What behavior will observe with an interpreter that uses
order : The predicate expression is evaluated first , and the result
The first DEFINE it 's used to create a procedure " p " without any
that is , procedure p is " recursivelly " returning the value of " p "
(define (p) (p))
p
The second DEFINE it 's used to create a procedure " test " with 2
(define (test x y)
(if (= x 0)
0
y))
(test 0 1)
0
(test 1 1)
1
The " magic " is on the third expression :
(test 0 (p))
1 ) Evaluate ( test 0 ( p ) )
2 ) Evaluate subexpression 0 , and return 0 . Now we have :
( test 0 ( p ) )
3 ) Now evaluate subexpression ( p ): this return the value of
procedure p , which is p itself . Now we have :
( test 0 ( p ) )
4 ) Woops ! It 's need to evaluate the ( p ) subexpression again
( test 0 ( p ) )
5 ) And so on ... we have an infinite loop . The problem was the
APPLICATIVE - ORDER : the arguments are evaluated first , and only
1 ) Evaluate ( test 0 ( p ) )
2 ) Expand to : ( if (= 0 0 ) 0 ( p ) )
3 ) Now the interpreter evaluates (= 0 0 ) , which is # t , and so the
0
4 ) The important point is :
|
927d21c3d4b6206e0cf40286044c6bb10e9a8dadf07740b48e5231df6d718189 | kitlang/kit | Base.hs | module Kit.Compiler.Typers.Base where
| null | https://raw.githubusercontent.com/kitlang/kit/2769a7a8e51fe4466c50439d1a1ebdad0fb79710/src/Kit/Compiler/Typers/Base.hs | haskell | module Kit.Compiler.Typers.Base where
| |
2fa52512ec99987caeb33192d4a1ef5f6fbde168a9bcd8deced790688d55ba97 | ygmpkk/house | Texturing.hs | --------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.Texturing
Copyright : ( c ) 2003
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
This module corresponds to section 3.8 ( Texturing ) of the OpenGL 1.4 specs .
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.Texturing (
TextureTarget(..), marshalTextureTarget,
PixelInternalFormat(..),
marshalPixelInternalFormat, unmarshalPixelInternalFormat
) where
import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum )
--------------------------------------------------------------------------------
data TextureTarget =
Texture1D
| Texture2D
| Texture3D
| ProxyTexture1D
| ProxyTexture2D
| ProxyTexture3D
| TextureCubeMap
| ProxyTextureCubeMap
| TextureCubeMapPositiveX
| TextureCubeMapNegativeX
| TextureCubeMapPositiveY
| TextureCubeMapNegativeY
| TextureCubeMapPositiveZ
| TextureCubeMapNegativeZ
deriving ( Eq, Ord, Show )
marshalTextureTarget :: TextureTarget -> GLenum
marshalTextureTarget x = case x of
Texture1D -> 0xde0
Texture2D -> 0xde1
Texture3D -> 0x806f
ProxyTexture1D -> 0x8063
ProxyTexture2D -> 0x8064
ProxyTexture3D -> 0x8070
TextureCubeMap -> 0x8513
ProxyTextureCubeMap -> 0x851b
TextureCubeMapPositiveX -> 0x8515
TextureCubeMapNegativeX -> 0x8516
TextureCubeMapPositiveY -> 0x8517
TextureCubeMapNegativeY -> 0x8518
TextureCubeMapPositiveZ -> 0x8519
TextureCubeMapNegativeZ -> 0x851a
--------------------------------------------------------------------------------
data PixelInternalFormat =
Alpha'
| DepthComponent'
| Luminance'
| LuminanceAlpha'
| Intensity
| RGB'
| RGBA'
| Alpha4
| Alpha8
| Alpha12
| Alpha16
| DepthComponent16
| DepthComponent24
| DepthComponent32
| Luminance4
| Luminance8
| Luminance12
| Luminance16
| Luminance4Alpha4
| Luminance6Alpha2
| Luminance8Alpha8
| Luminance12Alpha4
| Luminance12Alpha12
| Luminance16Alpha16
| Intensity4
| Intensity8
| Intensity12
| Intensity16
| R3G3B2
| RGB4
| RGB5
| RGB8
| RGB10
| RGB12
| RGB16
| RGBA2
| RGBA4
| RGB5A1
| RGBA8
| RGB10A2
| RGBA12
| RGBA16
| CompressedAlpha
| CompressedLuminance
| CompressedLuminanceAlpha
| CompressedIntensity
| CompressedRGB
| CompressedRGBA
deriving ( Eq, Ord, Show )
marshalPixelInternalFormat :: PixelInternalFormat -> GLenum
marshalPixelInternalFormat x = case x of
Alpha' -> 0x1906
DepthComponent' -> 0x1902
Luminance' -> 0x1909
LuminanceAlpha' -> 0x190a
RGB' -> 0x1907
RGBA' -> 0x1908
Alpha4 -> 0x803b
Alpha8 -> 0x803c
Alpha12 -> 0x803d
Alpha16 -> 0x803e
DepthComponent16 -> 0x81a5
DepthComponent24 -> 0x81a6
DepthComponent32 -> 0x81a7
Luminance4 -> 0x803f
Luminance8 -> 0x8040
Luminance12 -> 0x8041
Luminance16 -> 0x8042
Luminance4Alpha4 -> 0x8043
Luminance6Alpha2 -> 0x8044
Luminance8Alpha8 -> 0x8045
Luminance12Alpha4 -> 0x8046
Luminance12Alpha12 -> 0x8047
Luminance16Alpha16 -> 0x8048
Intensity -> 0x8049
Intensity4 -> 0x804a
Intensity8 -> 0x804b
Intensity12 -> 0x804c
Intensity16 -> 0x804d
R3G3B2 -> 0x2a10
RGB4 -> 0x804f
RGB5 -> 0x8050
RGB8 -> 0x8051
RGB10 -> 0x8052
RGB12 -> 0x8053
RGB16 -> 0x8054
RGBA2 -> 0x8055
RGBA4 -> 0x8056
RGB5A1 -> 0x8057
RGBA8 -> 0x8058
RGB10A2 -> 0x8059
RGBA12 -> 0x805a
RGBA16 -> 0x805b
CompressedAlpha -> 0x84e9
CompressedLuminance -> 0x84ea
CompressedLuminanceAlpha -> 0x84eb
CompressedIntensity -> 0x84ec
CompressedRGB -> 0x84ed
CompressedRGBA -> 0x84ee
unmarshalPixelInternalFormat :: GLenum -> PixelInternalFormat
unmarshalPixelInternalFormat x
| x == 0x1906 = Alpha'
| x == 0x1902 = DepthComponent'
| x == 0x1909 = Luminance'
| x == 0x190a = LuminanceAlpha'
| x == 0x1907 = RGB'
| x == 0x1908 = RGBA'
| x == 0x803b = Alpha4
| x == 0x803c = Alpha8
| x == 0x803d = Alpha12
| x == 0x803e = Alpha16
| x == 0x81a5 = DepthComponent16
| x == 0x81a6 = DepthComponent24
| x == 0x81a7 = DepthComponent32
| x == 0x803f = Luminance4
| x == 0x8040 = Luminance8
| x == 0x8041 = Luminance12
| x == 0x8042 = Luminance16
| x == 0x8043 = Luminance4Alpha4
| x == 0x8044 = Luminance6Alpha2
| x == 0x8045 = Luminance8Alpha8
| x == 0x8046 = Luminance12Alpha4
| x == 0x8047 = Luminance12Alpha12
| x == 0x8048 = Luminance16Alpha16
| x == 0x8049 = Intensity
| x == 0x804a = Intensity4
| x == 0x804b = Intensity8
| x == 0x804c = Intensity12
| x == 0x804d = Intensity16
| x == 0x2a10 = R3G3B2
| x == 0x804f = RGB4
| x == 0x8050 = RGB5
| x == 0x8051 = RGB8
| x == 0x8052 = RGB10
| x == 0x8053 = RGB12
| x == 0x8054 = RGB16
| x == 0x8055 = RGBA2
| x == 0x8056 = RGBA4
| x == 0x8057 = RGB5A1
| x == 0x8058 = RGBA8
| x == 0x8059 = RGB10A2
| x == 0x805a = RGBA12
| x == 0x805b = RGBA16
| x == 0x84e9 = CompressedAlpha
| x == 0x84ea = CompressedLuminance
| x == 0x84eb = CompressedLuminanceAlpha
| x == 0x84ec = CompressedIntensity
| x == 0x84ed = CompressedRGB
| x == 0x84ee = CompressedRGBA
| otherwise = error ("unmarshalPixelInternalFormat: illegal value " ++ show x)
| null | https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/OpenGL/Graphics/Rendering/OpenGL/GL/Texturing.hs | haskell | ------------------------------------------------------------------------------
|
Module : Graphics.Rendering.OpenGL.GL.Texturing
License : BSD-style (see the file libraries/OpenGL/LICENSE)
Maintainer :
Stability : provisional
Portability : portable
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | Copyright : ( c ) 2003
This module corresponds to section 3.8 ( Texturing ) of the OpenGL 1.4 specs .
module Graphics.Rendering.OpenGL.GL.Texturing (
TextureTarget(..), marshalTextureTarget,
PixelInternalFormat(..),
marshalPixelInternalFormat, unmarshalPixelInternalFormat
) where
import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum )
data TextureTarget =
Texture1D
| Texture2D
| Texture3D
| ProxyTexture1D
| ProxyTexture2D
| ProxyTexture3D
| TextureCubeMap
| ProxyTextureCubeMap
| TextureCubeMapPositiveX
| TextureCubeMapNegativeX
| TextureCubeMapPositiveY
| TextureCubeMapNegativeY
| TextureCubeMapPositiveZ
| TextureCubeMapNegativeZ
deriving ( Eq, Ord, Show )
marshalTextureTarget :: TextureTarget -> GLenum
marshalTextureTarget x = case x of
Texture1D -> 0xde0
Texture2D -> 0xde1
Texture3D -> 0x806f
ProxyTexture1D -> 0x8063
ProxyTexture2D -> 0x8064
ProxyTexture3D -> 0x8070
TextureCubeMap -> 0x8513
ProxyTextureCubeMap -> 0x851b
TextureCubeMapPositiveX -> 0x8515
TextureCubeMapNegativeX -> 0x8516
TextureCubeMapPositiveY -> 0x8517
TextureCubeMapNegativeY -> 0x8518
TextureCubeMapPositiveZ -> 0x8519
TextureCubeMapNegativeZ -> 0x851a
data PixelInternalFormat =
Alpha'
| DepthComponent'
| Luminance'
| LuminanceAlpha'
| Intensity
| RGB'
| RGBA'
| Alpha4
| Alpha8
| Alpha12
| Alpha16
| DepthComponent16
| DepthComponent24
| DepthComponent32
| Luminance4
| Luminance8
| Luminance12
| Luminance16
| Luminance4Alpha4
| Luminance6Alpha2
| Luminance8Alpha8
| Luminance12Alpha4
| Luminance12Alpha12
| Luminance16Alpha16
| Intensity4
| Intensity8
| Intensity12
| Intensity16
| R3G3B2
| RGB4
| RGB5
| RGB8
| RGB10
| RGB12
| RGB16
| RGBA2
| RGBA4
| RGB5A1
| RGBA8
| RGB10A2
| RGBA12
| RGBA16
| CompressedAlpha
| CompressedLuminance
| CompressedLuminanceAlpha
| CompressedIntensity
| CompressedRGB
| CompressedRGBA
deriving ( Eq, Ord, Show )
marshalPixelInternalFormat :: PixelInternalFormat -> GLenum
marshalPixelInternalFormat x = case x of
Alpha' -> 0x1906
DepthComponent' -> 0x1902
Luminance' -> 0x1909
LuminanceAlpha' -> 0x190a
RGB' -> 0x1907
RGBA' -> 0x1908
Alpha4 -> 0x803b
Alpha8 -> 0x803c
Alpha12 -> 0x803d
Alpha16 -> 0x803e
DepthComponent16 -> 0x81a5
DepthComponent24 -> 0x81a6
DepthComponent32 -> 0x81a7
Luminance4 -> 0x803f
Luminance8 -> 0x8040
Luminance12 -> 0x8041
Luminance16 -> 0x8042
Luminance4Alpha4 -> 0x8043
Luminance6Alpha2 -> 0x8044
Luminance8Alpha8 -> 0x8045
Luminance12Alpha4 -> 0x8046
Luminance12Alpha12 -> 0x8047
Luminance16Alpha16 -> 0x8048
Intensity -> 0x8049
Intensity4 -> 0x804a
Intensity8 -> 0x804b
Intensity12 -> 0x804c
Intensity16 -> 0x804d
R3G3B2 -> 0x2a10
RGB4 -> 0x804f
RGB5 -> 0x8050
RGB8 -> 0x8051
RGB10 -> 0x8052
RGB12 -> 0x8053
RGB16 -> 0x8054
RGBA2 -> 0x8055
RGBA4 -> 0x8056
RGB5A1 -> 0x8057
RGBA8 -> 0x8058
RGB10A2 -> 0x8059
RGBA12 -> 0x805a
RGBA16 -> 0x805b
CompressedAlpha -> 0x84e9
CompressedLuminance -> 0x84ea
CompressedLuminanceAlpha -> 0x84eb
CompressedIntensity -> 0x84ec
CompressedRGB -> 0x84ed
CompressedRGBA -> 0x84ee
unmarshalPixelInternalFormat :: GLenum -> PixelInternalFormat
unmarshalPixelInternalFormat x
| x == 0x1906 = Alpha'
| x == 0x1902 = DepthComponent'
| x == 0x1909 = Luminance'
| x == 0x190a = LuminanceAlpha'
| x == 0x1907 = RGB'
| x == 0x1908 = RGBA'
| x == 0x803b = Alpha4
| x == 0x803c = Alpha8
| x == 0x803d = Alpha12
| x == 0x803e = Alpha16
| x == 0x81a5 = DepthComponent16
| x == 0x81a6 = DepthComponent24
| x == 0x81a7 = DepthComponent32
| x == 0x803f = Luminance4
| x == 0x8040 = Luminance8
| x == 0x8041 = Luminance12
| x == 0x8042 = Luminance16
| x == 0x8043 = Luminance4Alpha4
| x == 0x8044 = Luminance6Alpha2
| x == 0x8045 = Luminance8Alpha8
| x == 0x8046 = Luminance12Alpha4
| x == 0x8047 = Luminance12Alpha12
| x == 0x8048 = Luminance16Alpha16
| x == 0x8049 = Intensity
| x == 0x804a = Intensity4
| x == 0x804b = Intensity8
| x == 0x804c = Intensity12
| x == 0x804d = Intensity16
| x == 0x2a10 = R3G3B2
| x == 0x804f = RGB4
| x == 0x8050 = RGB5
| x == 0x8051 = RGB8
| x == 0x8052 = RGB10
| x == 0x8053 = RGB12
| x == 0x8054 = RGB16
| x == 0x8055 = RGBA2
| x == 0x8056 = RGBA4
| x == 0x8057 = RGB5A1
| x == 0x8058 = RGBA8
| x == 0x8059 = RGB10A2
| x == 0x805a = RGBA12
| x == 0x805b = RGBA16
| x == 0x84e9 = CompressedAlpha
| x == 0x84ea = CompressedLuminance
| x == 0x84eb = CompressedLuminanceAlpha
| x == 0x84ec = CompressedIntensity
| x == 0x84ed = CompressedRGB
| x == 0x84ee = CompressedRGBA
| otherwise = error ("unmarshalPixelInternalFormat: illegal value " ++ show x)
|
5b60950aea5e97223364ef57136b7202d64ee0eedaa02a280e497364bc6b593d | xsc/lein-ancient | collect.clj | (ns leiningen.ancient.collect
(:require [leiningen.ancient.artifact.files :as f]
[clojure.java.io :as io])
(:import [java.io File]
[org.apache.commons.io FileUtils]))
# # Project
(defn project-file-at
"Find project file in the given directory.
Returns `nil` "
[path]
(let [f (io/file path)]
(if (.isDirectory f)
(->> (io/file f "project.clj")
(f/project-file))
(if (.isFile f)
(f/project-file f)))))
(defn current-project-file
"Find the current project file"
[project]
(project-file-at (:root project)))
(defn recursive-project-files
"Find all project files in a directory and its children."
[path]
(letfn [(lazy-find [^java.io.File dir]
(lazy-seq
(when-not (FileUtils/isSymlink dir)
(when (.isDirectory dir)
(let [f (io/file dir "project.clj")
rst (filter #(.isDirectory ^java.io.File %) (.listFiles dir))]
(if (.isFile f)
(cons f (mapcat lazy-find rst))
(mapcat lazy-find rst)))))))]
(->> (io/file path)
(.getCanonicalPath)
(io/file)
(lazy-find)
(map f/project-file))))
;; ## Profiles
(defn- lein-home
"Get the Leiningen home directory."
[]
(or (if-let [p (System/getenv "LEIN_HOME")]
(let [f (io/file p)]
(if (.isDirectory f)
f)))
(let [home (System/getProperty "user.home")]
(io/file home ".lein"))))
(defn- project-profiles-file
[project]
(io/file (:root project) "profiles.clj"))
(defn- default-profiles-file
"Get the default profiles.clj."
[]
(io/file (lein-home) "profiles.clj"))
(defn- profiles-directory-files
"Get the sub-profiles directory."
[]
(let [d (io/file (lein-home) "profiles.d")]
(keep
(fn [^File f]
(let [n (.getName f)]
(if (or (.endsWith n ".clj")
(.endsWith n ".edn"))
(-> (subs n 0 (- (count n) 4))
(keyword)
(vector)
(vector f)))))
(.listFiles d))))
(defn profiles-file-at
[path]
(let [f (io/file path)]
(if (.isDirectory f)
(->> (io/file f "profiles.clj")
(f/profiles-file))
(if (.isFile f)
(f/profiles-file f)))))
(defn profiles-files
"Collect all profiles files."
[project]
(->> (profiles-directory-files)
(cons [[] (default-profiles-file)])
(cons [[] (project-profiles-file project)])
(keep
(fn [[prefix ^File f]]
(if (.isFile f)
(->> (cons :profiles prefix)
(vec)
(f/profiles-file f)))))))
| null | https://raw.githubusercontent.com/xsc/lein-ancient/ddcb0a1d655eda37daa47bea63e5eee72985a1ed/src/leiningen/ancient/collect.clj | clojure | ## Profiles | (ns leiningen.ancient.collect
(:require [leiningen.ancient.artifact.files :as f]
[clojure.java.io :as io])
(:import [java.io File]
[org.apache.commons.io FileUtils]))
# # Project
(defn project-file-at
"Find project file in the given directory.
Returns `nil` "
[path]
(let [f (io/file path)]
(if (.isDirectory f)
(->> (io/file f "project.clj")
(f/project-file))
(if (.isFile f)
(f/project-file f)))))
(defn current-project-file
"Find the current project file"
[project]
(project-file-at (:root project)))
(defn recursive-project-files
"Find all project files in a directory and its children."
[path]
(letfn [(lazy-find [^java.io.File dir]
(lazy-seq
(when-not (FileUtils/isSymlink dir)
(when (.isDirectory dir)
(let [f (io/file dir "project.clj")
rst (filter #(.isDirectory ^java.io.File %) (.listFiles dir))]
(if (.isFile f)
(cons f (mapcat lazy-find rst))
(mapcat lazy-find rst)))))))]
(->> (io/file path)
(.getCanonicalPath)
(io/file)
(lazy-find)
(map f/project-file))))
(defn- lein-home
"Get the Leiningen home directory."
[]
(or (if-let [p (System/getenv "LEIN_HOME")]
(let [f (io/file p)]
(if (.isDirectory f)
f)))
(let [home (System/getProperty "user.home")]
(io/file home ".lein"))))
(defn- project-profiles-file
[project]
(io/file (:root project) "profiles.clj"))
(defn- default-profiles-file
"Get the default profiles.clj."
[]
(io/file (lein-home) "profiles.clj"))
(defn- profiles-directory-files
"Get the sub-profiles directory."
[]
(let [d (io/file (lein-home) "profiles.d")]
(keep
(fn [^File f]
(let [n (.getName f)]
(if (or (.endsWith n ".clj")
(.endsWith n ".edn"))
(-> (subs n 0 (- (count n) 4))
(keyword)
(vector)
(vector f)))))
(.listFiles d))))
(defn profiles-file-at
[path]
(let [f (io/file path)]
(if (.isDirectory f)
(->> (io/file f "profiles.clj")
(f/profiles-file))
(if (.isFile f)
(f/profiles-file f)))))
(defn profiles-files
"Collect all profiles files."
[project]
(->> (profiles-directory-files)
(cons [[] (default-profiles-file)])
(cons [[] (project-profiles-file project)])
(keep
(fn [[prefix ^File f]]
(if (.isFile f)
(->> (cons :profiles prefix)
(vec)
(f/profiles-file f)))))))
|
acd11abd2d67f26efd77126345c1ca1b498d58cb4d312bbc1fc499f4ea4315a6 | craigl64/clim-ccl | layout.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Package : SILICA ; Base : 10 ; Lowercase : Yes -*-
;; See the file LICENSE for the full license governing this code.
;;
(in-package :silica)
" Copyright ( c ) 1991 , 1992 Franz , Inc. All rights reserved .
Portions copyright ( c ) 1992 Symbolics , Inc. All rights reserved .
Portions copyright ( c ) 1989 , 1990 Xerox Corp. All rights reserved . "
(define-protocol-class space-requirement ())
(defmethod print-object ((object space-requirement) stream)
(print-unreadable-object (object stream :type t)
(multiple-value-bind (width min-width max-width height min-height max-height)
(space-requirement-components object)
(format stream "~D<w=~D<~D ~D<h=~D<~D"
min-width width max-width
min-height height max-height))))
(defclass null-space-requirement (space-requirement) ())
(defmethod space-requirement-components ((sr null-space-requirement))
(values 0 0 0 0 0 0))
(defmethod space-requirement-width ((sr null-space-requirement)) 0)
(defmethod space-requirement-min-width ((sr null-space-requirement)) 0)
(defmethod space-requirement-max-width ((sr null-space-requirement)) 0)
(defmethod space-requirement-height ((sr null-space-requirement)) 0)
(defmethod space-requirement-min-height ((sr null-space-requirement)) 0)
(defmethod space-requirement-max-height ((sr null-space-requirement)) 0)
(defvar +null-space-requirement+ (make-instance 'null-space-requirement))
(defclass simple-space-requirement (space-requirement)
((width :initarg :width :accessor space-requirement-width)
(height :initarg :height :accessor space-requirement-height)))
(defmethod space-requirement-components ((sr simple-space-requirement))
(with-slots (width height) sr
(values width width width
height height height)))
;(defmethod space-requirement-width ((sr simple-space-requirement))
; (slot-value sr 'width))
(defmethod space-requirement-min-width ((sr simple-space-requirement))
(slot-value sr 'width))
(defmethod space-requirement-max-width ((sr simple-space-requirement))
(slot-value sr 'width))
;(defmethod space-requirement-height ((sr simple-space-requirement))
; (slot-value sr 'height))
(defmethod space-requirement-min-height ((sr simple-space-requirement))
(slot-value sr 'height))
(defmethod space-requirement-max-height ((sr simple-space-requirement))
(slot-value sr 'height))
(defclass general-space-requirement (space-requirement)
((width :initarg :width :reader space-requirement-width)
(min-width :reader space-requirement-min-width)
(max-width :reader space-requirement-max-width)
(height :initarg :height :reader space-requirement-height)
(min-height :reader space-requirement-min-height)
(max-height :reader space-requirement-max-height)))
(defmethod space-requirement-components ((sr general-space-requirement))
(with-slots (width min-width max-width
height min-height max-height) sr
(values width min-width max-width
height min-height max-height)))
(defmethod initialize-instance :after ((sr general-space-requirement)
&key (width (error "Width not specified"))
(min-width width)
(max-width width)
(height (error "Height not specified"))
(min-height height)
(max-height height))
(setf (slot-value sr 'min-height) min-height
(slot-value sr 'max-height) max-height
(slot-value sr 'min-width) min-width
(slot-value sr 'max-width) max-width))
(defun make-space-requirement (&key (width 0) (min-width width) (max-width width)
(height 0) (min-height height) (max-height height))
(cond ((and (eq width min-width) (eq width max-width)
(eq height min-height) (eq height max-height))
;; Compare with EQ since width and height can be :COMPUTE
(if (and (eq width 0) (eq height 0))
+null-space-requirement+
(make-instance 'simple-space-requirement
:width width :height height)))
(t
(make-instance 'general-space-requirement
:width width :min-width min-width :max-width max-width
:height height :min-height min-height :max-height max-height))))
(defconstant +fill+
expression below gives 100 in aclpc - too small
#-(or aclpc acl86win32)
(floor (/ (expt 10 (floor (log most-positive-fixnum 10))) 100)))
Layout protocol
;(defgeneric compose-space (sheet)
; )
;
;(defmethod compose-space (sheet)
; (multiple-value-bind (width height)
; (bounding-rectangle-size sheet)
; (make-space-requirement :width width :height height)))
;
;(defgeneric allocate-space (sheet width height))
;
( defmethod allocate - space ( sheet width height )
; (declare (ignore sheet width height)))
(defun parse-box-contents (contents)
(mapcar #'(lambda (x)
;; Handle top-down layout syntax
(if (and (consp x)
(typep (first x) '(or (member :fill) number)))
`(list ,(first x) ,(second x))
x))
contents))
(defmacro vertically ((&rest options &key spacing &allow-other-keys)
&body contents)
(declare (ignore spacing))
`(make-pane 'vbox-pane
:contents (list ,@(parse-box-contents contents))
,@options))
(defmacro horizontally ((&rest options &key spacing &allow-other-keys)
&body contents)
(declare (ignore spacing))
`(make-pane 'hbox-pane
:contents (list ,@(parse-box-contents contents))
,@options))
(defmethod resize-sheet ((sheet basic-sheet) width height)
(unless (and (> width 0) (> height 0))
(error "Trying to resize sheet ~S to be too small (~D x ~D)"
sheet width height))
(with-bounding-rectangle* (left top right bottom) sheet
(let ((owidth (- right left))
(oheight (- bottom top)))
(if (or (/= owidth width)
(/= oheight height)
#+allegro
(mirror-needs-changing-p sheet left top width height))
;; It should be safe to modify the sheet's region, since
;; each sheet gets a fresh region when it is created
(let ((region (sheet-region sheet)))
(setf (slot-value region 'left) left
(slot-value region 'top) top
(slot-value region 'right) (+ left width)
(slot-value region 'bottom) (+ top height))
(note-sheet-region-changed sheet))
;;--- Do this so that we relayout the rest of tree.
;;--- I guess we do not want to do this always but ...
(allocate-space sheet owidth oheight)))))
;;;-- This sucks but it seems to get round the problem of the mirror
;;;-- geometry being completely wrong after the layout has been changed
(defmethod mirror-needs-changing-p ((sheet sheet) left top width height)
(declare (ignore left top width height))
nil)
(defmethod mirror-needs-changing-p ((sheet mirrored-sheet-mixin)
left top width height)
(and (sheet-direct-mirror sheet)
(multiple-value-bind (mleft mtop mright mbottom)
(mirror-region* (port sheet) sheet)
(or (/= left mleft)
(/= top mtop)
(/= width (- mright mleft))
(/= height (- mbottom mtop))))))
(defmethod move-sheet ((sheet basic-sheet) x y)
(let ((transform (sheet-transformation sheet)))
(multiple-value-bind (old-x old-y)
(transform-position transform 0 0)
(with-bounding-rectangle* (left top right bottom) sheet
(when (or (and x (/= old-x x))
(and y (/= old-y y))
(mirror-needs-changing-p sheet x y (- right left) (- bottom top)))
;; We would like to use volatile transformations here, but it's
;; not really safe, since the current implementation of transformations
;; is likely to cause them to be shared
(setf (sheet-transformation sheet)
(compose-translation-with-transformation
transform
(if x (- x old-x) 0) (if y (- y old-y) 0))))))))
(defmethod move-and-resize-sheet ((sheet basic-sheet) x y width height)
(resize-sheet sheet width height)
(move-sheet sheet x y))
(defgeneric sheet-flags (sheet)
(:documentation "Returns a list of flags that the port may have set concerning the sheet.")
(:method ((sheet basic-sheet))
()))
(defgeneric (setf sheet-flags) (new-value sheet)
(:documentation "Set a list of flags, as supported by the port. Ignores any flags that the port doesn't understand.")
(:method (new-value (sheet basic-sheet))
(declare (ignore new-value))
nil))
;;; Various
(define-protocol-class pane (sheet))
#+aclpc ;;; aclpc is anal about initialization args, so we must appease
(defmethod initialize-instance :around ((pane pane) &key background text-style)
(apply #'call-next-method nil))
--- What about PANE - FOREGROUND / BACKGROUND vs. MEDIUM - FOREGROUND / BACKGROUND ?
(defclass basic-pane
(sheet-transformation-mixin
standard-sheet-input-mixin
standard-repainting-mixin
temporary-medium-sheet-output-mixin
basic-sheet
pane)
((frame :reader pane-frame :initarg :frame)
(framem :reader frame-manager :initarg :frame-manager)
(name :accessor pane-name :initform nil :initarg :name)))
(defmethod print-object ((object basic-pane) stream)
(if (and (slot-boundp object 'name)
(stringp (slot-value object 'name)))
(print-unreadable-object (object stream :type t :identity t)
(format stream "~A" (slot-value object 'name)))
(call-next-method)))
(defmethod handle-repaint ((pane basic-pane) region)
(declare (ignore region))
nil)
;;--- This is suspicious - it should either be on a composite-pane or
;;--- on a top-level sheet
#+++ignore
(defmethod note-sheet-region-changed :after ((sheet basic-pane) &key port)
(declare (ignore port))
(multiple-value-bind (width height) (bounding-rectangle-size sheet)
(allocate-space sheet width height)))
(defmethod pane-frame ((sheet basic-sheet)) nil)
;(defclass list-contents-mixin ()
( ( contents : initform nil )
( nslots : initform nil : initarg : )
; ; Reverse - p is provided because it makes sense to let users specify
; ;; vertical lists from top to bottom, but internally it is easier to deal
; ;; with bottom to top, because of the lower left coordinate system.
; ; For example , a user would like to list the vbox contents from top to
; ;; bottom, while y coords increases from bottom to top. Whereas with
; ; a hbox , user specifys left to right just as x coord increases left
; ;; to right.
; ;;
; ;; A problem with reverse-p solution is that when new panes are inserted,
; ;; all panes before them in the user's view of contents changes coord,
; ;; but the user may expect the one's later in the list to change coords.
; ;; For example in a vertical list, adding a pane to the end will
; ;; reposition all of the list items.
;
; ;; A possible solution is to user a upper left coordinate
; ;; system so that added items have absolute y values that are increasing.
; ; Once upon a time told me he prefered this , but it 'll have to wait
; ;; for now. A deeper problem with this solution is that different panes
; ;; would have different coordinate systems which maybe confusing if the
; ;; coordinate system is exposed to the client in anyway.
( reverse - p : initform nil : initarg : reverse - p ) ) )
;
;;;;
;;;; Insertion/Deletion Protocols
;;;;
;
( defmethod contents ( ( lcm list - contents - mixin ) )
( with - slots ( reverse - p contents ) lcm
; (if reverse-p (reverse contents)
; contents)))
;
( defmethod ( setf contents ) ( new - contents ( lcm list - contents - mixin ) )
( with - slots ( reverse - p contents children ) lcm
( dolist ( pane contents )
; (sheet-disown-child lcm pane))
( dolist ( pane new - contents )
; (sheet-adopt-child lcm pane))
( setf contents ( if reverse - p ( reverse new - contents )
; new-contents)
; ;; So that things repaint from top to bottom
; ;; ??? However, it only work is you go through this method.
children ( if reverse - p ( nreverse children )
; children))
;
( note - space - requirements - changed ( sheet - parent lcm ) lcm ) ) )
;
;
;
;(defun check-position (position reverse-p contents)
; (let ((len (length contents)))
; (when reverse-p
; (setq position (if position (- len position) 0)))
( unless position ( setq position len ) )
; (check-type position number)
; (assert (and (<= 0 position) (<= position len))
; (position)
; "Position argument out of bounds")
; position))
;
( defmethod insert - panes ( ( lcm list - contents - mixin ) panes
; &key position &allow-other-keys)
( with - slots ( reverse - p contents ) lcm
; (setq position (check-position position reverse-p contents))
( dolist ( pane panes )
; (insert-pane lcm pane :position position :batch-p t)
( unless reverse - p ( incf position ) ) )
( note - space - requirements - changed ( sheet - parent lcm ) lcm ) ) )
;
( defmethod insert - pane ( ( lcm list - contents - mixin ) ( pane basic - pane )
; &key position batch-p &allow-other-keys)
( with - slots ( contents reverse - p ) lcm
; (unless batch-p
; (setq position (check-position position reverse-p contents)))
( if ( zerop position )
; (push pane contents)
( let ( ( tail ( ( 1- position ) contents ) ) )
( setf ( cdr tail )
; (cons pane (cdr tail)))))
; (sheet-adopt-child lcm pane)
; (unless batch-p
( note - space - requirements - changed ( sheet - parent lcm ) lcm ) ) ) )
;
( defmethod remove - panes ( ( lcm list - contents - mixin ) panes )
( dolist ( pane panes )
( with - slots ( contents ) lcm
( setf contents ( delete pane contents ) )
; (sheet-disown-child lcm pane)))
( note - space - requirements - changed ( sheet - parent lcm ) lcm ) )
;
( defmethod remove - pane ( ( lcm list - contents - mixin ) ( pane basic - pane )
; &key batch-p &allow-other-keys)
( with - slots ( contents ) lcm
( setf contents ( delete pane contents : test # ' eq ) )
; (sheet-disown-child lcm pane)
( unless batch - p ( note - space - requirements - changed ( sheet - parent lcm ) lcm ) ) ) )
;
( defmethod note - space - requirements - changed : before ( parent ( lcm list - contents - mixin ) )
# -PCL ; ; PCL uses this variable for method - table cache misses , unfortunately .
; (declare (ignore parent))
( with - slots ( nslots contents ) lcm
( setf nslots ( length contents ) ) ) )
--- CLIM 0.9 has some other methods on top - level sheets -- do we want them ?
(defclass top-level-sheet
(;;--- Temporary kludge until we get the protocols correct
;;--- so that ACCEPT works correctly on a raw sheet
clim-internals::window-stream
wrapping-space-mixin
sheet-multiple-child-mixin
mirrored-sheet-mixin
permanent-medium-sheet-output-mixin
basic-pane)
((user-specified-size-p :initform :unspecified :initarg :user-specified-size-p)
(user-specified-position-p :initform :unspecified :initarg :user-specified-position-p))
;;--- More of same...
(:default-initargs :text-cursor nil :text-margin most-positive-fixnum))
(defmethod window-refresh ((sheet top-level-sheet))
nil)
;;; spr24242:
;;; Note:
The following methods are specified in the Clim documentation
( at the end of Sec 19.5.2 ) .
;;;
;;; These are methods are basically copies of methods on the class
clim - stream - sheet ( in clim / db - stream.lisp ) .
(defmethod window-expose ((stream top-level-sheet))
(setf (window-visibility stream) t))
(defmethod (setf window-visibility) (visibility (stream top-level-sheet))
(let ((frame (pane-frame stream)))
(if frame
(if visibility
(enable-frame frame)
(disable-frame frame))
(setf (sheet-enabled-p stream) visibility))))
(defmethod window-visibility ((stream top-level-sheet))
: Is the Unix code more correct ? ? ?
#+(or aclpc acl86win32)
(mirror-visible-p (port stream) stream)
#-(or aclpc acl86win32)
(let ((frame (pane-frame stream)))
(and (if frame
(eq (frame-state frame) :enabled)
(sheet-enabled-p stream))
(mirror-visible-p (port stream) stream)))
)
(defmethod window-stack-on-top ((stream top-level-sheet))
(raise-sheet (window-top-level-window stream)))
(defmethod window-stack-on-bottom ((stream top-level-sheet))
(bury-sheet (window-top-level-window stream)))
(defmethod window-inside-edges ((stream top-level-sheet))
(bounding-rectangle* (sheet-region (or (pane-viewport stream) stream))))
(defmethod window-inside-size ((stream top-level-sheet))
(bounding-rectangle-size (sheet-region (or (pane-viewport stream) stream))))
;;--- Needed methods include:
--- INVOKE - WITH - RECORDING - OPTIONS
--- DEFAULT - TEXT - MARGIN
;;--- STREAM-READ-GESTURE
(defmethod note-layout-mixin-region-changed ((pane top-level-sheet) &key port)
(let ((frame (pane-frame pane)))
(if (and port frame (frame-top-level-sheet frame))
We do this because if the WM has resized us then we want to
do the complete LAYOUT - FRAME thing including clearing caches
;; etc etc. Don't do this if the frame doesn't own this top-level
;; sheet yet (still initializing).
(multiple-value-call #'layout-frame
(pane-frame pane)
(bounding-rectangle-size pane))
Otherwise just call ALLOCATE - SPACE etc
(call-next-method))))
#+++ignore
(defmethod allocate-space ((sheet top-level-sheet) width height)
(resize-sheet (first (sheet-children sheet)) width height))
#+++ignore
(defmethod compose-space ((sheet top-level-sheet) &key width height)
(compose-space (first (sheet-children sheet)) :width width :height height))
(defclass composite-pane
(sheet-multiple-child-mixin
basic-pane)
())
(defclass leaf-pane
(sheet-permanently-enabled-mixin
client-overridability-mixin
basic-pane)
((cursor :initarg :cursor :initform nil
:accessor sheet-cursor)))
| null | https://raw.githubusercontent.com/craigl64/clim-ccl/301efbd770745b429f2b00b4e8ca6624de9d9ea9/silica/layout.lisp | lisp | Syntax : ANSI - Common - Lisp ; Package : SILICA ; Base : 10 ; Lowercase : Yes -*-
See the file LICENSE for the full license governing this code.
(defmethod space-requirement-width ((sr simple-space-requirement))
(slot-value sr 'width))
(defmethod space-requirement-height ((sr simple-space-requirement))
(slot-value sr 'height))
Compare with EQ since width and height can be :COMPUTE
(defgeneric compose-space (sheet)
)
(defmethod compose-space (sheet)
(multiple-value-bind (width height)
(bounding-rectangle-size sheet)
(make-space-requirement :width width :height height)))
(defgeneric allocate-space (sheet width height))
(declare (ignore sheet width height)))
Handle top-down layout syntax
It should be safe to modify the sheet's region, since
each sheet gets a fresh region when it is created
--- Do this so that we relayout the rest of tree.
--- I guess we do not want to do this always but ...
-- This sucks but it seems to get round the problem of the mirror
-- geometry being completely wrong after the layout has been changed
We would like to use volatile transformations here, but it's
not really safe, since the current implementation of transformations
is likely to cause them to be shared
Various
aclpc is anal about initialization args, so we must appease
--- This is suspicious - it should either be on a composite-pane or
--- on a top-level sheet
(defclass list-contents-mixin ()
; Reverse - p is provided because it makes sense to let users specify
;; vertical lists from top to bottom, but internally it is easier to deal
;; with bottom to top, because of the lower left coordinate system.
; For example , a user would like to list the vbox contents from top to
;; bottom, while y coords increases from bottom to top. Whereas with
; a hbox , user specifys left to right just as x coord increases left
;; to right.
;;
;; A problem with reverse-p solution is that when new panes are inserted,
;; all panes before them in the user's view of contents changes coord,
;; but the user may expect the one's later in the list to change coords.
;; For example in a vertical list, adding a pane to the end will
;; reposition all of the list items.
;; A possible solution is to user a upper left coordinate
;; system so that added items have absolute y values that are increasing.
; Once upon a time told me he prefered this , but it 'll have to wait
;; for now. A deeper problem with this solution is that different panes
;; would have different coordinate systems which maybe confusing if the
;; coordinate system is exposed to the client in anyway.
Insertion/Deletion Protocols
(if reverse-p (reverse contents)
contents)))
(sheet-disown-child lcm pane))
(sheet-adopt-child lcm pane))
new-contents)
;; So that things repaint from top to bottom
;; ??? However, it only work is you go through this method.
children))
(defun check-position (position reverse-p contents)
(let ((len (length contents)))
(when reverse-p
(setq position (if position (- len position) 0)))
(check-type position number)
(assert (and (<= 0 position) (<= position len))
(position)
"Position argument out of bounds")
position))
&key position &allow-other-keys)
(setq position (check-position position reverse-p contents))
(insert-pane lcm pane :position position :batch-p t)
&key position batch-p &allow-other-keys)
(unless batch-p
(setq position (check-position position reverse-p contents)))
(push pane contents)
(cons pane (cdr tail)))))
(sheet-adopt-child lcm pane)
(unless batch-p
(sheet-disown-child lcm pane)))
&key batch-p &allow-other-keys)
(sheet-disown-child lcm pane)
; PCL uses this variable for method - table cache misses , unfortunately .
(declare (ignore parent))
--- Temporary kludge until we get the protocols correct
--- so that ACCEPT works correctly on a raw sheet
--- More of same...
spr24242:
Note:
These are methods are basically copies of methods on the class
--- Needed methods include:
--- STREAM-READ-GESTURE
etc etc. Don't do this if the frame doesn't own this top-level
sheet yet (still initializing). |
(in-package :silica)
" Copyright ( c ) 1991 , 1992 Franz , Inc. All rights reserved .
Portions copyright ( c ) 1992 Symbolics , Inc. All rights reserved .
Portions copyright ( c ) 1989 , 1990 Xerox Corp. All rights reserved . "
(define-protocol-class space-requirement ())
(defmethod print-object ((object space-requirement) stream)
(print-unreadable-object (object stream :type t)
(multiple-value-bind (width min-width max-width height min-height max-height)
(space-requirement-components object)
(format stream "~D<w=~D<~D ~D<h=~D<~D"
min-width width max-width
min-height height max-height))))
(defclass null-space-requirement (space-requirement) ())
(defmethod space-requirement-components ((sr null-space-requirement))
(values 0 0 0 0 0 0))
(defmethod space-requirement-width ((sr null-space-requirement)) 0)
(defmethod space-requirement-min-width ((sr null-space-requirement)) 0)
(defmethod space-requirement-max-width ((sr null-space-requirement)) 0)
(defmethod space-requirement-height ((sr null-space-requirement)) 0)
(defmethod space-requirement-min-height ((sr null-space-requirement)) 0)
(defmethod space-requirement-max-height ((sr null-space-requirement)) 0)
(defvar +null-space-requirement+ (make-instance 'null-space-requirement))
(defclass simple-space-requirement (space-requirement)
((width :initarg :width :accessor space-requirement-width)
(height :initarg :height :accessor space-requirement-height)))
(defmethod space-requirement-components ((sr simple-space-requirement))
(with-slots (width height) sr
(values width width width
height height height)))
(defmethod space-requirement-min-width ((sr simple-space-requirement))
(slot-value sr 'width))
(defmethod space-requirement-max-width ((sr simple-space-requirement))
(slot-value sr 'width))
(defmethod space-requirement-min-height ((sr simple-space-requirement))
(slot-value sr 'height))
(defmethod space-requirement-max-height ((sr simple-space-requirement))
(slot-value sr 'height))
(defclass general-space-requirement (space-requirement)
((width :initarg :width :reader space-requirement-width)
(min-width :reader space-requirement-min-width)
(max-width :reader space-requirement-max-width)
(height :initarg :height :reader space-requirement-height)
(min-height :reader space-requirement-min-height)
(max-height :reader space-requirement-max-height)))
(defmethod space-requirement-components ((sr general-space-requirement))
(with-slots (width min-width max-width
height min-height max-height) sr
(values width min-width max-width
height min-height max-height)))
(defmethod initialize-instance :after ((sr general-space-requirement)
&key (width (error "Width not specified"))
(min-width width)
(max-width width)
(height (error "Height not specified"))
(min-height height)
(max-height height))
(setf (slot-value sr 'min-height) min-height
(slot-value sr 'max-height) max-height
(slot-value sr 'min-width) min-width
(slot-value sr 'max-width) max-width))
(defun make-space-requirement (&key (width 0) (min-width width) (max-width width)
(height 0) (min-height height) (max-height height))
(cond ((and (eq width min-width) (eq width max-width)
(eq height min-height) (eq height max-height))
(if (and (eq width 0) (eq height 0))
+null-space-requirement+
(make-instance 'simple-space-requirement
:width width :height height)))
(t
(make-instance 'general-space-requirement
:width width :min-width min-width :max-width max-width
:height height :min-height min-height :max-height max-height))))
(defconstant +fill+
expression below gives 100 in aclpc - too small
#-(or aclpc acl86win32)
(floor (/ (expt 10 (floor (log most-positive-fixnum 10))) 100)))
Layout protocol
( defmethod allocate - space ( sheet width height )
(defun parse-box-contents (contents)
(mapcar #'(lambda (x)
(if (and (consp x)
(typep (first x) '(or (member :fill) number)))
`(list ,(first x) ,(second x))
x))
contents))
(defmacro vertically ((&rest options &key spacing &allow-other-keys)
&body contents)
(declare (ignore spacing))
`(make-pane 'vbox-pane
:contents (list ,@(parse-box-contents contents))
,@options))
(defmacro horizontally ((&rest options &key spacing &allow-other-keys)
&body contents)
(declare (ignore spacing))
`(make-pane 'hbox-pane
:contents (list ,@(parse-box-contents contents))
,@options))
(defmethod resize-sheet ((sheet basic-sheet) width height)
(unless (and (> width 0) (> height 0))
(error "Trying to resize sheet ~S to be too small (~D x ~D)"
sheet width height))
(with-bounding-rectangle* (left top right bottom) sheet
(let ((owidth (- right left))
(oheight (- bottom top)))
(if (or (/= owidth width)
(/= oheight height)
#+allegro
(mirror-needs-changing-p sheet left top width height))
(let ((region (sheet-region sheet)))
(setf (slot-value region 'left) left
(slot-value region 'top) top
(slot-value region 'right) (+ left width)
(slot-value region 'bottom) (+ top height))
(note-sheet-region-changed sheet))
(allocate-space sheet owidth oheight)))))
(defmethod mirror-needs-changing-p ((sheet sheet) left top width height)
(declare (ignore left top width height))
nil)
(defmethod mirror-needs-changing-p ((sheet mirrored-sheet-mixin)
left top width height)
(and (sheet-direct-mirror sheet)
(multiple-value-bind (mleft mtop mright mbottom)
(mirror-region* (port sheet) sheet)
(or (/= left mleft)
(/= top mtop)
(/= width (- mright mleft))
(/= height (- mbottom mtop))))))
(defmethod move-sheet ((sheet basic-sheet) x y)
(let ((transform (sheet-transformation sheet)))
(multiple-value-bind (old-x old-y)
(transform-position transform 0 0)
(with-bounding-rectangle* (left top right bottom) sheet
(when (or (and x (/= old-x x))
(and y (/= old-y y))
(mirror-needs-changing-p sheet x y (- right left) (- bottom top)))
(setf (sheet-transformation sheet)
(compose-translation-with-transformation
transform
(if x (- x old-x) 0) (if y (- y old-y) 0))))))))
(defmethod move-and-resize-sheet ((sheet basic-sheet) x y width height)
(resize-sheet sheet width height)
(move-sheet sheet x y))
(defgeneric sheet-flags (sheet)
(:documentation "Returns a list of flags that the port may have set concerning the sheet.")
(:method ((sheet basic-sheet))
()))
(defgeneric (setf sheet-flags) (new-value sheet)
(:documentation "Set a list of flags, as supported by the port. Ignores any flags that the port doesn't understand.")
(:method (new-value (sheet basic-sheet))
(declare (ignore new-value))
nil))
(define-protocol-class pane (sheet))
(defmethod initialize-instance :around ((pane pane) &key background text-style)
(apply #'call-next-method nil))
--- What about PANE - FOREGROUND / BACKGROUND vs. MEDIUM - FOREGROUND / BACKGROUND ?
(defclass basic-pane
(sheet-transformation-mixin
standard-sheet-input-mixin
standard-repainting-mixin
temporary-medium-sheet-output-mixin
basic-sheet
pane)
((frame :reader pane-frame :initarg :frame)
(framem :reader frame-manager :initarg :frame-manager)
(name :accessor pane-name :initform nil :initarg :name)))
(defmethod print-object ((object basic-pane) stream)
(if (and (slot-boundp object 'name)
(stringp (slot-value object 'name)))
(print-unreadable-object (object stream :type t :identity t)
(format stream "~A" (slot-value object 'name)))
(call-next-method)))
(defmethod handle-repaint ((pane basic-pane) region)
(declare (ignore region))
nil)
#+++ignore
(defmethod note-sheet-region-changed :after ((sheet basic-pane) &key port)
(declare (ignore port))
(multiple-value-bind (width height) (bounding-rectangle-size sheet)
(allocate-space sheet width height)))
(defmethod pane-frame ((sheet basic-sheet)) nil)
( ( contents : initform nil )
( nslots : initform nil : initarg : )
( reverse - p : initform nil : initarg : reverse - p ) ) )
( defmethod contents ( ( lcm list - contents - mixin ) )
( with - slots ( reverse - p contents ) lcm
( defmethod ( setf contents ) ( new - contents ( lcm list - contents - mixin ) )
( with - slots ( reverse - p contents children ) lcm
( dolist ( pane contents )
( dolist ( pane new - contents )
( setf contents ( if reverse - p ( reverse new - contents )
children ( if reverse - p ( nreverse children )
( note - space - requirements - changed ( sheet - parent lcm ) lcm ) ) )
( unless position ( setq position len ) )
( defmethod insert - panes ( ( lcm list - contents - mixin ) panes
( with - slots ( reverse - p contents ) lcm
( dolist ( pane panes )
( unless reverse - p ( incf position ) ) )
( note - space - requirements - changed ( sheet - parent lcm ) lcm ) ) )
( defmethod insert - pane ( ( lcm list - contents - mixin ) ( pane basic - pane )
( with - slots ( contents reverse - p ) lcm
( if ( zerop position )
( let ( ( tail ( ( 1- position ) contents ) ) )
( setf ( cdr tail )
( note - space - requirements - changed ( sheet - parent lcm ) lcm ) ) ) )
( defmethod remove - panes ( ( lcm list - contents - mixin ) panes )
( dolist ( pane panes )
( with - slots ( contents ) lcm
( setf contents ( delete pane contents ) )
( note - space - requirements - changed ( sheet - parent lcm ) lcm ) )
( defmethod remove - pane ( ( lcm list - contents - mixin ) ( pane basic - pane )
( with - slots ( contents ) lcm
( setf contents ( delete pane contents : test # ' eq ) )
( unless batch - p ( note - space - requirements - changed ( sheet - parent lcm ) lcm ) ) ) )
( defmethod note - space - requirements - changed : before ( parent ( lcm list - contents - mixin ) )
( with - slots ( nslots contents ) lcm
( setf nslots ( length contents ) ) ) )
--- CLIM 0.9 has some other methods on top - level sheets -- do we want them ?
(defclass top-level-sheet
clim-internals::window-stream
wrapping-space-mixin
sheet-multiple-child-mixin
mirrored-sheet-mixin
permanent-medium-sheet-output-mixin
basic-pane)
((user-specified-size-p :initform :unspecified :initarg :user-specified-size-p)
(user-specified-position-p :initform :unspecified :initarg :user-specified-position-p))
(:default-initargs :text-cursor nil :text-margin most-positive-fixnum))
(defmethod window-refresh ((sheet top-level-sheet))
nil)
The following methods are specified in the Clim documentation
( at the end of Sec 19.5.2 ) .
clim - stream - sheet ( in clim / db - stream.lisp ) .
(defmethod window-expose ((stream top-level-sheet))
(setf (window-visibility stream) t))
(defmethod (setf window-visibility) (visibility (stream top-level-sheet))
(let ((frame (pane-frame stream)))
(if frame
(if visibility
(enable-frame frame)
(disable-frame frame))
(setf (sheet-enabled-p stream) visibility))))
(defmethod window-visibility ((stream top-level-sheet))
: Is the Unix code more correct ? ? ?
#+(or aclpc acl86win32)
(mirror-visible-p (port stream) stream)
#-(or aclpc acl86win32)
(let ((frame (pane-frame stream)))
(and (if frame
(eq (frame-state frame) :enabled)
(sheet-enabled-p stream))
(mirror-visible-p (port stream) stream)))
)
(defmethod window-stack-on-top ((stream top-level-sheet))
(raise-sheet (window-top-level-window stream)))
(defmethod window-stack-on-bottom ((stream top-level-sheet))
(bury-sheet (window-top-level-window stream)))
(defmethod window-inside-edges ((stream top-level-sheet))
(bounding-rectangle* (sheet-region (or (pane-viewport stream) stream))))
(defmethod window-inside-size ((stream top-level-sheet))
(bounding-rectangle-size (sheet-region (or (pane-viewport stream) stream))))
--- INVOKE - WITH - RECORDING - OPTIONS
--- DEFAULT - TEXT - MARGIN
(defmethod note-layout-mixin-region-changed ((pane top-level-sheet) &key port)
(let ((frame (pane-frame pane)))
(if (and port frame (frame-top-level-sheet frame))
We do this because if the WM has resized us then we want to
do the complete LAYOUT - FRAME thing including clearing caches
(multiple-value-call #'layout-frame
(pane-frame pane)
(bounding-rectangle-size pane))
Otherwise just call ALLOCATE - SPACE etc
(call-next-method))))
#+++ignore
(defmethod allocate-space ((sheet top-level-sheet) width height)
(resize-sheet (first (sheet-children sheet)) width height))
#+++ignore
(defmethod compose-space ((sheet top-level-sheet) &key width height)
(compose-space (first (sheet-children sheet)) :width width :height height))
(defclass composite-pane
(sheet-multiple-child-mixin
basic-pane)
())
(defclass leaf-pane
(sheet-permanently-enabled-mixin
client-overridability-mixin
basic-pane)
((cursor :initarg :cursor :initform nil
:accessor sheet-cursor)))
|
830db5f279e47812f15e003eff27227e4e131c8a9d3a30d00c17528190d8d160 | yallop/ocaml-reex | reex_print.mli |
* Copyright ( c ) 2022 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2022 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
val pp : Format.formatter -> Reex_types.t -> unit
| null | https://raw.githubusercontent.com/yallop/ocaml-reex/8941fb7033762f6b87fa2f33afa87440001eccbe/lib/reex_print.mli | ocaml |
* Copyright ( c ) 2022 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2022 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
val pp : Format.formatter -> Reex_types.t -> unit
| |
aed798c28ec2c3c6f3d1897461714d338ee05156ac6a2a993a9d796def9dadd3 | nirum-lang/nirum | Identifier.hs | # LANGUAGE OverloadedLists #
module Nirum.Constructs.Identifier ( Identifier
, fromString
, fromText
, identifierRule
, normalize
, reservedKeywords
, show
, toCode
, tokens
, toCamelCaseText
, toNormalizedString
, toNormalizedText
, toString
, toSnakeCaseText
, toText
, toPascalCaseText
, toLispCaseText
, (==)
) where
import Data.Char (toLower, toUpper)
import Data.Maybe (fromMaybe)
import Data.String (IsString (fromString))
import Data.Void
import qualified Data.Text as T
import qualified Data.Set as S
import qualified Text.Megaparsec as P
import Text.Megaparsec.Char (oneOf, satisfy)
import Nirum.Constructs (Construct (toCode))
|
Case - insensitive identifier . It also does n't distinguish hyphens
from underscores .
It has more restrict rules than the most of programming languages :
* It ca n't start with digits or hyphens / underscores .
* / underscores ca n't continuously appear more than once .
* Only roman alphabets , Arabic numerals , hyphens and underscores
are allowed .
These rules are for portability between various programming languages .
For example , @BOOK_CATEGORY@ and @Book - Category@ are all normalized
to @book - category@ , and it can be translated to :
[ snake_case ] @book_category@
[ camelCase ] @bookCategory@
[ PascalCase ] @BookCategory@
[ lisp - case ] @book - category@
Case-insensitive identifier. It also doesn't distinguish hyphens
from underscores.
It has more restrict rules than the most of programming languages:
* It can't start with digits or hyphens/underscores.
* Hyphens/underscores can't continuously appear more than once.
* Only roman alphabets, Arabic numerals, hyphens and underscores
are allowed.
These rules are for portability between various programming languages.
For example, @BOOK_CATEGORY@ and @Book-Category@ are all normalized
to @book-category@, and it can be translated to:
[snake_case] @book_category@
[camelCase] @bookCategory@
[PascalCase] @BookCategory@
[lisp-case] @book-category@
-}
newtype Identifier = Identifier T.Text deriving (Show)
reservedKeywords :: S.Set Identifier
reservedKeywords = [ "enum"
, "record"
, "service"
, "throws"
, "type"
, "unboxed"
, "union"
, "default"
, "as"
]
identifierRule :: P.Parsec Void T.Text Identifier
identifierRule = do
firstChar <- satisfy isAlpha
restChars <- P.many $ satisfy isAlnum
restWords <- P.many $ do
sep <- oneOf ("-_" :: String)
chars <- P.some $ satisfy isAlnum
return $ T.pack $ sep : chars
return $ Identifier $ T.concat $ T.pack (firstChar : restChars) : restWords
where
isAlpha :: Char -> Bool
isAlpha c = 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z'
isDigit :: Char -> Bool
isDigit c = '0' <= c && c <= '9'
isAlnum :: Char -> Bool
isAlnum c = isAlpha c || isDigit c
-- | Constructs an 'Identifier' value from the given identifier string.
-- It could return 'Nothing' if the given identifier is invalid.
fromText :: T.Text -> Maybe Identifier
fromText text =
case P.parse rule "" text of
Right ident -> Just ident
Left _ -> Nothing
where
rule :: P.Parsec Void T.Text Identifier
rule = do
identifier' <- identifierRule
_ <- P.eof
return identifier'
normalize :: Identifier -> Identifier
normalize (Identifier i) =
Identifier $ T.map (\ c -> if c == '_' then '-' else toLower c) i
toText :: Identifier -> T.Text
toText (Identifier text) = text
toNormalizedText :: Identifier -> T.Text
toNormalizedText = toText . normalize
tokens :: Identifier -> [T.Text]
tokens ident = T.split (== '-') $ toText $ normalize ident
instance Eq Identifier where
a@(Identifier _) == b@(Identifier _) =
toNormalizedText a == toNormalizedText b
instance Ord Identifier where
compare a@(Identifier _) b@(Identifier _) =
compare (toNormalizedText a) (toNormalizedText b)
instance Construct Identifier where
toCode ident
| ident `S.member` reservedKeywords = '`' `T.cons` text `T.snoc` '`'
| otherwise = text
where
text = toText ident
instance IsString Identifier where
fromString string = fromMaybe (error $ "invalid identifier: " ++ string) $
fromText (T.pack string)
toString :: Identifier -> String
toString = T.unpack . toText
toNormalizedString :: Identifier -> String
toNormalizedString = T.unpack . toNormalizedText
toPascalCaseText :: Identifier -> T.Text
toPascalCaseText identifier =
T.concat $ fmap makeFirstUpper (tokens identifier)
where
makeFirstUpper :: T.Text -> T.Text
makeFirstUpper t = toUpper (T.head t) `T.cons` T.tail t
toCamelCaseText :: Identifier -> T.Text
toCamelCaseText identifier =
toLower (T.head pascalCased) `T.cons` T.tail pascalCased
where
pascalCased :: T.Text
pascalCased = toPascalCaseText identifier
toSnakeCaseText :: Identifier -> T.Text
toSnakeCaseText identifier = T.intercalate "_" $ tokens identifier
toLispCaseText :: Identifier -> T.Text
toLispCaseText = toNormalizedText
| null | https://raw.githubusercontent.com/nirum-lang/nirum/4d4488b0524874abc6e693479a5cc70c961bad33/src/Nirum/Constructs/Identifier.hs | haskell | | Constructs an 'Identifier' value from the given identifier string.
It could return 'Nothing' if the given identifier is invalid. | # LANGUAGE OverloadedLists #
module Nirum.Constructs.Identifier ( Identifier
, fromString
, fromText
, identifierRule
, normalize
, reservedKeywords
, show
, toCode
, tokens
, toCamelCaseText
, toNormalizedString
, toNormalizedText
, toString
, toSnakeCaseText
, toText
, toPascalCaseText
, toLispCaseText
, (==)
) where
import Data.Char (toLower, toUpper)
import Data.Maybe (fromMaybe)
import Data.String (IsString (fromString))
import Data.Void
import qualified Data.Text as T
import qualified Data.Set as S
import qualified Text.Megaparsec as P
import Text.Megaparsec.Char (oneOf, satisfy)
import Nirum.Constructs (Construct (toCode))
|
Case - insensitive identifier . It also does n't distinguish hyphens
from underscores .
It has more restrict rules than the most of programming languages :
* It ca n't start with digits or hyphens / underscores .
* / underscores ca n't continuously appear more than once .
* Only roman alphabets , Arabic numerals , hyphens and underscores
are allowed .
These rules are for portability between various programming languages .
For example , @BOOK_CATEGORY@ and @Book - Category@ are all normalized
to @book - category@ , and it can be translated to :
[ snake_case ] @book_category@
[ camelCase ] @bookCategory@
[ PascalCase ] @BookCategory@
[ lisp - case ] @book - category@
Case-insensitive identifier. It also doesn't distinguish hyphens
from underscores.
It has more restrict rules than the most of programming languages:
* It can't start with digits or hyphens/underscores.
* Hyphens/underscores can't continuously appear more than once.
* Only roman alphabets, Arabic numerals, hyphens and underscores
are allowed.
These rules are for portability between various programming languages.
For example, @BOOK_CATEGORY@ and @Book-Category@ are all normalized
to @book-category@, and it can be translated to:
[snake_case] @book_category@
[camelCase] @bookCategory@
[PascalCase] @BookCategory@
[lisp-case] @book-category@
-}
newtype Identifier = Identifier T.Text deriving (Show)
reservedKeywords :: S.Set Identifier
reservedKeywords = [ "enum"
, "record"
, "service"
, "throws"
, "type"
, "unboxed"
, "union"
, "default"
, "as"
]
identifierRule :: P.Parsec Void T.Text Identifier
identifierRule = do
firstChar <- satisfy isAlpha
restChars <- P.many $ satisfy isAlnum
restWords <- P.many $ do
sep <- oneOf ("-_" :: String)
chars <- P.some $ satisfy isAlnum
return $ T.pack $ sep : chars
return $ Identifier $ T.concat $ T.pack (firstChar : restChars) : restWords
where
isAlpha :: Char -> Bool
isAlpha c = 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z'
isDigit :: Char -> Bool
isDigit c = '0' <= c && c <= '9'
isAlnum :: Char -> Bool
isAlnum c = isAlpha c || isDigit c
fromText :: T.Text -> Maybe Identifier
fromText text =
case P.parse rule "" text of
Right ident -> Just ident
Left _ -> Nothing
where
rule :: P.Parsec Void T.Text Identifier
rule = do
identifier' <- identifierRule
_ <- P.eof
return identifier'
normalize :: Identifier -> Identifier
normalize (Identifier i) =
Identifier $ T.map (\ c -> if c == '_' then '-' else toLower c) i
toText :: Identifier -> T.Text
toText (Identifier text) = text
toNormalizedText :: Identifier -> T.Text
toNormalizedText = toText . normalize
tokens :: Identifier -> [T.Text]
tokens ident = T.split (== '-') $ toText $ normalize ident
instance Eq Identifier where
a@(Identifier _) == b@(Identifier _) =
toNormalizedText a == toNormalizedText b
instance Ord Identifier where
compare a@(Identifier _) b@(Identifier _) =
compare (toNormalizedText a) (toNormalizedText b)
instance Construct Identifier where
toCode ident
| ident `S.member` reservedKeywords = '`' `T.cons` text `T.snoc` '`'
| otherwise = text
where
text = toText ident
instance IsString Identifier where
fromString string = fromMaybe (error $ "invalid identifier: " ++ string) $
fromText (T.pack string)
toString :: Identifier -> String
toString = T.unpack . toText
toNormalizedString :: Identifier -> String
toNormalizedString = T.unpack . toNormalizedText
toPascalCaseText :: Identifier -> T.Text
toPascalCaseText identifier =
T.concat $ fmap makeFirstUpper (tokens identifier)
where
makeFirstUpper :: T.Text -> T.Text
makeFirstUpper t = toUpper (T.head t) `T.cons` T.tail t
toCamelCaseText :: Identifier -> T.Text
toCamelCaseText identifier =
toLower (T.head pascalCased) `T.cons` T.tail pascalCased
where
pascalCased :: T.Text
pascalCased = toPascalCaseText identifier
toSnakeCaseText :: Identifier -> T.Text
toSnakeCaseText identifier = T.intercalate "_" $ tokens identifier
toLispCaseText :: Identifier -> T.Text
toLispCaseText = toNormalizedText
|
eaa8f1f26db2fd37ca309cc2ac8f5b3535a3f6e11353e11285b9901fc74c5151 | Zulu-Inuoe/clution | copy-array.lisp | (in-package :cl-utilities)
(defun copy-array (array &key (undisplace nil))
"Shallow copies the contents of any array into another array with
equivalent properties. If array is displaced, then this function will
normally create another displaced array with similar properties,
unless UNDISPLACE is non-NIL, in which case the contents of the array
will be copied into a completely new, not displaced, array."
(declare (type array array))
(let ((copy (%make-array-with-same-properties array undisplace)))
(unless (array-displacement copy)
(dotimes (n (array-total-size copy))
(setf (row-major-aref copy n) (row-major-aref array n))))
copy))
(defun %make-array-with-same-properties (array undisplace)
"Make an array with the same properties (size, adjustability, etc.)
as another array, optionally undisplacing the array."
(apply #'make-array
(list* (array-dimensions array)
:element-type (array-element-type array)
:adjustable (adjustable-array-p array)
:fill-pointer (when (array-has-fill-pointer-p array)
(fill-pointer array))
(multiple-value-bind (displacement offset)
(array-displacement array)
(when (and displacement (not undisplace))
(list :displaced-to displacement
:displaced-index-offset offset)))))) | null | https://raw.githubusercontent.com/Zulu-Inuoe/clution/b72f7afe5f770ff68a066184a389c23551863f7f/cl-clution/qlfile-libs/cl-utilities-1.2.4/copy-array.lisp | lisp | (in-package :cl-utilities)
(defun copy-array (array &key (undisplace nil))
"Shallow copies the contents of any array into another array with
equivalent properties. If array is displaced, then this function will
normally create another displaced array with similar properties,
unless UNDISPLACE is non-NIL, in which case the contents of the array
will be copied into a completely new, not displaced, array."
(declare (type array array))
(let ((copy (%make-array-with-same-properties array undisplace)))
(unless (array-displacement copy)
(dotimes (n (array-total-size copy))
(setf (row-major-aref copy n) (row-major-aref array n))))
copy))
(defun %make-array-with-same-properties (array undisplace)
"Make an array with the same properties (size, adjustability, etc.)
as another array, optionally undisplacing the array."
(apply #'make-array
(list* (array-dimensions array)
:element-type (array-element-type array)
:adjustable (adjustable-array-p array)
:fill-pointer (when (array-has-fill-pointer-p array)
(fill-pointer array))
(multiple-value-bind (displacement offset)
(array-displacement array)
(when (and displacement (not undisplace))
(list :displaced-to displacement
:displaced-index-offset offset)))))) | |
6d8b3b516fed147bb1b6ac26cd39b3eee3c6de041902ab0416ab4c9df3fd273f | facebook/duckling | UK_XX.hs | 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 .
-----------------------------------------------------------------
-- Auto-generated by regenClassifiers
--
-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
@generated
-----------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ranking.Classifiers.UK_XX (classifiers) where
import Data.String
import Prelude
import qualified Data.HashMap.Strict as HashMap
import Duckling.Ranking.Types
classifiers :: Classifiers
classifiers
= HashMap.fromList
[("\1050\1074\1110\1090\1077\1085\1100",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time> timezone",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods =
HashMap.fromList
[("hh:mm", -0.6931471805599453),
("minute", -0.6931471805599453)],
n = 3},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("integer (numeric)",
Classifier{okData =
ClassData{prior = -0.7693745459478296, unseen = -4.634728988229636,
likelihoods = HashMap.fromList [("", 0.0)], n = 101},
koData =
ClassData{prior = -0.6223211279913329, unseen = -4.77912349311153,
likelihoods = HashMap.fromList [("", 0.0)], n = 117}}),
("integer (3..19)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.4849066497880004,
likelihoods = HashMap.fromList [("", 0.0)], n = 10},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("lunch",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time> <part-of-day>",
Classifier{okData =
ClassData{prior = -0.13976194237515874,
unseen = -4.709530201312334,
likelihoods =
HashMap.fromList
[("<time-of-day> o'clockmorning", -3.6018680771243066),
("until <time-of-day>afternoon", -4.007333185232471),
("dayhour", -2.503255788456197),
("at <time-of-day>evening", -4.007333185232471),
("\1074\1095\1086\1088\1072evening", -4.007333185232471),
("intersect by ','evening", -3.6018680771243066),
("\1089\1100\1086\1075\1086\1076\1085\1110afternoon",
-4.007333185232471),
("intersectevening", -2.2155737160044158),
("hourhour", -1.3331845358059422),
("\1079\1072\1074\1090\1088\1072lunch", -4.007333185232471),
("at <time-of-day>afternoon", -3.6018680771243066),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082morning",
-4.007333185232471),
("<time-of-day> o'clockafternoon", -3.0910424533583156),
("until <time-of-day>morning", -4.007333185232471),
("minutehour", -3.0910424533583156),
("\1089\1100\1086\1075\1086\1076\1085\1110evening",
-4.007333185232471),
("time-of-day (latent)morning", -4.007333185232471),
("hh:mmmorning", -4.007333185232471),
("time-of-day (latent)evening", -4.007333185232471),
("\1079\1072\1074\1090\1088\1072evening", -4.007333185232471),
("<time-of-day> o'clockevening", -3.6018680771243066),
("hh:mmnight", -4.007333185232471),
("hh:mmafternoon", -4.007333185232471),
("on <date>morning", -4.007333185232471),
("at <time-of-day>morning", -4.007333185232471),
("\1063\1077\1090\1074\1077\1088morning", -4.007333185232471)],
n = 40},
koData =
ClassData{prior = -2.03688192726104, unseen = -3.7612001156935624,
likelihoods =
HashMap.fromList
[("yearhour", -2.639057329615259),
("intersectevening", -2.3513752571634776),
("hourhour", -2.128231705849268),
("year (latent)afternoon", -3.044522437723423),
("year (latent)night", -3.044522437723423),
("time-of-day (latent)afternoon", -3.044522437723423)],
n = 6}}),
("numbers prefix with -, minus",
Classifier{okData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -3.258096538021482,
likelihoods =
HashMap.fromList
[("integer (numeric)", -0.4462871026284195),
("decimal number", -1.0216512475319814)],
n = 23}}),
("\1087\1110\1089\1083\1103\1079\1072\1074\1090\1088\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1074\1095\1086\1088\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("mm/dd",
Classifier{okData =
ClassData{prior = -0.8754687373538999,
unseen = -2.4849066497880004,
likelihoods = HashMap.fromList [("", 0.0)], n = 10},
koData =
ClassData{prior = -0.5389965007326869, unseen = -2.772588722239781,
likelihoods = HashMap.fromList [("", 0.0)], n = 14}}),
("\1057\1091\1073\1086\1090\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("at <time-of-day>",
Classifier{okData =
ClassData{prior = -0.1431008436406733, unseen = -4.060443010546419,
likelihoods =
HashMap.fromList
[("<time-of-day> o'clock", -1.845826690498331),
("time-of-day (latent)", -1.3350010667323402),
("hh:mm", -2.4336133554004498), ("hour", -0.9075570519054005),
("minute", -2.4336133554004498)],
n = 26},
koData =
ClassData{prior = -2.0149030205422647, unseen = -2.639057329615259,
likelihoods =
HashMap.fromList
[("time-of-day (latent)", -0.9555114450274363),
("hour", -0.9555114450274363)],
n = 4}}),
("absorption of , after named day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.1354942159291497,
likelihoods =
HashMap.fromList
[("\1057\1091\1073\1086\1090\1072", -2.3978952727983707),
("\1057\1077\1088\1077\1076\1072", -2.3978952727983707),
("\1053\1077\1076\1110\1083\1103", -2.3978952727983707),
("day", -0.8938178760220964),
("\1055'\1103\1090\1085\1080\1094\1103", -1.7047480922384253),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082",
-1.9924301646902063)],
n = 8},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}}),
("on <date>",
Classifier{okData =
ClassData{prior = -0.2006706954621511, unseen = -3.367295829986474,
likelihoods =
HashMap.fromList
[("<time> <part-of-day>", -2.639057329615259),
("\1057\1091\1073\1086\1090\1072", -2.639057329615259),
("\1063\1077\1090\1074\1077\1088", -2.639057329615259),
("intersect", -1.540445040947149), ("day", -1.9459101490553135),
("hour", -1.7227665977411035),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082",
-2.639057329615259),
("minute", -2.2335922215070942)],
n = 9},
koData =
ClassData{prior = -1.7047480922384253, unseen = -2.70805020110221,
likelihoods =
HashMap.fromList
[("intersect", -1.9459101490553135),
("\1041\1077\1088\1077\1079\1077\1085\1100",
-1.9459101490553135),
("month", -1.540445040947149)],
n = 2}}),
("\1074\1077\1089\1085\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("between <time-of-day> and <time-of-day> (interval)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("hh:mmtime-of-day (latent)", -1.6739764335716716),
("minuteminute", -1.6739764335716716),
("time-of-day (latent)time-of-day (latent)",
-2.0794415416798357),
("hh:mmhh:mm", -1.6739764335716716),
("hourhour", -2.0794415416798357),
("minutehour", -1.6739764335716716)],
n = 5},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}}),
("\1063\1077\1090\1074\1077\1088",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("month (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time-of-day> o'clock",
Classifier{okData =
ClassData{prior = -0.14518200984449783,
unseen = -4.248495242049359,
likelihoods =
HashMap.fromList
[("at <time-of-day>", -2.03688192726104),
("time-of-day (latent)", -1.289667525430819),
("until <time-of-day>", -2.847812143477369),
("hour", -0.7375989431307791),
("after <time-of-day>", -2.847812143477369)],
n = 32},
koData =
ClassData{prior = -2.001480000210124, unseen = -2.772588722239781,
likelihoods =
HashMap.fromList
[("time-of-day (latent)", -0.916290731874155),
("hour", -0.916290731874155)],
n = 5}}),
("hour (grain)",
Classifier{okData =
ClassData{prior = -1.4350845252893227,
unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -0.2719337154836418, unseen = -2.890371757896165,
likelihoods = HashMap.fromList [("", 0.0)], n = 16}}),
("<ordinal> quarter",
Classifier{okData =
ClassData{prior = -0.6931471805599453,
unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("ordinals (first..19th)quarter (grain)", -0.6931471805599453),
("quarter", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -0.6931471805599453,
unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("ordinals (first..19th)quarter (grain)", -0.6931471805599453),
("quarter", -0.6931471805599453)],
n = 1}}),
("\1057\1077\1088\1077\1076\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("intersect",
Classifier{okData =
ClassData{prior = -0.2411620568168881, unseen = -5.817111159963204,
likelihoods =
HashMap.fromList
[("\1055\1086\1085\1077\1076\1110\1083\1086\1082this <cycle>",
-5.120983351265121),
("hourday", -4.204692619390966),
("<datetime> - <datetime> (interval)year", -5.120983351265121),
("hh:mm<part-of-day> of <time>", -4.204692619390966),
("dayhour", -2.287770007208905),
("daymonth", -3.868220382769753),
("monthyear", -3.5115454388310208),
("yearhour", -5.120983351265121),
("intersect<time-of-day> o'clock", -4.204692619390966),
("absorption of , after named daymm/dd/yyyy",
-5.120983351265121),
("<day-of-month> (ordinal)\1041\1077\1088\1077\1079\1077\1085\1100",
-5.120983351265121),
("\1046\1086\1074\1090\1077\1085\1100year", -4.022371062597012),
("intersect<time> <part-of-day>", -4.204692619390966),
("\1051\1080\1089\1090\1086\1087\1072\1076year",
-5.120983351265121),
("\1057\1077\1088\1077\1076\1072\1046\1086\1074\1090\1077\1085\1100",
-4.715518243156957),
("intersect\1046\1086\1074\1090\1077\1085\1100",
-5.120983351265121),
("intersect by ','year", -4.715518243156957),
("\1063\1077\1090\1074\1077\1088hh:mm", -5.120983351265121),
("on <date><time-of-day> o'clock", -5.120983351265121),
("\1041\1077\1088\1077\1079\1077\1085\1100year",
-5.120983351265121),
("\1057\1091\1073\1086\1090\1072<time-of-day> o'clock",
-5.120983351265121),
("mm/dd<time-of-day> o'clock", -5.120983351265121),
("\1057\1077\1088\1077\1076\1072next <cycle>",
-5.120983351265121),
("last <day-of-week> of <time>year", -5.120983351265121),
("\1042\1077\1088\1077\1089\1077\1085\1100year",
-4.715518243156957),
("on <date>between <time-of-day> and <time-of-day> (interval)",
-4.715518243156957),
("on <date>at <time-of-day>", -4.715518243156957),
("\1063\1077\1090\1074\1077\1088between <time-of-day> and <time-of-day> (interval)",
-4.204692619390966),
("dayday", -2.9809171877688505),
("at <time-of-day>\1079\1072\1074\1090\1088\1072",
-5.120983351265121),
("\1057\1091\1073\1086\1090\1072at <time-of-day>",
-4.715518243156957),
("mm/ddat <time-of-day>", -4.715518243156957),
("<time> <part-of-day>between <time-of-day> and <time-of-day> (interval)",
-5.120983351265121),
("<day-of-month> (ordinal)intersect", -4.427836170705175),
("hourhour", -5.120983351265121),
("hh:mmintersect by ','", -5.120983351265121),
("intersect<day-of-month> (non ordinal) <named-month>",
-4.715518243156957),
("dayyear", -2.869691552658626),
("<day-of-month> (ordinal)\1042\1110\1074\1090\1086\1088\1086\1082",
-5.120983351265121),
("<day-of-month> (non ordinal) <named-month>intersect",
-5.120983351265121),
("\1089\1100\1086\1075\1086\1076\1085\1110<time-of-day> o'clock",
-5.120983351265121),
("minutehour", -3.868220382769753),
("absorption of , after named day<day-of-month> (non ordinal) <named-month>",
-3.7346889901452305),
("\1063\1077\1090\1074\1077\1088<part-of-day> of <time>",
-5.120983351265121),
("at <time-of-day><day-of-month> (non ordinal) <named-month>",
-5.120983351265121),
("\1063\1077\1090\1074\1077\1088<datetime> - <datetime> (interval)",
-5.120983351265121),
("hh:mm<day-of-month> (non ordinal) <named-month>",
-5.120983351265121),
("\1063\1077\1090\1074\1077\1088<time-of-day> - <time-of-day> (interval)",
-4.715518243156957),
("hh:mmintersect", -5.120983351265121),
("intersect by ','intersect", -5.120983351265121),
("\1042\1110\1074\1090\1086\1088\1086\1082this <cycle>",
-5.120983351265121),
("dayminute", -3.175073202209808),
("<time> <part-of-day>intersect", -5.120983351265121),
("intersectyear", -4.022371062597012),
("<ordinal> <cycle> of <time>year", -5.120983351265121),
("minuteday", -3.616905954488847),
("absorption of , after named dayintersect",
-4.204692619390966),
("\1079\1072\1074\1090\1088\1072<time-of-day> o'clock",
-5.120983351265121),
("year<time-of-day> o'clock", -5.120983351265121),
("<time-of-day> o'clock\1079\1072\1074\1090\1088\1072",
-4.715518243156957),
("intersect by ','<time> <part-of-day>", -5.120983351265121),
("<time> <part-of-day>intersect by ','", -5.120983351265121),
("<day-of-month> (ordinal)\1057\1077\1088\1077\1076\1072",
-5.120983351265121),
("mm/ddyear", -4.715518243156957),
("intersect by ','<time-of-day> o'clock", -5.120983351265121),
("<time> <part-of-day>\1057\1091\1073\1086\1090\1072",
-5.120983351265121),
("absorption of , after named daymm/dd", -5.120983351265121),
("<time> <part-of-day>absorption of , after named day",
-5.120983351265121),
("intersectintersect", -4.715518243156957),
("<part-of-day> of <time><day-of-month> (non ordinal) <named-month>",
-5.120983351265121),
("dayweek", -4.204692619390966),
("\1079\1072\1074\1090\1088\1072at <time-of-day>",
-4.715518243156957),
("\1057\1077\1088\1077\1076\1072intersect", -5.120983351265121),
("weekyear", -4.715518243156957),
("\1063\1077\1090\1074\1077\1088<time> timezone",
-4.715518243156957),
("\1089\1100\1086\1075\1086\1076\1085\1110at <time-of-day>",
-4.204692619390966),
("\1089\1100\1086\1075\1086\1076\1085\1110<time> <part-of-day>",
-5.120983351265121),
("\1050\1072\1090\1086\1083\1080\1094\1100\1082\1077 \1056\1110\1079\1076\1074\1086year",
-5.120983351265121),
("\1057\1077\1088\1077\1076\1072this <cycle>",
-5.120983351265121),
("last <cycle> of <time>year", -4.715518243156957),
("<day-of-month> (non ordinal) <named-month>year",
-4.022371062597012)],
n = 121},
koData =
ClassData{prior = -1.540445040947149, unseen = -5.075173815233827,
likelihoods =
HashMap.fromList
[("dayhour", -4.375757021660286),
("daymonth", -3.2771447329921766),
("monthyear", -3.122994053164918),
("yearhour", -4.375757021660286),
("intersect<time-of-day> o'clock", -4.375757021660286),
("intersect<time> <part-of-day>", -4.375757021660286),
("absorption of , after named dayhh:mm", -4.375757021660286),
("intersect\1046\1086\1074\1090\1077\1085\1100",
-4.375757021660286),
("\1063\1077\1090\1074\1077\1088hh:mm", -3.970291913552122),
("\1041\1077\1088\1077\1079\1077\1085\1100year",
-3.970291913552122),
("\1051\1080\1087\1077\1085\1100intersect", -4.375757021660286),
("monthhour", -3.6826098411003407),
("dayday", -3.2771447329921766),
("\1042\1110\1074\1090\1086\1088\1086\1082after <time-of-day>",
-4.375757021660286),
("<day-of-month> (ordinal)intersect", -4.375757021660286),
("dayyear", -2.7663191092261856),
("<day-of-month> (ordinal)\1042\1110\1074\1090\1086\1088\1086\1082",
-3.970291913552122),
("\1051\1080\1087\1077\1085\1100year", -3.970291913552122),
("dayminute", -3.6826098411003407),
("intersectyear", -3.970291913552122),
("<day-of-month> (ordinal)\1057\1077\1088\1077\1076\1072",
-4.375757021660286),
("year<time> <part-of-day>", -4.375757021660286),
("mm/ddyear", -3.2771447329921766),
("on <date>year", -4.375757021660286),
("\1057\1077\1088\1077\1076\1072intersect", -4.375757021660286),
("\1053\1077\1076\1110\1083\1103intersect", -4.375757021660286),
("\1050\1074\1110\1090\1077\1085\1100year", -4.375757021660286),
("\1089\1100\1086\1075\1086\1076\1085\1110at <time-of-day>",
-4.375757021660286),
("after <time-of-day>year", -4.375757021660286),
("\1056\1110\1079\1076\1074\1086 \1061\1088\1080\1089\1090\1086\1074\1077year",
-4.375757021660286),
("\1053\1077\1076\1110\1083\1103on <date>",
-3.970291913552122)],
n = 33}}),
("<ordinal> <cycle> of <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.4849066497880004,
likelihoods =
HashMap.fromList
[("daymonth", -1.7047480922384253),
("ordinals (first..19th)day (grain)\1046\1086\1074\1090\1077\1085\1100",
-1.7047480922384253),
("ordinals (first..19th)week (grain)\1046\1086\1074\1090\1077\1085\1100",
-1.7047480922384253),
("ordinals (first..19th)week (grain)intersect",
-1.7047480922384253),
("weekmonth", -1.2992829841302609)],
n = 3},
koData =
ClassData{prior = -infinity, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [], n = 0}}),
("year (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.5649493574615367,
likelihoods = HashMap.fromList [("", 0.0)], n = 11},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("next <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.1354942159291497,
likelihoods =
HashMap.fromList
[("week", -1.7047480922384253),
("month (grain)", -2.3978952727983707),
("year (grain)", -1.9924301646902063),
("week (grain)", -1.7047480922384253),
("quarter", -2.3978952727983707), ("year", -1.9924301646902063),
("month", -2.3978952727983707),
("quarter (grain)", -2.3978952727983707)],
n = 7},
koData =
ClassData{prior = -infinity, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [], n = 0}}),
("year (latent)",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 2}}),
("mm/dd/yyyy",
Classifier{okData =
ClassData{prior = -1.0116009116784799, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -0.45198512374305727,
unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7}}),
("<ordinal> quarter <year>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("quarteryear", -0.6931471805599453),
("ordinals (first..19th)quarter (grain)year",
-0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("\1051\1080\1087\1077\1085\1100",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1050\1110\1085\1077\1094\1100 \1084\1110\1089\1103\1094\1103",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1079\1080\1084\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("nth <time> of <time>",
Classifier{okData =
ClassData{prior = -0.40546510810816444,
unseen = -3.044522437723423,
likelihoods =
HashMap.fromList
[("daymonth", -1.3862943611198906),
("dayyear", -1.8971199848858813),
("ordinals (first..19th)\1042\1110\1074\1090\1086\1088\1086\1082\1046\1086\1074\1090\1077\1085\1100",
-2.3025850929940455),
("ordinals (first..19th)\1042\1110\1074\1090\1086\1088\1086\1082intersect",
-2.3025850929940455),
("ordinals (first..19th)\1057\1077\1088\1077\1076\1072intersect",
-1.8971199848858813),
("ordinals (first..19th)intersectyear", -1.8971199848858813)],
n = 6},
koData =
ClassData{prior = -1.0986122886681098, unseen = -2.70805020110221,
likelihoods =
HashMap.fromList
[("daymonth", -1.252762968495368),
("ordinals (first..19th)\1057\1077\1088\1077\1076\1072\1046\1086\1074\1090\1077\1085\1100",
-1.540445040947149),
("ordinals (first..19th)\1042\1110\1074\1090\1086\1088\1086\1082\1042\1077\1088\1077\1089\1077\1085\1100",
-1.9459101490553135)],
n = 3}}),
("\1053\1077\1076\1110\1083\1103",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("week (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.1354942159291497,
likelihoods = HashMap.fromList [("", 0.0)], n = 21},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<part-of-day> of <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.044522437723423,
likelihoods =
HashMap.fromList
[("hourday", -1.2039728043259361),
("morning<day-of-month> (non ordinal) <named-month>",
-2.3025850929940455),
("hourhour", -2.3025850929940455),
("morningbetween <time-of-day> and <time-of-day> (interval)",
-2.3025850929940455),
("night\1057\1091\1073\1086\1090\1072", -2.3025850929940455),
("nightabsorption of , after named day", -2.3025850929940455),
("nightintersect by ','", -2.3025850929940455),
("nightintersect", -2.3025850929940455)],
n = 6},
koData =
ClassData{prior = -infinity, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [], n = 0}}),
("<day-of-month>(ordinal) <named-month>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("ordinals (first..19th)\1041\1077\1088\1077\1079\1077\1085\1100",
-0.6931471805599453),
("month", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("\1089\1100\1086\1075\1086\1076\1085\1110",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time> after next",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods =
HashMap.fromList
[("\1057\1077\1088\1077\1076\1072", -1.252762968495368),
("day", -0.8472978603872037),
("\1055'\1103\1090\1085\1080\1094\1103", -1.252762968495368)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [], n = 0}}),
("integer 2",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3978952727983707,
likelihoods = HashMap.fromList [("", 0.0)], n = 9},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("afternoon",
Classifier{okData =
ClassData{prior = -0.2231435513142097, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -1.6094379124341003,
unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1}}),
("this <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.9444389791664407,
likelihoods =
HashMap.fromList
[("week", -1.2809338454620642),
("year (grain)", -2.1972245773362196),
("week (grain)", -1.2809338454620642),
("quarter", -2.1972245773362196), ("year", -2.1972245773362196),
("quarter (grain)", -2.1972245773362196)],
n = 6},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}}),
("minute (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3978952727983707,
likelihoods = HashMap.fromList [("", 0.0)], n = 9},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("night",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1053\1086\1074\1080\1081 \1088\1110\1082",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1079\1072\1074\1090\1088\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("time-of-day (latent)",
Classifier{okData =
ClassData{prior = -0.35020242943311486,
unseen = -3.5553480614894135,
likelihoods =
HashMap.fromList
[("integer (numeric)", -9.237332013101517e-2),
("integer (3..19)", -2.833213344056216)],
n = 31},
koData =
ClassData{prior = -1.2192402764567243, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("integer (numeric)", -0.3746934494414107),
("integer (3..19)", -1.6739764335716716),
("integer 2", -2.0794415416798357)],
n = 13}}),
("year",
Classifier{okData =
ClassData{prior = -0.19105523676270922,
unseen = -3.044522437723423,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 19},
koData =
ClassData{prior = -1.749199854809259, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 4}}),
("last <day-of-week> of <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3978952727983707,
likelihoods =
HashMap.fromList
[("daymonth", -0.916290731874155),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082\1041\1077\1088\1077\1079\1077\1085\1100",
-1.6094379124341003),
("\1053\1077\1076\1110\1083\1103\1041\1077\1088\1077\1079\1077\1085\1100",
-1.6094379124341003),
("\1053\1077\1076\1110\1083\1103intersect",
-1.6094379124341003)],
n = 3},
koData =
ClassData{prior = -infinity, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [], n = 0}}),
("<integer> <unit-of-duration>",
Classifier{okData =
ClassData{prior = -1.114360645636249, unseen = -4.2626798770413155,
likelihoods =
HashMap.fromList
[("week", -2.456735772821304),
("integer 2week (grain)", -3.5553480614894135),
("integer (numeric)day (grain)", -2.8622008809294686),
("second", -3.5553480614894135),
("integer 2hour (grain)", -3.5553480614894135),
("integer (numeric)second (grain)", -3.5553480614894135),
("integer (numeric)year (grain)", -3.1498829533812494),
("day", -2.8622008809294686), ("year", -2.8622008809294686),
("integer (3..19)week (grain)", -3.5553480614894135),
("integer (numeric)week (grain)", -2.8622008809294686),
("hour", -2.8622008809294686), ("month", -3.5553480614894135),
("integer (numeric)minute (grain)", -2.456735772821304),
("integer (3..19)month (grain)", -3.5553480614894135),
("minute", -2.456735772821304),
("integer (numeric)hour (grain)", -3.1498829533812494),
("integer 2year (grain)", -3.5553480614894135)],
n = 21},
koData =
ClassData{prior = -0.39768296766610944, unseen = -4.74493212836325,
likelihoods =
HashMap.fromList
[("week", -3.126760535960395),
("integer 2week (grain)", -4.04305126783455),
("integer (numeric)day (grain)", -3.349904087274605),
("integer (3..19)day (grain)", -4.04305126783455),
("integer 2minute (grain)", -4.04305126783455),
("second", -3.126760535960395),
("integer 2month (grain)", -4.04305126783455),
("integer (3..19)second (grain)", -4.04305126783455),
("integer (numeric)second (grain)", -3.6375861597263857),
("integer (numeric)year (grain)", -3.6375861597263857),
("integer (3..19)year (grain)", -4.04305126783455),
("day", -2.9444389791664407), ("year", -3.126760535960395),
("integer (3..19)week (grain)", -4.04305126783455),
("integer 2day (grain)", -4.04305126783455),
("integer (numeric)week (grain)", -3.6375861597263857),
("integer (3..19)minute (grain)", -4.04305126783455),
("hour", -1.791759469228055), ("month", -3.126760535960395),
("integer (numeric)minute (grain)", -3.6375861597263857),
("integer (3..19)month (grain)", -4.04305126783455),
("integer (numeric)month (grain)", -3.6375861597263857),
("integer (3..19)hour (grain)", -4.04305126783455),
("integer 2second (grain)", -4.04305126783455),
("minute", -3.126760535960395),
("integer (numeric)hour (grain)", -1.845826690498331),
("integer 2year (grain)", -4.04305126783455)],
n = 43}}),
("ordinals (first..19th)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.4849066497880004,
likelihoods = HashMap.fromList [("", 0.0)], n = 10},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1042\1077\1088\1077\1089\1077\1085\1100",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<duration> after <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("yearday", -0.6931471805599453),
("<integer> <unit-of-duration>\1056\1110\1079\1076\1074\1086 \1061\1088\1080\1089\1090\1086\1074\1077",
-0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("\1041\1077\1088\1077\1079\1077\1085\1100",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1051\1102\1090\1080\1081",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3025850929940455,
likelihoods = HashMap.fromList [("", 0.0)], n = 8},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("dd.(mm.)? - dd.mm.(yy[yy]?)? (interval)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.639057329615259,
likelihoods = HashMap.fromList [("", 0.0)], n = 12},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("hh:mm",
Classifier{okData =
ClassData{prior = -0.5389965007326869,
unseen = -3.4011973816621555,
likelihoods = HashMap.fromList [("", 0.0)], n = 28},
koData =
ClassData{prior = -0.8754687373538999,
unseen = -3.0910424533583156,
likelihoods = HashMap.fromList [("", 0.0)], n = 20}}),
("intersect by ','",
Classifier{okData =
ClassData{prior = -6.0624621816434854e-2,
unseen = -3.891820298110627,
likelihoods =
HashMap.fromList
[("hourday", -3.1780538303479458),
("dayhour", -2.772588722239781),
("\1055'\1103\1090\1085\1080\1094\1103mm/dd",
-3.1780538303479458),
("\1055'\1103\1090\1085\1080\1094\1103intersect",
-2.2617630984737906),
("dayday", -1.3862943611198906),
("\1057\1077\1088\1077\1076\1072<day-of-month> (non ordinal) <named-month>",
-3.1780538303479458),
("intersect<day-of-month> (non ordinal) <named-month>",
-2.772588722239781),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082<day-of-month> (non ordinal) <named-month>",
-2.772588722239781),
("\1057\1091\1073\1086\1090\1072<day-of-month> (non ordinal) <named-month>",
-3.1780538303479458),
("minuteday", -2.772588722239781),
("\1055'\1103\1090\1085\1080\1094\1103mm/dd/yyyy",
-3.1780538303479458),
("<part-of-day> of <time><day-of-month> (non ordinal) <named-month>",
-3.1780538303479458),
("\1053\1077\1076\1110\1083\1103<day-of-month> (non ordinal) <named-month>",
-3.1780538303479458),
("\1055'\1103\1090\1085\1080\1094\1103<day-of-month> (non ordinal) <named-month>",
-2.772588722239781)],
n = 16},
koData =
ClassData{prior = -2.833213344056216, unseen = -2.9444389791664407,
likelihoods =
HashMap.fromList
[("\1055'\1103\1090\1085\1080\1094\1103hh:mm",
-2.1972245773362196),
("dayminute", -2.1972245773362196)],
n = 1}}),
("second (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("intersect by 'of', 'from', 's",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("dayweek", -0.6931471805599453),
("\1053\1077\1076\1110\1083\1103last <cycle>",
-0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("<duration> ago",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.995732273553991,
likelihoods =
HashMap.fromList
[("week", -1.55814461804655), ("day", -1.845826690498331),
("year", -2.2512917986064953),
("<integer> <unit-of-duration>", -0.8649974374866046),
("month", -2.2512917986064953)],
n = 7},
koData =
ClassData{prior = -infinity, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [], n = 0}}),
("\1051\1080\1089\1090\1086\1087\1072\1076",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("last <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3025850929940455,
likelihoods =
HashMap.fromList
[("\1053\1077\1076\1110\1083\1103", -1.0986122886681098),
("day", -0.8109302162163288),
("\1042\1110\1074\1090\1086\1088\1086\1082",
-1.5040773967762742)],
n = 3},
koData =
ClassData{prior = -infinity, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [], n = 0}}),
("<day-of-month> (ordinal)",
Classifier{okData =
ClassData{prior = -1.2039728043259361,
unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("ordinals (first..19th)", 0.0)],
n = 3},
koData =
ClassData{prior = -0.35667494393873245,
unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("ordinals (first..19th)", 0.0)],
n = 7}}),
("\1055'\1103\1090\1085\1080\1094\1103",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("until <time-of-day>",
Classifier{okData =
ClassData{prior = -0.1823215567939546,
unseen = -3.4011973816621555,
likelihoods =
HashMap.fromList
[("<time> <part-of-day>", -2.268683541318364),
("<time-of-day> o'clock", -1.9810014688665833),
("\1050\1110\1085\1077\1094\1100 \1084\1110\1089\1103\1094\1103",
-2.6741486494265287),
("time-of-day (latent)", -1.9810014688665833),
("hour", -1.0647107369924282), ("month", -2.6741486494265287),
("midnight|EOD|end of day", -2.6741486494265287)],
n = 10},
koData =
ClassData{prior = -1.791759469228055, unseen = -2.639057329615259,
likelihoods =
HashMap.fromList
[("hh:mm", -1.466337068793427), ("minute", -1.466337068793427)],
n = 2}}),
("\1046\1086\1074\1090\1077\1085\1100",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("evening",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("decimal number",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -3.6109179126442243,
likelihoods = HashMap.fromList [("", 0.0)], n = 35}}),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("midnight|EOD|end of day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("last <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("week", -1.3862943611198906),
("month (grain)", -2.0794415416798357),
("year (grain)", -2.0794415416798357),
("week (grain)", -1.3862943611198906),
("year", -2.0794415416798357), ("month", -2.0794415416798357)],
n = 5},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}}),
("next n <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.912023005428146,
likelihoods =
HashMap.fromList
[("week", -2.793208009442517),
("integer (numeric)day (grain)", -3.1986731175506815),
("integer (3..19)day (grain)", -3.1986731175506815),
("second", -2.793208009442517),
("integer (3..19)second (grain)", -3.1986731175506815),
("integer (numeric)second (grain)", -3.1986731175506815),
("integer (numeric)year (grain)", -3.1986731175506815),
("integer (3..19)year (grain)", -3.1986731175506815),
("day", -2.793208009442517), ("year", -2.793208009442517),
("integer (3..19)week (grain)", -3.1986731175506815),
("integer (numeric)week (grain)", -3.1986731175506815),
("integer (3..19)minute (grain)", -3.1986731175506815),
("hour", -2.793208009442517), ("month", -2.793208009442517),
("integer (numeric)minute (grain)", -3.1986731175506815),
("integer (3..19)month (grain)", -3.1986731175506815),
("integer (numeric)month (grain)", -3.1986731175506815),
("integer (3..19)hour (grain)", -3.1986731175506815),
("minute", -2.793208009442517),
("integer (numeric)hour (grain)", -3.1986731175506815)],
n = 14},
koData =
ClassData{prior = -infinity, unseen = -3.0910424533583156,
likelihoods = HashMap.fromList [], n = 0}}),
("in <duration>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.4657359027997265,
likelihoods =
HashMap.fromList
[("week", -2.740840023925201), ("second", -2.740840023925201),
("day", -2.740840023925201), ("year", -2.740840023925201),
("<integer> <unit-of-duration>", -0.8690378470236094),
("hour", -2.0476928433652555), ("minute", -1.6422277352570913)],
n = 12},
koData =
ClassData{prior = -infinity, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [], n = 0}}),
("<datetime> - <datetime> (interval)",
Classifier{okData =
ClassData{prior = -0.5108256237659907,
unseen = -3.4657359027997265,
likelihoods =
HashMap.fromList
[("intersecthh:mm", -2.740840023925201),
("minuteminute", -1.6422277352570913),
("hh:mmhh:mm", -1.824549292051046),
("dayday", -1.824549292051046),
("<day-of-month> (non ordinal) <named-month><day-of-month> (non ordinal) <named-month>",
-2.3353749158170367),
("mm/ddmm/dd", -2.3353749158170367)],
n = 9},
koData =
ClassData{prior = -0.916290731874155, unseen = -3.258096538021482,
likelihoods =
HashMap.fromList
[("monthday", -2.120263536200091),
("mm/ddmm/dd/yyyy", -2.5257286443082556),
("mm/ddhh:mm", -2.120263536200091),
("dayday", -2.120263536200091),
("mm/ddintersect", -2.5257286443082556),
("dayminute", -2.120263536200091),
("\1057\1077\1088\1087\1077\1085\1100<day-of-month> (non ordinal) <named-month>",
-2.5257286443082556),
("\1051\1080\1087\1077\1085\1100<day-of-month> (non ordinal) <named-month>",
-2.5257286443082556)],
n = 6}}),
("<time-of-day> - <time-of-day> (interval)",
Classifier{okData =
ClassData{prior = -0.3184537311185346,
unseen = -3.1354942159291497,
likelihoods =
HashMap.fromList
[("hh:mmtime-of-day (latent)", -1.7047480922384253),
("minuteminute", -1.2992829841302609),
("hh:mmhh:mm", -1.2992829841302609),
("minutehour", -1.7047480922384253)],
n = 8},
koData =
ClassData{prior = -1.2992829841302609,
unseen = -2.5649493574615367,
likelihoods =
HashMap.fromList
[("hh:mmtime-of-day (latent)", -1.791759469228055),
("hourminute", -1.3862943611198906),
("minutehour", -1.791759469228055),
("time-of-day (latent)hh:mm", -1.3862943611198906)],
n = 3}}),
("\1057\1077\1088\1087\1077\1085\1100",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("last n <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.7612001156935624,
likelihoods =
HashMap.fromList
[("week", -2.639057329615259),
("integer 2week (grain)", -3.044522437723423),
("integer (numeric)day (grain)", -3.044522437723423),
("integer 2minute (grain)", -3.044522437723423),
("second", -2.639057329615259),
("integer 2month (grain)", -3.044522437723423),
("integer (numeric)second (grain)", -3.044522437723423),
("integer (numeric)year (grain)", -3.044522437723423),
("day", -2.639057329615259), ("year", -2.639057329615259),
("integer 2day (grain)", -3.044522437723423),
("integer (numeric)week (grain)", -3.044522437723423),
("month", -2.639057329615259),
("integer (numeric)minute (grain)", -3.044522437723423),
("integer (numeric)month (grain)", -3.044522437723423),
("integer 2second (grain)", -3.044522437723423),
("minute", -2.639057329615259),
("integer 2year (grain)", -3.044522437723423)],
n = 12},
koData =
ClassData{prior = -infinity, unseen = -2.9444389791664407,
likelihoods = HashMap.fromList [], n = 0}}),
("nth <time> after <time>",
Classifier{okData =
ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055,
likelihoods =
HashMap.fromList
[("dayday", -0.916290731874155),
("ordinals (first..19th)\1042\1110\1074\1090\1086\1088\1086\1082intersect",
-0.916290731874155)],
n = 1},
koData =
ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055,
likelihoods =
HashMap.fromList
[("dayday", -0.916290731874155),
("ordinals (first..19th)\1042\1110\1074\1090\1086\1088\1086\1082\1050\1072\1090\1086\1083\1080\1094\1100\1082\1077 \1056\1110\1079\1076\1074\1086",
-0.916290731874155)],
n = 1}}),
("\1056\1110\1079\1076\1074\1086 \1061\1088\1080\1089\1090\1086\1074\1077",
Classifier{okData =
ClassData{prior = -0.40546510810816444,
unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -1.0986122886681098,
unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1}}),
("<day-of-month> (non ordinal) <named-month>",
Classifier{okData =
ClassData{prior = -8.338160893905101e-2,
unseen = -3.9889840465642745,
likelihoods =
HashMap.fromList
[("integer (numeric)\1051\1080\1087\1077\1085\1100",
-2.3608540011180215),
("integer (numeric)\1050\1074\1110\1090\1077\1085\1100",
-3.2771447329921766),
("integer (numeric)\1041\1077\1088\1077\1079\1077\1085\1100",
-2.3608540011180215),
("integer (numeric)\1051\1102\1090\1080\1081",
-1.7730673362159024),
("integer (numeric)\1057\1077\1088\1087\1077\1085\1100",
-2.3608540011180215),
("month", -0.7922380832041762),
("integer (numeric)\1042\1077\1088\1077\1089\1077\1085\1100",
-2.871679624884012)],
n = 23},
koData =
ClassData{prior = -2.5257286443082556,
unseen = -2.4849066497880004,
likelihoods =
HashMap.fromList
[("integer (numeric)\1051\1080\1087\1077\1085\1100",
-1.2992829841302609),
("month", -1.2992829841302609)],
n = 2}}),
("this|next <day-of-week>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3978952727983707,
likelihoods =
HashMap.fromList
[("\1057\1077\1088\1077\1076\1072", -1.6094379124341003),
("day", -0.916290731874155),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082",
-1.6094379124341003),
("\1042\1110\1074\1090\1086\1088\1086\1082",
-1.6094379124341003)],
n = 3},
koData =
ClassData{prior = -infinity, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [], n = 0}}),
("quarter (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("last <cycle> of <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.70805020110221,
likelihoods =
HashMap.fromList
[("daymonth", -1.540445040947149),
("day (grain)intersect", -1.9459101490553135),
("day (grain)\1046\1086\1074\1090\1077\1085\1100",
-1.9459101490553135),
("weekmonth", -1.540445040947149),
("week (grain)intersect", -1.9459101490553135),
("week (grain)\1042\1077\1088\1077\1089\1077\1085\1100",
-1.9459101490553135)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}}),
("morning",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("week-end",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1042\1110\1074\1090\1086\1088\1086\1082",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("after <time-of-day>",
Classifier{okData =
ClassData{prior = -0.40546510810816444,
unseen = -2.995732273553991,
likelihoods =
HashMap.fromList
[("<time-of-day> o'clock", -1.55814461804655),
("time-of-day (latent)", -1.55814461804655),
("hour", -0.9985288301111273)],
n = 6},
koData =
ClassData{prior = -1.0986122886681098, unseen = -2.639057329615259,
likelihoods =
HashMap.fromList
[("intersect", -1.8718021769015913),
("day", -1.1786549963416462),
("\1056\1110\1079\1076\1074\1086 \1061\1088\1080\1089\1090\1086\1074\1077",
-1.8718021769015913),
("\1050\1072\1090\1086\1083\1080\1094\1100\1082\1077 \1056\1110\1079\1076\1074\1086",
-1.8718021769015913)],
n = 3}}),
("day (grain)",
Classifier{okData =
ClassData{prior = -0.10536051565782628,
unseen = -2.3978952727983707,
likelihoods = HashMap.fromList [("", 0.0)], n = 9},
koData =
ClassData{prior = -2.3025850929940455,
unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1}}),
("<month> dd-dd (interval)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods =
HashMap.fromList
[("\1051\1080\1087\1077\1085\1100", -0.6931471805599453),
("month", -0.6931471805599453)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("\1083\1110\1090\1086",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1087\1086\1079\1072\1074\1095\1086\1088\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1050\1072\1090\1086\1083\1080\1094\1100\1082\1077 \1056\1110\1079\1076\1074\1086",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("this <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.70805020110221,
likelihoods =
HashMap.fromList
[("\1074\1077\1089\1085\1072", -1.9459101490553135),
("\1079\1080\1084\1072", -1.9459101490553135),
("day", -1.252762968495368), ("hour", -1.9459101490553135),
("week-end", -1.9459101490553135),
("\1083\1110\1090\1086", -1.9459101490553135)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}}),
("within <duration>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("week", -0.6931471805599453),
("<integer> <unit-of-duration>", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}})] | null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Ranking/Classifiers/UK_XX.hs | haskell | 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
---------------------------------------------------------------
Auto-generated by regenClassifiers
DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
---------------------------------------------------------------
# LANGUAGE OverloadedStrings # | Copyright ( c ) 2016 - present , Facebook , Inc.
of patent rights can be found in the PATENTS file in the same directory .
@generated
module Duckling.Ranking.Classifiers.UK_XX (classifiers) where
import Data.String
import Prelude
import qualified Data.HashMap.Strict as HashMap
import Duckling.Ranking.Types
classifiers :: Classifiers
classifiers
= HashMap.fromList
[("\1050\1074\1110\1090\1077\1085\1100",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time> timezone",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods =
HashMap.fromList
[("hh:mm", -0.6931471805599453),
("minute", -0.6931471805599453)],
n = 3},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("integer (numeric)",
Classifier{okData =
ClassData{prior = -0.7693745459478296, unseen = -4.634728988229636,
likelihoods = HashMap.fromList [("", 0.0)], n = 101},
koData =
ClassData{prior = -0.6223211279913329, unseen = -4.77912349311153,
likelihoods = HashMap.fromList [("", 0.0)], n = 117}}),
("integer (3..19)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.4849066497880004,
likelihoods = HashMap.fromList [("", 0.0)], n = 10},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("lunch",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time> <part-of-day>",
Classifier{okData =
ClassData{prior = -0.13976194237515874,
unseen = -4.709530201312334,
likelihoods =
HashMap.fromList
[("<time-of-day> o'clockmorning", -3.6018680771243066),
("until <time-of-day>afternoon", -4.007333185232471),
("dayhour", -2.503255788456197),
("at <time-of-day>evening", -4.007333185232471),
("\1074\1095\1086\1088\1072evening", -4.007333185232471),
("intersect by ','evening", -3.6018680771243066),
("\1089\1100\1086\1075\1086\1076\1085\1110afternoon",
-4.007333185232471),
("intersectevening", -2.2155737160044158),
("hourhour", -1.3331845358059422),
("\1079\1072\1074\1090\1088\1072lunch", -4.007333185232471),
("at <time-of-day>afternoon", -3.6018680771243066),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082morning",
-4.007333185232471),
("<time-of-day> o'clockafternoon", -3.0910424533583156),
("until <time-of-day>morning", -4.007333185232471),
("minutehour", -3.0910424533583156),
("\1089\1100\1086\1075\1086\1076\1085\1110evening",
-4.007333185232471),
("time-of-day (latent)morning", -4.007333185232471),
("hh:mmmorning", -4.007333185232471),
("time-of-day (latent)evening", -4.007333185232471),
("\1079\1072\1074\1090\1088\1072evening", -4.007333185232471),
("<time-of-day> o'clockevening", -3.6018680771243066),
("hh:mmnight", -4.007333185232471),
("hh:mmafternoon", -4.007333185232471),
("on <date>morning", -4.007333185232471),
("at <time-of-day>morning", -4.007333185232471),
("\1063\1077\1090\1074\1077\1088morning", -4.007333185232471)],
n = 40},
koData =
ClassData{prior = -2.03688192726104, unseen = -3.7612001156935624,
likelihoods =
HashMap.fromList
[("yearhour", -2.639057329615259),
("intersectevening", -2.3513752571634776),
("hourhour", -2.128231705849268),
("year (latent)afternoon", -3.044522437723423),
("year (latent)night", -3.044522437723423),
("time-of-day (latent)afternoon", -3.044522437723423)],
n = 6}}),
("numbers prefix with -, minus",
Classifier{okData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -3.258096538021482,
likelihoods =
HashMap.fromList
[("integer (numeric)", -0.4462871026284195),
("decimal number", -1.0216512475319814)],
n = 23}}),
("\1087\1110\1089\1083\1103\1079\1072\1074\1090\1088\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1074\1095\1086\1088\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("mm/dd",
Classifier{okData =
ClassData{prior = -0.8754687373538999,
unseen = -2.4849066497880004,
likelihoods = HashMap.fromList [("", 0.0)], n = 10},
koData =
ClassData{prior = -0.5389965007326869, unseen = -2.772588722239781,
likelihoods = HashMap.fromList [("", 0.0)], n = 14}}),
("\1057\1091\1073\1086\1090\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("", 0.0)], n = 3},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("at <time-of-day>",
Classifier{okData =
ClassData{prior = -0.1431008436406733, unseen = -4.060443010546419,
likelihoods =
HashMap.fromList
[("<time-of-day> o'clock", -1.845826690498331),
("time-of-day (latent)", -1.3350010667323402),
("hh:mm", -2.4336133554004498), ("hour", -0.9075570519054005),
("minute", -2.4336133554004498)],
n = 26},
koData =
ClassData{prior = -2.0149030205422647, unseen = -2.639057329615259,
likelihoods =
HashMap.fromList
[("time-of-day (latent)", -0.9555114450274363),
("hour", -0.9555114450274363)],
n = 4}}),
("absorption of , after named day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.1354942159291497,
likelihoods =
HashMap.fromList
[("\1057\1091\1073\1086\1090\1072", -2.3978952727983707),
("\1057\1077\1088\1077\1076\1072", -2.3978952727983707),
("\1053\1077\1076\1110\1083\1103", -2.3978952727983707),
("day", -0.8938178760220964),
("\1055'\1103\1090\1085\1080\1094\1103", -1.7047480922384253),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082",
-1.9924301646902063)],
n = 8},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}}),
("on <date>",
Classifier{okData =
ClassData{prior = -0.2006706954621511, unseen = -3.367295829986474,
likelihoods =
HashMap.fromList
[("<time> <part-of-day>", -2.639057329615259),
("\1057\1091\1073\1086\1090\1072", -2.639057329615259),
("\1063\1077\1090\1074\1077\1088", -2.639057329615259),
("intersect", -1.540445040947149), ("day", -1.9459101490553135),
("hour", -1.7227665977411035),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082",
-2.639057329615259),
("minute", -2.2335922215070942)],
n = 9},
koData =
ClassData{prior = -1.7047480922384253, unseen = -2.70805020110221,
likelihoods =
HashMap.fromList
[("intersect", -1.9459101490553135),
("\1041\1077\1088\1077\1079\1077\1085\1100",
-1.9459101490553135),
("month", -1.540445040947149)],
n = 2}}),
("\1074\1077\1089\1085\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("between <time-of-day> and <time-of-day> (interval)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("hh:mmtime-of-day (latent)", -1.6739764335716716),
("minuteminute", -1.6739764335716716),
("time-of-day (latent)time-of-day (latent)",
-2.0794415416798357),
("hh:mmhh:mm", -1.6739764335716716),
("hourhour", -2.0794415416798357),
("minutehour", -1.6739764335716716)],
n = 5},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}}),
("\1063\1077\1090\1074\1077\1088",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("month (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time-of-day> o'clock",
Classifier{okData =
ClassData{prior = -0.14518200984449783,
unseen = -4.248495242049359,
likelihoods =
HashMap.fromList
[("at <time-of-day>", -2.03688192726104),
("time-of-day (latent)", -1.289667525430819),
("until <time-of-day>", -2.847812143477369),
("hour", -0.7375989431307791),
("after <time-of-day>", -2.847812143477369)],
n = 32},
koData =
ClassData{prior = -2.001480000210124, unseen = -2.772588722239781,
likelihoods =
HashMap.fromList
[("time-of-day (latent)", -0.916290731874155),
("hour", -0.916290731874155)],
n = 5}}),
("hour (grain)",
Classifier{okData =
ClassData{prior = -1.4350845252893227,
unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -0.2719337154836418, unseen = -2.890371757896165,
likelihoods = HashMap.fromList [("", 0.0)], n = 16}}),
("<ordinal> quarter",
Classifier{okData =
ClassData{prior = -0.6931471805599453,
unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("ordinals (first..19th)quarter (grain)", -0.6931471805599453),
("quarter", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -0.6931471805599453,
unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("ordinals (first..19th)quarter (grain)", -0.6931471805599453),
("quarter", -0.6931471805599453)],
n = 1}}),
("\1057\1077\1088\1077\1076\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("intersect",
Classifier{okData =
ClassData{prior = -0.2411620568168881, unseen = -5.817111159963204,
likelihoods =
HashMap.fromList
[("\1055\1086\1085\1077\1076\1110\1083\1086\1082this <cycle>",
-5.120983351265121),
("hourday", -4.204692619390966),
("<datetime> - <datetime> (interval)year", -5.120983351265121),
("hh:mm<part-of-day> of <time>", -4.204692619390966),
("dayhour", -2.287770007208905),
("daymonth", -3.868220382769753),
("monthyear", -3.5115454388310208),
("yearhour", -5.120983351265121),
("intersect<time-of-day> o'clock", -4.204692619390966),
("absorption of , after named daymm/dd/yyyy",
-5.120983351265121),
("<day-of-month> (ordinal)\1041\1077\1088\1077\1079\1077\1085\1100",
-5.120983351265121),
("\1046\1086\1074\1090\1077\1085\1100year", -4.022371062597012),
("intersect<time> <part-of-day>", -4.204692619390966),
("\1051\1080\1089\1090\1086\1087\1072\1076year",
-5.120983351265121),
("\1057\1077\1088\1077\1076\1072\1046\1086\1074\1090\1077\1085\1100",
-4.715518243156957),
("intersect\1046\1086\1074\1090\1077\1085\1100",
-5.120983351265121),
("intersect by ','year", -4.715518243156957),
("\1063\1077\1090\1074\1077\1088hh:mm", -5.120983351265121),
("on <date><time-of-day> o'clock", -5.120983351265121),
("\1041\1077\1088\1077\1079\1077\1085\1100year",
-5.120983351265121),
("\1057\1091\1073\1086\1090\1072<time-of-day> o'clock",
-5.120983351265121),
("mm/dd<time-of-day> o'clock", -5.120983351265121),
("\1057\1077\1088\1077\1076\1072next <cycle>",
-5.120983351265121),
("last <day-of-week> of <time>year", -5.120983351265121),
("\1042\1077\1088\1077\1089\1077\1085\1100year",
-4.715518243156957),
("on <date>between <time-of-day> and <time-of-day> (interval)",
-4.715518243156957),
("on <date>at <time-of-day>", -4.715518243156957),
("\1063\1077\1090\1074\1077\1088between <time-of-day> and <time-of-day> (interval)",
-4.204692619390966),
("dayday", -2.9809171877688505),
("at <time-of-day>\1079\1072\1074\1090\1088\1072",
-5.120983351265121),
("\1057\1091\1073\1086\1090\1072at <time-of-day>",
-4.715518243156957),
("mm/ddat <time-of-day>", -4.715518243156957),
("<time> <part-of-day>between <time-of-day> and <time-of-day> (interval)",
-5.120983351265121),
("<day-of-month> (ordinal)intersect", -4.427836170705175),
("hourhour", -5.120983351265121),
("hh:mmintersect by ','", -5.120983351265121),
("intersect<day-of-month> (non ordinal) <named-month>",
-4.715518243156957),
("dayyear", -2.869691552658626),
("<day-of-month> (ordinal)\1042\1110\1074\1090\1086\1088\1086\1082",
-5.120983351265121),
("<day-of-month> (non ordinal) <named-month>intersect",
-5.120983351265121),
("\1089\1100\1086\1075\1086\1076\1085\1110<time-of-day> o'clock",
-5.120983351265121),
("minutehour", -3.868220382769753),
("absorption of , after named day<day-of-month> (non ordinal) <named-month>",
-3.7346889901452305),
("\1063\1077\1090\1074\1077\1088<part-of-day> of <time>",
-5.120983351265121),
("at <time-of-day><day-of-month> (non ordinal) <named-month>",
-5.120983351265121),
("\1063\1077\1090\1074\1077\1088<datetime> - <datetime> (interval)",
-5.120983351265121),
("hh:mm<day-of-month> (non ordinal) <named-month>",
-5.120983351265121),
("\1063\1077\1090\1074\1077\1088<time-of-day> - <time-of-day> (interval)",
-4.715518243156957),
("hh:mmintersect", -5.120983351265121),
("intersect by ','intersect", -5.120983351265121),
("\1042\1110\1074\1090\1086\1088\1086\1082this <cycle>",
-5.120983351265121),
("dayminute", -3.175073202209808),
("<time> <part-of-day>intersect", -5.120983351265121),
("intersectyear", -4.022371062597012),
("<ordinal> <cycle> of <time>year", -5.120983351265121),
("minuteday", -3.616905954488847),
("absorption of , after named dayintersect",
-4.204692619390966),
("\1079\1072\1074\1090\1088\1072<time-of-day> o'clock",
-5.120983351265121),
("year<time-of-day> o'clock", -5.120983351265121),
("<time-of-day> o'clock\1079\1072\1074\1090\1088\1072",
-4.715518243156957),
("intersect by ','<time> <part-of-day>", -5.120983351265121),
("<time> <part-of-day>intersect by ','", -5.120983351265121),
("<day-of-month> (ordinal)\1057\1077\1088\1077\1076\1072",
-5.120983351265121),
("mm/ddyear", -4.715518243156957),
("intersect by ','<time-of-day> o'clock", -5.120983351265121),
("<time> <part-of-day>\1057\1091\1073\1086\1090\1072",
-5.120983351265121),
("absorption of , after named daymm/dd", -5.120983351265121),
("<time> <part-of-day>absorption of , after named day",
-5.120983351265121),
("intersectintersect", -4.715518243156957),
("<part-of-day> of <time><day-of-month> (non ordinal) <named-month>",
-5.120983351265121),
("dayweek", -4.204692619390966),
("\1079\1072\1074\1090\1088\1072at <time-of-day>",
-4.715518243156957),
("\1057\1077\1088\1077\1076\1072intersect", -5.120983351265121),
("weekyear", -4.715518243156957),
("\1063\1077\1090\1074\1077\1088<time> timezone",
-4.715518243156957),
("\1089\1100\1086\1075\1086\1076\1085\1110at <time-of-day>",
-4.204692619390966),
("\1089\1100\1086\1075\1086\1076\1085\1110<time> <part-of-day>",
-5.120983351265121),
("\1050\1072\1090\1086\1083\1080\1094\1100\1082\1077 \1056\1110\1079\1076\1074\1086year",
-5.120983351265121),
("\1057\1077\1088\1077\1076\1072this <cycle>",
-5.120983351265121),
("last <cycle> of <time>year", -4.715518243156957),
("<day-of-month> (non ordinal) <named-month>year",
-4.022371062597012)],
n = 121},
koData =
ClassData{prior = -1.540445040947149, unseen = -5.075173815233827,
likelihoods =
HashMap.fromList
[("dayhour", -4.375757021660286),
("daymonth", -3.2771447329921766),
("monthyear", -3.122994053164918),
("yearhour", -4.375757021660286),
("intersect<time-of-day> o'clock", -4.375757021660286),
("intersect<time> <part-of-day>", -4.375757021660286),
("absorption of , after named dayhh:mm", -4.375757021660286),
("intersect\1046\1086\1074\1090\1077\1085\1100",
-4.375757021660286),
("\1063\1077\1090\1074\1077\1088hh:mm", -3.970291913552122),
("\1041\1077\1088\1077\1079\1077\1085\1100year",
-3.970291913552122),
("\1051\1080\1087\1077\1085\1100intersect", -4.375757021660286),
("monthhour", -3.6826098411003407),
("dayday", -3.2771447329921766),
("\1042\1110\1074\1090\1086\1088\1086\1082after <time-of-day>",
-4.375757021660286),
("<day-of-month> (ordinal)intersect", -4.375757021660286),
("dayyear", -2.7663191092261856),
("<day-of-month> (ordinal)\1042\1110\1074\1090\1086\1088\1086\1082",
-3.970291913552122),
("\1051\1080\1087\1077\1085\1100year", -3.970291913552122),
("dayminute", -3.6826098411003407),
("intersectyear", -3.970291913552122),
("<day-of-month> (ordinal)\1057\1077\1088\1077\1076\1072",
-4.375757021660286),
("year<time> <part-of-day>", -4.375757021660286),
("mm/ddyear", -3.2771447329921766),
("on <date>year", -4.375757021660286),
("\1057\1077\1088\1077\1076\1072intersect", -4.375757021660286),
("\1053\1077\1076\1110\1083\1103intersect", -4.375757021660286),
("\1050\1074\1110\1090\1077\1085\1100year", -4.375757021660286),
("\1089\1100\1086\1075\1086\1076\1085\1110at <time-of-day>",
-4.375757021660286),
("after <time-of-day>year", -4.375757021660286),
("\1056\1110\1079\1076\1074\1086 \1061\1088\1080\1089\1090\1086\1074\1077year",
-4.375757021660286),
("\1053\1077\1076\1110\1083\1103on <date>",
-3.970291913552122)],
n = 33}}),
("<ordinal> <cycle> of <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.4849066497880004,
likelihoods =
HashMap.fromList
[("daymonth", -1.7047480922384253),
("ordinals (first..19th)day (grain)\1046\1086\1074\1090\1077\1085\1100",
-1.7047480922384253),
("ordinals (first..19th)week (grain)\1046\1086\1074\1090\1077\1085\1100",
-1.7047480922384253),
("ordinals (first..19th)week (grain)intersect",
-1.7047480922384253),
("weekmonth", -1.2992829841302609)],
n = 3},
koData =
ClassData{prior = -infinity, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [], n = 0}}),
("year (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.5649493574615367,
likelihoods = HashMap.fromList [("", 0.0)], n = 11},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("next <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.1354942159291497,
likelihoods =
HashMap.fromList
[("week", -1.7047480922384253),
("month (grain)", -2.3978952727983707),
("year (grain)", -1.9924301646902063),
("week (grain)", -1.7047480922384253),
("quarter", -2.3978952727983707), ("year", -1.9924301646902063),
("month", -2.3978952727983707),
("quarter (grain)", -2.3978952727983707)],
n = 7},
koData =
ClassData{prior = -infinity, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [], n = 0}}),
("year (latent)",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 2}}),
("mm/dd/yyyy",
Classifier{okData =
ClassData{prior = -1.0116009116784799, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -0.45198512374305727,
unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7}}),
("<ordinal> quarter <year>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("quarteryear", -0.6931471805599453),
("ordinals (first..19th)quarter (grain)year",
-0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("\1051\1080\1087\1077\1085\1100",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1050\1110\1085\1077\1094\1100 \1084\1110\1089\1103\1094\1103",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1079\1080\1084\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("nth <time> of <time>",
Classifier{okData =
ClassData{prior = -0.40546510810816444,
unseen = -3.044522437723423,
likelihoods =
HashMap.fromList
[("daymonth", -1.3862943611198906),
("dayyear", -1.8971199848858813),
("ordinals (first..19th)\1042\1110\1074\1090\1086\1088\1086\1082\1046\1086\1074\1090\1077\1085\1100",
-2.3025850929940455),
("ordinals (first..19th)\1042\1110\1074\1090\1086\1088\1086\1082intersect",
-2.3025850929940455),
("ordinals (first..19th)\1057\1077\1088\1077\1076\1072intersect",
-1.8971199848858813),
("ordinals (first..19th)intersectyear", -1.8971199848858813)],
n = 6},
koData =
ClassData{prior = -1.0986122886681098, unseen = -2.70805020110221,
likelihoods =
HashMap.fromList
[("daymonth", -1.252762968495368),
("ordinals (first..19th)\1057\1077\1088\1077\1076\1072\1046\1086\1074\1090\1077\1085\1100",
-1.540445040947149),
("ordinals (first..19th)\1042\1110\1074\1090\1086\1088\1086\1082\1042\1077\1088\1077\1089\1077\1085\1100",
-1.9459101490553135)],
n = 3}}),
("\1053\1077\1076\1110\1083\1103",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("week (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.1354942159291497,
likelihoods = HashMap.fromList [("", 0.0)], n = 21},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<part-of-day> of <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.044522437723423,
likelihoods =
HashMap.fromList
[("hourday", -1.2039728043259361),
("morning<day-of-month> (non ordinal) <named-month>",
-2.3025850929940455),
("hourhour", -2.3025850929940455),
("morningbetween <time-of-day> and <time-of-day> (interval)",
-2.3025850929940455),
("night\1057\1091\1073\1086\1090\1072", -2.3025850929940455),
("nightabsorption of , after named day", -2.3025850929940455),
("nightintersect by ','", -2.3025850929940455),
("nightintersect", -2.3025850929940455)],
n = 6},
koData =
ClassData{prior = -infinity, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [], n = 0}}),
("<day-of-month>(ordinal) <named-month>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("ordinals (first..19th)\1041\1077\1088\1077\1079\1077\1085\1100",
-0.6931471805599453),
("month", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("\1089\1100\1086\1075\1086\1076\1085\1110",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<time> after next",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods =
HashMap.fromList
[("\1057\1077\1088\1077\1076\1072", -1.252762968495368),
("day", -0.8472978603872037),
("\1055'\1103\1090\1085\1080\1094\1103", -1.252762968495368)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [], n = 0}}),
("integer 2",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3978952727983707,
likelihoods = HashMap.fromList [("", 0.0)], n = 9},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("afternoon",
Classifier{okData =
ClassData{prior = -0.2231435513142097, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -1.6094379124341003,
unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1}}),
("this <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.9444389791664407,
likelihoods =
HashMap.fromList
[("week", -1.2809338454620642),
("year (grain)", -2.1972245773362196),
("week (grain)", -1.2809338454620642),
("quarter", -2.1972245773362196), ("year", -2.1972245773362196),
("quarter (grain)", -2.1972245773362196)],
n = 6},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}}),
("minute (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3978952727983707,
likelihoods = HashMap.fromList [("", 0.0)], n = 9},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("night",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1053\1086\1074\1080\1081 \1088\1110\1082",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1079\1072\1074\1090\1088\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("time-of-day (latent)",
Classifier{okData =
ClassData{prior = -0.35020242943311486,
unseen = -3.5553480614894135,
likelihoods =
HashMap.fromList
[("integer (numeric)", -9.237332013101517e-2),
("integer (3..19)", -2.833213344056216)],
n = 31},
koData =
ClassData{prior = -1.2192402764567243, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("integer (numeric)", -0.3746934494414107),
("integer (3..19)", -1.6739764335716716),
("integer 2", -2.0794415416798357)],
n = 13}}),
("year",
Classifier{okData =
ClassData{prior = -0.19105523676270922,
unseen = -3.044522437723423,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 19},
koData =
ClassData{prior = -1.749199854809259, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("integer (numeric)", 0.0)],
n = 4}}),
("last <day-of-week> of <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3978952727983707,
likelihoods =
HashMap.fromList
[("daymonth", -0.916290731874155),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082\1041\1077\1088\1077\1079\1077\1085\1100",
-1.6094379124341003),
("\1053\1077\1076\1110\1083\1103\1041\1077\1088\1077\1079\1077\1085\1100",
-1.6094379124341003),
("\1053\1077\1076\1110\1083\1103intersect",
-1.6094379124341003)],
n = 3},
koData =
ClassData{prior = -infinity, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [], n = 0}}),
("<integer> <unit-of-duration>",
Classifier{okData =
ClassData{prior = -1.114360645636249, unseen = -4.2626798770413155,
likelihoods =
HashMap.fromList
[("week", -2.456735772821304),
("integer 2week (grain)", -3.5553480614894135),
("integer (numeric)day (grain)", -2.8622008809294686),
("second", -3.5553480614894135),
("integer 2hour (grain)", -3.5553480614894135),
("integer (numeric)second (grain)", -3.5553480614894135),
("integer (numeric)year (grain)", -3.1498829533812494),
("day", -2.8622008809294686), ("year", -2.8622008809294686),
("integer (3..19)week (grain)", -3.5553480614894135),
("integer (numeric)week (grain)", -2.8622008809294686),
("hour", -2.8622008809294686), ("month", -3.5553480614894135),
("integer (numeric)minute (grain)", -2.456735772821304),
("integer (3..19)month (grain)", -3.5553480614894135),
("minute", -2.456735772821304),
("integer (numeric)hour (grain)", -3.1498829533812494),
("integer 2year (grain)", -3.5553480614894135)],
n = 21},
koData =
ClassData{prior = -0.39768296766610944, unseen = -4.74493212836325,
likelihoods =
HashMap.fromList
[("week", -3.126760535960395),
("integer 2week (grain)", -4.04305126783455),
("integer (numeric)day (grain)", -3.349904087274605),
("integer (3..19)day (grain)", -4.04305126783455),
("integer 2minute (grain)", -4.04305126783455),
("second", -3.126760535960395),
("integer 2month (grain)", -4.04305126783455),
("integer (3..19)second (grain)", -4.04305126783455),
("integer (numeric)second (grain)", -3.6375861597263857),
("integer (numeric)year (grain)", -3.6375861597263857),
("integer (3..19)year (grain)", -4.04305126783455),
("day", -2.9444389791664407), ("year", -3.126760535960395),
("integer (3..19)week (grain)", -4.04305126783455),
("integer 2day (grain)", -4.04305126783455),
("integer (numeric)week (grain)", -3.6375861597263857),
("integer (3..19)minute (grain)", -4.04305126783455),
("hour", -1.791759469228055), ("month", -3.126760535960395),
("integer (numeric)minute (grain)", -3.6375861597263857),
("integer (3..19)month (grain)", -4.04305126783455),
("integer (numeric)month (grain)", -3.6375861597263857),
("integer (3..19)hour (grain)", -4.04305126783455),
("integer 2second (grain)", -4.04305126783455),
("minute", -3.126760535960395),
("integer (numeric)hour (grain)", -1.845826690498331),
("integer 2year (grain)", -4.04305126783455)],
n = 43}}),
("ordinals (first..19th)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.4849066497880004,
likelihoods = HashMap.fromList [("", 0.0)], n = 10},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1042\1077\1088\1077\1089\1077\1085\1100",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("<duration> after <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("yearday", -0.6931471805599453),
("<integer> <unit-of-duration>\1056\1110\1079\1076\1074\1086 \1061\1088\1080\1089\1090\1086\1074\1077",
-0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("\1041\1077\1088\1077\1079\1077\1085\1100",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1051\1102\1090\1080\1081",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3025850929940455,
likelihoods = HashMap.fromList [("", 0.0)], n = 8},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("dd.(mm.)? - dd.mm.(yy[yy]?)? (interval)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.639057329615259,
likelihoods = HashMap.fromList [("", 0.0)], n = 12},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("hh:mm",
Classifier{okData =
ClassData{prior = -0.5389965007326869,
unseen = -3.4011973816621555,
likelihoods = HashMap.fromList [("", 0.0)], n = 28},
koData =
ClassData{prior = -0.8754687373538999,
unseen = -3.0910424533583156,
likelihoods = HashMap.fromList [("", 0.0)], n = 20}}),
("intersect by ','",
Classifier{okData =
ClassData{prior = -6.0624621816434854e-2,
unseen = -3.891820298110627,
likelihoods =
HashMap.fromList
[("hourday", -3.1780538303479458),
("dayhour", -2.772588722239781),
("\1055'\1103\1090\1085\1080\1094\1103mm/dd",
-3.1780538303479458),
("\1055'\1103\1090\1085\1080\1094\1103intersect",
-2.2617630984737906),
("dayday", -1.3862943611198906),
("\1057\1077\1088\1077\1076\1072<day-of-month> (non ordinal) <named-month>",
-3.1780538303479458),
("intersect<day-of-month> (non ordinal) <named-month>",
-2.772588722239781),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082<day-of-month> (non ordinal) <named-month>",
-2.772588722239781),
("\1057\1091\1073\1086\1090\1072<day-of-month> (non ordinal) <named-month>",
-3.1780538303479458),
("minuteday", -2.772588722239781),
("\1055'\1103\1090\1085\1080\1094\1103mm/dd/yyyy",
-3.1780538303479458),
("<part-of-day> of <time><day-of-month> (non ordinal) <named-month>",
-3.1780538303479458),
("\1053\1077\1076\1110\1083\1103<day-of-month> (non ordinal) <named-month>",
-3.1780538303479458),
("\1055'\1103\1090\1085\1080\1094\1103<day-of-month> (non ordinal) <named-month>",
-2.772588722239781)],
n = 16},
koData =
ClassData{prior = -2.833213344056216, unseen = -2.9444389791664407,
likelihoods =
HashMap.fromList
[("\1055'\1103\1090\1085\1080\1094\1103hh:mm",
-2.1972245773362196),
("dayminute", -2.1972245773362196)],
n = 1}}),
("second (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("intersect by 'of', 'from', 's",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("dayweek", -0.6931471805599453),
("\1053\1077\1076\1110\1083\1103last <cycle>",
-0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("<duration> ago",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.995732273553991,
likelihoods =
HashMap.fromList
[("week", -1.55814461804655), ("day", -1.845826690498331),
("year", -2.2512917986064953),
("<integer> <unit-of-duration>", -0.8649974374866046),
("month", -2.2512917986064953)],
n = 7},
koData =
ClassData{prior = -infinity, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [], n = 0}}),
("\1051\1080\1089\1090\1086\1087\1072\1076",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("last <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3025850929940455,
likelihoods =
HashMap.fromList
[("\1053\1077\1076\1110\1083\1103", -1.0986122886681098),
("day", -0.8109302162163288),
("\1042\1110\1074\1090\1086\1088\1086\1082",
-1.5040773967762742)],
n = 3},
koData =
ClassData{prior = -infinity, unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [], n = 0}}),
("<day-of-month> (ordinal)",
Classifier{okData =
ClassData{prior = -1.2039728043259361,
unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [("ordinals (first..19th)", 0.0)],
n = 3},
koData =
ClassData{prior = -0.35667494393873245,
unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("ordinals (first..19th)", 0.0)],
n = 7}}),
("\1055'\1103\1090\1085\1080\1094\1103",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [("", 0.0)], n = 5},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("until <time-of-day>",
Classifier{okData =
ClassData{prior = -0.1823215567939546,
unseen = -3.4011973816621555,
likelihoods =
HashMap.fromList
[("<time> <part-of-day>", -2.268683541318364),
("<time-of-day> o'clock", -1.9810014688665833),
("\1050\1110\1085\1077\1094\1100 \1084\1110\1089\1103\1094\1103",
-2.6741486494265287),
("time-of-day (latent)", -1.9810014688665833),
("hour", -1.0647107369924282), ("month", -2.6741486494265287),
("midnight|EOD|end of day", -2.6741486494265287)],
n = 10},
koData =
ClassData{prior = -1.791759469228055, unseen = -2.639057329615259,
likelihoods =
HashMap.fromList
[("hh:mm", -1.466337068793427), ("minute", -1.466337068793427)],
n = 2}}),
("\1046\1086\1074\1090\1077\1085\1100",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("evening",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("decimal number",
Classifier{okData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0},
koData =
ClassData{prior = 0.0, unseen = -3.6109179126442243,
likelihoods = HashMap.fromList [("", 0.0)], n = 35}}),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("midnight|EOD|end of day",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("last <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.833213344056216,
likelihoods =
HashMap.fromList
[("week", -1.3862943611198906),
("month (grain)", -2.0794415416798357),
("year (grain)", -2.0794415416798357),
("week (grain)", -1.3862943611198906),
("year", -2.0794415416798357), ("month", -2.0794415416798357)],
n = 5},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}}),
("next n <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.912023005428146,
likelihoods =
HashMap.fromList
[("week", -2.793208009442517),
("integer (numeric)day (grain)", -3.1986731175506815),
("integer (3..19)day (grain)", -3.1986731175506815),
("second", -2.793208009442517),
("integer (3..19)second (grain)", -3.1986731175506815),
("integer (numeric)second (grain)", -3.1986731175506815),
("integer (numeric)year (grain)", -3.1986731175506815),
("integer (3..19)year (grain)", -3.1986731175506815),
("day", -2.793208009442517), ("year", -2.793208009442517),
("integer (3..19)week (grain)", -3.1986731175506815),
("integer (numeric)week (grain)", -3.1986731175506815),
("integer (3..19)minute (grain)", -3.1986731175506815),
("hour", -2.793208009442517), ("month", -2.793208009442517),
("integer (numeric)minute (grain)", -3.1986731175506815),
("integer (3..19)month (grain)", -3.1986731175506815),
("integer (numeric)month (grain)", -3.1986731175506815),
("integer (3..19)hour (grain)", -3.1986731175506815),
("minute", -2.793208009442517),
("integer (numeric)hour (grain)", -3.1986731175506815)],
n = 14},
koData =
ClassData{prior = -infinity, unseen = -3.0910424533583156,
likelihoods = HashMap.fromList [], n = 0}}),
("in <duration>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.4657359027997265,
likelihoods =
HashMap.fromList
[("week", -2.740840023925201), ("second", -2.740840023925201),
("day", -2.740840023925201), ("year", -2.740840023925201),
("<integer> <unit-of-duration>", -0.8690378470236094),
("hour", -2.0476928433652555), ("minute", -1.6422277352570913)],
n = 12},
koData =
ClassData{prior = -infinity, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [], n = 0}}),
("<datetime> - <datetime> (interval)",
Classifier{okData =
ClassData{prior = -0.5108256237659907,
unseen = -3.4657359027997265,
likelihoods =
HashMap.fromList
[("intersecthh:mm", -2.740840023925201),
("minuteminute", -1.6422277352570913),
("hh:mmhh:mm", -1.824549292051046),
("dayday", -1.824549292051046),
("<day-of-month> (non ordinal) <named-month><day-of-month> (non ordinal) <named-month>",
-2.3353749158170367),
("mm/ddmm/dd", -2.3353749158170367)],
n = 9},
koData =
ClassData{prior = -0.916290731874155, unseen = -3.258096538021482,
likelihoods =
HashMap.fromList
[("monthday", -2.120263536200091),
("mm/ddmm/dd/yyyy", -2.5257286443082556),
("mm/ddhh:mm", -2.120263536200091),
("dayday", -2.120263536200091),
("mm/ddintersect", -2.5257286443082556),
("dayminute", -2.120263536200091),
("\1057\1077\1088\1087\1077\1085\1100<day-of-month> (non ordinal) <named-month>",
-2.5257286443082556),
("\1051\1080\1087\1077\1085\1100<day-of-month> (non ordinal) <named-month>",
-2.5257286443082556)],
n = 6}}),
("<time-of-day> - <time-of-day> (interval)",
Classifier{okData =
ClassData{prior = -0.3184537311185346,
unseen = -3.1354942159291497,
likelihoods =
HashMap.fromList
[("hh:mmtime-of-day (latent)", -1.7047480922384253),
("minuteminute", -1.2992829841302609),
("hh:mmhh:mm", -1.2992829841302609),
("minutehour", -1.7047480922384253)],
n = 8},
koData =
ClassData{prior = -1.2992829841302609,
unseen = -2.5649493574615367,
likelihoods =
HashMap.fromList
[("hh:mmtime-of-day (latent)", -1.791759469228055),
("hourminute", -1.3862943611198906),
("minutehour", -1.791759469228055),
("time-of-day (latent)hh:mm", -1.3862943611198906)],
n = 3}}),
("\1057\1077\1088\1087\1077\1085\1100",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("last n <cycle>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -3.7612001156935624,
likelihoods =
HashMap.fromList
[("week", -2.639057329615259),
("integer 2week (grain)", -3.044522437723423),
("integer (numeric)day (grain)", -3.044522437723423),
("integer 2minute (grain)", -3.044522437723423),
("second", -2.639057329615259),
("integer 2month (grain)", -3.044522437723423),
("integer (numeric)second (grain)", -3.044522437723423),
("integer (numeric)year (grain)", -3.044522437723423),
("day", -2.639057329615259), ("year", -2.639057329615259),
("integer 2day (grain)", -3.044522437723423),
("integer (numeric)week (grain)", -3.044522437723423),
("month", -2.639057329615259),
("integer (numeric)minute (grain)", -3.044522437723423),
("integer (numeric)month (grain)", -3.044522437723423),
("integer 2second (grain)", -3.044522437723423),
("minute", -2.639057329615259),
("integer 2year (grain)", -3.044522437723423)],
n = 12},
koData =
ClassData{prior = -infinity, unseen = -2.9444389791664407,
likelihoods = HashMap.fromList [], n = 0}}),
("nth <time> after <time>",
Classifier{okData =
ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055,
likelihoods =
HashMap.fromList
[("dayday", -0.916290731874155),
("ordinals (first..19th)\1042\1110\1074\1090\1086\1088\1086\1082intersect",
-0.916290731874155)],
n = 1},
koData =
ClassData{prior = -0.6931471805599453, unseen = -1.791759469228055,
likelihoods =
HashMap.fromList
[("dayday", -0.916290731874155),
("ordinals (first..19th)\1042\1110\1074\1090\1086\1088\1086\1082\1050\1072\1090\1086\1083\1080\1094\1100\1082\1077 \1056\1110\1079\1076\1074\1086",
-0.916290731874155)],
n = 1}}),
("\1056\1110\1079\1076\1074\1086 \1061\1088\1080\1089\1090\1086\1074\1077",
Classifier{okData =
ClassData{prior = -0.40546510810816444,
unseen = -1.3862943611198906,
likelihoods = HashMap.fromList [("", 0.0)], n = 2},
koData =
ClassData{prior = -1.0986122886681098,
unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1}}),
("<day-of-month> (non ordinal) <named-month>",
Classifier{okData =
ClassData{prior = -8.338160893905101e-2,
unseen = -3.9889840465642745,
likelihoods =
HashMap.fromList
[("integer (numeric)\1051\1080\1087\1077\1085\1100",
-2.3608540011180215),
("integer (numeric)\1050\1074\1110\1090\1077\1085\1100",
-3.2771447329921766),
("integer (numeric)\1041\1077\1088\1077\1079\1077\1085\1100",
-2.3608540011180215),
("integer (numeric)\1051\1102\1090\1080\1081",
-1.7730673362159024),
("integer (numeric)\1057\1077\1088\1087\1077\1085\1100",
-2.3608540011180215),
("month", -0.7922380832041762),
("integer (numeric)\1042\1077\1088\1077\1089\1077\1085\1100",
-2.871679624884012)],
n = 23},
koData =
ClassData{prior = -2.5257286443082556,
unseen = -2.4849066497880004,
likelihoods =
HashMap.fromList
[("integer (numeric)\1051\1080\1087\1077\1085\1100",
-1.2992829841302609),
("month", -1.2992829841302609)],
n = 2}}),
("this|next <day-of-week>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.3978952727983707,
likelihoods =
HashMap.fromList
[("\1057\1077\1088\1077\1076\1072", -1.6094379124341003),
("day", -0.916290731874155),
("\1055\1086\1085\1077\1076\1110\1083\1086\1082",
-1.6094379124341003),
("\1042\1110\1074\1090\1086\1088\1086\1082",
-1.6094379124341003)],
n = 3},
koData =
ClassData{prior = -infinity, unseen = -1.6094379124341003,
likelihoods = HashMap.fromList [], n = 0}}),
("quarter (grain)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.791759469228055,
likelihoods = HashMap.fromList [("", 0.0)], n = 4},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("last <cycle> of <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.70805020110221,
likelihoods =
HashMap.fromList
[("daymonth", -1.540445040947149),
("day (grain)intersect", -1.9459101490553135),
("day (grain)\1046\1086\1074\1090\1077\1085\1100",
-1.9459101490553135),
("weekmonth", -1.540445040947149),
("week (grain)intersect", -1.9459101490553135),
("week (grain)\1042\1077\1088\1077\1089\1077\1085\1100",
-1.9459101490553135)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}}),
("morning",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.0794415416798357,
likelihoods = HashMap.fromList [("", 0.0)], n = 6},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("week-end",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1042\1110\1074\1090\1086\1088\1086\1082",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.1972245773362196,
likelihoods = HashMap.fromList [("", 0.0)], n = 7},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("after <time-of-day>",
Classifier{okData =
ClassData{prior = -0.40546510810816444,
unseen = -2.995732273553991,
likelihoods =
HashMap.fromList
[("<time-of-day> o'clock", -1.55814461804655),
("time-of-day (latent)", -1.55814461804655),
("hour", -0.9985288301111273)],
n = 6},
koData =
ClassData{prior = -1.0986122886681098, unseen = -2.639057329615259,
likelihoods =
HashMap.fromList
[("intersect", -1.8718021769015913),
("day", -1.1786549963416462),
("\1056\1110\1079\1076\1074\1086 \1061\1088\1080\1089\1090\1086\1074\1077",
-1.8718021769015913),
("\1050\1072\1090\1086\1083\1080\1094\1100\1082\1077 \1056\1110\1079\1076\1074\1086",
-1.8718021769015913)],
n = 3}}),
("day (grain)",
Classifier{okData =
ClassData{prior = -0.10536051565782628,
unseen = -2.3978952727983707,
likelihoods = HashMap.fromList [("", 0.0)], n = 9},
koData =
ClassData{prior = -2.3025850929940455,
unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1}}),
("<month> dd-dd (interval)",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.9459101490553135,
likelihoods =
HashMap.fromList
[("\1051\1080\1087\1077\1085\1100", -0.6931471805599453),
("month", -0.6931471805599453)],
n = 2},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}}),
("\1083\1110\1090\1086",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1087\1086\1079\1072\1074\1095\1086\1088\1072",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("\1050\1072\1090\1086\1083\1080\1094\1100\1082\1077 \1056\1110\1079\1076\1074\1086",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [("", 0.0)], n = 1},
koData =
ClassData{prior = -infinity, unseen = -0.6931471805599453,
likelihoods = HashMap.fromList [], n = 0}}),
("this <time>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -2.70805020110221,
likelihoods =
HashMap.fromList
[("\1074\1077\1089\1085\1072", -1.9459101490553135),
("\1079\1080\1084\1072", -1.9459101490553135),
("day", -1.252762968495368), ("hour", -1.9459101490553135),
("week-end", -1.9459101490553135),
("\1083\1110\1090\1086", -1.9459101490553135)],
n = 4},
koData =
ClassData{prior = -infinity, unseen = -1.9459101490553135,
likelihoods = HashMap.fromList [], n = 0}}),
("within <duration>",
Classifier{okData =
ClassData{prior = 0.0, unseen = -1.6094379124341003,
likelihoods =
HashMap.fromList
[("week", -0.6931471805599453),
("<integer> <unit-of-duration>", -0.6931471805599453)],
n = 1},
koData =
ClassData{prior = -infinity, unseen = -1.0986122886681098,
likelihoods = HashMap.fromList [], n = 0}})] |
e6f603ab3a84f44cb47f92f3e8c5d1dc14d5a476e0541df10c99633d1a1b41cb | epiccastle/spire | test_utils.clj | (ns spire.test-utils
(:require
[clojure.test :refer :all]
[clojure.java.shell :as shell]
[clojure.java.io :as io]
[clojure.string :as string]
[spire.ssh :as ssh]
[spire.state]
)
(:import [java.nio.file Files]))
(defn test-pipelines [func]
(func "localhost" nil))
(defn test-ssh-exec [session command in out opts]
;;(println command)
(shell/sh "bash" "-c" command :in in))
(defn test-scp-to [session local-paths remote-path & opts]
;; just handles a single file for now
(io/copy (io/file local-paths) (io/file remote-path)))
(defmacro ^{:private true} assert-args
[& pairs]
`(do (when-not ~(first pairs)
(throw (IllegalArgumentException.
(str (first ~'&form) " requires " ~(second pairs) " in " ~'*ns* ":" (:line (meta ~'&form))))))
~(let [more (nnext pairs)]
(when more
(list* `assert-args more)))))
(defmacro with-temp-files [bindings & body]
(assert-args
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(let [[sym fname & remain] bindings]
(if-not remain
`(let [~sym (create-temp-file ~fname)]
(try ~@body
(finally (remove-file ~sym))))
`(let [~sym (create-temp-file ~fname)]
(try
(with-temp-files ~(subvec bindings 2) ~@body)
(finally (remove-file ~sym)))))))
#_ (macroexpand-1 '(with-temp-files [f "mytemp"] 1 2 3))
#_ (macroexpand-1 '(with-temp-files [f "mytemp" g "mytemp2"] 1 2 3))
(def tmp-dir "/tmp")
(defn rand-string [n]
(apply str (map (fn [_] (rand-nth "abcdefghijklmnopqrztuvwxyz0123456789")) (range n))))
(defn create-temp-file [src]
(let [tmp (io/file tmp-dir (str "spire-test-" (rand-string 8)))]
(io/copy (io/file src) tmp)
(.getPath tmp)))
(defn create-temp-file-name []
(let [tmp (io/file tmp-dir (str "spire-test-" (rand-string 8)))]
(.getPath tmp)))
#_ (create-temp-file "project.clj")
(defn delete-recursive [f]
(let [f (io/file f)]
(when (.isDirectory f)
(doseq [path (.listFiles f)]
(delete-recursive path)))
(.delete f)))
(defn remove-file [tmp]
(assert (string/starts-with? tmp tmp-dir))
(delete-recursive tmp))
#_ (remove-file (create-temp-file "project.clj"))
#_ (with-temp-files [f "project.clj"] (+ 10 20))
#_ (with-temp-files [f "project.clj"] (+ 10 20) (throw (ex-info "foo" {})))
(defmacro with-temp-file-names [syms & body]
(let [[sym & remain] syms]
(if-not remain
`(let [~sym (create-temp-file-name)]
(try ~@body
(finally (remove-file ~sym))
))
`(let [~sym (create-temp-file-name)]
(try
(with-temp-file-names ~(subvec syms 1) ~@body)
(finally (remove-file ~sym))
)))))
(defn is-root? []
(= "root" (System/getProperty "user.name")))
(defn last-line [f]
(last (line-seq (io/reader f))))
(defn last-user []
(let [[username password uid gid userinfo homedir]
(-> "/etc/passwd"
last-line
(string/split #":")
)]
{:username username
:password password
:uid uid
:gid gid
:userinfo userinfo
:homedir homedir}))
#_ (last-user)
(defn last-group []
(let [[groupname _ gid]
(-> "/etc/group"
last-line
(string/split #":"))]
{:groupname groupname
:gid gid}))
#_ (last-group)
(defn run [command]
(let [{:keys [exit err out]} (shell/sh "bash" "-c" command)]
(assert (zero? exit) (format "%s failed: %d\nerr: %s\nout: %s\n" command exit err out))
out))
(defn uname []
(string/trim (run "uname")))
;;
You can get the value directly using a stat output format , e.g. BSD / OS X :
;; stat -f "%OLp" <file>
or in Linux
stat --format ' % a ' < file >
and in
;; stat -c '%a' <file>
;;
(defn mode [f]
(->
(if (= "Linux" (uname))
"stat -c '%%a' \"%s\""
"stat -f '%%OLp' \"%s\"")
(format f)
run
string/trim
))
#_ (mode "project.clj")
(defn ssh-run [cmd]
(let [{:keys [out err exit]}
(ssh/ssh-exec @spire.state/connection cmd "" "UTF-8" {})]
(assert (zero? exit) (str "remote command '" cmd "' failed. err:" err))
out))
(defn makedirs [path]
(.mkdirs (io/file path)))
(defn ln-s [dest src]
(run (format "ln -s '%s' '%s'" dest src)))
(def stat-linux->bsd
{
"%s" "%z" ;; file size
"%F" "%OMp" ;; File type
"%n" "%N" ;; file name
"%a" "%OLp" ;; access rights
"%X" "%a" ;; last access seconds since epoch
last modified seconds since epoch
})
(defn make-stat-command [linux-args]
(if (= "Linux" (uname))
(format "stat -c '%s'" (string/join " " linux-args))
(format "stat -f '%s'" (string/join " " (map #(stat-linux->bsd % %) linux-args)))))
(defn make-md5-command []
(if (= "Linux" (uname))
"md5sum"
"md5")
)
;; often after an operation we want to check that files contain certain
;; contents, have certain flags and attributes, or match the contents
;; and attributes of other files. Following are some helper functions and
;; macros to assist test writing
(defn recurse-stat-match? [local-path remote-path stat-params]
(= (run
(format "cd \"%s\" && find . -exec %s {} \\;"
local-path (make-stat-command stat-params)))
(ssh-run
(format "cd \"%s\" && find . -exec %s {} \\;"
remote-path (make-stat-command stat-params)))))
(defn recurse-file-size-type-name-match?
[local-path remote-path]
(recurse-stat-match? local-path remote-path ["%s" "%F" "%n"])
)
(defn recurse-file-size-type-name-mode-match?
[local-path remote-path]
(recurse-stat-match? local-path remote-path ["%s" "%F" "%n" "%a"])
)
(defn recurse-access-modified-match?
[local-path remote-path]
(recurse-stat-match? local-path remote-path ["%X" "%Y"])
)
(defn find-files-md5-match? [local remote]
(= (run
(format "cd \"%s\" && find . -type f -exec %s {} \\;"
local
(make-md5-command)))
(ssh-run
(format "cd \"%s\" && find . -type f -exec %s {} \\;"
remote
(make-md5-command)))))
(defn files-md5-match? [local remote]
(if (= "Linux" (uname))
(let [[local-md5 local-path]
(string/split
(run
(format "md5sum \"%s\""
local))
#" ")
[remote-md5 remote-path]
(string/split
(ssh-run
(format "md5sum \"%s\""
remote))
#" ")]
( prn local - md5 remote - md5 )
(= local-md5 remote-md5))
(let [[_ local-md5]
(string/split
(run
(format "md5 \"%s\""
local))
#"\s*=\s*")
[_ remote-md5]
(string/split
(ssh-run
(format "md5 \"%s\""
remote))
#"\s*=\s*")]
( prn local - md5 remote - md5 )
(= local-md5 remote-md5))
))
(defn find-local-files-mode-is? [local mode-str]
(let [modes (run
(format "cd \"%s\" && find . -type f -exec %s {} \\;"
local
(make-stat-command ["%a"])))
mode-lines (string/split-lines modes)
]
(every? #(= mode-str %) mode-lines)))
(defn find-local-dirs-mode-is? [local mode-str]
(let [modes (run
(format "cd \"%s\" && find . -type d -exec %s {} \\;"
local
(make-stat-command ["%a"])))
mode-lines (string/split-lines modes)
]
(every? #(= mode-str %) mode-lines)))
(defn find-remote-files-mode-is? [local mode-str]
(let [modes (ssh-run
(format "cd \"%s\" && find . -type f -exec %s {} \\;"
local
(make-stat-command ["%a"])))
mode-lines (string/split-lines modes)
]
(every? #(= mode-str %) mode-lines)))
(defn find-remote-dirs-mode-is? [local mode-str]
(let [modes (ssh-run
(format "cd \"%s\" && find . -type d -exec %s {} \\;"
local
(make-stat-command ["%a"])))
mode-lines (string/split-lines modes)
]
(every? #(= mode-str %) mode-lines)))
(defn stat-local [local stat-params]
(string/trim
(run
(format "%s \"%s\""
(make-stat-command stat-params)
local)))
)
(defmacro should-ex-data [data & body]
`(try ~@body
(catch clojure.lang.ExceptionInfo e#
(is (= ~data (ex-data e#))))))
(defn slurp-bytes
"Slurp the bytes from a slurpable thing"
[x]
(with-open [out (java.io.ByteArrayOutputStream.)]
(clojure.java.io/copy (clojure.java.io/input-stream x) out)
(.toByteArray out)))
(defn spit-bytes
"binary spit"
[file bytes]
(with-open [out (io/output-stream (io/file file))]
(.write out bytes)))
(defn sym-link? [f]
(Files/isSymbolicLink (.toPath f)))
| null | https://raw.githubusercontent.com/epiccastle/spire/3c61a22daa685b7e8bda09d135ada00606de1aec/test/clojure/spire/test_utils.clj | clojure | (println command)
just handles a single file for now
stat -f "%OLp" <file>
stat -c '%a' <file>
file size
File type
file name
access rights
last access seconds since epoch
often after an operation we want to check that files contain certain
contents, have certain flags and attributes, or match the contents
and attributes of other files. Following are some helper functions and
macros to assist test writing | (ns spire.test-utils
(:require
[clojure.test :refer :all]
[clojure.java.shell :as shell]
[clojure.java.io :as io]
[clojure.string :as string]
[spire.ssh :as ssh]
[spire.state]
)
(:import [java.nio.file Files]))
(defn test-pipelines [func]
(func "localhost" nil))
(defn test-ssh-exec [session command in out opts]
(shell/sh "bash" "-c" command :in in))
(defn test-scp-to [session local-paths remote-path & opts]
(io/copy (io/file local-paths) (io/file remote-path)))
(defmacro ^{:private true} assert-args
[& pairs]
`(do (when-not ~(first pairs)
(throw (IllegalArgumentException.
(str (first ~'&form) " requires " ~(second pairs) " in " ~'*ns* ":" (:line (meta ~'&form))))))
~(let [more (nnext pairs)]
(when more
(list* `assert-args more)))))
(defmacro with-temp-files [bindings & body]
(assert-args
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(let [[sym fname & remain] bindings]
(if-not remain
`(let [~sym (create-temp-file ~fname)]
(try ~@body
(finally (remove-file ~sym))))
`(let [~sym (create-temp-file ~fname)]
(try
(with-temp-files ~(subvec bindings 2) ~@body)
(finally (remove-file ~sym)))))))
#_ (macroexpand-1 '(with-temp-files [f "mytemp"] 1 2 3))
#_ (macroexpand-1 '(with-temp-files [f "mytemp" g "mytemp2"] 1 2 3))
(def tmp-dir "/tmp")
(defn rand-string [n]
(apply str (map (fn [_] (rand-nth "abcdefghijklmnopqrztuvwxyz0123456789")) (range n))))
(defn create-temp-file [src]
(let [tmp (io/file tmp-dir (str "spire-test-" (rand-string 8)))]
(io/copy (io/file src) tmp)
(.getPath tmp)))
(defn create-temp-file-name []
(let [tmp (io/file tmp-dir (str "spire-test-" (rand-string 8)))]
(.getPath tmp)))
#_ (create-temp-file "project.clj")
(defn delete-recursive [f]
(let [f (io/file f)]
(when (.isDirectory f)
(doseq [path (.listFiles f)]
(delete-recursive path)))
(.delete f)))
(defn remove-file [tmp]
(assert (string/starts-with? tmp tmp-dir))
(delete-recursive tmp))
#_ (remove-file (create-temp-file "project.clj"))
#_ (with-temp-files [f "project.clj"] (+ 10 20))
#_ (with-temp-files [f "project.clj"] (+ 10 20) (throw (ex-info "foo" {})))
(defmacro with-temp-file-names [syms & body]
(let [[sym & remain] syms]
(if-not remain
`(let [~sym (create-temp-file-name)]
(try ~@body
(finally (remove-file ~sym))
))
`(let [~sym (create-temp-file-name)]
(try
(with-temp-file-names ~(subvec syms 1) ~@body)
(finally (remove-file ~sym))
)))))
(defn is-root? []
(= "root" (System/getProperty "user.name")))
(defn last-line [f]
(last (line-seq (io/reader f))))
(defn last-user []
(let [[username password uid gid userinfo homedir]
(-> "/etc/passwd"
last-line
(string/split #":")
)]
{:username username
:password password
:uid uid
:gid gid
:userinfo userinfo
:homedir homedir}))
#_ (last-user)
(defn last-group []
(let [[groupname _ gid]
(-> "/etc/group"
last-line
(string/split #":"))]
{:groupname groupname
:gid gid}))
#_ (last-group)
(defn run [command]
(let [{:keys [exit err out]} (shell/sh "bash" "-c" command)]
(assert (zero? exit) (format "%s failed: %d\nerr: %s\nout: %s\n" command exit err out))
out))
(defn uname []
(string/trim (run "uname")))
You can get the value directly using a stat output format , e.g. BSD / OS X :
or in Linux
stat --format ' % a ' < file >
and in
(defn mode [f]
(->
(if (= "Linux" (uname))
"stat -c '%%a' \"%s\""
"stat -f '%%OLp' \"%s\"")
(format f)
run
string/trim
))
#_ (mode "project.clj")
(defn ssh-run [cmd]
(let [{:keys [out err exit]}
(ssh/ssh-exec @spire.state/connection cmd "" "UTF-8" {})]
(assert (zero? exit) (str "remote command '" cmd "' failed. err:" err))
out))
(defn makedirs [path]
(.mkdirs (io/file path)))
(defn ln-s [dest src]
(run (format "ln -s '%s' '%s'" dest src)))
(def stat-linux->bsd
{
last modified seconds since epoch
})
(defn make-stat-command [linux-args]
(if (= "Linux" (uname))
(format "stat -c '%s'" (string/join " " linux-args))
(format "stat -f '%s'" (string/join " " (map #(stat-linux->bsd % %) linux-args)))))
(defn make-md5-command []
(if (= "Linux" (uname))
"md5sum"
"md5")
)
(defn recurse-stat-match? [local-path remote-path stat-params]
(= (run
(format "cd \"%s\" && find . -exec %s {} \\;"
local-path (make-stat-command stat-params)))
(ssh-run
(format "cd \"%s\" && find . -exec %s {} \\;"
remote-path (make-stat-command stat-params)))))
(defn recurse-file-size-type-name-match?
[local-path remote-path]
(recurse-stat-match? local-path remote-path ["%s" "%F" "%n"])
)
(defn recurse-file-size-type-name-mode-match?
[local-path remote-path]
(recurse-stat-match? local-path remote-path ["%s" "%F" "%n" "%a"])
)
(defn recurse-access-modified-match?
[local-path remote-path]
(recurse-stat-match? local-path remote-path ["%X" "%Y"])
)
(defn find-files-md5-match? [local remote]
(= (run
(format "cd \"%s\" && find . -type f -exec %s {} \\;"
local
(make-md5-command)))
(ssh-run
(format "cd \"%s\" && find . -type f -exec %s {} \\;"
remote
(make-md5-command)))))
(defn files-md5-match? [local remote]
(if (= "Linux" (uname))
(let [[local-md5 local-path]
(string/split
(run
(format "md5sum \"%s\""
local))
#" ")
[remote-md5 remote-path]
(string/split
(ssh-run
(format "md5sum \"%s\""
remote))
#" ")]
( prn local - md5 remote - md5 )
(= local-md5 remote-md5))
(let [[_ local-md5]
(string/split
(run
(format "md5 \"%s\""
local))
#"\s*=\s*")
[_ remote-md5]
(string/split
(ssh-run
(format "md5 \"%s\""
remote))
#"\s*=\s*")]
( prn local - md5 remote - md5 )
(= local-md5 remote-md5))
))
(defn find-local-files-mode-is? [local mode-str]
(let [modes (run
(format "cd \"%s\" && find . -type f -exec %s {} \\;"
local
(make-stat-command ["%a"])))
mode-lines (string/split-lines modes)
]
(every? #(= mode-str %) mode-lines)))
(defn find-local-dirs-mode-is? [local mode-str]
(let [modes (run
(format "cd \"%s\" && find . -type d -exec %s {} \\;"
local
(make-stat-command ["%a"])))
mode-lines (string/split-lines modes)
]
(every? #(= mode-str %) mode-lines)))
(defn find-remote-files-mode-is? [local mode-str]
(let [modes (ssh-run
(format "cd \"%s\" && find . -type f -exec %s {} \\;"
local
(make-stat-command ["%a"])))
mode-lines (string/split-lines modes)
]
(every? #(= mode-str %) mode-lines)))
(defn find-remote-dirs-mode-is? [local mode-str]
(let [modes (ssh-run
(format "cd \"%s\" && find . -type d -exec %s {} \\;"
local
(make-stat-command ["%a"])))
mode-lines (string/split-lines modes)
]
(every? #(= mode-str %) mode-lines)))
(defn stat-local [local stat-params]
(string/trim
(run
(format "%s \"%s\""
(make-stat-command stat-params)
local)))
)
(defmacro should-ex-data [data & body]
`(try ~@body
(catch clojure.lang.ExceptionInfo e#
(is (= ~data (ex-data e#))))))
(defn slurp-bytes
"Slurp the bytes from a slurpable thing"
[x]
(with-open [out (java.io.ByteArrayOutputStream.)]
(clojure.java.io/copy (clojure.java.io/input-stream x) out)
(.toByteArray out)))
(defn spit-bytes
"binary spit"
[file bytes]
(with-open [out (io/output-stream (io/file file))]
(.write out bytes)))
(defn sym-link? [f]
(Files/isSymbolicLink (.toPath f)))
|
21cbaaee3d77c022c8b6973874abbf432b36f2016ee9c416707445f9929291d6 | csabahruska/jhc-grin | Val.hs | # LANGUAGE FlexibleInstances #
module Grin.Val(
FromVal(..),
ToVal(..),
tn_2Tup,
valToList,
cChar,
cWord,
cInt,
convertName,
region_heap,
region_atomic_heap,
region_stack,
region_block
) where
import Data.Char
import Cmm.Number
import Grin.Grin
import Name.Name
import Name.Names
import Name.VConsts
import StringTable.Atom
nil = convertName dc_EmptyList
cons = convertName dc_Cons
cChar = convertName dc_Char
cWord = convertName dc_Word
cInt = convertName dc_Int
tn_2Tup = convertName $ nameTuple DataConstructor 2
tn_Boolzh = convertName dc_Boolzh
tn_unit = convertName dc_Unit
-- This allocates data on the heap.
region_heap = Item (toAtom "heap") TyRegion
-- This allocates data on the atomic heap.
region_atomic_heap = Item (toAtom "atomicHeap") TyRegion
-- This allocates data in the innermost enclosing region, including implicit regions.
region_block = Item (toAtom "block") TyRegion
-- This allocates data on the stack, generally equivalent to 'block' for most back ends.
region_stack = Item (toAtom "stack") TyRegion
instance ConNames Val where
vTrue = NodeC tn_Boolzh [toUnVal (1 :: Int)]
vFalse = NodeC tn_Boolzh [toUnVal (0 :: Int)]
vUnit = NodeC tn_unit []
class ToVal a where
toVal :: a -> Val
toUnVal :: a -> Val
toUnVal x = toVal x
class FromVal a where
fromVal :: Monad m => Val -> m a
fromUnVal :: Monad m => Val -> m a
fromUnVal x = fromVal x
instance ToVal Bool where
toVal True = vTrue
toVal False = vFalse
instance ToVal a => ToVal [a] where
toVal [] = NodeC nil []
toVal (x:xs) = NodeC cons [Const (toVal x),Const (toVal xs)]
instance ToVal (Val,Val) where
toVal (x,y) = NodeC tn_2Tup [x,y]
instance ToVal Char where
toVal c = NodeC cChar [toUnVal c]
toUnVal c = Lit (fromIntegral $ ord c) tIntzh
instance ToVal Int where
toVal c = NodeC cInt [toUnVal c]
toUnVal c = Lit (fromIntegral c) tIntzh
instance ToVal Val where
toVal x = x
instance FromVal Int where
fromVal (NodeC _ [Lit i _]) | Just x <- toIntegral i = return x
fromVal n = fail $ "Val is not Int: " ++ show n
fromUnVal (Lit i _) | Just x <- toIntegral i = return x
fromUnVal n = fail $ "Val is not UnInt: " ++ show n
instance FromVal Char where
fromVal (NodeC _ [Lit i _]) | Just x <- toIntegral i, x >= ord minBound && x <= ord maxBound = return (chr x)
fromVal n = fail $ "Val is not Char: " ++ show n
fromUnVal (Lit i _) | Just x <- toIntegral i, x >= ord minBound && x <= ord maxBound = return (chr x)
fromUnVal n = fail $ "Val is not UnChar: " ++ show n
instance FromVal a => FromVal [a] where
fromVal (NodeC n []) | n == nil = return []
fromVal (NodeC n [Const a,Const b]) | n == cons = do
x <- fromVal a
xs <- fromVal b
return (x:xs)
fromVal n = fail $ "Val is not [a]: " ++ show n
instance FromVal Bool where
fromVal n
| n == toVal True = return True
| n == toVal False = return False
fromVal n = fail $ "Val is not Bool: " ++ show n
instance FromVal Val where
fromVal n = return n
valToList (NodeC n []) | n == nil = return []
valToList (NodeC n [a,Const b]) | n == cons = do
xs <- valToList b
return (a:xs)
valToList n = fail $ "Val is not [a]: " ++ show n
convertName n = toAtom (t':s) where
(t,s) = fromName n
t' | t == TypeConstructor = 'T'
| t == DataConstructor = 'C'
| t == Val = 'f'
| otherwise = error $ "convertName: " ++ show (t,s)
| null | https://raw.githubusercontent.com/csabahruska/jhc-grin/30210f659167e357c1ccc52284cf719cfa90d306/src/Grin/Val.hs | haskell | This allocates data on the heap.
This allocates data on the atomic heap.
This allocates data in the innermost enclosing region, including implicit regions.
This allocates data on the stack, generally equivalent to 'block' for most back ends. | # LANGUAGE FlexibleInstances #
module Grin.Val(
FromVal(..),
ToVal(..),
tn_2Tup,
valToList,
cChar,
cWord,
cInt,
convertName,
region_heap,
region_atomic_heap,
region_stack,
region_block
) where
import Data.Char
import Cmm.Number
import Grin.Grin
import Name.Name
import Name.Names
import Name.VConsts
import StringTable.Atom
nil = convertName dc_EmptyList
cons = convertName dc_Cons
cChar = convertName dc_Char
cWord = convertName dc_Word
cInt = convertName dc_Int
tn_2Tup = convertName $ nameTuple DataConstructor 2
tn_Boolzh = convertName dc_Boolzh
tn_unit = convertName dc_Unit
region_heap = Item (toAtom "heap") TyRegion
region_atomic_heap = Item (toAtom "atomicHeap") TyRegion
region_block = Item (toAtom "block") TyRegion
region_stack = Item (toAtom "stack") TyRegion
instance ConNames Val where
vTrue = NodeC tn_Boolzh [toUnVal (1 :: Int)]
vFalse = NodeC tn_Boolzh [toUnVal (0 :: Int)]
vUnit = NodeC tn_unit []
class ToVal a where
toVal :: a -> Val
toUnVal :: a -> Val
toUnVal x = toVal x
class FromVal a where
fromVal :: Monad m => Val -> m a
fromUnVal :: Monad m => Val -> m a
fromUnVal x = fromVal x
instance ToVal Bool where
toVal True = vTrue
toVal False = vFalse
instance ToVal a => ToVal [a] where
toVal [] = NodeC nil []
toVal (x:xs) = NodeC cons [Const (toVal x),Const (toVal xs)]
instance ToVal (Val,Val) where
toVal (x,y) = NodeC tn_2Tup [x,y]
instance ToVal Char where
toVal c = NodeC cChar [toUnVal c]
toUnVal c = Lit (fromIntegral $ ord c) tIntzh
instance ToVal Int where
toVal c = NodeC cInt [toUnVal c]
toUnVal c = Lit (fromIntegral c) tIntzh
instance ToVal Val where
toVal x = x
instance FromVal Int where
fromVal (NodeC _ [Lit i _]) | Just x <- toIntegral i = return x
fromVal n = fail $ "Val is not Int: " ++ show n
fromUnVal (Lit i _) | Just x <- toIntegral i = return x
fromUnVal n = fail $ "Val is not UnInt: " ++ show n
instance FromVal Char where
fromVal (NodeC _ [Lit i _]) | Just x <- toIntegral i, x >= ord minBound && x <= ord maxBound = return (chr x)
fromVal n = fail $ "Val is not Char: " ++ show n
fromUnVal (Lit i _) | Just x <- toIntegral i, x >= ord minBound && x <= ord maxBound = return (chr x)
fromUnVal n = fail $ "Val is not UnChar: " ++ show n
instance FromVal a => FromVal [a] where
fromVal (NodeC n []) | n == nil = return []
fromVal (NodeC n [Const a,Const b]) | n == cons = do
x <- fromVal a
xs <- fromVal b
return (x:xs)
fromVal n = fail $ "Val is not [a]: " ++ show n
instance FromVal Bool where
fromVal n
| n == toVal True = return True
| n == toVal False = return False
fromVal n = fail $ "Val is not Bool: " ++ show n
instance FromVal Val where
fromVal n = return n
valToList (NodeC n []) | n == nil = return []
valToList (NodeC n [a,Const b]) | n == cons = do
xs <- valToList b
return (a:xs)
valToList n = fail $ "Val is not [a]: " ++ show n
convertName n = toAtom (t':s) where
(t,s) = fromName n
t' | t == TypeConstructor = 'T'
| t == DataConstructor = 'C'
| t == Val = 'f'
| otherwise = error $ "convertName: " ++ show (t,s)
|
bbf55051ef72bf84b4388f6f4f75cba9847fca65ae295701870c4fe3a4d912e9 | ultralisp/ultralisp | check.lisp | (uiop:define-package #:ultralisp/models/check
(:use #:cl)
(:import-from #:rove
#:deftest)
(:import-from #:mito)
(:import-from #:ultralisp-test/utils
#:with-test-db)
(:import-from #:ultralisp/models/dist-source
#:add-source-to-dist)
(:import-from #:ultralisp-test/utils
#:make-project
#:get-source)
(:import-from #:rove
#:ok)
(:export
#:lisp-implementation))
(in-package #:ultralisp/models/check)
(deftest test-check-lisp-implementation
(with-test-db
(let* ((project (make-project "40ants" "defmain"))
(lispworks-dist (mito:create-dao 'ultralisp/models/dist:dist
:name "LispWorks"
:lisp-implementation :lispworks)))
;; And to switch dist into a READY state
;; (build-dists)
(let* ((source (get-source project)))
(add-source-to-dist lispworks-dist source)
;; At this point source will be bound to default "ultralisp" dist
;; and to the "lispworks" dist.
(let ((check (make-check source :via-cron)))
;; check's implementation should match the dist ones
(ok (eql (ultralisp/models/check::lisp-implementation check)
:lispworks)))))))
| null | https://raw.githubusercontent.com/ultralisp/ultralisp/37bd5d92b2cf751cd03ced69bac785bf4bcb6c15/t/models/check.lisp | lisp | And to switch dist into a READY state
(build-dists)
At this point source will be bound to default "ultralisp" dist
and to the "lispworks" dist.
check's implementation should match the dist ones | (uiop:define-package #:ultralisp/models/check
(:use #:cl)
(:import-from #:rove
#:deftest)
(:import-from #:mito)
(:import-from #:ultralisp-test/utils
#:with-test-db)
(:import-from #:ultralisp/models/dist-source
#:add-source-to-dist)
(:import-from #:ultralisp-test/utils
#:make-project
#:get-source)
(:import-from #:rove
#:ok)
(:export
#:lisp-implementation))
(in-package #:ultralisp/models/check)
(deftest test-check-lisp-implementation
(with-test-db
(let* ((project (make-project "40ants" "defmain"))
(lispworks-dist (mito:create-dao 'ultralisp/models/dist:dist
:name "LispWorks"
:lisp-implementation :lispworks)))
(let* ((source (get-source project)))
(add-source-to-dist lispworks-dist source)
(let ((check (make-check source :via-cron)))
(ok (eql (ultralisp/models/check::lisp-implementation check)
:lispworks)))))))
|
77ebb7fdf1fd6e332778f2de25e415fd50cab1ffb1dfa8e8b2e04b49120c2170 | kaoskorobase/mescaline | Time.hs | # LANGUAGE GeneralizedNewtypeDeriving #
module Mescaline.Time (
Duration
, Seconds
, Beats
, HasDelta(..)
, HasDuration(..)
, ToRest(..)
) where
import Control.Lens
type Time = Double -- ^ Absolute or relative time stamp
type Duration = Double -- ^ Difference of times
newtype Seconds = Seconds Double deriving (Eq, Fractional, Num, Ord, Real, RealFrac, Show)
newtype Beats = Beats Double deriving (Eq, Fractional, Num, Ord, Real, RealFrac, Show)
class HasDelta a where
delta :: Lens' a Duration
class HasDuration a where
duration :: Lens' a Duration
class ToRest a where
rest :: Duration -> a
| null | https://raw.githubusercontent.com/kaoskorobase/mescaline/13554fc4826d0c977d0010c0b4fb74ba12ced6b9/lib/mescaline-patterns/src/Mescaline/Time.hs | haskell | ^ Absolute or relative time stamp
^ Difference of times | # LANGUAGE GeneralizedNewtypeDeriving #
module Mescaline.Time (
Duration
, Seconds
, Beats
, HasDelta(..)
, HasDuration(..)
, ToRest(..)
) where
import Control.Lens
newtype Seconds = Seconds Double deriving (Eq, Fractional, Num, Ord, Real, RealFrac, Show)
newtype Beats = Beats Double deriving (Eq, Fractional, Num, Ord, Real, RealFrac, Show)
class HasDelta a where
delta :: Lens' a Duration
class HasDuration a where
duration :: Lens' a Duration
class ToRest a where
rest :: Duration -> a
|
94780627d12156fc53d9338e73b5f857bde90d09cb1eb121ecc96d41be1a0c40 | alaricsp/chicken-scheme | private-namespace.scm | ;;;; compiler-namespace.scm - A simple namespace system to keep compiler variables hidden
;
Copyright ( c ) 2007 ,
Copyright ( c ) 2008 - 2009 , The Chicken Team
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
; conditions are met:
;
; Redistributions of source code must retain the above copyright notice, this list of conditions and the following
; disclaimer.
; Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
; disclaimer in the documentation and/or other materials provided with the distribution.
; Neither the name of the author nor the names of its contributors may be used to endorse or promote
; products derived from this software without specific prior written permission.
;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS
; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
; AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR
; OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
; POSSIBILITY OF SUCH DAMAGE.
(define-syntax private
(lambda (form r c)
(let ((namespace (cadr form))
(vars (cddr form)))
(##sys#check-symbol namespace 'private)
(let* ((str (symbol->string namespace)) ; somewhat questionable (renaming)
(prefix (string-append
(string (integer->char (string-length str)))
(symbol->string namespace))))
(for-each
(lambda (var)
(put!
var 'c:namespace
(##sys#string->qualified-symbol prefix (symbol->string var))))
vars)
'(##core#undefined) ) ) ) )
(set! ##sys#alias-global-hook
(lambda (var . assign) ; must work with old chicken
(or (get var 'c:namespace) var) ) )
| null | https://raw.githubusercontent.com/alaricsp/chicken-scheme/1eb14684c26b7c2250ca9b944c6b671cb62cafbc/private-namespace.scm | scheme | compiler-namespace.scm - A simple namespace system to keep compiler variables hidden
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the author nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
somewhat questionable (renaming)
must work with old chicken | Copyright ( c ) 2007 ,
Copyright ( c ) 2008 - 2009 , The Chicken Team
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS
CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR
(define-syntax private
(lambda (form r c)
(let ((namespace (cadr form))
(vars (cddr form)))
(##sys#check-symbol namespace 'private)
(prefix (string-append
(string (integer->char (string-length str)))
(symbol->string namespace))))
(for-each
(lambda (var)
(put!
var 'c:namespace
(##sys#string->qualified-symbol prefix (symbol->string var))))
vars)
'(##core#undefined) ) ) ) )
(set! ##sys#alias-global-hook
(or (get var 'c:namespace) var) ) )
|
daa2ca158b9da23ca48324ea0128378b8c5b69015e62601e755f6a1728955527 | tnelson/Forge | lexer.rkt | #lang racket/base
(require brag/support)
(require (rename-in br-parser-tools/lex-sre [- :-] [+ :+]))
(define forge-lexer
(lexer
;; Embedded s-expressions for escaping to forge/core
[(from/to "<$>" "</$>")
(token+ 'SEXPR-TOK "<$>" lexeme "</$>" lexeme-start lexeme-end)]
[(from/to "--$" "\n")
(token+ 'SEXPR-TOK "--$" lexeme "\n" lexeme-start lexeme-end)]
[(from/to "//$" "\n")
(token+ 'SEXPR-TOK "//$" lexeme "\n" lexeme-start lexeme-end)]
[(from/to "/*$" "*/")
(token+ 'SEXPR-TOK "/*$" lexeme "*/" lexeme-start lexeme-end)]
;; file paths
[(from/to "\"" "\"")
(token+ 'FILE-PATH-TOK "\"" lexeme "\"" lexeme-start lexeme-end)]
;; old instances (old, to remove)
;[(from/to "<instance" "</instance>")
( token+ ' INSTANCE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
;[(from/to "<alloy" "</alloy>")
( token+ ' INSTANCE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
;[(from/to "<sig" "</sig>")
( token+ ' INSTANCE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
[ ( from / to " < field " " < > " )
( token+ ' INSTANCE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
;; comments
[(or (from/stop-before "--" "\n") (from/stop-before "//" "\n") (from/to "/*" "*/"))
(token+ 'COMMENT "" lexeme "" lexeme-start lexeme-end #t)]
[(from/stop-before "#lang" "\n")
(token+ 'COMMENT "" lexeme "" lexeme-start lexeme-end #t)]
reserved for later use ( also by )
[(or "$" "%" "?")
(token+ 'RESERVED-TOK "" lexeme "" lexeme-start lexeme-end)]
reserved by 6 or future plans
[(or "after" "before" "fact" "transition" "state"
"module" )
(token+ 'RESERVED-TOK "" lexeme "" lexeme-start lexeme-end)]
;; numeric
[(or "0" (: (char-range "1" "9") (* (char-range "0" "9"))))
(token+ 'NUM-CONST-TOK "" lexeme "" lexeme-start lexeme-end #f #t)]
["->" (token+ 'ARROW-TOK "" lexeme "" lexeme-start lexeme-end)]
["." (token+ 'DOT-TOK "" lexeme "" lexeme-start lexeme-end)]
["=" (token+ 'EQ-TOK "" lexeme "" lexeme-start lexeme-end)]
[ " = = " ( token+ ' DOUBLE - EQ - TOK " " lexeme " " lexeme - start lexeme - end ) ]
["|" (token+ 'BAR-TOK "" lexeme "" lexeme-start lexeme-end)]
["-" (token+ 'MINUS-TOK "" lexeme "" lexeme-start lexeme-end)]
["~" (token+ 'TILDE-TOK "" lexeme "" lexeme-start lexeme-end)]
["*" (token+ 'STAR-TOK "" lexeme "" lexeme-start lexeme-end)]
["^" (token+ 'EXP-TOK "" lexeme "" lexeme-start lexeme-end)]
[">=" (token+ 'GEQ-TOK "" lexeme "" lexeme-start lexeme-end)]
["<:" (token+ 'SUBT-TOK "" lexeme "" lexeme-start lexeme-end)]
[":>" (token+ 'SUPT-TOK "" lexeme "" lexeme-start lexeme-end)]
["++" (token+ 'PPLUS-TOK "" lexeme "" lexeme-start lexeme-end)]
["<" (token+ 'LT-TOK "" lexeme "" lexeme-start lexeme-end)]
[">" (token+ 'GT-TOK "" lexeme "" lexeme-start lexeme-end)]
["&" (token+ 'AMP-TOK "" lexeme "" lexeme-start lexeme-end)]
["+" (token+ 'PLUS-TOK "" lexeme "" lexeme-start lexeme-end)]
[(or "<=" "=<") (token+ 'LEQ-TOK "" lexeme "" lexeme-start lexeme-end)]
[(or "!" "not") (token+ 'NEG-TOK "" lexeme "" lexeme-start lexeme-end)]
[(or "||" "or") (token+ 'OR-TOK "" lexeme "" lexeme-start lexeme-end)]
[(or "&&" "and") (token+ 'AND-TOK "" lexeme "" lexeme-start lexeme-end)]
[(or "<=>" "iff") (token+ 'IFF-TOK "" lexeme "" lexeme-start lexeme-end)]
[(or "=>" "implies") (token+ 'IMP-TOK "" lexeme "" lexeme-start lexeme-end)]
;; keywords
["abstract" (token+ `ABSTRACT-TOK "" lexeme "" lexeme-start lexeme-end)]
["all" (token+ `ALL-TOK "" lexeme "" lexeme-start lexeme-end)]
["as" (token+ `AS-TOK "" lexeme "" lexeme-start lexeme-end)]
["assert" (token+ `ASSERT-TOK "" lexeme "" lexeme-start lexeme-end)]
["but" (token+ `BUT-TOK "" lexeme "" lexeme-start lexeme-end)]
["check" (token+ `CHECK-TOK "" lexeme "" lexeme-start lexeme-end)]
["disj" (token+ `DISJ-TOK "" lexeme "" lexeme-start lexeme-end)]
["else" (token+ `ELSE-TOK "" lexeme "" lexeme-start lexeme-end)]
["exactly" (token+ `EXACTLY-TOK "" lexeme "" lexeme-start lexeme-end)]
["example" (token+ `EXAMPLE-TOK "" lexeme "" lexeme-start lexeme-end)]
["expect" (token+ `EXPECT-TOK "" lexeme "" lexeme-start lexeme-end)]
["extends" (token+ `EXTENDS-TOK "" lexeme "" lexeme-start lexeme-end)]
["for" (token+ `FOR-TOK "" lexeme "" lexeme-start lexeme-end)]
["fun" (token+ `FUN-TOK "" lexeme "" lexeme-start lexeme-end)]
["iden" (token+ `IDEN-TOK "" lexeme "" lexeme-start lexeme-end)]
["in" (token+ `IN-TOK "" lexeme "" lexeme-start lexeme-end)]
["ni" (token+ `NI-TOK "" lexeme "" lexeme-start lexeme-end)]
["is" (token+ `IS-TOK "" lexeme "" lexeme-start lexeme-end)]
["let" (token+ `LET-TOK "" lexeme "" lexeme-start lexeme-end)]
["lone" (token+ `LONE-TOK "" lexeme "" lexeme-start lexeme-end)]
[ " module " ( token+ ` MODULE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
["no" (token+ `NO-TOK "" lexeme "" lexeme-start lexeme-end)]
["none" (token+ `NONE-TOK "" lexeme "" lexeme-start lexeme-end)]
["one" (token+ `ONE-TOK "" lexeme "" lexeme-start lexeme-end)]
["func" (token+ `FUNC-TOK "" lexeme "" lexeme-start lexeme-end)]
["pfunc" (token+ `PFUNC-TOK "" lexeme "" lexeme-start lexeme-end)]
["open" (token+ `OPEN-TOK "" lexeme "" lexeme-start lexeme-end)]
["pred" (token+ `PRED-TOK "" lexeme "" lexeme-start lexeme-end)]
["run" (token+ `RUN-TOK "" lexeme "" lexeme-start lexeme-end)]
["sat" (token+ `SAT-TOK "" lexeme "" lexeme-start lexeme-end)]
["set" (token+ `SET-TOK "" lexeme "" lexeme-start lexeme-end)]
["sig" (token+ `SIG-TOK "" lexeme "" lexeme-start lexeme-end)]
["some" (token+ `SOME-TOK "" lexeme "" lexeme-start lexeme-end)]
["sum" (token+ `SUM-TOK "" lexeme "" lexeme-start lexeme-end #f #t)]
["test" (token+ `TEST-TOK "" lexeme "" lexeme-start lexeme-end)]
["theorem" (token+ `THEOREM-TOK "" lexeme "" lexeme-start lexeme-end)]
["two" (token+ `TWO-TOK "" lexeme "" lexeme-start lexeme-end)]
["univ" (token+ `UNIV-TOK "" lexeme "" lexeme-start lexeme-end)]
["unsat" (token+ `UNSAT-TOK "" lexeme "" lexeme-start lexeme-end)]
["wheat" (token+ `WHEAT-TOK "" lexeme "" lexeme-start lexeme-end)]
["break" (token+ `BREAK-TOK "" lexeme "" lexeme-start lexeme-end)]
["sufficient" (token+ `SUFFICIENT-TOK "" lexeme "" lexeme-start lexeme-end)]
["necessary" (token+ `NECESSARY-TOK "" lexeme "" lexeme-start lexeme-end)]
["suite" (token+ `SUITE-TOK "" lexeme "" lexeme-start lexeme-end)]
[ " state " ( token+ ` STATE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
[ " facts " ( token+ ` STATE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
[ " transition"(token+ ` TRANSITION - TOK " " lexeme " " lexeme - start lexeme - end ) ]
[ " trace " ( token+ ` TRACE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
["bind" (token+ `BIND-TOK "" lexeme "" lexeme-start lexeme-end)]
["option" (token+ `OPTION-TOK "" lexeme "" lexeme-start lexeme-end)]
["inst" (token+ `INST-TOK "" lexeme "" lexeme-start lexeme-end)]
; Electrum operators
["always" (token+ `ALWAYS-TOK "" lexeme "" lexeme-start lexeme-end)]
["eventually" (token+ `EVENTUALLY-TOK "" lexeme "" lexeme-start lexeme-end)]
["next_state" (token+ `AFTER-TOK "" lexeme "" lexeme-start lexeme-end)]
["until" (token+ `UNTIL-TOK "" lexeme "" lexeme-start lexeme-end)]
["releases" (token+ `RELEASE-TOK "" lexeme "" lexeme-start lexeme-end)]
["historically" (token+ `HISTORICALLY-TOK "" lexeme "" lexeme-start lexeme-end)]
["once" (token+ `ONCE-TOK "" lexeme "" lexeme-start lexeme-end)]
["prev_state" (token+ `BEFORE-TOK "" lexeme "" lexeme-start lexeme-end)]
["since" (token+ `SINCE-TOK "" lexeme "" lexeme-start lexeme-end)]
["triggered" (token+ `TRIGGERED-TOK "" lexeme "" lexeme-start lexeme-end)]
; Used by the evaluator
["eval" (token+ `EVAL-TOK "" lexeme "" lexeme-start lexeme-end)]
; Electrum var relation label
["var" (token+ `VAR-TOK "" lexeme "" lexeme-start lexeme-end)]
; Electrum prime
["'" (token+ `PRIME-TOK "" lexeme "" lexeme-start lexeme-end)]
this to prevent it from being used as a sig / relation name
["Time" (token+ `TIME-TOK "" lexeme "" lexeme-start lexeme-end)]
;; int stuff
["Int" (token+ `INT-TOK "" lexeme "" lexeme-start lexeme-end #f #t)]
["#" (token+ `CARD-TOK "" lexeme "" lexeme-start lexeme-end)]
Backquote to make atom names
["`" (token+ `BACKQUOTE-TOK "" lexeme "" lexeme-start lexeme-end)]
;; punctuation
["(" (token+ 'LEFT-PAREN-TOK "" lexeme "" lexeme-start lexeme-end)]
[")" (token+ 'RIGHT-PAREN-TOK "" lexeme "" lexeme-start lexeme-end)]
["{" (token+ 'LEFT-CURLY-TOK "" lexeme "" lexeme-start lexeme-end)]
["}" (token+ 'RIGHT-CURLY-TOK "" lexeme "" lexeme-start lexeme-end)]
["[" (token+ 'LEFT-SQUARE-TOK "" lexeme "" lexeme-start lexeme-end)]
["]" (token+ 'RIGHT-SQUARE-TOK "" lexeme "" lexeme-start lexeme-end)]
["," (token+ 'COMMA-TOK "" lexeme "" lexeme-start lexeme-end)]
[";" (token+ 'SEMICOLON-TOK "" lexeme "" lexeme-start lexeme-end)]
["/" (token+ 'SLASH-TOK "" lexeme "" lexeme-start lexeme-end)]
[":" (token+ 'COLON-TOK "" lexeme "" lexeme-start lexeme-end)]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; identifiers
; Don't allow priming
[(: (or alphabetic "@" "_") (* (or alphabetic numeric "_" "\""))) ;; "’" "”"
(token+ 'IDENTIFIER-TOK "" lexeme "" lexeme-start lexeme-end #f #t)]
[(* (char-set "➡️")) ;; "’" "”"
(token+ 'IDENTIFIER-TOK "" lexeme "" lexeme-start lexeme-end)]
;; otherwise
[whitespace (token+ lexeme "" lexeme "" lexeme-start lexeme-end #t)]
[any-char (token+ 'RESERVED-TOK "" lexeme "" lexeme-start lexeme-end)]))
(define (keyword? str)
(member str
(list
"abstract"
"all"
"and"
"as"
"assert"
"but"
"check"
"disj"
"else"
"eval"
"exactly"
"example"
"expect"
"extends"
"fact"
"for"
"fun"
"iden"
"iff"
"implies"
"in"
"ni"
"is"
"let"
"lone"
;"module"
"no"
"none"
"not"
"one"
"open"
"or"
"pred"
"run"
"set"
"sig"
"some"
"sum"
"test"
"two"
"expect"
"sat"
"unsat"
"theorem"
"univ"
"break"
"sufficient"
"necessary"
"of"
"suite"
;"state"
;"facts"
;"transition"
;"trace"
"bind"
"option"
"inst"
"always"
"eventually"
"after"
"until"
"releases"
"var"
"'"
"Time"
'Int
'sum
'sing
'add
'subtract
'multiply
'divide
'abs
'sign
'max
'min
"#"
"`"
'_
'this
)))
(define (paren? str)
(member str
(list "("
")"
"{"
"}"
"["
"]")))
(define (token+ type left lex right lex-start lex-end [skip? #f] [sym? #f])
(let ([l0 (string-length left)]
[l1 (string-length right)]
[trimmed (trim-ends left lex right)])
(token type (cond [(and sym? (string->number trimmed)) (string->number trimmed)]
[sym? (string->symbol trimmed)]
[else trimmed])
#:position (+ (pos lex-start) l0)
#:line (line lex-start)
#:column (+ (col lex-start) l0)
#:span (- (pos lex-end)
(pos lex-start) l0 l1)
#:skip? skip?)))
(provide forge-lexer keyword? paren?)
| null | https://raw.githubusercontent.com/tnelson/Forge/995b47b0138709ff3858f567b0008277505dd2fc/forge/lang/alloy-syntax/lexer.rkt | racket | Embedded s-expressions for escaping to forge/core
file paths
old instances (old, to remove)
[(from/to "<instance" "</instance>")
[(from/to "<alloy" "</alloy>")
[(from/to "<sig" "</sig>")
comments
numeric
keywords
Electrum operators
Used by the evaluator
Electrum var relation label
Electrum prime
int stuff
punctuation
identifiers
Don't allow priming
"’" "”"
otherwise
"module"
"state"
"facts"
"transition"
"trace" | #lang racket/base
(require brag/support)
(require (rename-in br-parser-tools/lex-sre [- :-] [+ :+]))
(define forge-lexer
(lexer
[(from/to "<$>" "</$>")
(token+ 'SEXPR-TOK "<$>" lexeme "</$>" lexeme-start lexeme-end)]
[(from/to "--$" "\n")
(token+ 'SEXPR-TOK "--$" lexeme "\n" lexeme-start lexeme-end)]
[(from/to "//$" "\n")
(token+ 'SEXPR-TOK "//$" lexeme "\n" lexeme-start lexeme-end)]
[(from/to "/*$" "*/")
(token+ 'SEXPR-TOK "/*$" lexeme "*/" lexeme-start lexeme-end)]
[(from/to "\"" "\"")
(token+ 'FILE-PATH-TOK "\"" lexeme "\"" lexeme-start lexeme-end)]
( token+ ' INSTANCE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
( token+ ' INSTANCE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
( token+ ' INSTANCE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
[ ( from / to " < field " " < > " )
( token+ ' INSTANCE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
[(or (from/stop-before "--" "\n") (from/stop-before "//" "\n") (from/to "/*" "*/"))
(token+ 'COMMENT "" lexeme "" lexeme-start lexeme-end #t)]
[(from/stop-before "#lang" "\n")
(token+ 'COMMENT "" lexeme "" lexeme-start lexeme-end #t)]
reserved for later use ( also by )
[(or "$" "%" "?")
(token+ 'RESERVED-TOK "" lexeme "" lexeme-start lexeme-end)]
reserved by 6 or future plans
[(or "after" "before" "fact" "transition" "state"
"module" )
(token+ 'RESERVED-TOK "" lexeme "" lexeme-start lexeme-end)]
[(or "0" (: (char-range "1" "9") (* (char-range "0" "9"))))
(token+ 'NUM-CONST-TOK "" lexeme "" lexeme-start lexeme-end #f #t)]
["->" (token+ 'ARROW-TOK "" lexeme "" lexeme-start lexeme-end)]
["." (token+ 'DOT-TOK "" lexeme "" lexeme-start lexeme-end)]
["=" (token+ 'EQ-TOK "" lexeme "" lexeme-start lexeme-end)]
[ " = = " ( token+ ' DOUBLE - EQ - TOK " " lexeme " " lexeme - start lexeme - end ) ]
["|" (token+ 'BAR-TOK "" lexeme "" lexeme-start lexeme-end)]
["-" (token+ 'MINUS-TOK "" lexeme "" lexeme-start lexeme-end)]
["~" (token+ 'TILDE-TOK "" lexeme "" lexeme-start lexeme-end)]
["*" (token+ 'STAR-TOK "" lexeme "" lexeme-start lexeme-end)]
["^" (token+ 'EXP-TOK "" lexeme "" lexeme-start lexeme-end)]
[">=" (token+ 'GEQ-TOK "" lexeme "" lexeme-start lexeme-end)]
["<:" (token+ 'SUBT-TOK "" lexeme "" lexeme-start lexeme-end)]
[":>" (token+ 'SUPT-TOK "" lexeme "" lexeme-start lexeme-end)]
["++" (token+ 'PPLUS-TOK "" lexeme "" lexeme-start lexeme-end)]
["<" (token+ 'LT-TOK "" lexeme "" lexeme-start lexeme-end)]
[">" (token+ 'GT-TOK "" lexeme "" lexeme-start lexeme-end)]
["&" (token+ 'AMP-TOK "" lexeme "" lexeme-start lexeme-end)]
["+" (token+ 'PLUS-TOK "" lexeme "" lexeme-start lexeme-end)]
[(or "<=" "=<") (token+ 'LEQ-TOK "" lexeme "" lexeme-start lexeme-end)]
[(or "!" "not") (token+ 'NEG-TOK "" lexeme "" lexeme-start lexeme-end)]
[(or "||" "or") (token+ 'OR-TOK "" lexeme "" lexeme-start lexeme-end)]
[(or "&&" "and") (token+ 'AND-TOK "" lexeme "" lexeme-start lexeme-end)]
[(or "<=>" "iff") (token+ 'IFF-TOK "" lexeme "" lexeme-start lexeme-end)]
[(or "=>" "implies") (token+ 'IMP-TOK "" lexeme "" lexeme-start lexeme-end)]
["abstract" (token+ `ABSTRACT-TOK "" lexeme "" lexeme-start lexeme-end)]
["all" (token+ `ALL-TOK "" lexeme "" lexeme-start lexeme-end)]
["as" (token+ `AS-TOK "" lexeme "" lexeme-start lexeme-end)]
["assert" (token+ `ASSERT-TOK "" lexeme "" lexeme-start lexeme-end)]
["but" (token+ `BUT-TOK "" lexeme "" lexeme-start lexeme-end)]
["check" (token+ `CHECK-TOK "" lexeme "" lexeme-start lexeme-end)]
["disj" (token+ `DISJ-TOK "" lexeme "" lexeme-start lexeme-end)]
["else" (token+ `ELSE-TOK "" lexeme "" lexeme-start lexeme-end)]
["exactly" (token+ `EXACTLY-TOK "" lexeme "" lexeme-start lexeme-end)]
["example" (token+ `EXAMPLE-TOK "" lexeme "" lexeme-start lexeme-end)]
["expect" (token+ `EXPECT-TOK "" lexeme "" lexeme-start lexeme-end)]
["extends" (token+ `EXTENDS-TOK "" lexeme "" lexeme-start lexeme-end)]
["for" (token+ `FOR-TOK "" lexeme "" lexeme-start lexeme-end)]
["fun" (token+ `FUN-TOK "" lexeme "" lexeme-start lexeme-end)]
["iden" (token+ `IDEN-TOK "" lexeme "" lexeme-start lexeme-end)]
["in" (token+ `IN-TOK "" lexeme "" lexeme-start lexeme-end)]
["ni" (token+ `NI-TOK "" lexeme "" lexeme-start lexeme-end)]
["is" (token+ `IS-TOK "" lexeme "" lexeme-start lexeme-end)]
["let" (token+ `LET-TOK "" lexeme "" lexeme-start lexeme-end)]
["lone" (token+ `LONE-TOK "" lexeme "" lexeme-start lexeme-end)]
[ " module " ( token+ ` MODULE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
["no" (token+ `NO-TOK "" lexeme "" lexeme-start lexeme-end)]
["none" (token+ `NONE-TOK "" lexeme "" lexeme-start lexeme-end)]
["one" (token+ `ONE-TOK "" lexeme "" lexeme-start lexeme-end)]
["func" (token+ `FUNC-TOK "" lexeme "" lexeme-start lexeme-end)]
["pfunc" (token+ `PFUNC-TOK "" lexeme "" lexeme-start lexeme-end)]
["open" (token+ `OPEN-TOK "" lexeme "" lexeme-start lexeme-end)]
["pred" (token+ `PRED-TOK "" lexeme "" lexeme-start lexeme-end)]
["run" (token+ `RUN-TOK "" lexeme "" lexeme-start lexeme-end)]
["sat" (token+ `SAT-TOK "" lexeme "" lexeme-start lexeme-end)]
["set" (token+ `SET-TOK "" lexeme "" lexeme-start lexeme-end)]
["sig" (token+ `SIG-TOK "" lexeme "" lexeme-start lexeme-end)]
["some" (token+ `SOME-TOK "" lexeme "" lexeme-start lexeme-end)]
["sum" (token+ `SUM-TOK "" lexeme "" lexeme-start lexeme-end #f #t)]
["test" (token+ `TEST-TOK "" lexeme "" lexeme-start lexeme-end)]
["theorem" (token+ `THEOREM-TOK "" lexeme "" lexeme-start lexeme-end)]
["two" (token+ `TWO-TOK "" lexeme "" lexeme-start lexeme-end)]
["univ" (token+ `UNIV-TOK "" lexeme "" lexeme-start lexeme-end)]
["unsat" (token+ `UNSAT-TOK "" lexeme "" lexeme-start lexeme-end)]
["wheat" (token+ `WHEAT-TOK "" lexeme "" lexeme-start lexeme-end)]
["break" (token+ `BREAK-TOK "" lexeme "" lexeme-start lexeme-end)]
["sufficient" (token+ `SUFFICIENT-TOK "" lexeme "" lexeme-start lexeme-end)]
["necessary" (token+ `NECESSARY-TOK "" lexeme "" lexeme-start lexeme-end)]
["suite" (token+ `SUITE-TOK "" lexeme "" lexeme-start lexeme-end)]
[ " state " ( token+ ` STATE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
[ " facts " ( token+ ` STATE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
[ " transition"(token+ ` TRANSITION - TOK " " lexeme " " lexeme - start lexeme - end ) ]
[ " trace " ( token+ ` TRACE - TOK " " lexeme " " lexeme - start lexeme - end ) ]
["bind" (token+ `BIND-TOK "" lexeme "" lexeme-start lexeme-end)]
["option" (token+ `OPTION-TOK "" lexeme "" lexeme-start lexeme-end)]
["inst" (token+ `INST-TOK "" lexeme "" lexeme-start lexeme-end)]
["always" (token+ `ALWAYS-TOK "" lexeme "" lexeme-start lexeme-end)]
["eventually" (token+ `EVENTUALLY-TOK "" lexeme "" lexeme-start lexeme-end)]
["next_state" (token+ `AFTER-TOK "" lexeme "" lexeme-start lexeme-end)]
["until" (token+ `UNTIL-TOK "" lexeme "" lexeme-start lexeme-end)]
["releases" (token+ `RELEASE-TOK "" lexeme "" lexeme-start lexeme-end)]
["historically" (token+ `HISTORICALLY-TOK "" lexeme "" lexeme-start lexeme-end)]
["once" (token+ `ONCE-TOK "" lexeme "" lexeme-start lexeme-end)]
["prev_state" (token+ `BEFORE-TOK "" lexeme "" lexeme-start lexeme-end)]
["since" (token+ `SINCE-TOK "" lexeme "" lexeme-start lexeme-end)]
["triggered" (token+ `TRIGGERED-TOK "" lexeme "" lexeme-start lexeme-end)]
["eval" (token+ `EVAL-TOK "" lexeme "" lexeme-start lexeme-end)]
["var" (token+ `VAR-TOK "" lexeme "" lexeme-start lexeme-end)]
["'" (token+ `PRIME-TOK "" lexeme "" lexeme-start lexeme-end)]
this to prevent it from being used as a sig / relation name
["Time" (token+ `TIME-TOK "" lexeme "" lexeme-start lexeme-end)]
["Int" (token+ `INT-TOK "" lexeme "" lexeme-start lexeme-end #f #t)]
["#" (token+ `CARD-TOK "" lexeme "" lexeme-start lexeme-end)]
Backquote to make atom names
["`" (token+ `BACKQUOTE-TOK "" lexeme "" lexeme-start lexeme-end)]
["(" (token+ 'LEFT-PAREN-TOK "" lexeme "" lexeme-start lexeme-end)]
[")" (token+ 'RIGHT-PAREN-TOK "" lexeme "" lexeme-start lexeme-end)]
["{" (token+ 'LEFT-CURLY-TOK "" lexeme "" lexeme-start lexeme-end)]
["}" (token+ 'RIGHT-CURLY-TOK "" lexeme "" lexeme-start lexeme-end)]
["[" (token+ 'LEFT-SQUARE-TOK "" lexeme "" lexeme-start lexeme-end)]
["]" (token+ 'RIGHT-SQUARE-TOK "" lexeme "" lexeme-start lexeme-end)]
["," (token+ 'COMMA-TOK "" lexeme "" lexeme-start lexeme-end)]
[";" (token+ 'SEMICOLON-TOK "" lexeme "" lexeme-start lexeme-end)]
["/" (token+ 'SLASH-TOK "" lexeme "" lexeme-start lexeme-end)]
[":" (token+ 'COLON-TOK "" lexeme "" lexeme-start lexeme-end)]
[(: (or alphabetic "@" "_") (* (or alphabetic numeric "_" "\""))) ;; "’" "”"
(token+ 'IDENTIFIER-TOK "" lexeme "" lexeme-start lexeme-end #f #t)]
(token+ 'IDENTIFIER-TOK "" lexeme "" lexeme-start lexeme-end)]
[whitespace (token+ lexeme "" lexeme "" lexeme-start lexeme-end #t)]
[any-char (token+ 'RESERVED-TOK "" lexeme "" lexeme-start lexeme-end)]))
(define (keyword? str)
(member str
(list
"abstract"
"all"
"and"
"as"
"assert"
"but"
"check"
"disj"
"else"
"eval"
"exactly"
"example"
"expect"
"extends"
"fact"
"for"
"fun"
"iden"
"iff"
"implies"
"in"
"ni"
"is"
"let"
"lone"
"no"
"none"
"not"
"one"
"open"
"or"
"pred"
"run"
"set"
"sig"
"some"
"sum"
"test"
"two"
"expect"
"sat"
"unsat"
"theorem"
"univ"
"break"
"sufficient"
"necessary"
"of"
"suite"
"bind"
"option"
"inst"
"always"
"eventually"
"after"
"until"
"releases"
"var"
"'"
"Time"
'Int
'sum
'sing
'add
'subtract
'multiply
'divide
'abs
'sign
'max
'min
"#"
"`"
'_
'this
)))
(define (paren? str)
(member str
(list "("
")"
"{"
"}"
"["
"]")))
(define (token+ type left lex right lex-start lex-end [skip? #f] [sym? #f])
(let ([l0 (string-length left)]
[l1 (string-length right)]
[trimmed (trim-ends left lex right)])
(token type (cond [(and sym? (string->number trimmed)) (string->number trimmed)]
[sym? (string->symbol trimmed)]
[else trimmed])
#:position (+ (pos lex-start) l0)
#:line (line lex-start)
#:column (+ (col lex-start) l0)
#:span (- (pos lex-end)
(pos lex-start) l0 l1)
#:skip? skip?)))
(provide forge-lexer keyword? paren?)
|
fffa02ce999f9664bc9f44af0128ab045556dfd6e4af8a5c06188a2923cf8f93 | purescript/purescript | Types.hs | module Language.PureScript.Sugar.Operators.Types where
import Prelude
import Control.Monad.Except
import Language.PureScript.AST
import Language.PureScript.Errors
import Language.PureScript.Names
import Language.PureScript.Sugar.Operators.Common
import Language.PureScript.Types
matchTypeOperators
:: MonadError MultipleErrors m
=> SourceSpan
-> [[(Qualified (OpName 'TypeOpName), Associativity)]]
-> SourceType
-> m SourceType
matchTypeOperators ss = matchOperators isBinOp extractOp fromOp reapply id
where
isBinOp :: SourceType -> Bool
isBinOp BinaryNoParensType{} = True
isBinOp _ = False
extractOp :: SourceType -> Maybe (SourceType, SourceType, SourceType)
extractOp (BinaryNoParensType _ op l r) = Just (op, l, r)
extractOp _ = Nothing
fromOp :: SourceType -> Maybe (SourceSpan, Qualified (OpName 'TypeOpName))
fromOp (TypeOp _ q@(Qualified _ (OpName _))) = Just (ss, q)
fromOp _ = Nothing
reapply :: a -> Qualified (OpName 'TypeOpName) -> SourceType -> SourceType -> SourceType
reapply _ op = srcTypeApp . srcTypeApp (TypeOp (ss, []) op)
| null | https://raw.githubusercontent.com/purescript/purescript/02bd6ae60bcd18cbfa892f268ef6359d84ed7c9b/src/Language/PureScript/Sugar/Operators/Types.hs | haskell | module Language.PureScript.Sugar.Operators.Types where
import Prelude
import Control.Monad.Except
import Language.PureScript.AST
import Language.PureScript.Errors
import Language.PureScript.Names
import Language.PureScript.Sugar.Operators.Common
import Language.PureScript.Types
matchTypeOperators
:: MonadError MultipleErrors m
=> SourceSpan
-> [[(Qualified (OpName 'TypeOpName), Associativity)]]
-> SourceType
-> m SourceType
matchTypeOperators ss = matchOperators isBinOp extractOp fromOp reapply id
where
isBinOp :: SourceType -> Bool
isBinOp BinaryNoParensType{} = True
isBinOp _ = False
extractOp :: SourceType -> Maybe (SourceType, SourceType, SourceType)
extractOp (BinaryNoParensType _ op l r) = Just (op, l, r)
extractOp _ = Nothing
fromOp :: SourceType -> Maybe (SourceSpan, Qualified (OpName 'TypeOpName))
fromOp (TypeOp _ q@(Qualified _ (OpName _))) = Just (ss, q)
fromOp _ = Nothing
reapply :: a -> Qualified (OpName 'TypeOpName) -> SourceType -> SourceType -> SourceType
reapply _ op = srcTypeApp . srcTypeApp (TypeOp (ss, []) op)
| |
b9b77e7eba8280d91565e9ce14922e86eeb36caeb532e436a299d144e95fdbfa | maranget/hevea | tagout.mli | (***********************************************************************)
(* *)
(* HEVEA *)
(* *)
, projet , INRIA Rocquencourt
(* *)
Copyright 2012 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
(* Erase tags (for title in hacha) *)
exception Error
val tagout : string -> string
| null | https://raw.githubusercontent.com/maranget/hevea/226eac8c506f82a600d453492fbc1b9784dd865f/tagout.mli | ocaml | *********************************************************************
HEVEA
*********************************************************************
Erase tags (for title in hacha) | , projet , INRIA Rocquencourt
Copyright 2012 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
exception Error
val tagout : string -> string
|
8d821d225335ec8c236c9b4fdc307bfd9abeae91995fb4951018950b2278964d | anton-k/hindley-milner-type-check | Subst.hs | -- | Capture-avoiding substitutions.
module Type.Check.HM.Subst(
CanApply(..)
, Subst(..)
, delta
, applyToVar
) where
import Data.Fix
import qualified Data.Map.Strict as M
import Type.Check.HM.Type
-- | Substitutions of type variables for monomorphic types.
newtype Subst loc v = Subst { unSubst :: M.Map v (Type loc v) }
deriving (Eq, Ord, Monoid)
instance Ord v => Semigroup (Subst loc v) where
(Subst ma) <> sb@(Subst mb) = Subst $ fmap (apply sb) ma <> M.difference mb ma
-- | Singleton substitution.
delta :: v -> Type loc v -> Subst loc v
delta v = Subst . M.singleton v
applyToVar :: Ord v => Subst loc v -> v -> Maybe (Type loc v)
applyToVar (Subst m) v = M.lookup v m
---------------------------------------------------------------
-- | Class for application of substitutions to various types.
class CanApply f where
apply :: Ord v => Subst loc v -> f loc v -> f loc v
instance CanApply Type where
apply (Subst s) = foldFix go . unType
where
go = \case
VarT loc v -> case M.lookup v s of
Nothing -> varT loc v
Just t -> t
ConT loc name args -> conT loc name args
ArrowT loc a b -> arrowT loc a b
TupleT loc as -> tupleT loc as
ListT loc a -> listT loc a
instance CanApply Signature where
apply (Subst s) (Signature (Fix expr)) = case expr of
MonoT t -> monoT $ apply (Subst s) t
ForAllT loc x t -> forAllT loc x $ apply (Subst $ M.delete x s) (Signature t)
| null | https://raw.githubusercontent.com/anton-k/hindley-milner-type-check/6c8e9de630f347ac8bc8590906b7e3b509fa57c0/src/Type/Check/HM/Subst.hs | haskell | | Capture-avoiding substitutions.
| Substitutions of type variables for monomorphic types.
| Singleton substitution.
-------------------------------------------------------------
| Class for application of substitutions to various types. | module Type.Check.HM.Subst(
CanApply(..)
, Subst(..)
, delta
, applyToVar
) where
import Data.Fix
import qualified Data.Map.Strict as M
import Type.Check.HM.Type
newtype Subst loc v = Subst { unSubst :: M.Map v (Type loc v) }
deriving (Eq, Ord, Monoid)
instance Ord v => Semigroup (Subst loc v) where
(Subst ma) <> sb@(Subst mb) = Subst $ fmap (apply sb) ma <> M.difference mb ma
delta :: v -> Type loc v -> Subst loc v
delta v = Subst . M.singleton v
applyToVar :: Ord v => Subst loc v -> v -> Maybe (Type loc v)
applyToVar (Subst m) v = M.lookup v m
class CanApply f where
apply :: Ord v => Subst loc v -> f loc v -> f loc v
instance CanApply Type where
apply (Subst s) = foldFix go . unType
where
go = \case
VarT loc v -> case M.lookup v s of
Nothing -> varT loc v
Just t -> t
ConT loc name args -> conT loc name args
ArrowT loc a b -> arrowT loc a b
TupleT loc as -> tupleT loc as
ListT loc a -> listT loc a
instance CanApply Signature where
apply (Subst s) (Signature (Fix expr)) = case expr of
MonoT t -> monoT $ apply (Subst s) t
ForAllT loc x t -> forAllT loc x $ apply (Subst $ M.delete x s) (Signature t)
|
08d7d6356e1abe1f55135477dfd681f452acc9663ec16ca086ea8df5a94c9fff | ocaml/opam | split_install.ml | #!/usr/bin/env opam-admin.top
#directory "+../opam-lib";;
#directory "+../re";;
open Opam_admin_top;;
open OpamTypes;;
iter_packages ~opam:(fun _ opam ->
let module O = OpamFile.OPAM in
if O.install opam <> [] then opam else
let rec rev_split_while acc cond = function
| [] -> acc, []
| x::r when cond x -> rev_split_while (x::acc) cond r
| l -> acc, List.rev l
in
let condition = function
| (CString "install",_)::_, _ -> true
| (CString "cp",_)::r, _ ->
(try
let dest =
match List.filter (function
| CString s, _ -> not (OpamStd.String.starts_with ~prefix:"-" s)
| CIdent _, _ -> true)
(List.rev r)
with
| (d, _)::_ -> d
| _ -> raise Not_found
in
let dests = ["prefix";"bin";"sbin";"lib";"man";"doc";"share";"etc";
"toplevel";"stublibs";"doc"] in
match dest with
| CIdent i -> List.mem i dests
| CString s ->
Re.(execp (compile (seq [alt (List.map str dests); str "}%"])) s)
with Not_found -> false)
| l, _ ->
List.exists (function
| (CString arg, _) -> OpamStd.String.contains ~sub:"install" arg
| _ -> false)
l
in
let install, build =
rev_split_while [] condition (List.rev (O.build opam))
in
opam |>
OpamFile.OPAM.with_build build |>
OpamFile.OPAM.with_install install)
()
;;
| null | https://raw.githubusercontent.com/ocaml/opam/074df6b6d87d4114116ea41311892b342cfad3de/admin-scripts/split_install.ml | ocaml | #!/usr/bin/env opam-admin.top
#directory "+../opam-lib";;
#directory "+../re";;
open Opam_admin_top;;
open OpamTypes;;
iter_packages ~opam:(fun _ opam ->
let module O = OpamFile.OPAM in
if O.install opam <> [] then opam else
let rec rev_split_while acc cond = function
| [] -> acc, []
| x::r when cond x -> rev_split_while (x::acc) cond r
| l -> acc, List.rev l
in
let condition = function
| (CString "install",_)::_, _ -> true
| (CString "cp",_)::r, _ ->
(try
let dest =
match List.filter (function
| CString s, _ -> not (OpamStd.String.starts_with ~prefix:"-" s)
| CIdent _, _ -> true)
(List.rev r)
with
| (d, _)::_ -> d
| _ -> raise Not_found
in
let dests = ["prefix";"bin";"sbin";"lib";"man";"doc";"share";"etc";
"toplevel";"stublibs";"doc"] in
match dest with
| CIdent i -> List.mem i dests
| CString s ->
Re.(execp (compile (seq [alt (List.map str dests); str "}%"])) s)
with Not_found -> false)
| l, _ ->
List.exists (function
| (CString arg, _) -> OpamStd.String.contains ~sub:"install" arg
| _ -> false)
l
in
let install, build =
rev_split_while [] condition (List.rev (O.build opam))
in
opam |>
OpamFile.OPAM.with_build build |>
OpamFile.OPAM.with_install install)
()
;;
| |
ca31bd8fe50bef6830860c4bebf97d892f06a8e1512c9afe439ac590a2a1647b | ocharles/blog | 2014-02-25-dtypes-1.hs | # LANGUAGE DataKinds #
{-# LANGUAGE GADTs #-}
# LANGUAGE TypeFamilies #
data PgType = PgInt | PgString
type family InterpretType (t :: PgType) :: *
type instance InterpretType 'PgInt = Int
type instance InterpretType 'PgString = String
data SPgType :: PgType -> * where
SPgInt :: SPgType 'PgInt
SPgString :: SPgType 'PgString
exampleValues :: SPgType t -> InterpretType t
exampleValues SPgInt = 42
exampleValues SPgString = "Forty two"
data PgFunction
= PgReturn PgType
| PgArrow PgType PgFunction
type family InterpretFunction (t :: PgFunction) :: *
type instance InterpretFunction ('PgReturn t) = InterpretType t
type instance InterpretFunction ('PgArrow t ts) = InterpretType t -> InterpretFunction ts
data SPgFunction :: PgFunction -> * where
SPgReturn :: SPgType t -> SPgFunction ('PgReturn t)
SPgArrow :: SPgType t -> SPgFunction ts -> SPgFunction ('PgArrow t ts)
exampleFunctions :: SPgFunction t -> InterpretFunction t
exampleFunctions (SPgReturn SPgInt) = 42
exampleFunctions (SPgArrow SPgInt (SPgReturn SPgInt)) = \x -> x * x
exampleFunctions (SPgArrow SPgString (SPgReturn SPgInt)) = length
| null | https://raw.githubusercontent.com/ocharles/blog/fa8e911d3c03b134eee891d187a1bb574f23a530/code/2014-02-25-dtypes-1.hs | haskell | # LANGUAGE GADTs # | # LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
data PgType = PgInt | PgString
type family InterpretType (t :: PgType) :: *
type instance InterpretType 'PgInt = Int
type instance InterpretType 'PgString = String
data SPgType :: PgType -> * where
SPgInt :: SPgType 'PgInt
SPgString :: SPgType 'PgString
exampleValues :: SPgType t -> InterpretType t
exampleValues SPgInt = 42
exampleValues SPgString = "Forty two"
data PgFunction
= PgReturn PgType
| PgArrow PgType PgFunction
type family InterpretFunction (t :: PgFunction) :: *
type instance InterpretFunction ('PgReturn t) = InterpretType t
type instance InterpretFunction ('PgArrow t ts) = InterpretType t -> InterpretFunction ts
data SPgFunction :: PgFunction -> * where
SPgReturn :: SPgType t -> SPgFunction ('PgReturn t)
SPgArrow :: SPgType t -> SPgFunction ts -> SPgFunction ('PgArrow t ts)
exampleFunctions :: SPgFunction t -> InterpretFunction t
exampleFunctions (SPgReturn SPgInt) = 42
exampleFunctions (SPgArrow SPgInt (SPgReturn SPgInt)) = \x -> x * x
exampleFunctions (SPgArrow SPgString (SPgReturn SPgInt)) = length
|
1454aaa5028c2cc4c4240029ce276533f477a417092d1b50e48ade68c1d9e7f5 | f-o-a-m/kepler | Application.hs | module SimpleStorage.Application
( SimpleStorageModules
, handlersContext
) where
import Data.Proxy
import SimpleStorage.Modules.SimpleStorage as SimpleStorage
import Tendermint.SDK.Application (HandlersContext (..),
ModuleList (..),
baseAppAnteHandler)
import qualified Tendermint.SDK.BaseApp as BA
import Tendermint.SDK.Crypto (Secp256k1)
import qualified Tendermint.SDK.Modules.Auth as A
--------------------------------------------------------------------------------
type SimpleStorageModules =
'[ SimpleStorage.SimpleStorage
, A.Auth
]
handlersContext :: HandlersContext Secp256k1 SimpleStorageModules BA.CoreEffs
handlersContext = HandlersContext
{ signatureAlgP = Proxy @Secp256k1
, modules = simpleStorageModules
, beginBlocker = BA.defaultBeginBlocker
, endBlocker = BA.defaultEndBlocker
, compileToCore = BA.defaultCompileToCore
, anteHandler = baseAppAnteHandler
}
where
simpleStorageModules =
SimpleStorage.simpleStorageModule
:+ A.authModule
:+ NilModules
| null | https://raw.githubusercontent.com/f-o-a-m/kepler/6c1ad7f37683f509c2f1660e3561062307d3056b/hs-abci-docs/simple-storage/src/SimpleStorage/Application.hs | haskell | ------------------------------------------------------------------------------ | module SimpleStorage.Application
( SimpleStorageModules
, handlersContext
) where
import Data.Proxy
import SimpleStorage.Modules.SimpleStorage as SimpleStorage
import Tendermint.SDK.Application (HandlersContext (..),
ModuleList (..),
baseAppAnteHandler)
import qualified Tendermint.SDK.BaseApp as BA
import Tendermint.SDK.Crypto (Secp256k1)
import qualified Tendermint.SDK.Modules.Auth as A
type SimpleStorageModules =
'[ SimpleStorage.SimpleStorage
, A.Auth
]
handlersContext :: HandlersContext Secp256k1 SimpleStorageModules BA.CoreEffs
handlersContext = HandlersContext
{ signatureAlgP = Proxy @Secp256k1
, modules = simpleStorageModules
, beginBlocker = BA.defaultBeginBlocker
, endBlocker = BA.defaultEndBlocker
, compileToCore = BA.defaultCompileToCore
, anteHandler = baseAppAnteHandler
}
where
simpleStorageModules =
SimpleStorage.simpleStorageModule
:+ A.authModule
:+ NilModules
|
755ca27caac5eae47232abd23a973d13ae0bd3b6f1e8bca85161dbd7512e7c91 | ocaml-opam/opam2web | o2wJson.mli | (**************************************************************************)
(* *)
Copyright 2012 - 2019 OCamlPro
Copyright 2012 INRIA
(* *)
(* All rights reserved.This file is distributed under the terms of the *)
GNU Lesser General Public License version 3.0 with linking
(* exception. *)
(* *)
OPAM 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. *)
(* *)
(**************************************************************************)
open O2wTypes
* Basic json functions : construct the association with the content . Fields
are named as follow : " package " , " name " , " version " , " date " , " downloads " ,
" month_downloads " .
are named as follow: "package", "name", "version", "date", "downloads",
"month_downloads". *)
val json_package: package -> string * Yojson.t
val json_name: name -> string * Yojson.t
val json_version: version -> string * Yojson.t
val json_downloads: int64 -> string * Yojson.t
val json_month_downloads: int64 -> string * Yojson.t
val json_timestamp: float -> string * Yojson.t
(** Basic json function with option argument. If [None], the value of the
string * Yojson.tiation is `null` *)
val json_downloads_opt: int64 option -> string * Yojson.t
val json_month_downloads_opt: int64 option -> string * Yojson.t
val json_timestamp_opt: float option -> string * Yojson.t
(** [write filename json] outputs json into json/[filename] file *)
val write: string -> Yojson.t -> unit
| null | https://raw.githubusercontent.com/ocaml-opam/opam2web/0797940ad5fa779555d34a5561dc288e10fca0b1/src/o2wJson.mli | ocaml | ************************************************************************
All rights reserved.This file is distributed under the terms of the
exception.
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
License for more details.
************************************************************************
* Basic json function with option argument. If [None], the value of the
string * Yojson.tiation is `null`
* [write filename json] outputs json into json/[filename] file | Copyright 2012 - 2019 OCamlPro
Copyright 2012 INRIA
GNU Lesser General Public License version 3.0 with linking
OPAM is distributed in the hope that it will be useful , but WITHOUT
or FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public
open O2wTypes
* Basic json functions : construct the association with the content . Fields
are named as follow : " package " , " name " , " version " , " date " , " downloads " ,
" month_downloads " .
are named as follow: "package", "name", "version", "date", "downloads",
"month_downloads". *)
val json_package: package -> string * Yojson.t
val json_name: name -> string * Yojson.t
val json_version: version -> string * Yojson.t
val json_downloads: int64 -> string * Yojson.t
val json_month_downloads: int64 -> string * Yojson.t
val json_timestamp: float -> string * Yojson.t
val json_downloads_opt: int64 option -> string * Yojson.t
val json_month_downloads_opt: int64 option -> string * Yojson.t
val json_timestamp_opt: float option -> string * Yojson.t
val write: string -> Yojson.t -> unit
|
e14bbcc31b725f4e0fa8da18cab78ca9b9e351b98865a261befa8bedf3cc45cb | waxeye-org/waxeye | expand.rkt | ;; Waxeye Parser Generator
;; www.waxeye.org
Copyright ( C ) 2008 - 2010 Orlando Hill
Licensed under the MIT license . See ' LICENSE ' for details .
#lang racket/base
(require waxeye/ast
"gen.rkt")
(provide (all-defined-out))
(define (expand-grammar grammar)
(define (lift-only-sub-exp visitor exp)
(let ((chil (ast-c exp)))
(for-each visitor chil)
When we only have the one exp
(let ((only (car chil))); Lift that to become our new expression
(set-ast-t! exp (ast-t only))
(set-ast-c! exp (ast-c only))
(set-ast-pos! exp (ast-pos only))))))
(define (visit-alternation exp)
(lift-only-sub-exp visit-sequence exp))
(define (visit-sequence exp)
(set-ast-c! exp (map expand-unit (ast-c exp)))
(lift-only-sub-exp visit-exp exp))
(define (visit-only-child exp)
(visit-exp (car (ast-c exp))))
(define (visit-exp exp)
(let ((type (ast-t exp)))
(case type
((action) (void))
((alternation) (visit-alternation exp))
((and) (visit-only-child exp))
((caseLiteral) (visit-case-literal exp))
((charClass) (visit-char-class exp))
((closure) (visit-only-child exp))
((identifier) (void))
((label) (void))
((literal) (visit-literal exp))
((not) (visit-only-child exp))
((optional) (visit-only-child exp))
((plus) (visit-only-child exp))
((sequence) (visit-sequence exp))
((void) (visit-only-child exp))
((wildCard) (void))
(else (error 'expand-grammar "unknown expression type: ~s" type)))))
(define (expand-def def)
(visit-alternation (caddr (ast-c def))))
(for-each expand-def (get-defs grammar)))
(define (expand-unit exp)
(define (make-prefix v e)
(let ((r (car (ast-c v))))
(ast
(cond
((equal? r #\*) 'closure)
((equal? r #\+) 'plus)
((equal? r #\?) 'optional)
((equal? r #\:) 'void)
((equal? r #\&) 'and)
((equal? r #\!) 'not)
(else (error 'make-prefix "unknown expression type: ~s" r)))
(list e)
(cons 0 0))))
(define (make-label v e)
(let ((r (car (ast-c v))))
(ast 'label (list e) (cons 0 0))))
(define (expand-unit-iter el)
(let ((rest (cdr el)))
(if (null? rest)
(car el)
(let ((type (ast-t (car el))))
((case type
((prefix) make-prefix)
((label) make-label)
(else (error 'expand-unit-iter "unknown expression type: ~s" type)))
(car el)
(expand-unit-iter rest))))))
(expand-unit-iter (ast-c exp)))
(define (visit-case-literal exp)
(define (cc-chil c)
(if (char-alphabetic? c)
(list (char-upcase c) (char-downcase c))
(list c)))
(convert-chars! exp)
(let ((letters (ast-c exp)))
(if (memf char-alphabetic? letters)
(if (null? (cdr letters))
(let ((c (car letters)))
(set-ast-t! exp 'charClass)
(set-ast-c! exp (cc-chil c)))
(begin
(set-ast-t! exp 'sequence)
(set-ast-c! exp (map (lambda (a)
(ast 'charClass (cc-chil a) (cons 0 0)))
letters))))
(set-ast-t! exp 'literal))))
(define (convert-char c)
(define (cc-char c)
(let ((chil (ast-c c)))
(if (= (length chil) 1)
(car chil)
(let ((s (cadr chil)))
(cond
((equal? s #\n) #\linefeed)
((equal? s #\t) #\tab)
((equal? s #\r) #\return)
(else s))))))
(define (cc-hex c)
(integer->char (string->number (list->string (ast-c c)) 16)))
(if (equal? (ast-t c) 'hex)
(cc-hex c)
(cc-char c)))
(define (convert-chars! exp)
(set-ast-c! exp (map convert-char (ast-c exp))))
(define (visit-literal exp)
(convert-chars! exp))
(define (visit-char-class exp)
(define (cc-part part)
(let ((range (ast-c part)))
(if (= (length range) 1)
(convert-char (car range))
(let ((r1 (convert-char (car range))) (r2 (convert-char (cadr range))))
(cond
((char=? r1 r2) r1)
((char<? r1 r2) (cons r1 r2))
(else
(cons r2 r1)))))))
;; The order of ranges with the same start doesn't matter as they get
;; merged no matter what their ends are.
(define (cc-less-than? a b)
(char<? (if (char? a)
a
(car a))
(if (char? b)
b
(car b))))
(define (minimise cc)
(define (next-to? a b)
(= (- (char->integer b) (char->integer a)) 1))
(if (null? cc)
'()
(let ((a (car cc)) (rest (cdr cc)))
(if (null? rest)
cc
(let ((b (car rest)))
(if (char? a)
(if (char? b)
(if (char=? a b) ; Is duplicate char?
(minimise (cons a (cdr rest)))
(if (next-to? a b) ; Is a next to b?
(minimise (cons (cons a b) (cdr rest)))
(cons a (minimise rest))))
(if (next-to? a (car b)) ; Is a next to range b?
(minimise (cons (cons a (cdr b)) (cdr rest)))
(cons a (minimise rest))))
(if (char? b)
(if (or (char=? b (car a)) ; Is b within range a?
(char<=? b (cdr a)))
(minimise (cons a (cdr rest)))
(if (next-to? (cdr a) b) ; Is b next to range a?
(minimise (cons (cons (car a) b) (cdr rest)))
(cons a (minimise rest))))
(if (or (char<=? (car b) (cdr a)) ; Can we merge the ranges?
(next-to? (cdr a) (car b)))
(minimise (cons
(cons (integer->char (min (char->integer (car a)) (char->integer (car b))))
(integer->char (max (char->integer (cdr a)) (char->integer (cdr b)))))
(cdr rest)))
(cons a (minimise rest))))))))))
(set-ast-c! exp (minimise (sort (map cc-part (ast-c exp)) cc-less-than?))))
| null | https://raw.githubusercontent.com/waxeye-org/waxeye/723da0475fc0c8e3dd43da46665ef7c62734857b/src/waxeye/expand.rkt | racket | Waxeye Parser Generator
www.waxeye.org
Lift that to become our new expression
The order of ranges with the same start doesn't matter as they get
merged no matter what their ends are.
Is duplicate char?
Is a next to b?
Is a next to range b?
Is b within range a?
Is b next to range a?
Can we merge the ranges? | Copyright ( C ) 2008 - 2010 Orlando Hill
Licensed under the MIT license . See ' LICENSE ' for details .
#lang racket/base
(require waxeye/ast
"gen.rkt")
(provide (all-defined-out))
(define (expand-grammar grammar)
(define (lift-only-sub-exp visitor exp)
(let ((chil (ast-c exp)))
(for-each visitor chil)
When we only have the one exp
(set-ast-t! exp (ast-t only))
(set-ast-c! exp (ast-c only))
(set-ast-pos! exp (ast-pos only))))))
(define (visit-alternation exp)
(lift-only-sub-exp visit-sequence exp))
(define (visit-sequence exp)
(set-ast-c! exp (map expand-unit (ast-c exp)))
(lift-only-sub-exp visit-exp exp))
(define (visit-only-child exp)
(visit-exp (car (ast-c exp))))
(define (visit-exp exp)
(let ((type (ast-t exp)))
(case type
((action) (void))
((alternation) (visit-alternation exp))
((and) (visit-only-child exp))
((caseLiteral) (visit-case-literal exp))
((charClass) (visit-char-class exp))
((closure) (visit-only-child exp))
((identifier) (void))
((label) (void))
((literal) (visit-literal exp))
((not) (visit-only-child exp))
((optional) (visit-only-child exp))
((plus) (visit-only-child exp))
((sequence) (visit-sequence exp))
((void) (visit-only-child exp))
((wildCard) (void))
(else (error 'expand-grammar "unknown expression type: ~s" type)))))
(define (expand-def def)
(visit-alternation (caddr (ast-c def))))
(for-each expand-def (get-defs grammar)))
(define (expand-unit exp)
(define (make-prefix v e)
(let ((r (car (ast-c v))))
(ast
(cond
((equal? r #\*) 'closure)
((equal? r #\+) 'plus)
((equal? r #\?) 'optional)
((equal? r #\:) 'void)
((equal? r #\&) 'and)
((equal? r #\!) 'not)
(else (error 'make-prefix "unknown expression type: ~s" r)))
(list e)
(cons 0 0))))
(define (make-label v e)
(let ((r (car (ast-c v))))
(ast 'label (list e) (cons 0 0))))
(define (expand-unit-iter el)
(let ((rest (cdr el)))
(if (null? rest)
(car el)
(let ((type (ast-t (car el))))
((case type
((prefix) make-prefix)
((label) make-label)
(else (error 'expand-unit-iter "unknown expression type: ~s" type)))
(car el)
(expand-unit-iter rest))))))
(expand-unit-iter (ast-c exp)))
(define (visit-case-literal exp)
(define (cc-chil c)
(if (char-alphabetic? c)
(list (char-upcase c) (char-downcase c))
(list c)))
(convert-chars! exp)
(let ((letters (ast-c exp)))
(if (memf char-alphabetic? letters)
(if (null? (cdr letters))
(let ((c (car letters)))
(set-ast-t! exp 'charClass)
(set-ast-c! exp (cc-chil c)))
(begin
(set-ast-t! exp 'sequence)
(set-ast-c! exp (map (lambda (a)
(ast 'charClass (cc-chil a) (cons 0 0)))
letters))))
(set-ast-t! exp 'literal))))
(define (convert-char c)
(define (cc-char c)
(let ((chil (ast-c c)))
(if (= (length chil) 1)
(car chil)
(let ((s (cadr chil)))
(cond
((equal? s #\n) #\linefeed)
((equal? s #\t) #\tab)
((equal? s #\r) #\return)
(else s))))))
(define (cc-hex c)
(integer->char (string->number (list->string (ast-c c)) 16)))
(if (equal? (ast-t c) 'hex)
(cc-hex c)
(cc-char c)))
(define (convert-chars! exp)
(set-ast-c! exp (map convert-char (ast-c exp))))
(define (visit-literal exp)
(convert-chars! exp))
(define (visit-char-class exp)
(define (cc-part part)
(let ((range (ast-c part)))
(if (= (length range) 1)
(convert-char (car range))
(let ((r1 (convert-char (car range))) (r2 (convert-char (cadr range))))
(cond
((char=? r1 r2) r1)
((char<? r1 r2) (cons r1 r2))
(else
(cons r2 r1)))))))
(define (cc-less-than? a b)
(char<? (if (char? a)
a
(car a))
(if (char? b)
b
(car b))))
(define (minimise cc)
(define (next-to? a b)
(= (- (char->integer b) (char->integer a)) 1))
(if (null? cc)
'()
(let ((a (car cc)) (rest (cdr cc)))
(if (null? rest)
cc
(let ((b (car rest)))
(if (char? a)
(if (char? b)
(minimise (cons a (cdr rest)))
(minimise (cons (cons a b) (cdr rest)))
(cons a (minimise rest))))
(minimise (cons (cons a (cdr b)) (cdr rest)))
(cons a (minimise rest))))
(if (char? b)
(char<=? b (cdr a)))
(minimise (cons a (cdr rest)))
(minimise (cons (cons (car a) b) (cdr rest)))
(cons a (minimise rest))))
(next-to? (cdr a) (car b)))
(minimise (cons
(cons (integer->char (min (char->integer (car a)) (char->integer (car b))))
(integer->char (max (char->integer (cdr a)) (char->integer (cdr b)))))
(cdr rest)))
(cons a (minimise rest))))))))))
(set-ast-c! exp (minimise (sort (map cc-part (ast-c exp)) cc-less-than?))))
|
e49091aaa535a275e6221c8b23d2a0041ba45455e92cd1c2a721bac9ce83d455 | lazy-cat-io/metaverse | path.cljs | (ns metaverse.runner.path
(:require
[metaverse.runner.config :as config]
[metaverse.runner.utils.path :as path]))
(def assets-dir
(path/join config/root-dir "assets"))
(def icons-dir
(path/join assets-dir "icons"))
| null | https://raw.githubusercontent.com/lazy-cat-io/metaverse/2e5754967ac0e4219197da3ff6937b666d2d26fa/src/main/clojure/metaverse/runner/path.cljs | clojure | (ns metaverse.runner.path
(:require
[metaverse.runner.config :as config]
[metaverse.runner.utils.path :as path]))
(def assets-dir
(path/join config/root-dir "assets"))
(def icons-dir
(path/join assets-dir "icons"))
| |
8a097f1411cdb5b922484e71e11e9b3bdad284f6b466587524fc3c687a072075 | mirage/bechamel | measurement_raw.mli | type t
(** Type of samples. *)
val make : measures:float array -> labels:string array -> float -> t
* [ make ~measures ~labels run ] is samples of one record of [ run ] runs .
[ labels.(i ) ] is associated to [ measures.(i ) ] .
[labels.(i)] is associated to [measures.(i)]. *)
val run : t -> float
(** [run t] is the number of runs of [t]. *)
val get_index : label:string -> t -> int
(** [get_index ~label t] is the index of the measure identified by [label]. *)
val get : label:string -> t -> float
(** [get ~label t] is the recorded measure [label] into [t]. *)
val pp : t Fmt.t
(** Pretty-printer of {!t}. *)
val exists : label:string -> t -> bool
(** [exists ~label t] returns [true] if the measure [label] exists into [t].
Otherwise, it returns [false]. *)
| null | https://raw.githubusercontent.com/mirage/bechamel/3e1887305badf5dcc1ecb06beb5b023f55b4193c/lib/measurement_raw.mli | ocaml | * Type of samples.
* [run t] is the number of runs of [t].
* [get_index ~label t] is the index of the measure identified by [label].
* [get ~label t] is the recorded measure [label] into [t].
* Pretty-printer of {!t}.
* [exists ~label t] returns [true] if the measure [label] exists into [t].
Otherwise, it returns [false]. | type t
val make : measures:float array -> labels:string array -> float -> t
* [ make ~measures ~labels run ] is samples of one record of [ run ] runs .
[ labels.(i ) ] is associated to [ measures.(i ) ] .
[labels.(i)] is associated to [measures.(i)]. *)
val run : t -> float
val get_index : label:string -> t -> int
val get : label:string -> t -> float
val pp : t Fmt.t
val exists : label:string -> t -> bool
|
a8613a0070fb91b9aeddd885e1f2080e48f24a05da168eb1f4250e29b9e6add1 | lisp/de.setf.xml | namespace.lisp | -*- Mode : lisp ; Syntax : ansi - common - lisp ; Base : 10 ; Package : xml - query - data - model ; -*-
(in-package :xml-query-data-model)
(setq xml-query-data-model:*namespace*
(xml-query-data-model:defnamespace "#"
(:use)
(:nicknames)
(:export)
(:documentation nil)))
(let ((xml-query-data-model::p
(or (find-package "#")
(make-package "#"
:use
nil
:nicknames
'nil))))
(dolist (xml-query-data-model::s 'nil)
(export (intern xml-query-data-model::s xml-query-data-model::p)
xml-query-data-model::p)))
;;; (xqdm:find-namespace "#" :if-does-not-exist :load)
| null | https://raw.githubusercontent.com/lisp/de.setf.xml/827681c969342096c3b95735d84b447befa69fa6/namespaces/www-w3-org/2000/10/swap/pim/contact/namespace.lisp | lisp | Syntax : ansi - common - lisp ; Base : 10 ; Package : xml - query - data - model ; -*-
(xqdm:find-namespace "#" :if-does-not-exist :load) |
(in-package :xml-query-data-model)
(setq xml-query-data-model:*namespace*
(xml-query-data-model:defnamespace "#"
(:use)
(:nicknames)
(:export)
(:documentation nil)))
(let ((xml-query-data-model::p
(or (find-package "#")
(make-package "#"
:use
nil
:nicknames
'nil))))
(dolist (xml-query-data-model::s 'nil)
(export (intern xml-query-data-model::s xml-query-data-model::p)
xml-query-data-model::p)))
|
0c13f6eb43b1e938d1ef193263285a8506fb5c6591316855643ee0378c2a4dd0 | hyperfiddle/electric | ssr.cljc | (ns hyperfiddle.server.ssr
(:require [hfdl.impl.switch :refer [switch]]
[hfdl.lang :refer [vars]]
[missionary.core :as m]))
TODO use org.w3c.dom instead , or just drop this aspect of the UI .
(defprotocol ITextNode
(-get-text-content [this])
(-set-text-content! [this text]))
(deftype TextNode [^:volatile-mutable text]
ITextNode
(-get-text-content [this] text)
(-set-text-content! [this text'] (set! text text') this))
#?(:clj
(defmethod print-method TextNode [this w]
(print-simple (pr-str [:text (-get-text-content this)]) w)))
TODO use org.w3c.dom instead , or just drop this aspect of the UI .
(defprotocol INode
(-get-children [this])
(-append-child! [this child])
(-remove-child! [this child]))
(deftype Node [tag ^:volatile-mutable children]
INode
(-get-children [this] children)
(-append-child! [this child] (set! children (conj children child)) this)
(-remove-child! [this child] (set! children (disj children child)) this))
#?(:clj
(defmethod print-method Node [this w]
(print-simple (pr-str (into [(.tag this)] (-get-children this))) w)))
(defn create-text-node [initial-value] (TextNode. (str initial-value)))
(defn create-tag-node [tag] (Node. tag #{}))
(defn by-id [id] (Node. id #{}))
(defn set-text-content! [elem text] (-set-text-content! elem text))
(defn text [>text]
(let [elem (create-text-node "")]
(m/stream! (m/latest #(set-text-content! elem %) >text))
(m/ap elem)))
(defn append-childs [parent items] (reduce #(-append-child! %1 %2) parent items))
(defn remove-childs [parent items] (reduce #(-remove-child! %1 %2) parent items))
(defn mount [parent items]
(m/observe
(fn [!]
(! (append-childs parent items))
(fn []
(remove-childs parent items)))))
props not supported on SSR yet
(let [elem (create-tag-node elem)]
(when (seq (filter identity >childs))
(m/stream! (switch (apply m/latest #(mount elem %&) >childs))))
(m/ap elem)))
(defn append-child! [parent >child]
(m/stream! (switch (m/latest #(mount parent [%]) >child)))
parent)
(defn mount-component-at-node! [id >component]
(append-child! (by-id id) >component))
(def exports (vars by-id text tag mount-component-at-node!))
| null | https://raw.githubusercontent.com/hyperfiddle/electric/1c75f9e0a429cbf42fc7feb9e443062b37cf876a/scratch/server/ssr.cljc | clojure | (ns hyperfiddle.server.ssr
(:require [hfdl.impl.switch :refer [switch]]
[hfdl.lang :refer [vars]]
[missionary.core :as m]))
TODO use org.w3c.dom instead , or just drop this aspect of the UI .
(defprotocol ITextNode
(-get-text-content [this])
(-set-text-content! [this text]))
(deftype TextNode [^:volatile-mutable text]
ITextNode
(-get-text-content [this] text)
(-set-text-content! [this text'] (set! text text') this))
#?(:clj
(defmethod print-method TextNode [this w]
(print-simple (pr-str [:text (-get-text-content this)]) w)))
TODO use org.w3c.dom instead , or just drop this aspect of the UI .
(defprotocol INode
(-get-children [this])
(-append-child! [this child])
(-remove-child! [this child]))
(deftype Node [tag ^:volatile-mutable children]
INode
(-get-children [this] children)
(-append-child! [this child] (set! children (conj children child)) this)
(-remove-child! [this child] (set! children (disj children child)) this))
#?(:clj
(defmethod print-method Node [this w]
(print-simple (pr-str (into [(.tag this)] (-get-children this))) w)))
(defn create-text-node [initial-value] (TextNode. (str initial-value)))
(defn create-tag-node [tag] (Node. tag #{}))
(defn by-id [id] (Node. id #{}))
(defn set-text-content! [elem text] (-set-text-content! elem text))
(defn text [>text]
(let [elem (create-text-node "")]
(m/stream! (m/latest #(set-text-content! elem %) >text))
(m/ap elem)))
(defn append-childs [parent items] (reduce #(-append-child! %1 %2) parent items))
(defn remove-childs [parent items] (reduce #(-remove-child! %1 %2) parent items))
(defn mount [parent items]
(m/observe
(fn [!]
(! (append-childs parent items))
(fn []
(remove-childs parent items)))))
props not supported on SSR yet
(let [elem (create-tag-node elem)]
(when (seq (filter identity >childs))
(m/stream! (switch (apply m/latest #(mount elem %&) >childs))))
(m/ap elem)))
(defn append-child! [parent >child]
(m/stream! (switch (m/latest #(mount parent [%]) >child)))
parent)
(defn mount-component-at-node! [id >component]
(append-child! (by-id id) >component))
(def exports (vars by-id text tag mount-component-at-node!))
| |
d9565f5632638095eb3d180059f8192e9766de2601d691693b523f0fb97c55b1 | nuty/rapider | item.rkt | #lang racket
(require
sxml
racket/logging)
(define (extract-data html partern)
((sxpath partern) html))
(define (item-field
#:name name
#:xpath xpath
#:filter [filter (void)])
(list name xpath filter))
(define (make-item-hash fields)
(define item-hash (make-hash))
(for/list ([field (in-list fields)])
(let*
([name (first field)]
[xpath (second field)]
[filter (third field)])
(cond
[(equal? filter (void)) (hash-set! item-hash name (hash 'xpath xpath))]
[else
(hash-set! item-hash name (hash 'xpath xpath 'filter filter))])))
item-hash)
(define (item . fields)
(define item-hash (make-item-hash fields))
(define (parse-item doc)
(define result-hash (make-hash))
(for ([key (hash-keys item-hash)])
(let*
([meta (hash-ref item-hash key)]
[xpath (hash-ref meta 'xpath)]
[filter (if (hash-has-key? meta 'filter) (hash-ref meta 'filter) "")])
(cond
[(equal? filter "")
(let
([origin-data (extract-data doc xpath)])
(hash-set! result-hash key origin-data))]
[else
(let*
([origin-data (extract-data doc xpath)]
[filter-data (filter origin-data)])
(hash-set! result-hash key filter-data))])))
result-hash)
parse-item)
(define (save-to-csv
#:values values
#:csv-port csv-port
#:spliter [spliter ", "])
(define line (string-append (string-join values spliter) "\n"))
(display line csv-port)
(close-output-port csv-port))
(provide
save-to-csv
item
item-field
extract-data) | null | https://raw.githubusercontent.com/nuty/rapider/f167aa91522788e70affd49e8f350cd055dba3c4/rapider-lib/rapider/item.rkt | racket | #lang racket
(require
sxml
racket/logging)
(define (extract-data html partern)
((sxpath partern) html))
(define (item-field
#:name name
#:xpath xpath
#:filter [filter (void)])
(list name xpath filter))
(define (make-item-hash fields)
(define item-hash (make-hash))
(for/list ([field (in-list fields)])
(let*
([name (first field)]
[xpath (second field)]
[filter (third field)])
(cond
[(equal? filter (void)) (hash-set! item-hash name (hash 'xpath xpath))]
[else
(hash-set! item-hash name (hash 'xpath xpath 'filter filter))])))
item-hash)
(define (item . fields)
(define item-hash (make-item-hash fields))
(define (parse-item doc)
(define result-hash (make-hash))
(for ([key (hash-keys item-hash)])
(let*
([meta (hash-ref item-hash key)]
[xpath (hash-ref meta 'xpath)]
[filter (if (hash-has-key? meta 'filter) (hash-ref meta 'filter) "")])
(cond
[(equal? filter "")
(let
([origin-data (extract-data doc xpath)])
(hash-set! result-hash key origin-data))]
[else
(let*
([origin-data (extract-data doc xpath)]
[filter-data (filter origin-data)])
(hash-set! result-hash key filter-data))])))
result-hash)
parse-item)
(define (save-to-csv
#:values values
#:csv-port csv-port
#:spliter [spliter ", "])
(define line (string-append (string-join values spliter) "\n"))
(display line csv-port)
(close-output-port csv-port))
(provide
save-to-csv
item
item-field
extract-data) | |
6563226f325980f769538debbcaa02e353a549eb11554b99289d982181ba3681 | liamoc/holbert | Rule.hs | # LANGUAGE TypeFamilies , , DeriveGeneric , OverloadedStrings #
module Rule where
import qualified ProofTree as PT
import qualified Prop as P
import qualified Terms as T
import Controller
import Unification
import Debug.Trace
import Miso.String (MisoString, pack)
import Data.String
import qualified Miso.String as MS
import Optics.Core
import StringRep
import qualified Data.Char
import Control.Monad(when)
import Data.Maybe(fromMaybe,fromJust,mapMaybe)
import Data.List
import GHC.Generics(Generic)
import Data.Aeson (ToJSON,FromJSON)
import qualified Data.Map as M
data RuleType
= Axiom
| Theorem
| Inductive
deriving (Show, Eq, Generic, ToJSON, FromJSON)
data RuleItem = RI P.RuleName P.Prop (Maybe ProofState)
deriving (Show, Eq, Generic, ToJSON, FromJSON)
data Rule = R RuleType [RuleItem] [P.NamedProp]
deriving (Show, Eq, Generic, ToJSON, FromJSON)
type Counter = Int
data ProofState = PS PT.ProofTree Counter
deriving (Show, Eq, Generic, ToJSON, FromJSON)
name :: Lens' RuleItem P.RuleName
name = lensVL $ \act (RI n prp m) -> (\n' -> RI n' prp m) <$> act n
blank :: RuleType -> P.RuleName -> Rule
blank Axiom n = (R Axiom [RI n P.blank Nothing] [])
blank Inductive n = (R Inductive [RI n P.blank Nothing] [])
blank Theorem n = (R Theorem [RI n P.blank (Just $ PS (PT.fromProp P.blank) 0)] [])
ruleItems :: IxTraversal' Int Rule RuleItem
ruleItems = itraversalVL guts
where
guts f (R t ls rest) = R t <$> traverse (\(i, e) -> f i e) (zip [0..] ls) <*> pure rest
deleteItemFromRI :: Int -> [RuleItem] -> [RuleItem]
deleteItemFromRI _ [] = []
deleteItemFromRI n ris = left ++ right
where
(left , x:right) = splitAt n ris
-- warning, do not use this lens to assign to anything that might invalidate the proof state
-- use propUpdate for that (which will reset the proof state)
prop :: Lens' RuleItem P.Prop
prop = lensVL $ \act (RI n prp m) -> (\prp' -> RI n prp' m) <$> act prp
-- disjoint product of prop and name
namedProp :: Lens' RuleItem P.NamedProp
namedProp = lensVL $ \act (RI n prp m) -> (\(P.Defn n',prp') -> RI n' prp' m) <$> act (P.Defn n, prp)
propUpdate :: Setter' RuleItem P.Prop
propUpdate = sets guts
where
guts act (RI n p s)
| p' <- act p
= RI n p' (fmap (const $ PS (PT.fromProp p') 0) s)
proofState :: AffineTraversal' RuleItem ProofState
proofState = atraversal
(\i -> case i of RI _ _ (Just s) -> Right s
i -> Left i)
(\i s -> case i of RI n p (Just _) -> RI n p (Just s)
i -> i)
applyRewriteTactic :: RuleItem -> P.NamedProp -> Bool -> PT.Path -> Maybe RuleAction
applyRewriteTactic state np rev pth =
case traverseOf proofState (runUnifyPS $ PT.applyRewrite np rev pth) state of
Left _ -> Nothing
Right st' -> flip Tactic pth <$> preview proofState st'
applyERuleTactic :: RuleItem -> P.NamedProp -> P.NamedProp -> PT.Path -> Maybe RuleAction
applyERuleTactic state assm np pth =
case traverseOf proofState (runUnifyPS $ PT.applyElim np pth assm) state of
Left _ -> Nothing
Right st' -> flip Tactic pth <$> preview proofState st'
applyRuleTactic :: RuleItem -> P.NamedProp -> PT.Path -> Maybe RuleAction
applyRuleTactic state np pth =
case traverseOf proofState (runUnifyPS $ PT.apply np pth) state of
Left _ -> Nothing
Right st' -> flip Tactic pth <$> preview proofState st'
unresolved :: ProofState -> Bool
unresolved (PS pt c) = has PT.outstandingGoals pt
proofTree :: Lens' ProofState PT.ProofTree
proofTree = lensVL $ \act (PS pt c) -> flip PS c <$> act pt
runUnifyPS :: (PT.ProofTree -> UnifyM PT.ProofTree) -> ProofState -> Either UnifyError ProofState
runUnifyPS act (PS pt c) = case runUnifyM (act pt) c of
(Left e, c) -> Left e
(Right pt',c') -> Right (PS pt' c')
checkVariableName :: MS.MisoString -> Controller f ()
checkVariableName new = case T.invalidName new of
Just e -> errorMessage $ "Invalid variable name: " <> pack e
Nothing -> pure ()
data ProofFocus = GoalFocus Bool [(P.NamedProp, RuleAction)] -- bool is whether to show non-intro rules
| RewriteGoalFocus Bool [(P.NamedProp, RuleAction)] -- bool is rewrite direction
| AssumptionFocus Int [(P.NamedProp, RuleAction)]
| MetavariableFocus Int
| SubtitleFocus PT.Path
| ProofBinderFocus PT.Path Int deriving (Show, Eq)
data GoalSummary = GS [(PT.Path,Int,T.Name)] [(P.NamedProp, Maybe RuleAction)] T.Term PT.Path Bool deriving (Show, Eq)
getGoalSummary :: RuleItem -> PT.Path -> Maybe GoalSummary
getGoalSummary state' f = GS <$> pure (associate state' f)
<*> fmap (map tryApply . zip (map P.Local [0 ..]) . PT.locals . fst) (ipreview (PT.path f PT.%+ PT.step) =<< preview (proofState % proofTree) state')
<*> preview (proofState % proofTree % PT.path f % PT.inference) state'
<*> pure f <*> pure False
where
tryApply r = (r, applyRuleTactic state' r f)
associate (RI _ _ (Just (PS pt _))) f = go [] (reverse f) pt
go pth [] pt = zipWith (\i n -> (pth, i, n)) [0..] (view PT.goalbinders pt)
go pth (x:xs) pt = zipWith (\i n -> (pth, i, n)) [0..] (view PT.goalbinders pt) ++ case preview (PT.subgoal x) pt of
Nothing -> []
Just sg -> go (x:pth) xs sg
data RuleFocus = ProofFocus ProofFocus (Maybe GoalSummary)
| RuleBinderFocus P.Path Int
| NewRuleBinderFocus P.Path
| RuleTermFocus P.Path
| NameFocus
deriving (Show, Eq)
data RuleAction = Tactic ProofState PT.Path
| SetStyle PT.Path PT.ProofStyle
| SetSubgoalHeading PT.Path
| Nix PT.Path
| SelectGoal PT.Path Bool -- bool is to show non-intro rules or not
| ExamineAssumption Int
| RewriteGoal Bool
| RenameProofBinder PT.Path Int
| AddRuleBinder P.Path
| RenameRuleBinder P.Path Int
| DeleteRuleBinder P.Path Int
| UpdateTerm P.Path
| AddPremise P.Path
| DeletePremise P.Path
| Rename
| InstantiateMetavariable Int
| DeleteRI
deriving (Show, Eq)
editableRI tbl (ProofFocus (ProofBinderFocus pth i) g) = preview (proofState % proofTree % PT.path pth % PT.goalbinders % ix i)
editableRI tbl (RuleBinderFocus pth i) = preview (prop % P.path pth % P.metabinders % ix i)
editableRI tbl (RuleTermFocus pth) = Just . P.getConclusionString tbl pth . view prop
editableRI tbl (ProofFocus (MetavariableFocus i) g) = const (Just ("?" <> pack (show i)))
editableRI tbl NameFocus = preview name
editableRI tbl (ProofFocus (SubtitleFocus pth) g) = fmap (fromMaybe "Show:" . fmap PT.subtitle) . preview (proofState % proofTree % PT.path pth % PT.displaydata)
editableRI _ _ = const Nothing
leaveFocusRI (ProofFocus (ProofBinderFocus p i) g) = noFocus . handleRI (RenameProofBinder p i) --These define the action when the user leaves focus on an item
leaveFocusRI (RuleBinderFocus p i) = noFocus . handleRI (RenameRuleBinder p i)
leaveFocusRI (NewRuleBinderFocus p) = noFocus . handleRI (AddRuleBinder p)
leaveFocusRI (RuleTermFocus p) = noFocus . handleRI (UpdateTerm p)
leaveFocusRI NameFocus = noFocus . handleRI Rename
TODO handle other foci ?
leaveFocusRI _ = pure
handleRI :: RuleAction -> RuleItem -> Controller RuleFocus RuleItem
handleRI (SelectGoal pth b) state = do
let summary = getGoalSummary state pth
rules <- filter (if b then const True else P.isIntroduction . snd) <$> getKnownRules
setFocus (ProofFocus (GoalFocus b $ mapMaybe (\r -> (,) r <$> applyRuleTactic state r pth) rules) summary)
pure state
handleRI (ExamineAssumption i) state = do
foc <- getOriginalFocus
case foc of
Just (ProofFocus _ (Just gs@(GS _ lcls _ p _))) | (it:_) <- drop i lcls -> do
rules <- getKnownRules
setFocus (ProofFocus (AssumptionFocus i (mapMaybe (\r -> (,) r <$> applyERuleTactic state (fst it) r p) rules)) (Just gs))
pure state
_ -> pure state
handleRI (RewriteGoal rev) state = do
foc <- getOriginalFocus
case foc of
Just (ProofFocus _ (Just gs@(GS _ lcls t p _))) ->
case applyRuleTactic state P.builtInRefl p of
Just a -> handleRI a state
Nothing -> do
rules <- filter (P.isRewrite . snd) . (map fst lcls ++) <$> getKnownRules
setFocus (ProofFocus (RewriteGoalFocus rev (mapMaybe (\r -> (,) r <$> applyRewriteTactic state r rev p ) rules)) (Just gs))
pure state
_ -> pure state
handleRI (Tactic ps pth) state = let
state' = set proofState ps state
newFocus = if has (proofState % proofTree % PT.path (0:pth)) state'
then Just (0:pth)
else fst <$> ipreview (isingular (proofState % proofTree % PT.outstandingGoals)) state'
in do
case newFocus of
Just f -> handleRI (SelectGoal f False) state'
_ -> clearFocus >> pure state'
handleRI (SetStyle pth st) state = do
let f Nothing = Just (PT.PDD { PT.style = st, PT.subtitle = "Show:" })
f (Just pdd) = Just $ pdd { PT.style = st}
pure $ over (proofState % proofTree % PT.path pth % PT.displaydata) f state
handleRI (SetSubgoalHeading pth) state = do
new <- textInput
let f Nothing = Just (PT.PDD { PT.style = PT.Tree, PT.subtitle = new })
f (Just pdd) = Just $ pdd { PT.subtitle = new }
foc <- getOriginalFocus
let state' = over (proofState % proofTree % PT.path pth % PT.displaydata) f state
case foc of
Just (ProofFocus _ (Just (GS _ _ _ p _))) -> handleRI (SelectGoal p False) state'
_ -> pure state'
handleRI (Nix pth) state = do
clearFocus
pure $ set (proofState % proofTree % PT.path pth % PT.step) Nothing state
handleRI (RenameProofBinder pth i) state = do
new <- textInput
checkVariableName new
let state' = set (proofState % proofTree % PT.path pth % PT.goalbinders % ix i) new state
foc <- getOriginalFocus
case foc of
Just (ProofFocus _ (Just (GS _ _ _ p _))) -> handleRI (SelectGoal p False) state'
_ -> pure state'
handleRI (AddRuleBinder pth) state = do
new <- textInput
let news = filter (not . MS.null) (MS.splitOn "." new)
mapM checkVariableName news
invalidate (view name state)
setFocus (RuleTermFocus pth)
pure $ over (propUpdate % P.path pth) (P.addBinders news) state
handleRI (RenameRuleBinder pth i) state = do
new <- textInput
checkVariableName new
clearFocus -- should it be updateterm?
pure $ set (prop % P.path pth % P.metabinders % ix i) new state
handleRI (DeleteRuleBinder pth i) state = do
when (maybe False (P.isBinderUsed i) $ preview (prop % P.path pth) state) $ errorMessage "Cannot remove binder: is in use"
invalidate (view name state)
clearFocus
pure $ over (propUpdate % P.path pth) (P.removeBinder i) state
handleRI (UpdateTerm pth) state = do
new <- textInput
tbl <- syntaxTable
case toLensVL prop (P.setConclusionString tbl pth new) state of
Left e -> errorMessage $ "Parse error: " <> e
Right state' -> do
invalidate (view name state')
case pth of [] -> clearFocus
(_:pth') -> setFocus (RuleTermFocus pth')
pure $ over propUpdate id state' --hack..
handleRI (InstantiateMetavariable i) state = do
new <- textInput
tbl <- syntaxTable
case parse tbl [] new of
Left e -> errorMessage $ "Parse error: " <> e
Right obj -> do
foc <- getOriginalFocus
let state' = over (proofState % proofTree) (PT.applySubst (T.fromUnifier [(i,obj)])) state
case foc of
Just (ProofFocus _ (Just (GS _ _ _ p _))) -> handleRI (SelectGoal p False) state'
_ -> pure state'
handleRI (AddPremise pth) state = do
invalidate (view name state)
let newIndex = length $ fromMaybe [] (preview (prop % P.path pth % P.premises) state)
setFocusWithLeaving (RuleTermFocus (newIndex:pth))
pure $ over (propUpdate % P.path pth % P.premises) (++[P.blank]) state
handleRI (DeletePremise []) state = pure state -- shouldn't happen
handleRI (DeletePremise (x:pth)) state = do
invalidate (view name state)
setFocus (RuleTermFocus (pth))
pure $ over (propUpdate % P.path pth) (P.removePremise x) state
handleRI Rename state = do
new <- textInput
when (new == "") $ errorMessage "Name cannot be empty"
when (MS.all Data.Char.isSpace new) $ errorMessage "Name cannot be empty"
renameResource (view name state) new
clearFocus
pure $ set name new state
generateDerivedRules :: [P.RuleName] -> RuleType -> [RuleItem] -> Controller (Focus Rule) [P.NamedProp]
generateDerivedRules old Inductive rs =
let rs' = filter P.isIntroduction (map (view prop) rs)
definitions = foldr (\x m -> M.insertWith (++) (P.introRoot x) [x] m) M.empty rs'
caseRules = map snd $ M.toList $ M.mapWithKey (\(k,i) intros -> P.caseRule k i intros) definitions
allIntros = concatMap snd $ M.toList definitions
inductionRules = map snd $ M.toList $ M.mapWithKey (\(k,i) intros -> P.inductionRule k i (M.keys definitions) allIntros) definitions
newRules = caseRules ++ inductionRules
in do generateDiffs old (mapMaybe (P.defnName . fst) newRules)
pure newRules
where
generateDiffs old [] = mapM_ invalidate old
generateDiffs old (n:ns) | n `notElem` old = newResource n >> generateDiffs old ns
| otherwise = generateDiffs old ns
generateDerivedRules _ _ _ = pure []
instance Control Rule where
data Focus Rule = RF Int RuleFocus
| AddingRule
deriving (Show, Eq)
data Action Rule = RA Int RuleAction
| AddRule
deriving (Show, Eq)
defined (R _ ls rest) = map (\(RI n prp _) -> (P.Defn n,prp) ) ls ++ rest
inserted _ = RF 0 (RuleTermFocus [])
invalidated s r = over (ruleItems % proofState % proofTree) (PT.clear s) r
renamed (s,s') r = over (ruleItems % proofState % proofTree) (PT.renameRule (s,s')) r
editable tbl (RF i rf) (R _ ls _) = editableRI tbl rf (ls !! i)
editable tbl AddingRule _ = Nothing
leaveFocus (RF i rf) r = atraverseOf (elementOf ruleItems i) pure (leaveFocusRI rf) r
leaveFocus AddingRule r = pure r
handle (RA i DeleteRI) r@(R ruleType lst rest) = do
let (left , x:right) = splitAt i lst
let ruleName = view name x
invalidate ruleName
rest' <- generateDerivedRules (mapMaybe (P.defnName . fst) rest) ruleType (left ++ right)
pure (R ruleType (left ++ right) rest')
handle (RA i a) r = do
R t sgs rest <- zoomFocus (RF i) (\(RF i' rf) -> if i == i' then Just rf else Nothing)
(atraverseOf (elementOf ruleItems i) pure (handleRI a) r)
b <- anyInvalidated
if b then do
rest' <- generateDerivedRules (mapMaybe (P.defnName . fst) rest) t sgs
pure (R t sgs rest')
else pure (R t sgs rest)
handle AddRule (R t ls rest) = do
name <- textInput
newResource name
rest' <- generateDerivedRules (mapMaybe (P.defnName . fst) rest) t (ls ++ [RI name P.blank Nothing])
let s' = R t (ls ++ [RI name P.blank Nothing]) rest'
setFocus (RF (length ls) $ RuleTermFocus [])
pure s'
| null | https://raw.githubusercontent.com/liamoc/holbert/2733be72ac99cab4db9a804c097e5e6e3a7c3334/Rule.hs | haskell | warning, do not use this lens to assign to anything that might invalidate the proof state
use propUpdate for that (which will reset the proof state)
disjoint product of prop and name
bool is whether to show non-intro rules
bool is rewrite direction
bool is to show non-intro rules or not
These define the action when the user leaves focus on an item
should it be updateterm?
hack..
shouldn't happen | # LANGUAGE TypeFamilies , , DeriveGeneric , OverloadedStrings #
module Rule where
import qualified ProofTree as PT
import qualified Prop as P
import qualified Terms as T
import Controller
import Unification
import Debug.Trace
import Miso.String (MisoString, pack)
import Data.String
import qualified Miso.String as MS
import Optics.Core
import StringRep
import qualified Data.Char
import Control.Monad(when)
import Data.Maybe(fromMaybe,fromJust,mapMaybe)
import Data.List
import GHC.Generics(Generic)
import Data.Aeson (ToJSON,FromJSON)
import qualified Data.Map as M
data RuleType
= Axiom
| Theorem
| Inductive
deriving (Show, Eq, Generic, ToJSON, FromJSON)
data RuleItem = RI P.RuleName P.Prop (Maybe ProofState)
deriving (Show, Eq, Generic, ToJSON, FromJSON)
data Rule = R RuleType [RuleItem] [P.NamedProp]
deriving (Show, Eq, Generic, ToJSON, FromJSON)
type Counter = Int
data ProofState = PS PT.ProofTree Counter
deriving (Show, Eq, Generic, ToJSON, FromJSON)
name :: Lens' RuleItem P.RuleName
name = lensVL $ \act (RI n prp m) -> (\n' -> RI n' prp m) <$> act n
blank :: RuleType -> P.RuleName -> Rule
blank Axiom n = (R Axiom [RI n P.blank Nothing] [])
blank Inductive n = (R Inductive [RI n P.blank Nothing] [])
blank Theorem n = (R Theorem [RI n P.blank (Just $ PS (PT.fromProp P.blank) 0)] [])
ruleItems :: IxTraversal' Int Rule RuleItem
ruleItems = itraversalVL guts
where
guts f (R t ls rest) = R t <$> traverse (\(i, e) -> f i e) (zip [0..] ls) <*> pure rest
deleteItemFromRI :: Int -> [RuleItem] -> [RuleItem]
deleteItemFromRI _ [] = []
deleteItemFromRI n ris = left ++ right
where
(left , x:right) = splitAt n ris
prop :: Lens' RuleItem P.Prop
prop = lensVL $ \act (RI n prp m) -> (\prp' -> RI n prp' m) <$> act prp
namedProp :: Lens' RuleItem P.NamedProp
namedProp = lensVL $ \act (RI n prp m) -> (\(P.Defn n',prp') -> RI n' prp' m) <$> act (P.Defn n, prp)
propUpdate :: Setter' RuleItem P.Prop
propUpdate = sets guts
where
guts act (RI n p s)
| p' <- act p
= RI n p' (fmap (const $ PS (PT.fromProp p') 0) s)
proofState :: AffineTraversal' RuleItem ProofState
proofState = atraversal
(\i -> case i of RI _ _ (Just s) -> Right s
i -> Left i)
(\i s -> case i of RI n p (Just _) -> RI n p (Just s)
i -> i)
applyRewriteTactic :: RuleItem -> P.NamedProp -> Bool -> PT.Path -> Maybe RuleAction
applyRewriteTactic state np rev pth =
case traverseOf proofState (runUnifyPS $ PT.applyRewrite np rev pth) state of
Left _ -> Nothing
Right st' -> flip Tactic pth <$> preview proofState st'
applyERuleTactic :: RuleItem -> P.NamedProp -> P.NamedProp -> PT.Path -> Maybe RuleAction
applyERuleTactic state assm np pth =
case traverseOf proofState (runUnifyPS $ PT.applyElim np pth assm) state of
Left _ -> Nothing
Right st' -> flip Tactic pth <$> preview proofState st'
applyRuleTactic :: RuleItem -> P.NamedProp -> PT.Path -> Maybe RuleAction
applyRuleTactic state np pth =
case traverseOf proofState (runUnifyPS $ PT.apply np pth) state of
Left _ -> Nothing
Right st' -> flip Tactic pth <$> preview proofState st'
unresolved :: ProofState -> Bool
unresolved (PS pt c) = has PT.outstandingGoals pt
proofTree :: Lens' ProofState PT.ProofTree
proofTree = lensVL $ \act (PS pt c) -> flip PS c <$> act pt
runUnifyPS :: (PT.ProofTree -> UnifyM PT.ProofTree) -> ProofState -> Either UnifyError ProofState
runUnifyPS act (PS pt c) = case runUnifyM (act pt) c of
(Left e, c) -> Left e
(Right pt',c') -> Right (PS pt' c')
checkVariableName :: MS.MisoString -> Controller f ()
checkVariableName new = case T.invalidName new of
Just e -> errorMessage $ "Invalid variable name: " <> pack e
Nothing -> pure ()
| AssumptionFocus Int [(P.NamedProp, RuleAction)]
| MetavariableFocus Int
| SubtitleFocus PT.Path
| ProofBinderFocus PT.Path Int deriving (Show, Eq)
data GoalSummary = GS [(PT.Path,Int,T.Name)] [(P.NamedProp, Maybe RuleAction)] T.Term PT.Path Bool deriving (Show, Eq)
getGoalSummary :: RuleItem -> PT.Path -> Maybe GoalSummary
getGoalSummary state' f = GS <$> pure (associate state' f)
<*> fmap (map tryApply . zip (map P.Local [0 ..]) . PT.locals . fst) (ipreview (PT.path f PT.%+ PT.step) =<< preview (proofState % proofTree) state')
<*> preview (proofState % proofTree % PT.path f % PT.inference) state'
<*> pure f <*> pure False
where
tryApply r = (r, applyRuleTactic state' r f)
associate (RI _ _ (Just (PS pt _))) f = go [] (reverse f) pt
go pth [] pt = zipWith (\i n -> (pth, i, n)) [0..] (view PT.goalbinders pt)
go pth (x:xs) pt = zipWith (\i n -> (pth, i, n)) [0..] (view PT.goalbinders pt) ++ case preview (PT.subgoal x) pt of
Nothing -> []
Just sg -> go (x:pth) xs sg
data RuleFocus = ProofFocus ProofFocus (Maybe GoalSummary)
| RuleBinderFocus P.Path Int
| NewRuleBinderFocus P.Path
| RuleTermFocus P.Path
| NameFocus
deriving (Show, Eq)
data RuleAction = Tactic ProofState PT.Path
| SetStyle PT.Path PT.ProofStyle
| SetSubgoalHeading PT.Path
| Nix PT.Path
| ExamineAssumption Int
| RewriteGoal Bool
| RenameProofBinder PT.Path Int
| AddRuleBinder P.Path
| RenameRuleBinder P.Path Int
| DeleteRuleBinder P.Path Int
| UpdateTerm P.Path
| AddPremise P.Path
| DeletePremise P.Path
| Rename
| InstantiateMetavariable Int
| DeleteRI
deriving (Show, Eq)
editableRI tbl (ProofFocus (ProofBinderFocus pth i) g) = preview (proofState % proofTree % PT.path pth % PT.goalbinders % ix i)
editableRI tbl (RuleBinderFocus pth i) = preview (prop % P.path pth % P.metabinders % ix i)
editableRI tbl (RuleTermFocus pth) = Just . P.getConclusionString tbl pth . view prop
editableRI tbl (ProofFocus (MetavariableFocus i) g) = const (Just ("?" <> pack (show i)))
editableRI tbl NameFocus = preview name
editableRI tbl (ProofFocus (SubtitleFocus pth) g) = fmap (fromMaybe "Show:" . fmap PT.subtitle) . preview (proofState % proofTree % PT.path pth % PT.displaydata)
editableRI _ _ = const Nothing
leaveFocusRI (RuleBinderFocus p i) = noFocus . handleRI (RenameRuleBinder p i)
leaveFocusRI (NewRuleBinderFocus p) = noFocus . handleRI (AddRuleBinder p)
leaveFocusRI (RuleTermFocus p) = noFocus . handleRI (UpdateTerm p)
leaveFocusRI NameFocus = noFocus . handleRI Rename
TODO handle other foci ?
leaveFocusRI _ = pure
handleRI :: RuleAction -> RuleItem -> Controller RuleFocus RuleItem
handleRI (SelectGoal pth b) state = do
let summary = getGoalSummary state pth
rules <- filter (if b then const True else P.isIntroduction . snd) <$> getKnownRules
setFocus (ProofFocus (GoalFocus b $ mapMaybe (\r -> (,) r <$> applyRuleTactic state r pth) rules) summary)
pure state
handleRI (ExamineAssumption i) state = do
foc <- getOriginalFocus
case foc of
Just (ProofFocus _ (Just gs@(GS _ lcls _ p _))) | (it:_) <- drop i lcls -> do
rules <- getKnownRules
setFocus (ProofFocus (AssumptionFocus i (mapMaybe (\r -> (,) r <$> applyERuleTactic state (fst it) r p) rules)) (Just gs))
pure state
_ -> pure state
handleRI (RewriteGoal rev) state = do
foc <- getOriginalFocus
case foc of
Just (ProofFocus _ (Just gs@(GS _ lcls t p _))) ->
case applyRuleTactic state P.builtInRefl p of
Just a -> handleRI a state
Nothing -> do
rules <- filter (P.isRewrite . snd) . (map fst lcls ++) <$> getKnownRules
setFocus (ProofFocus (RewriteGoalFocus rev (mapMaybe (\r -> (,) r <$> applyRewriteTactic state r rev p ) rules)) (Just gs))
pure state
_ -> pure state
handleRI (Tactic ps pth) state = let
state' = set proofState ps state
newFocus = if has (proofState % proofTree % PT.path (0:pth)) state'
then Just (0:pth)
else fst <$> ipreview (isingular (proofState % proofTree % PT.outstandingGoals)) state'
in do
case newFocus of
Just f -> handleRI (SelectGoal f False) state'
_ -> clearFocus >> pure state'
handleRI (SetStyle pth st) state = do
let f Nothing = Just (PT.PDD { PT.style = st, PT.subtitle = "Show:" })
f (Just pdd) = Just $ pdd { PT.style = st}
pure $ over (proofState % proofTree % PT.path pth % PT.displaydata) f state
handleRI (SetSubgoalHeading pth) state = do
new <- textInput
let f Nothing = Just (PT.PDD { PT.style = PT.Tree, PT.subtitle = new })
f (Just pdd) = Just $ pdd { PT.subtitle = new }
foc <- getOriginalFocus
let state' = over (proofState % proofTree % PT.path pth % PT.displaydata) f state
case foc of
Just (ProofFocus _ (Just (GS _ _ _ p _))) -> handleRI (SelectGoal p False) state'
_ -> pure state'
handleRI (Nix pth) state = do
clearFocus
pure $ set (proofState % proofTree % PT.path pth % PT.step) Nothing state
handleRI (RenameProofBinder pth i) state = do
new <- textInput
checkVariableName new
let state' = set (proofState % proofTree % PT.path pth % PT.goalbinders % ix i) new state
foc <- getOriginalFocus
case foc of
Just (ProofFocus _ (Just (GS _ _ _ p _))) -> handleRI (SelectGoal p False) state'
_ -> pure state'
handleRI (AddRuleBinder pth) state = do
new <- textInput
let news = filter (not . MS.null) (MS.splitOn "." new)
mapM checkVariableName news
invalidate (view name state)
setFocus (RuleTermFocus pth)
pure $ over (propUpdate % P.path pth) (P.addBinders news) state
handleRI (RenameRuleBinder pth i) state = do
new <- textInput
checkVariableName new
pure $ set (prop % P.path pth % P.metabinders % ix i) new state
handleRI (DeleteRuleBinder pth i) state = do
when (maybe False (P.isBinderUsed i) $ preview (prop % P.path pth) state) $ errorMessage "Cannot remove binder: is in use"
invalidate (view name state)
clearFocus
pure $ over (propUpdate % P.path pth) (P.removeBinder i) state
handleRI (UpdateTerm pth) state = do
new <- textInput
tbl <- syntaxTable
case toLensVL prop (P.setConclusionString tbl pth new) state of
Left e -> errorMessage $ "Parse error: " <> e
Right state' -> do
invalidate (view name state')
case pth of [] -> clearFocus
(_:pth') -> setFocus (RuleTermFocus pth')
handleRI (InstantiateMetavariable i) state = do
new <- textInput
tbl <- syntaxTable
case parse tbl [] new of
Left e -> errorMessage $ "Parse error: " <> e
Right obj -> do
foc <- getOriginalFocus
let state' = over (proofState % proofTree) (PT.applySubst (T.fromUnifier [(i,obj)])) state
case foc of
Just (ProofFocus _ (Just (GS _ _ _ p _))) -> handleRI (SelectGoal p False) state'
_ -> pure state'
handleRI (AddPremise pth) state = do
invalidate (view name state)
let newIndex = length $ fromMaybe [] (preview (prop % P.path pth % P.premises) state)
setFocusWithLeaving (RuleTermFocus (newIndex:pth))
pure $ over (propUpdate % P.path pth % P.premises) (++[P.blank]) state
handleRI (DeletePremise (x:pth)) state = do
invalidate (view name state)
setFocus (RuleTermFocus (pth))
pure $ over (propUpdate % P.path pth) (P.removePremise x) state
handleRI Rename state = do
new <- textInput
when (new == "") $ errorMessage "Name cannot be empty"
when (MS.all Data.Char.isSpace new) $ errorMessage "Name cannot be empty"
renameResource (view name state) new
clearFocus
pure $ set name new state
generateDerivedRules :: [P.RuleName] -> RuleType -> [RuleItem] -> Controller (Focus Rule) [P.NamedProp]
generateDerivedRules old Inductive rs =
let rs' = filter P.isIntroduction (map (view prop) rs)
definitions = foldr (\x m -> M.insertWith (++) (P.introRoot x) [x] m) M.empty rs'
caseRules = map snd $ M.toList $ M.mapWithKey (\(k,i) intros -> P.caseRule k i intros) definitions
allIntros = concatMap snd $ M.toList definitions
inductionRules = map snd $ M.toList $ M.mapWithKey (\(k,i) intros -> P.inductionRule k i (M.keys definitions) allIntros) definitions
newRules = caseRules ++ inductionRules
in do generateDiffs old (mapMaybe (P.defnName . fst) newRules)
pure newRules
where
generateDiffs old [] = mapM_ invalidate old
generateDiffs old (n:ns) | n `notElem` old = newResource n >> generateDiffs old ns
| otherwise = generateDiffs old ns
generateDerivedRules _ _ _ = pure []
instance Control Rule where
data Focus Rule = RF Int RuleFocus
| AddingRule
deriving (Show, Eq)
data Action Rule = RA Int RuleAction
| AddRule
deriving (Show, Eq)
defined (R _ ls rest) = map (\(RI n prp _) -> (P.Defn n,prp) ) ls ++ rest
inserted _ = RF 0 (RuleTermFocus [])
invalidated s r = over (ruleItems % proofState % proofTree) (PT.clear s) r
renamed (s,s') r = over (ruleItems % proofState % proofTree) (PT.renameRule (s,s')) r
editable tbl (RF i rf) (R _ ls _) = editableRI tbl rf (ls !! i)
editable tbl AddingRule _ = Nothing
leaveFocus (RF i rf) r = atraverseOf (elementOf ruleItems i) pure (leaveFocusRI rf) r
leaveFocus AddingRule r = pure r
handle (RA i DeleteRI) r@(R ruleType lst rest) = do
let (left , x:right) = splitAt i lst
let ruleName = view name x
invalidate ruleName
rest' <- generateDerivedRules (mapMaybe (P.defnName . fst) rest) ruleType (left ++ right)
pure (R ruleType (left ++ right) rest')
handle (RA i a) r = do
R t sgs rest <- zoomFocus (RF i) (\(RF i' rf) -> if i == i' then Just rf else Nothing)
(atraverseOf (elementOf ruleItems i) pure (handleRI a) r)
b <- anyInvalidated
if b then do
rest' <- generateDerivedRules (mapMaybe (P.defnName . fst) rest) t sgs
pure (R t sgs rest')
else pure (R t sgs rest)
handle AddRule (R t ls rest) = do
name <- textInput
newResource name
rest' <- generateDerivedRules (mapMaybe (P.defnName . fst) rest) t (ls ++ [RI name P.blank Nothing])
let s' = R t (ls ++ [RI name P.blank Nothing]) rest'
setFocus (RF (length ls) $ RuleTermFocus [])
pure s'
|
9af92d39e526d32640f1777c1013e633f56129881b472407fdb71de31cbe0cd7 | mwotton/Hubris-Haskell | Setup.hs | # LANGUAGE NamedFieldPuns #
import Distribution.Simple
import Distribution.Simple.Setup
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Utils
import qualified Distribution.PackageDescription as D
import Distribution.Verbosity
import System.Directory
import System.Process
import Maybe
import qualified Distribution.ModuleName as Modname
main = do
includeDir <- readProcess "ruby" ["-rrbconfig", "-e", "print RbConfig::CONFIG['rubyhdrdir']"] ""
archDir <- readProcess "ruby" ["-rrbconfig", "-e", "print RbConfig::CONFIG['archdir'].gsub(/\\/lib\\//, '/include/')"] ""
defaultMainWithHooks (hooks includeDir archDir)
hooks includeDir archDir = simpleUserHooks
{
preConf = \arg flags -> do
-- probably a nicer way of getting that directory...
createDirectoryIfMissing True "dist/build/autogen"
-- FILTHY HACK
writeFile "dist/build/autogen/Includes.hs" ("module Includes where\nextraIncludeDirs=[\"" ++ includeDir++"\",\"" ++ archDir ++ "\"]") -- show (configExtraIncludeDirs flags))
return D.emptyHookedBuildInfo,
confHook = \ info flags -> (confHook simpleUserHooks) info (flags { configSharedLib = Flag True, configExtraIncludeDirs = [includeDir] }),
sDistHook = \ pkg lbi hooks flags -> let lib = fromJust $ D.library pkg
modules = filter (/= Modname.fromString "Includes") $ D.exposedModules lib
pkg' = pkg { D.library = Just $ lib { D.exposedModules = modules } }
in sDistHook simpleUserHooks pkg' lbi hooks flags
}
| null | https://raw.githubusercontent.com/mwotton/Hubris-Haskell/3b81cb8244118c63dab8b415fb1a59960d728c0f/Setup.hs | haskell | probably a nicer way of getting that directory...
FILTHY HACK
show (configExtraIncludeDirs flags)) | # LANGUAGE NamedFieldPuns #
import Distribution.Simple
import Distribution.Simple.Setup
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Utils
import qualified Distribution.PackageDescription as D
import Distribution.Verbosity
import System.Directory
import System.Process
import Maybe
import qualified Distribution.ModuleName as Modname
main = do
includeDir <- readProcess "ruby" ["-rrbconfig", "-e", "print RbConfig::CONFIG['rubyhdrdir']"] ""
archDir <- readProcess "ruby" ["-rrbconfig", "-e", "print RbConfig::CONFIG['archdir'].gsub(/\\/lib\\//, '/include/')"] ""
defaultMainWithHooks (hooks includeDir archDir)
hooks includeDir archDir = simpleUserHooks
{
preConf = \arg flags -> do
createDirectoryIfMissing True "dist/build/autogen"
return D.emptyHookedBuildInfo,
confHook = \ info flags -> (confHook simpleUserHooks) info (flags { configSharedLib = Flag True, configExtraIncludeDirs = [includeDir] }),
sDistHook = \ pkg lbi hooks flags -> let lib = fromJust $ D.library pkg
modules = filter (/= Modname.fromString "Includes") $ D.exposedModules lib
pkg' = pkg { D.library = Just $ lib { D.exposedModules = modules } }
in sDistHook simpleUserHooks pkg' lbi hooks flags
}
|
b0a11081c31aefb31953dea00f43889a794895fbb326ba672c94531bc978f31a | rudymatela/speculate | arithficial.hs | import QuickSpec
f :: Num a => a -> a -> a
f x y = x*17+23
g :: Num a => a -> a -> a
g x y = 42
h :: Num a => a -> a -> a
h x y = y*13+19
main = quickSpec signature
{ maxTermSize = Just 5
, constants =
[ constant "0" (0 :: Int)
, constant "id" (id :: Int -> Int)
, constant "+" ((+) :: Int -> Int -> Int)
, constant "f" (f :: Int -> Int -> Int)
, constant "g" (g :: Int -> Int -> Int)
, constant "h" (h :: Int -> Int -> Int)
]
}
| null | https://raw.githubusercontent.com/rudymatela/speculate/8ec39747d03033db4349d554467d4b78bb72935d/bench/qs2/arithficial.hs | haskell | import QuickSpec
f :: Num a => a -> a -> a
f x y = x*17+23
g :: Num a => a -> a -> a
g x y = 42
h :: Num a => a -> a -> a
h x y = y*13+19
main = quickSpec signature
{ maxTermSize = Just 5
, constants =
[ constant "0" (0 :: Int)
, constant "id" (id :: Int -> Int)
, constant "+" ((+) :: Int -> Int -> Int)
, constant "f" (f :: Int -> Int -> Int)
, constant "g" (g :: Int -> Int -> Int)
, constant "h" (h :: Int -> Int -> Int)
]
}
| |
e44c754513e64127bf7644665a89b9372ab72720f93c21166ad15d6233fc3d30 | semerdzhiev/fp-2020-21 | solutions.rkt | #lang racket
(define (id x) x)
(define (accumulate from to op term acc)
(if (> from to)
acc
(accumulate (+ from 1)
to
op
term
(op acc (term from)))))
(define (meetTwice? f g a b)
(define (p? x) (= (f x) (g x)))
(define (op acc x)
(if (p? x)
(+ acc 1)
acc))
(<= 2
(accumulate
a
b
op
id
0)))
(meetTwice? (lambda (x) x) sqrt 0 5)
1
число 12345
дължина n = 5
x = 0
n - x = 5
x = 2
n - x = 3
12345
234
3
(define (reverse-num-acc n)
(define (op acc x)
(+ (* acc 10) (remainder (quotient n (expt 10 x)) 10)))
(accumulate n
(floor (log n 10))
op
id
0))
acc = 12345
x = 0
to = 5
(define (op acc x)
1234
(expt 10 (- (floor (log acc 10)) 1))))
acc = 12345
1234 % 10 ^ 3
; 10^n
; n - 2 (дължината на acc - 2)
; 1234567
123456 % 10 ^ 5
(op 12345 2)
Вложена дефиниция и пазим на обръщането
в допълнителна променлива
log 10 n - пъти
(define (reverse-num n)
(define (iter k m)
(if (= k 0)
m
(iter (quotient k 10) (+ (* m 10) (remainder k 10)))))
(iter n 0))
(reverse-num-acc 12345)
; k m
12345 0
1234 5
123 54
12 543
; ...
| null | https://raw.githubusercontent.com/semerdzhiev/fp-2020-21/64fa00c4f940f75a28cc5980275b124ca21244bc/group-d/pre-exam-1/solutions.rkt | racket | 10^n
n - 2 (дължината на acc - 2)
1234567
k m
... | #lang racket
(define (id x) x)
(define (accumulate from to op term acc)
(if (> from to)
acc
(accumulate (+ from 1)
to
op
term
(op acc (term from)))))
(define (meetTwice? f g a b)
(define (p? x) (= (f x) (g x)))
(define (op acc x)
(if (p? x)
(+ acc 1)
acc))
(<= 2
(accumulate
a
b
op
id
0)))
(meetTwice? (lambda (x) x) sqrt 0 5)
1
число 12345
дължина n = 5
x = 0
n - x = 5
x = 2
n - x = 3
12345
234
3
(define (reverse-num-acc n)
(define (op acc x)
(+ (* acc 10) (remainder (quotient n (expt 10 x)) 10)))
(accumulate n
(floor (log n 10))
op
id
0))
acc = 12345
x = 0
to = 5
(define (op acc x)
1234
(expt 10 (- (floor (log acc 10)) 1))))
acc = 12345
1234 % 10 ^ 3
123456 % 10 ^ 5
(op 12345 2)
Вложена дефиниция и пазим на обръщането
в допълнителна променлива
log 10 n - пъти
(define (reverse-num n)
(define (iter k m)
(if (= k 0)
m
(iter (quotient k 10) (+ (* m 10) (remainder k 10)))))
(iter n 0))
(reverse-num-acc 12345)
12345 0
1234 5
123 54
12 543
|
e5acaef551c5fc8bd16fedd1950dad19c116499a91c50a556de558a369ef3400 | OCamlPro/typerex-lint | web_main.ml | (**************************************************************************)
(* *)
(* OCamlPro Typerex *)
(* *)
Copyright OCamlPro 2011 - 2016 . All rights reserved .
(* This file is distributed under the terms of the GPL v3.0 *)
( GNU General Public Licence version 3.0 ) .
(* *)
(* Contact: <> (/) *)
(* *)
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. *)
(**************************************************************************)
open Tyxml_js.Html
open Lint_warning_types
open Lint_web_analysis_info
open Web_errors
let header =
div
~a:[
a_class ["ocp-lint-web-header"]
]
[
h1 [pcdata "ocp-lint-web"];
]
let footer analysis_info =
let open Unix in
let time = analysis_info.analysis_date in
let msg =
Printf.sprintf "generated the %04d-%02d-%02d at %02d:%02d from %s"
(1900 + time.tm_year)
(time.tm_mon + 1)
time.tm_mday
time.tm_hour
time.tm_min
analysis_info.analysis_root
in
div
~a:[
a_class ["ocp-lint-web-footer"]
]
[pcdata msg]
let content_attach_creator analysis_info navigation_system = function
| Web_navigation_system.HomeElement ->
Web_home_content.content navigation_system analysis_info,
Web_navigation_system.No_attached_data
| Web_navigation_system.WarningsElement ->
Web_warnings_content.content navigation_system analysis_info,
Web_navigation_system.No_attached_data
| Web_navigation_system.ErrorsElement ->
Web_errors_content.content navigation_system analysis_info,
Web_navigation_system.No_attached_data
| Web_navigation_system.FileElement file_info ->
let file_warnings_info =
List.filter begin fun warning_info ->
Web_utils.file_equals file_info warning_info.warning_file
end analysis_info.warnings_info
in
let file_errors_info =
List.filter begin fun error_info ->
Web_utils.file_equals file_info error_info.error_file
end analysis_info.errors_info
in
let file_content_data =
Web_file_content_data.create
file_info
file_warnings_info
file_errors_info
(div [])
(Web_file_content.alterable_panel_content_creator file_info)
in
Web_file_content.content navigation_system file_content_data,
Web_navigation_system.File_content_attached_data file_content_data
let main_page analysis_info =
let navigation_system =
Web_navigation_system.create (content_attach_creator analysis_info)
in
Web_navigation_system.init
navigation_system;
let tabs =
Tyxml_js.Of_dom.of_element
navigation_system.Web_navigation_system.navigation_dom_tabs
in
let contents =
Tyxml_js.Of_dom.of_element
navigation_system.Web_navigation_system.navigation_dom_contents
in
div
[
header;
br ();
tabs;
contents;
footer analysis_info;
br ();
]
let load_main_page analysis_info =
let body = main_page analysis_info in
Dom.appendChild (Dom_html.document##body) (Tyxml_js.To_dom.of_element body)
let onload _ =
try
let analysis_info =
analysis_info_of_json
(Web_utils.json_from_js_var Lint_web.analysis_info_var)
in
load_main_page analysis_info;
Js._true
with
| Web_exception e ->
process_error e;
Js._false
| e ->
failwith ("uncatched exception " ^ (Printexc.to_string e))
let () =
Dom_html.window##onload <- Dom_html.handler onload;
| null | https://raw.githubusercontent.com/OCamlPro/typerex-lint/6d9e994c8278fb65e1f7de91d74876531691120c/tools/ocp-lint-web/src/web_main.ml | ocaml | ************************************************************************
OCamlPro Typerex
This file is distributed under the terms of the GPL v3.0
Contact: <> (/)
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
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.
************************************************************************ | Copyright OCamlPro 2011 - 2016 . All rights reserved .
( GNU General Public Licence version 3.0 ) .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
open Tyxml_js.Html
open Lint_warning_types
open Lint_web_analysis_info
open Web_errors
let header =
div
~a:[
a_class ["ocp-lint-web-header"]
]
[
h1 [pcdata "ocp-lint-web"];
]
let footer analysis_info =
let open Unix in
let time = analysis_info.analysis_date in
let msg =
Printf.sprintf "generated the %04d-%02d-%02d at %02d:%02d from %s"
(1900 + time.tm_year)
(time.tm_mon + 1)
time.tm_mday
time.tm_hour
time.tm_min
analysis_info.analysis_root
in
div
~a:[
a_class ["ocp-lint-web-footer"]
]
[pcdata msg]
let content_attach_creator analysis_info navigation_system = function
| Web_navigation_system.HomeElement ->
Web_home_content.content navigation_system analysis_info,
Web_navigation_system.No_attached_data
| Web_navigation_system.WarningsElement ->
Web_warnings_content.content navigation_system analysis_info,
Web_navigation_system.No_attached_data
| Web_navigation_system.ErrorsElement ->
Web_errors_content.content navigation_system analysis_info,
Web_navigation_system.No_attached_data
| Web_navigation_system.FileElement file_info ->
let file_warnings_info =
List.filter begin fun warning_info ->
Web_utils.file_equals file_info warning_info.warning_file
end analysis_info.warnings_info
in
let file_errors_info =
List.filter begin fun error_info ->
Web_utils.file_equals file_info error_info.error_file
end analysis_info.errors_info
in
let file_content_data =
Web_file_content_data.create
file_info
file_warnings_info
file_errors_info
(div [])
(Web_file_content.alterable_panel_content_creator file_info)
in
Web_file_content.content navigation_system file_content_data,
Web_navigation_system.File_content_attached_data file_content_data
let main_page analysis_info =
let navigation_system =
Web_navigation_system.create (content_attach_creator analysis_info)
in
Web_navigation_system.init
navigation_system;
let tabs =
Tyxml_js.Of_dom.of_element
navigation_system.Web_navigation_system.navigation_dom_tabs
in
let contents =
Tyxml_js.Of_dom.of_element
navigation_system.Web_navigation_system.navigation_dom_contents
in
div
[
header;
br ();
tabs;
contents;
footer analysis_info;
br ();
]
let load_main_page analysis_info =
let body = main_page analysis_info in
Dom.appendChild (Dom_html.document##body) (Tyxml_js.To_dom.of_element body)
let onload _ =
try
let analysis_info =
analysis_info_of_json
(Web_utils.json_from_js_var Lint_web.analysis_info_var)
in
load_main_page analysis_info;
Js._true
with
| Web_exception e ->
process_error e;
Js._false
| e ->
failwith ("uncatched exception " ^ (Printexc.to_string e))
let () =
Dom_html.window##onload <- Dom_html.handler onload;
|
5b202d43385a7c5428931eb610967c2311b5965029edb8620f8f546be95508cb | joelburget/react-haskell | HLint.hs | import "hint" HLint.HLint
ignore "Use camelCase"
| null | https://raw.githubusercontent.com/joelburget/react-haskell/5de76473b7cfdd6b85ac618bea31e658794b54e2/HLint.hs | haskell | import "hint" HLint.HLint
ignore "Use camelCase"
| |
701e7c23cc06a99b54d923bf3c997ed1f3977211ac247839c7f6554d10194d77 | AvisoNovate/pretty | binary.clj | (ns io.aviso.binary
"Utilities for formatting binary data (byte arrays) or binary deltas."
(:require [io.aviso.ansi :as ansi]
[io.aviso.columns :as c])
(:import (java.nio ByteBuffer)))
(defprotocol BinaryData
"Allows various data sources to be treated as a byte-array data type that
supports a length and random access to individual bytes.
BinaryData is extended onto byte arrays, java.nio.ByteBuffer, java.lang.String, java.lang.StringBuilder, and onto nil."
(data-length [this] "The total number of bytes available.")
(byte-at [this index] "The byte value at a specific offset."))
(extend-type (Class/forName "[B")
BinaryData
(data-length [ary] (alength (bytes ary)))
(byte-at [ary index] (aget (bytes ary) index)))
(extend-type ByteBuffer
BinaryData
(data-length [b] (.remaining b))
(byte-at [b index] (.get ^ByteBuffer b (int index))))
;;; Extends String as a convenience; assumes that the
String is in utf-8 .
(extend-type String
BinaryData
(data-length [s] (.length s))
(byte-at [s index] (-> s (.charAt index) int byte)))
(extend-type StringBuilder
BinaryData
(data-length [sb] (.length sb))
(byte-at [sb index]
(-> sb (.charAt index) int byte)))
(extend-type nil
BinaryData
(data-length [_] 0)
(byte-at [_ _index] (throw (IndexOutOfBoundsException. "Can't use byte-at with nil."))))
(def ^:private ^:const bytes-per-diff-line 16)
(def ^:private ^:const bytes-per-ascii-line 16)
(def ^:private ^:const bytes-per-line (* 2 bytes-per-diff-line))
(def ^:private printable-chars
(into #{}
(map byte (str "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789"
" !@#$%^&*()-_=+[]{}\\|'\";:,./<>?`~"))))
(def ^:private nonprintable-placeholder (ansi/bold-magenta-bg " "))
(defn- to-ascii
[b]
(if (printable-chars b)
(char b)
nonprintable-placeholder))
(defn- write-line
[formatter write-ascii? offset data line-count]
(let [line-bytes (for [i (range line-count)]
(byte-at data (+ offset i)))]
(formatter
(format "%04X" offset)
(apply str (interpose " "
(map #(format "%02X" %) line-bytes)))
(if write-ascii?
(apply str (map to-ascii line-bytes))))))
(def ^:private standard-binary-columns
[4
": "
:none])
(defn- ascii-binary-columns [per-line]
[4
": "
(* 3 per-line)
"|"
per-line
"|"
])
(defn write-binary
"Formats a BinaryData into a hex-dump string, consisting of multiple lines; each line formatted as:
0000: 43 68 6F 6F 73 65 20 69 6D 6D 75 74 61 62 69 6C 69 74 79 2C 20 61 6E 64 20 73 65 65 20 77 68 65
0020: 72 65 20 74 68 61 74 20 74 61 6B 65 73 20 79 6F 75 2E
The full version specifies:
- [[BinaryData]] to write
- option keys and values:
:ascii - boolean
: true to enable ASCII mode
:line-bytes - number
: number of bytes per line (defaults to 16 for ASCII, 32 otherwise)
In ASCII mode, the output is 16 bytes per line, but each line includes the ASCII printable characters:
0000: 43 68 6F 6F 73 65 20 69 6D 6D 75 74 61 62 69 6C |Choose immutabil|
0010: 69 74 79 2C 20 61 6E 64 20 73 65 65 20 77 68 65 |ity, and see whe|
0020: 72 65 20 74 68 61 74 20 74 61 6B 65 73 20 79 6F |re that takes yo|
0030: 75 2E |u. |
A placeholder character (a space with magenta background) is used for any non-printable
character."
([data]
(write-binary data nil))
([data options]
(let [{show-ascii? :ascii
per-line-option :line-bytes} options
per-line (or per-line-option
(if show-ascii? bytes-per-ascii-line bytes-per-line))
formatter (apply c/format-columns
(if show-ascii?
(ascii-binary-columns per-line)
standard-binary-columns))]
(assert (pos? per-line) "Must be at least one byte per line.")
(loop [offset 0]
(let [remaining (- (data-length data) offset)]
(when (pos? remaining)
(write-line formatter show-ascii? offset data (min per-line remaining))
(recur (long (+ per-line offset)))))))))
(defn format-binary
"Formats the data using [[write-binary]] and returns the result as a string."
([data]
(format-binary data nil))
([data options]
(with-out-str
(write-binary data options))))
(defn- match?
[byte-offset data-length data alternate-length alternate]
(and
(< byte-offset data-length)
(< byte-offset alternate-length)
(== (byte-at data byte-offset) (byte-at alternate byte-offset))))
(defn- to-hex
[byte-array byte-offset]
;; This could be made a lot more efficient!
(format "%02X" (byte-at byte-array byte-offset)))
(defn- write-byte-deltas
[ansi-color pad? offset data-length data alternate-length alternate]
(doseq [i (range bytes-per-diff-line)]
(let [byte-offset (+ offset i)]
(cond
;; Exact match on both sides is easy, just print it out.
(match? byte-offset data-length data alternate-length alternate) (print (str " " (to-hex data byte-offset)))
;; Some kind of mismatch, so decorate with this side's color
(< byte-offset data-length) (print (str " " (ansi-color (to-hex data byte-offset))))
;; Are we out of data on this side? Print a "--" decorated with the color.
(< byte-offset alternate-length) (print (str " " (ansi-color "--")))
;; This side must be longer than the alternate side.
;; On the left/green side, we need to pad with spaces
;; On the right/red side, we need nothing.
pad? (print " ")))))
(defn- write-delta-line
[offset expected-length ^bytes expected actual-length actual]
(printf "%04X:" offset)
(write-byte-deltas ansi/bold-green true offset expected-length expected actual-length actual)
(print " | ")
(write-byte-deltas ansi/bold-red false offset actual-length actual expected-length expected)
(println))
(defn write-binary-delta
"Formats a hex dump of the expected data (on the left) and actual data (on the right). Bytes
that do not match are highlighted in green on the expected side, and red on the actual side.
When one side is shorter than the other, it is padded with `--` placeholders to make this
more clearly visible.
expected and actual are [[BinaryData]].
Display 16 bytes (from each data set) per line."
[expected actual]
(let [expected-length (data-length expected)
actual-length (data-length actual)
target-length (max actual-length expected-length)]
(loop [offset 0]
(when (pos? (- target-length offset))
(write-delta-line offset expected-length expected actual-length actual)
(recur (long (+ bytes-per-diff-line offset)))))))
(defn format-binary-delta
"Formats the delta using [[write-binary-delta]] and returns the result as a string."
[expected actual]
(with-out-str
(write-binary-delta expected actual)))
| null | https://raw.githubusercontent.com/AvisoNovate/pretty/b82222670cf623b945adcee5aa75423ccedf2368/src/io/aviso/binary.clj | clojure | Extends String as a convenience; assumes that the
:,./<>?`~"))))
each line formatted as:
This could be made a lot more efficient!
Exact match on both sides is easy, just print it out.
Some kind of mismatch, so decorate with this side's color
Are we out of data on this side? Print a "--" decorated with the color.
This side must be longer than the alternate side.
On the left/green side, we need to pad with spaces
On the right/red side, we need nothing. | (ns io.aviso.binary
"Utilities for formatting binary data (byte arrays) or binary deltas."
(:require [io.aviso.ansi :as ansi]
[io.aviso.columns :as c])
(:import (java.nio ByteBuffer)))
(defprotocol BinaryData
"Allows various data sources to be treated as a byte-array data type that
supports a length and random access to individual bytes.
BinaryData is extended onto byte arrays, java.nio.ByteBuffer, java.lang.String, java.lang.StringBuilder, and onto nil."
(data-length [this] "The total number of bytes available.")
(byte-at [this index] "The byte value at a specific offset."))
(extend-type (Class/forName "[B")
BinaryData
(data-length [ary] (alength (bytes ary)))
(byte-at [ary index] (aget (bytes ary) index)))
(extend-type ByteBuffer
BinaryData
(data-length [b] (.remaining b))
(byte-at [b index] (.get ^ByteBuffer b (int index))))
String is in utf-8 .
(extend-type String
BinaryData
(data-length [s] (.length s))
(byte-at [s index] (-> s (.charAt index) int byte)))
(extend-type StringBuilder
BinaryData
(data-length [sb] (.length sb))
(byte-at [sb index]
(-> sb (.charAt index) int byte)))
(extend-type nil
BinaryData
(data-length [_] 0)
(byte-at [_ _index] (throw (IndexOutOfBoundsException. "Can't use byte-at with nil."))))
(def ^:private ^:const bytes-per-diff-line 16)
(def ^:private ^:const bytes-per-ascii-line 16)
(def ^:private ^:const bytes-per-line (* 2 bytes-per-diff-line))
(def ^:private printable-chars
(into #{}
(map byte (str "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789"
(def ^:private nonprintable-placeholder (ansi/bold-magenta-bg " "))
(defn- to-ascii
[b]
(if (printable-chars b)
(char b)
nonprintable-placeholder))
(defn- write-line
[formatter write-ascii? offset data line-count]
(let [line-bytes (for [i (range line-count)]
(byte-at data (+ offset i)))]
(formatter
(format "%04X" offset)
(apply str (interpose " "
(map #(format "%02X" %) line-bytes)))
(if write-ascii?
(apply str (map to-ascii line-bytes))))))
(def ^:private standard-binary-columns
[4
": "
:none])
(defn- ascii-binary-columns [per-line]
[4
": "
(* 3 per-line)
"|"
per-line
"|"
])
(defn write-binary
0000: 43 68 6F 6F 73 65 20 69 6D 6D 75 74 61 62 69 6C 69 74 79 2C 20 61 6E 64 20 73 65 65 20 77 68 65
0020: 72 65 20 74 68 61 74 20 74 61 6B 65 73 20 79 6F 75 2E
The full version specifies:
- [[BinaryData]] to write
- option keys and values:
:ascii - boolean
: true to enable ASCII mode
:line-bytes - number
: number of bytes per line (defaults to 16 for ASCII, 32 otherwise)
In ASCII mode, the output is 16 bytes per line, but each line includes the ASCII printable characters:
0000: 43 68 6F 6F 73 65 20 69 6D 6D 75 74 61 62 69 6C |Choose immutabil|
0010: 69 74 79 2C 20 61 6E 64 20 73 65 65 20 77 68 65 |ity, and see whe|
0020: 72 65 20 74 68 61 74 20 74 61 6B 65 73 20 79 6F |re that takes yo|
0030: 75 2E |u. |
A placeholder character (a space with magenta background) is used for any non-printable
character."
([data]
(write-binary data nil))
([data options]
(let [{show-ascii? :ascii
per-line-option :line-bytes} options
per-line (or per-line-option
(if show-ascii? bytes-per-ascii-line bytes-per-line))
formatter (apply c/format-columns
(if show-ascii?
(ascii-binary-columns per-line)
standard-binary-columns))]
(assert (pos? per-line) "Must be at least one byte per line.")
(loop [offset 0]
(let [remaining (- (data-length data) offset)]
(when (pos? remaining)
(write-line formatter show-ascii? offset data (min per-line remaining))
(recur (long (+ per-line offset)))))))))
(defn format-binary
"Formats the data using [[write-binary]] and returns the result as a string."
([data]
(format-binary data nil))
([data options]
(with-out-str
(write-binary data options))))
(defn- match?
[byte-offset data-length data alternate-length alternate]
(and
(< byte-offset data-length)
(< byte-offset alternate-length)
(== (byte-at data byte-offset) (byte-at alternate byte-offset))))
(defn- to-hex
[byte-array byte-offset]
(format "%02X" (byte-at byte-array byte-offset)))
(defn- write-byte-deltas
[ansi-color pad? offset data-length data alternate-length alternate]
(doseq [i (range bytes-per-diff-line)]
(let [byte-offset (+ offset i)]
(cond
(match? byte-offset data-length data alternate-length alternate) (print (str " " (to-hex data byte-offset)))
(< byte-offset data-length) (print (str " " (ansi-color (to-hex data byte-offset))))
(< byte-offset alternate-length) (print (str " " (ansi-color "--")))
pad? (print " ")))))
(defn- write-delta-line
[offset expected-length ^bytes expected actual-length actual]
(printf "%04X:" offset)
(write-byte-deltas ansi/bold-green true offset expected-length expected actual-length actual)
(print " | ")
(write-byte-deltas ansi/bold-red false offset actual-length actual expected-length expected)
(println))
(defn write-binary-delta
"Formats a hex dump of the expected data (on the left) and actual data (on the right). Bytes
that do not match are highlighted in green on the expected side, and red on the actual side.
When one side is shorter than the other, it is padded with `--` placeholders to make this
more clearly visible.
expected and actual are [[BinaryData]].
Display 16 bytes (from each data set) per line."
[expected actual]
(let [expected-length (data-length expected)
actual-length (data-length actual)
target-length (max actual-length expected-length)]
(loop [offset 0]
(when (pos? (- target-length offset))
(write-delta-line offset expected-length expected actual-length actual)
(recur (long (+ bytes-per-diff-line offset)))))))
(defn format-binary-delta
"Formats the delta using [[write-binary-delta]] and returns the result as a string."
[expected actual]
(with-out-str
(write-binary-delta expected actual)))
|
8803558a61b88a400c7b61d3cd164d779631148005448295d1475e69dd055581 | OlivierSohn/hamazed | Conversion.hs | {-# OPTIONS_HADDOCK hide #-}
# LANGUAGE NoImplicitPrelude #
module Imj.Geo.Continuous.Conversion
( -- * Conversion to / from discrete coordinates
| Discrete positions are converted to continuous positions by
placing them at the " pixel center " , ie by applying an offset of ( 0.5 , 0.5 ) in
' pos2vec ' .
Then , during the inverse transformation - in ' vec2pos ' , coordinates are just
floored .
Discrete speeds are converted with ' speed2vec ' . The half - pixel convention is not
applied for speeds . The inverse conversion is ' vec2speed ' .
placing them at the "pixel center", ie by applying an offset of (0.5, 0.5) in
'pos2vec'.
Then, during the inverse transformation - in 'vec2pos', coordinates are just
floored.
Discrete speeds are converted with 'speed2vec'. The half-pixel convention is not
applied for speeds. The inverse conversion is 'vec2speed'.
-}
pos2vec
, vec2pos
, speed2vec
, vec2speed
) where
import Imj.Prelude
import Imj.Geo.Continuous.Types
import Imj.Geo.Discrete.Types
-- | Convert a discrete position to a continuous position.
pos2vec :: Coords Pos -> Vec2 Pos
pos2vec (Coords r c) =
Vec2 (0.5 + fromIntegral c) (0.5 + fromIntegral r)
-- | Convert a continuous position to a discrete position.
vec2pos :: Vec2 Pos -> Coords Pos
vec2pos (Vec2 x y) =
Coords (floor y) (floor x)
-- | Convert a discrete speed to a continuous speed.
speed2vec :: Coords Vel -> Vec2 Vel
speed2vec (Coords r c) =
Vec2 (fromIntegral c) (fromIntegral r)
-- | Convert a continuous speed to a discrete speed.
vec2speed :: Vec2 Vel -> Coords Vel
vec2speed (Vec2 x y) =
Coords (fromIntegral (round y :: Int)) (fromIntegral (round x :: Int))
| null | https://raw.githubusercontent.com/OlivierSohn/hamazed/6c2b20d839ede7b8651fb7b425cb27ea93808a4a/imj-base/src/Imj/Geo/Continuous/Conversion.hs | haskell | # OPTIONS_HADDOCK hide #
* Conversion to / from discrete coordinates
| Convert a discrete position to a continuous position.
| Convert a continuous position to a discrete position.
| Convert a discrete speed to a continuous speed.
| Convert a continuous speed to a discrete speed. |
# LANGUAGE NoImplicitPrelude #
module Imj.Geo.Continuous.Conversion
| Discrete positions are converted to continuous positions by
placing them at the " pixel center " , ie by applying an offset of ( 0.5 , 0.5 ) in
' pos2vec ' .
Then , during the inverse transformation - in ' vec2pos ' , coordinates are just
floored .
Discrete speeds are converted with ' speed2vec ' . The half - pixel convention is not
applied for speeds . The inverse conversion is ' vec2speed ' .
placing them at the "pixel center", ie by applying an offset of (0.5, 0.5) in
'pos2vec'.
Then, during the inverse transformation - in 'vec2pos', coordinates are just
floored.
Discrete speeds are converted with 'speed2vec'. The half-pixel convention is not
applied for speeds. The inverse conversion is 'vec2speed'.
-}
pos2vec
, vec2pos
, speed2vec
, vec2speed
) where
import Imj.Prelude
import Imj.Geo.Continuous.Types
import Imj.Geo.Discrete.Types
pos2vec :: Coords Pos -> Vec2 Pos
pos2vec (Coords r c) =
Vec2 (0.5 + fromIntegral c) (0.5 + fromIntegral r)
vec2pos :: Vec2 Pos -> Coords Pos
vec2pos (Vec2 x y) =
Coords (floor y) (floor x)
speed2vec :: Coords Vel -> Vec2 Vel
speed2vec (Coords r c) =
Vec2 (fromIntegral c) (fromIntegral r)
vec2speed :: Vec2 Vel -> Coords Vel
vec2speed (Vec2 x y) =
Coords (fromIntegral (round y :: Int)) (fromIntegral (round x :: Int))
|
9d1e23d79b672977ce745ca1b6281ba090af2067e6d112585cc75f5b9351bae5 | haskell-foundation/foundation | UUID.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeOperators #
module Foundation.UUID
( UUID(..)
, newUUID
, nil
, fromBinary
, uuidParser
) where
import Data.Maybe (fromMaybe)
import Basement.Compat.Base
import Foundation.Collection (Element, Sequential, foldl')
import Foundation.Class.Storable
import Foundation.Hashing.Hashable
import Foundation.Bits
import Foundation.Parser
import Foundation.Numerical
import Foundation.Primitive
import Basement.Base16
import Basement.IntegralConv
import Basement.Types.OffsetSize
import qualified Basement.UArray as UA
import Foundation.Random (MonadRandom, getRandomBytes)
data UUID = UUID {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64
deriving (Eq,Ord,Typeable)
instance Show UUID where
show = toLString
instance NormalForm UUID where
toNormalForm !_ = ()
instance Hashable UUID where
hashMix (UUID a b) = hashMix a . hashMix b
instance Storable UUID where
peek p = UUID <$> (fromBE <$> peekOff ptr 0)
<*> (fromBE <$> peekOff ptr 1)
where ptr = castPtr p :: Ptr (BE Word64)
poke p (UUID a b) = do
pokeOff ptr 0 (toBE a)
pokeOff ptr 1 (toBE b)
where ptr = castPtr p :: Ptr (BE Word64)
instance StorableFixed UUID where
size _ = 16
alignment _ = 8
withComponent :: UUID -> (Word32 -> Word16 -> Word16 -> Word16 -> Word64 -> a) -> a
withComponent (UUID a b) f = f x1 x2 x3 x4 x5
where
!x1 = integralDownsize (a .>>. 32)
!x2 = integralDownsize ((a .>>. 16) .&. 0xffff)
!x3 = integralDownsize (a .&. 0xffff)
!x4 = integralDownsize (b .>>. 48)
!x5 = (b .&. 0x0000ffffffffffff)
# INLINE withComponent #
toLString :: UUID -> [Char]
toLString uuid = withComponent uuid $ \x1 x2 x3 x4 x5 ->
hexWord_4 x1 $ addDash $ hexWord_2 x2 $ addDash $ hexWord_2 x3 $ addDash $ hexWord_2 x4 $ addDash $ hexWord64_6 x5 []
where
addDash = (:) '-'
hexWord_2 w l = case hexWord16 w of
(c1,c2,c3,c4) -> c1:c2:c3:c4:l
hexWord_4 w l = case hexWord32 w of
(c1,c2,c3,c4,c5,c6,c7,c8) -> c1:c2:c3:c4:c5:c6:c7:c8:l
hexWord64_6 w l = case word64ToWord32s w of
Word32x2 wHigh wLow -> hexWord_2 (integralDownsize wHigh) $ hexWord_4 wLow l
nil :: UUID
nil = UUID 0 0
newUUID :: MonadRandom randomly => randomly UUID
newUUID = fromMaybe (error "Foundation.UUID.newUUID: the impossible happned")
. fromBinary
<$> getRandomBytes 16
fromBinary :: UA.UArray Word8 -> Maybe UUID
fromBinary ba
| UA.length ba /= 16 = Nothing
| otherwise = Just $ UUID w0 w1
where
w0 = (b15 .<<. 56) .|. (b14 .<<. 48) .|. (b13 .<<. 40) .|. (b12 .<<. 32) .|.
(b11 .<<. 24) .|. (b10 .<<. 16) .|. (b9 .<<. 8) .|. b8
w1 = (b7 .<<. 56) .|. (b6 .<<. 48) .|. (b5 .<<. 40) .|. (b4 .<<. 32) .|.
(b3 .<<. 24) .|. (b2 .<<. 16) .|. (b1 .<<. 8) .|. b0
b0 = integralUpsize (UA.unsafeIndex ba 0)
b1 = integralUpsize (UA.unsafeIndex ba 1)
b2 = integralUpsize (UA.unsafeIndex ba 2)
b3 = integralUpsize (UA.unsafeIndex ba 3)
b4 = integralUpsize (UA.unsafeIndex ba 4)
b5 = integralUpsize (UA.unsafeIndex ba 5)
b6 = integralUpsize (UA.unsafeIndex ba 6)
b7 = integralUpsize (UA.unsafeIndex ba 7)
b8 = integralUpsize (UA.unsafeIndex ba 8)
b9 = integralUpsize (UA.unsafeIndex ba 9)
b10 = integralUpsize (UA.unsafeIndex ba 10)
b11 = integralUpsize (UA.unsafeIndex ba 11)
b12 = integralUpsize (UA.unsafeIndex ba 12)
b13 = integralUpsize (UA.unsafeIndex ba 13)
b14 = integralUpsize (UA.unsafeIndex ba 14)
b15 = integralUpsize (UA.unsafeIndex ba 15)
uuidParser :: ( ParserSource input, Element input ~ Char
, Sequential (Chunk input), Element input ~ Element (Chunk input)
)
=> Parser input UUID
uuidParser = do
hex1 <- parseHex (CountOf 8) <* element '-'
hex2 <- parseHex (CountOf 4) <* element '-'
hex3 <- parseHex (CountOf 4) <* element '-'
hex4 <- parseHex (CountOf 4) <* element '-'
hex5 <- parseHex (CountOf 12)
return $ UUID (hex1 .<<. 32 .|. hex2 .<<. 16 .|. hex3)
(hex4 .<<. 48 .|. hex5)
parseHex :: ( ParserSource input, Element input ~ Char
, Sequential (Chunk input), Element input ~ Element (Chunk input)
)
=> CountOf Char -> Parser input Word64
parseHex count = do
r <- toList <$> take count
unless (and $ isValidHexa <$> r) $
reportError $ Satisfy $ Just $ "expecting hexadecimal character only: "
<> fromList (show r)
return $ listToHex 0 r
where
listToHex = foldl' (\acc' x -> acc' * 16 + fromHex x)
isValidHexa :: Char -> Bool
isValidHexa c = ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
fromHex '0' = 0
fromHex '1' = 1
fromHex '2' = 2
fromHex '3' = 3
fromHex '4' = 4
fromHex '5' = 5
fromHex '6' = 6
fromHex '7' = 7
fromHex '8' = 8
fromHex '9' = 9
fromHex 'a' = 10
fromHex 'b' = 11
fromHex 'c' = 12
fromHex 'd' = 13
fromHex 'e' = 14
fromHex 'f' = 15
fromHex 'A' = 10
fromHex 'B' = 11
fromHex 'C' = 12
fromHex 'D' = 13
fromHex 'E' = 14
fromHex 'F' = 15
fromHex _ = error "Foundation.UUID.parseUUID: the impossible happened"
| null | https://raw.githubusercontent.com/haskell-foundation/foundation/39985b94b4de4d02e8decb5e378b53ad3f72c0cc/foundation/Foundation/UUID.hs | haskell | # LANGUAGE OverloadedStrings #
# UNPACK #
# UNPACK # | # LANGUAGE FlexibleContexts #
# LANGUAGE TypeOperators #
module Foundation.UUID
( UUID(..)
, newUUID
, nil
, fromBinary
, uuidParser
) where
import Data.Maybe (fromMaybe)
import Basement.Compat.Base
import Foundation.Collection (Element, Sequential, foldl')
import Foundation.Class.Storable
import Foundation.Hashing.Hashable
import Foundation.Bits
import Foundation.Parser
import Foundation.Numerical
import Foundation.Primitive
import Basement.Base16
import Basement.IntegralConv
import Basement.Types.OffsetSize
import qualified Basement.UArray as UA
import Foundation.Random (MonadRandom, getRandomBytes)
deriving (Eq,Ord,Typeable)
instance Show UUID where
show = toLString
instance NormalForm UUID where
toNormalForm !_ = ()
instance Hashable UUID where
hashMix (UUID a b) = hashMix a . hashMix b
instance Storable UUID where
peek p = UUID <$> (fromBE <$> peekOff ptr 0)
<*> (fromBE <$> peekOff ptr 1)
where ptr = castPtr p :: Ptr (BE Word64)
poke p (UUID a b) = do
pokeOff ptr 0 (toBE a)
pokeOff ptr 1 (toBE b)
where ptr = castPtr p :: Ptr (BE Word64)
instance StorableFixed UUID where
size _ = 16
alignment _ = 8
withComponent :: UUID -> (Word32 -> Word16 -> Word16 -> Word16 -> Word64 -> a) -> a
withComponent (UUID a b) f = f x1 x2 x3 x4 x5
where
!x1 = integralDownsize (a .>>. 32)
!x2 = integralDownsize ((a .>>. 16) .&. 0xffff)
!x3 = integralDownsize (a .&. 0xffff)
!x4 = integralDownsize (b .>>. 48)
!x5 = (b .&. 0x0000ffffffffffff)
# INLINE withComponent #
toLString :: UUID -> [Char]
toLString uuid = withComponent uuid $ \x1 x2 x3 x4 x5 ->
hexWord_4 x1 $ addDash $ hexWord_2 x2 $ addDash $ hexWord_2 x3 $ addDash $ hexWord_2 x4 $ addDash $ hexWord64_6 x5 []
where
addDash = (:) '-'
hexWord_2 w l = case hexWord16 w of
(c1,c2,c3,c4) -> c1:c2:c3:c4:l
hexWord_4 w l = case hexWord32 w of
(c1,c2,c3,c4,c5,c6,c7,c8) -> c1:c2:c3:c4:c5:c6:c7:c8:l
hexWord64_6 w l = case word64ToWord32s w of
Word32x2 wHigh wLow -> hexWord_2 (integralDownsize wHigh) $ hexWord_4 wLow l
nil :: UUID
nil = UUID 0 0
newUUID :: MonadRandom randomly => randomly UUID
newUUID = fromMaybe (error "Foundation.UUID.newUUID: the impossible happned")
. fromBinary
<$> getRandomBytes 16
fromBinary :: UA.UArray Word8 -> Maybe UUID
fromBinary ba
| UA.length ba /= 16 = Nothing
| otherwise = Just $ UUID w0 w1
where
w0 = (b15 .<<. 56) .|. (b14 .<<. 48) .|. (b13 .<<. 40) .|. (b12 .<<. 32) .|.
(b11 .<<. 24) .|. (b10 .<<. 16) .|. (b9 .<<. 8) .|. b8
w1 = (b7 .<<. 56) .|. (b6 .<<. 48) .|. (b5 .<<. 40) .|. (b4 .<<. 32) .|.
(b3 .<<. 24) .|. (b2 .<<. 16) .|. (b1 .<<. 8) .|. b0
b0 = integralUpsize (UA.unsafeIndex ba 0)
b1 = integralUpsize (UA.unsafeIndex ba 1)
b2 = integralUpsize (UA.unsafeIndex ba 2)
b3 = integralUpsize (UA.unsafeIndex ba 3)
b4 = integralUpsize (UA.unsafeIndex ba 4)
b5 = integralUpsize (UA.unsafeIndex ba 5)
b6 = integralUpsize (UA.unsafeIndex ba 6)
b7 = integralUpsize (UA.unsafeIndex ba 7)
b8 = integralUpsize (UA.unsafeIndex ba 8)
b9 = integralUpsize (UA.unsafeIndex ba 9)
b10 = integralUpsize (UA.unsafeIndex ba 10)
b11 = integralUpsize (UA.unsafeIndex ba 11)
b12 = integralUpsize (UA.unsafeIndex ba 12)
b13 = integralUpsize (UA.unsafeIndex ba 13)
b14 = integralUpsize (UA.unsafeIndex ba 14)
b15 = integralUpsize (UA.unsafeIndex ba 15)
uuidParser :: ( ParserSource input, Element input ~ Char
, Sequential (Chunk input), Element input ~ Element (Chunk input)
)
=> Parser input UUID
uuidParser = do
hex1 <- parseHex (CountOf 8) <* element '-'
hex2 <- parseHex (CountOf 4) <* element '-'
hex3 <- parseHex (CountOf 4) <* element '-'
hex4 <- parseHex (CountOf 4) <* element '-'
hex5 <- parseHex (CountOf 12)
return $ UUID (hex1 .<<. 32 .|. hex2 .<<. 16 .|. hex3)
(hex4 .<<. 48 .|. hex5)
parseHex :: ( ParserSource input, Element input ~ Char
, Sequential (Chunk input), Element input ~ Element (Chunk input)
)
=> CountOf Char -> Parser input Word64
parseHex count = do
r <- toList <$> take count
unless (and $ isValidHexa <$> r) $
reportError $ Satisfy $ Just $ "expecting hexadecimal character only: "
<> fromList (show r)
return $ listToHex 0 r
where
listToHex = foldl' (\acc' x -> acc' * 16 + fromHex x)
isValidHexa :: Char -> Bool
isValidHexa c = ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
fromHex '0' = 0
fromHex '1' = 1
fromHex '2' = 2
fromHex '3' = 3
fromHex '4' = 4
fromHex '5' = 5
fromHex '6' = 6
fromHex '7' = 7
fromHex '8' = 8
fromHex '9' = 9
fromHex 'a' = 10
fromHex 'b' = 11
fromHex 'c' = 12
fromHex 'd' = 13
fromHex 'e' = 14
fromHex 'f' = 15
fromHex 'A' = 10
fromHex 'B' = 11
fromHex 'C' = 12
fromHex 'D' = 13
fromHex 'E' = 14
fromHex 'F' = 15
fromHex _ = error "Foundation.UUID.parseUUID: the impossible happened"
|
253111629f8cb2d513204a99775fe937c5c660b99cf5df9b2a2dbe46e13377e6 | marick/structural-typing | f_ALL_variants.clj | (ns structural-typing.use.condensed-type-descriptions.f-ALL-variants
(:require [structural-typing.preds :as pred])
(:use midje.sweet
structural-typing.type
structural-typing.global-type
structural-typing.clojure.core
structural-typing.assist.testutil)
(:refer-clojure :except [any?]))
(start-over!)
;; Most of the checking is common to these and ALL.
(fact "RANGE"
(fact "a single range"
(type! :R {[(RANGE 1 3)] even?})
(built-like :R [:wrong 4 2 :wrong]) => [:wrong 4 2 :wrong]
(check-for-explanations :R [:wrong 111 2 :wrong]) => (just (err:shouldbe [1] "even?" 111)))
(fact "a single range outside of a path"
(type! :R {(RANGE 1 3) even?})
(built-like :R [:wrong 4 2 :wrong]) => [:wrong 4 2 :wrong]
(check-for-explanations :R [:wrong 111 2 :wrong]) => (just (err:shouldbe [1] "even?" 111)))
(fact "a range within an ALL"
(type! :R {[ALL :x (RANGE 1 3)] even?})
(check-for-explanations :R [ {:x [:ignored 4 2]}
{:x [:ignored 1 2 :ignored]}])
=> (just (err:shouldbe [1 :x 1] "even?" 1)))
(fact "sequences are nil-padded on the right"
(type! :SECOND-AND-THIRD {[(RANGE 1 3)] [required-path pos?]})
(built-like :SECOND-AND-THIRD [:ignored 1 2]) => [:ignored 1 2]
(check-for-explanations :SECOND-AND-THIRD [:ignored 1])
=> (just (err:missing [2])))
(fact "two ranges in a path"
(type! :X {[:a (RANGE 1 4) :b (RANGE 1 5) pos?] even?})
(check-for-explanations :X {:a [:wrong :wrong
{:b [1 2 2 2 2 1]}
{:b [1 -1 -1 -1 -1 1]}
:wrong]})
=> (just (err:not-maplike [:a 1 :b] :wrong)))
(fact "a range can be taken of an infinite sequence"
(type! :X {(RANGE 1 3) even?})
(check-for-explanations :X (repeat 1)) => (just (err:shouldbe [1] "even?" 1)
(err:shouldbe [2] "even?" 1))))
(fact "indexes in paths"
(fact "describing the whole path"
(type! :X {[1] even?})
(built-like :X [1 2 3]) => [1 2 3]
(check-for-explanations :X [1 3 5]) => (just (err:shouldbe [1] "even?" 3)))
(fact "as part of a path"
(type! :X {[:a 2] {:b even?}})
(built-like :X {:a [0 1 {:b 2}]}) => {:a [0 1 {:b 2}]}
(check-for-explanations :X {:a [0 1 {:b 1}]}) => (just (err:shouldbe [:a 2 :b] "even?" 1))))
(start-over!)
| null | https://raw.githubusercontent.com/marick/structural-typing/9b44c303dcfd4a72c5b75ec7a1114687c809fba1/test/structural_typing/use/condensed_type_descriptions/f_ALL_variants.clj | clojure | Most of the checking is common to these and ALL. | (ns structural-typing.use.condensed-type-descriptions.f-ALL-variants
(:require [structural-typing.preds :as pred])
(:use midje.sweet
structural-typing.type
structural-typing.global-type
structural-typing.clojure.core
structural-typing.assist.testutil)
(:refer-clojure :except [any?]))
(start-over!)
(fact "RANGE"
(fact "a single range"
(type! :R {[(RANGE 1 3)] even?})
(built-like :R [:wrong 4 2 :wrong]) => [:wrong 4 2 :wrong]
(check-for-explanations :R [:wrong 111 2 :wrong]) => (just (err:shouldbe [1] "even?" 111)))
(fact "a single range outside of a path"
(type! :R {(RANGE 1 3) even?})
(built-like :R [:wrong 4 2 :wrong]) => [:wrong 4 2 :wrong]
(check-for-explanations :R [:wrong 111 2 :wrong]) => (just (err:shouldbe [1] "even?" 111)))
(fact "a range within an ALL"
(type! :R {[ALL :x (RANGE 1 3)] even?})
(check-for-explanations :R [ {:x [:ignored 4 2]}
{:x [:ignored 1 2 :ignored]}])
=> (just (err:shouldbe [1 :x 1] "even?" 1)))
(fact "sequences are nil-padded on the right"
(type! :SECOND-AND-THIRD {[(RANGE 1 3)] [required-path pos?]})
(built-like :SECOND-AND-THIRD [:ignored 1 2]) => [:ignored 1 2]
(check-for-explanations :SECOND-AND-THIRD [:ignored 1])
=> (just (err:missing [2])))
(fact "two ranges in a path"
(type! :X {[:a (RANGE 1 4) :b (RANGE 1 5) pos?] even?})
(check-for-explanations :X {:a [:wrong :wrong
{:b [1 2 2 2 2 1]}
{:b [1 -1 -1 -1 -1 1]}
:wrong]})
=> (just (err:not-maplike [:a 1 :b] :wrong)))
(fact "a range can be taken of an infinite sequence"
(type! :X {(RANGE 1 3) even?})
(check-for-explanations :X (repeat 1)) => (just (err:shouldbe [1] "even?" 1)
(err:shouldbe [2] "even?" 1))))
(fact "indexes in paths"
(fact "describing the whole path"
(type! :X {[1] even?})
(built-like :X [1 2 3]) => [1 2 3]
(check-for-explanations :X [1 3 5]) => (just (err:shouldbe [1] "even?" 3)))
(fact "as part of a path"
(type! :X {[:a 2] {:b even?}})
(built-like :X {:a [0 1 {:b 2}]}) => {:a [0 1 {:b 2}]}
(check-for-explanations :X {:a [0 1 {:b 1}]}) => (just (err:shouldbe [:a 2 :b] "even?" 1))))
(start-over!)
|
f930d129ec96708ebc2e3c5adecf036a82691dc0d5a9a2efc267e0684ff60d0e | mzp/coq-ide-for-ios | implicit_quantifiers.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
i $ I d : implicit_quantifiers.ml 13332 2010 - 07 - 26 22:12:43Z msozeau $ i
(*i*)
open Names
open Decl_kinds
open Term
open Sign
open Evd
open Environ
open Nametab
open Mod_subst
open Util
open Rawterm
open Topconstr
open Libnames
open Typeclasses
open Typeclasses_errors
open Pp
open Libobject
open Nameops
(*i*)
let generalizable_table = ref Idpred.empty
let _ =
Summary.declare_summary "generalizable-ident"
{ Summary.freeze_function = (fun () -> !generalizable_table);
Summary.unfreeze_function = (fun r -> generalizable_table := r);
Summary.init_function = (fun () -> generalizable_table := Idpred.empty) }
let declare_generalizable_ident table (loc,id) =
if id <> root_of_id id then
user_err_loc(loc,"declare_generalizable_ident",
(pr_id id ++ str
" is not declarable as generalizable identifier: it must have no trailing digits, quote, or _"));
if Idpred.mem id table then
user_err_loc(loc,"declare_generalizable_ident",
(pr_id id++str" is already declared as a generalizable identifier"))
else Idpred.add id table
let add_generalizable gen table =
match gen with
| None -> Idpred.empty
| Some [] -> Idpred.full
| Some l -> List.fold_left (fun table lid -> declare_generalizable_ident table lid)
table l
let cache_generalizable_type (_,(local,cmd)) =
generalizable_table := add_generalizable cmd !generalizable_table
let load_generalizable_type _ (_,(local,cmd)) =
generalizable_table := add_generalizable cmd !generalizable_table
let (in_generalizable, _) =
declare_object {(default_object "GENERALIZED-IDENT") with
load_function = load_generalizable_type;
cache_function = cache_generalizable_type;
classify_function = (fun (local, _ as obj) -> if local then Dispose else Keep obj)
}
let declare_generalizable local gen =
Lib.add_anonymous_leaf (in_generalizable (local, gen))
let find_generalizable_ident id = Idpred.mem (root_of_id id) !generalizable_table
let ids_of_list l =
List.fold_right Idset.add l Idset.empty
let locate_reference qid =
match Nametab.locate_extended qid with
| TrueGlobal ref -> true
| SynDef kn -> true
let is_global id =
try
locate_reference (qualid_of_ident id)
with Not_found ->
false
let is_freevar ids env x =
try
if Idset.mem x ids then false
else
try ignore(Environ.lookup_named x env) ; false
with _ -> not (is_global x)
with _ -> true
(* Auxiliary functions for the inference of implicitly quantified variables. *)
let ungeneralizable loc id =
user_err_loc (loc, "Generalization",
str "Unbound and ungeneralizable variable " ++ pr_id id)
let free_vars_of_constr_expr c ?(bound=Idset.empty) l =
let found loc id bdvars l =
if List.mem id l then l
else if is_freevar bdvars (Global.env ()) id
then
if find_generalizable_ident id then id :: l
else ungeneralizable loc id
else l
in
let rec aux bdvars l c = match c with
| CRef (Ident (loc,id)) -> found loc id bdvars l
| CNotation (_, "{ _ : _ | _ }", (CRef (Ident (_, id)) :: _, [], [])) when not (Idset.mem id bdvars) ->
fold_constr_expr_with_binders (fun a l -> Idset.add a l) aux (Idset.add id bdvars) l c
| c -> fold_constr_expr_with_binders (fun a l -> Idset.add a l) aux bdvars l c
in aux bound l c
let ids_of_names l =
List.fold_left (fun acc x -> match snd x with Name na -> na :: acc | Anonymous -> acc) [] l
let free_vars_of_binders ?(bound=Idset.empty) l (binders : local_binder list) =
let rec aux bdvars l c = match c with
((LocalRawAssum (n, _, c)) :: tl) ->
let bound = ids_of_names n in
let l' = free_vars_of_constr_expr c ~bound:bdvars l in
aux (Idset.union (ids_of_list bound) bdvars) l' tl
| ((LocalRawDef (n, c)) :: tl) ->
let bound = match snd n with Anonymous -> [] | Name n -> [n] in
let l' = free_vars_of_constr_expr c ~bound:bdvars l in
aux (Idset.union (ids_of_list bound) bdvars) l' tl
| [] -> bdvars, l
in aux bound l binders
let add_name_to_ids set na =
match na with
| Anonymous -> set
| Name id -> Idset.add id set
let generalizable_vars_of_rawconstr ?(bound=Idset.empty) ?(allowed=Idset.empty) =
let rec vars bound vs = function
| RVar (loc,id) ->
if is_freevar bound (Global.env ()) id then
if List.mem_assoc id vs then vs
else (id, loc) :: vs
else vs
| RApp (loc,f,args) -> List.fold_left (vars bound) vs (f::args)
| RLambda (loc,na,_,ty,c) | RProd (loc,na,_,ty,c) | RLetIn (loc,na,ty,c) ->
let vs' = vars bound vs ty in
let bound' = add_name_to_ids bound na in
vars bound' vs' c
| RCases (loc,sty,rtntypopt,tml,pl) ->
let vs1 = vars_option bound vs rtntypopt in
let vs2 = List.fold_left (fun vs (tm,_) -> vars bound vs tm) vs1 tml in
List.fold_left (vars_pattern bound) vs2 pl
| RLetTuple (loc,nal,rtntyp,b,c) ->
let vs1 = vars_return_type bound vs rtntyp in
let vs2 = vars bound vs1 b in
let bound' = List.fold_left add_name_to_ids bound nal in
vars bound' vs2 c
| RIf (loc,c,rtntyp,b1,b2) ->
let vs1 = vars_return_type bound vs rtntyp in
let vs2 = vars bound vs1 c in
let vs3 = vars bound vs2 b1 in
vars bound vs3 b2
| RRec (loc,fk,idl,bl,tyl,bv) ->
let bound' = Array.fold_right Idset.add idl bound in
let vars_fix i vs fid =
let vs1,bound1 =
List.fold_left
(fun (vs,bound) (na,k,bbd,bty) ->
let vs' = vars_option bound vs bbd in
let vs'' = vars bound vs' bty in
let bound' = add_name_to_ids bound na in
(vs'',bound')
)
(vs,bound')
bl.(i)
in
let vs2 = vars bound1 vs1 tyl.(i) in
vars bound1 vs2 bv.(i)
in
array_fold_left_i vars_fix vs idl
| RCast (loc,c,k) -> let v = vars bound vs c in
(match k with CastConv (_,t) -> vars bound v t | _ -> v)
| (RSort _ | RHole _ | RRef _ | REvar _ | RPatVar _ | RDynamic _) -> vs
and vars_pattern bound vs (loc,idl,p,c) =
let bound' = List.fold_right Idset.add idl bound in
vars bound' vs c
and vars_option bound vs = function None -> vs | Some p -> vars bound vs p
and vars_return_type bound vs (na,tyopt) =
let bound' = add_name_to_ids bound na in
vars_option bound' vs tyopt
in fun rt ->
let vars = List.rev (vars bound [] rt) in
List.iter (fun (id, loc) ->
if not (Idset.mem id allowed || find_generalizable_ident id) then
ungeneralizable loc id) vars;
vars
let rec make_fresh ids env x =
if is_freevar ids env x then x else make_fresh ids env (Nameops.lift_subscript x)
let next_ident_away_from id avoid = make_fresh avoid (Global.env ()) id
let next_name_away_from na avoid =
match na with
| Anonymous -> make_fresh avoid (Global.env ()) (id_of_string "anon")
| Name id -> make_fresh avoid (Global.env ()) id
let combine_params avoid fn applied needed =
let named, applied =
List.partition
(function
(t, Some (loc, ExplByName id)) ->
if not (List.exists (fun (_, (id', _, _)) -> Name id = id') needed) then
user_err_loc (loc,"",str "Wrong argument name: " ++ Nameops.pr_id id);
true
| _ -> false) applied
in
let named = List.map
(fun x -> match x with (t, Some (loc, ExplByName id)) -> id, t | _ -> assert false)
named
in
let needed = List.filter (fun (_, (_, b, _)) -> b = None) needed in
let rec aux ids avoid app need =
match app, need with
[], [] -> List.rev ids, avoid
| app, (_, (Name id, _, _)) :: need when List.mem_assoc id named ->
aux (List.assoc id named :: ids) avoid app need
| (x, None) :: app, (None, (Name id, _, _)) :: need ->
aux (x :: ids) avoid app need
| _, (Some cl, (_, _, _) as d) :: need ->
let t', avoid' = fn avoid d in
aux (t' :: ids) avoid' app need
| x :: app, (None, _) :: need -> aux (fst x :: ids) avoid app need
| [], (None, _ as decl) :: need ->
let t', avoid' = fn avoid decl in
aux (t' :: ids) avoid' app need
| (x,_) :: _, [] ->
user_err_loc (constr_loc x,"",str "Typeclass does not expect more arguments")
in aux [] avoid applied needed
let combine_params_freevar =
fun avoid (_, (na, _, _)) ->
let id' = next_name_away_from na avoid in
(CRef (Ident (dummy_loc, id')), Idset.add id' avoid)
let destClassApp cl =
match cl with
| CApp (loc, (None, CRef ref), l) -> loc, ref, List.map fst l
| CAppExpl (loc, (None, ref), l) -> loc, ref, l
| CRef ref -> loc_of_reference ref, ref, []
| _ -> raise Not_found
let destClassAppExpl cl =
match cl with
| CApp (loc, (None, CRef ref), l) -> loc, ref, l
| CRef ref -> loc_of_reference ref, ref, []
| _ -> raise Not_found
let implicit_application env ?(allow_partial=true) f ty =
let is_class =
try
let (loc, r, _ as clapp) = destClassAppExpl ty in
let (loc, qid) = qualid_of_reference r in
let gr = Nametab.locate qid in
if Typeclasses.is_class gr then Some (clapp, gr) else None
with Not_found -> None
in
match is_class with
| None -> ty, env
| Some ((loc, id, par), gr) ->
let avoid = Idset.union env (ids_of_list (free_vars_of_constr_expr ty ~bound:env [])) in
let c, avoid =
let c = class_info gr in
let (ci, rd) = c.cl_context in
if not allow_partial then
begin
let applen = List.fold_left (fun acc (x, y) -> if y = None then succ acc else acc) 0 par in
let needlen = List.fold_left (fun acc x -> if x = None then succ acc else acc) 0 ci in
if needlen <> applen then
Typeclasses_errors.mismatched_ctx_inst (Global.env ()) Parameters (List.map fst par) rd
end;
let pars = List.rev (List.combine ci rd) in
let args, avoid = combine_params avoid f par pars in
CAppExpl (loc, (None, id), args), avoid
in c, avoid
let implicits_of_rawterm ?(with_products=true) l =
let rec aux i c =
let abs loc na bk t b =
let rest = aux (succ i) b in
if bk = Implicit then
let name =
match na with
| Name id -> Some id
| Anonymous -> None
in
(ExplByPos (i, name), (true, true, true)) :: rest
else rest
in
match c with
| RProd (loc, na, bk, t, b) ->
if with_products then abs loc na bk t b
else
(if bk = Implicit then
msg_warning (str "Ignoring implicit status of product binder " ++
pr_name na ++ str " and following binders");
[])
| RLambda (loc, na, bk, t, b) -> abs loc na bk t b
| RLetIn (loc, na, t, b) -> aux i b
| _ -> []
in aux 1 l
| null | https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/interp/implicit_quantifiers.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i
i
Auxiliary functions for the inference of implicitly quantified variables. | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
i $ I d : implicit_quantifiers.ml 13332 2010 - 07 - 26 22:12:43Z msozeau $ i
open Names
open Decl_kinds
open Term
open Sign
open Evd
open Environ
open Nametab
open Mod_subst
open Util
open Rawterm
open Topconstr
open Libnames
open Typeclasses
open Typeclasses_errors
open Pp
open Libobject
open Nameops
let generalizable_table = ref Idpred.empty
let _ =
Summary.declare_summary "generalizable-ident"
{ Summary.freeze_function = (fun () -> !generalizable_table);
Summary.unfreeze_function = (fun r -> generalizable_table := r);
Summary.init_function = (fun () -> generalizable_table := Idpred.empty) }
let declare_generalizable_ident table (loc,id) =
if id <> root_of_id id then
user_err_loc(loc,"declare_generalizable_ident",
(pr_id id ++ str
" is not declarable as generalizable identifier: it must have no trailing digits, quote, or _"));
if Idpred.mem id table then
user_err_loc(loc,"declare_generalizable_ident",
(pr_id id++str" is already declared as a generalizable identifier"))
else Idpred.add id table
let add_generalizable gen table =
match gen with
| None -> Idpred.empty
| Some [] -> Idpred.full
| Some l -> List.fold_left (fun table lid -> declare_generalizable_ident table lid)
table l
let cache_generalizable_type (_,(local,cmd)) =
generalizable_table := add_generalizable cmd !generalizable_table
let load_generalizable_type _ (_,(local,cmd)) =
generalizable_table := add_generalizable cmd !generalizable_table
let (in_generalizable, _) =
declare_object {(default_object "GENERALIZED-IDENT") with
load_function = load_generalizable_type;
cache_function = cache_generalizable_type;
classify_function = (fun (local, _ as obj) -> if local then Dispose else Keep obj)
}
let declare_generalizable local gen =
Lib.add_anonymous_leaf (in_generalizable (local, gen))
let find_generalizable_ident id = Idpred.mem (root_of_id id) !generalizable_table
let ids_of_list l =
List.fold_right Idset.add l Idset.empty
let locate_reference qid =
match Nametab.locate_extended qid with
| TrueGlobal ref -> true
| SynDef kn -> true
let is_global id =
try
locate_reference (qualid_of_ident id)
with Not_found ->
false
let is_freevar ids env x =
try
if Idset.mem x ids then false
else
try ignore(Environ.lookup_named x env) ; false
with _ -> not (is_global x)
with _ -> true
let ungeneralizable loc id =
user_err_loc (loc, "Generalization",
str "Unbound and ungeneralizable variable " ++ pr_id id)
let free_vars_of_constr_expr c ?(bound=Idset.empty) l =
let found loc id bdvars l =
if List.mem id l then l
else if is_freevar bdvars (Global.env ()) id
then
if find_generalizable_ident id then id :: l
else ungeneralizable loc id
else l
in
let rec aux bdvars l c = match c with
| CRef (Ident (loc,id)) -> found loc id bdvars l
| CNotation (_, "{ _ : _ | _ }", (CRef (Ident (_, id)) :: _, [], [])) when not (Idset.mem id bdvars) ->
fold_constr_expr_with_binders (fun a l -> Idset.add a l) aux (Idset.add id bdvars) l c
| c -> fold_constr_expr_with_binders (fun a l -> Idset.add a l) aux bdvars l c
in aux bound l c
let ids_of_names l =
List.fold_left (fun acc x -> match snd x with Name na -> na :: acc | Anonymous -> acc) [] l
let free_vars_of_binders ?(bound=Idset.empty) l (binders : local_binder list) =
let rec aux bdvars l c = match c with
((LocalRawAssum (n, _, c)) :: tl) ->
let bound = ids_of_names n in
let l' = free_vars_of_constr_expr c ~bound:bdvars l in
aux (Idset.union (ids_of_list bound) bdvars) l' tl
| ((LocalRawDef (n, c)) :: tl) ->
let bound = match snd n with Anonymous -> [] | Name n -> [n] in
let l' = free_vars_of_constr_expr c ~bound:bdvars l in
aux (Idset.union (ids_of_list bound) bdvars) l' tl
| [] -> bdvars, l
in aux bound l binders
let add_name_to_ids set na =
match na with
| Anonymous -> set
| Name id -> Idset.add id set
let generalizable_vars_of_rawconstr ?(bound=Idset.empty) ?(allowed=Idset.empty) =
let rec vars bound vs = function
| RVar (loc,id) ->
if is_freevar bound (Global.env ()) id then
if List.mem_assoc id vs then vs
else (id, loc) :: vs
else vs
| RApp (loc,f,args) -> List.fold_left (vars bound) vs (f::args)
| RLambda (loc,na,_,ty,c) | RProd (loc,na,_,ty,c) | RLetIn (loc,na,ty,c) ->
let vs' = vars bound vs ty in
let bound' = add_name_to_ids bound na in
vars bound' vs' c
| RCases (loc,sty,rtntypopt,tml,pl) ->
let vs1 = vars_option bound vs rtntypopt in
let vs2 = List.fold_left (fun vs (tm,_) -> vars bound vs tm) vs1 tml in
List.fold_left (vars_pattern bound) vs2 pl
| RLetTuple (loc,nal,rtntyp,b,c) ->
let vs1 = vars_return_type bound vs rtntyp in
let vs2 = vars bound vs1 b in
let bound' = List.fold_left add_name_to_ids bound nal in
vars bound' vs2 c
| RIf (loc,c,rtntyp,b1,b2) ->
let vs1 = vars_return_type bound vs rtntyp in
let vs2 = vars bound vs1 c in
let vs3 = vars bound vs2 b1 in
vars bound vs3 b2
| RRec (loc,fk,idl,bl,tyl,bv) ->
let bound' = Array.fold_right Idset.add idl bound in
let vars_fix i vs fid =
let vs1,bound1 =
List.fold_left
(fun (vs,bound) (na,k,bbd,bty) ->
let vs' = vars_option bound vs bbd in
let vs'' = vars bound vs' bty in
let bound' = add_name_to_ids bound na in
(vs'',bound')
)
(vs,bound')
bl.(i)
in
let vs2 = vars bound1 vs1 tyl.(i) in
vars bound1 vs2 bv.(i)
in
array_fold_left_i vars_fix vs idl
| RCast (loc,c,k) -> let v = vars bound vs c in
(match k with CastConv (_,t) -> vars bound v t | _ -> v)
| (RSort _ | RHole _ | RRef _ | REvar _ | RPatVar _ | RDynamic _) -> vs
and vars_pattern bound vs (loc,idl,p,c) =
let bound' = List.fold_right Idset.add idl bound in
vars bound' vs c
and vars_option bound vs = function None -> vs | Some p -> vars bound vs p
and vars_return_type bound vs (na,tyopt) =
let bound' = add_name_to_ids bound na in
vars_option bound' vs tyopt
in fun rt ->
let vars = List.rev (vars bound [] rt) in
List.iter (fun (id, loc) ->
if not (Idset.mem id allowed || find_generalizable_ident id) then
ungeneralizable loc id) vars;
vars
let rec make_fresh ids env x =
if is_freevar ids env x then x else make_fresh ids env (Nameops.lift_subscript x)
let next_ident_away_from id avoid = make_fresh avoid (Global.env ()) id
let next_name_away_from na avoid =
match na with
| Anonymous -> make_fresh avoid (Global.env ()) (id_of_string "anon")
| Name id -> make_fresh avoid (Global.env ()) id
let combine_params avoid fn applied needed =
let named, applied =
List.partition
(function
(t, Some (loc, ExplByName id)) ->
if not (List.exists (fun (_, (id', _, _)) -> Name id = id') needed) then
user_err_loc (loc,"",str "Wrong argument name: " ++ Nameops.pr_id id);
true
| _ -> false) applied
in
let named = List.map
(fun x -> match x with (t, Some (loc, ExplByName id)) -> id, t | _ -> assert false)
named
in
let needed = List.filter (fun (_, (_, b, _)) -> b = None) needed in
let rec aux ids avoid app need =
match app, need with
[], [] -> List.rev ids, avoid
| app, (_, (Name id, _, _)) :: need when List.mem_assoc id named ->
aux (List.assoc id named :: ids) avoid app need
| (x, None) :: app, (None, (Name id, _, _)) :: need ->
aux (x :: ids) avoid app need
| _, (Some cl, (_, _, _) as d) :: need ->
let t', avoid' = fn avoid d in
aux (t' :: ids) avoid' app need
| x :: app, (None, _) :: need -> aux (fst x :: ids) avoid app need
| [], (None, _ as decl) :: need ->
let t', avoid' = fn avoid decl in
aux (t' :: ids) avoid' app need
| (x,_) :: _, [] ->
user_err_loc (constr_loc x,"",str "Typeclass does not expect more arguments")
in aux [] avoid applied needed
let combine_params_freevar =
fun avoid (_, (na, _, _)) ->
let id' = next_name_away_from na avoid in
(CRef (Ident (dummy_loc, id')), Idset.add id' avoid)
let destClassApp cl =
match cl with
| CApp (loc, (None, CRef ref), l) -> loc, ref, List.map fst l
| CAppExpl (loc, (None, ref), l) -> loc, ref, l
| CRef ref -> loc_of_reference ref, ref, []
| _ -> raise Not_found
let destClassAppExpl cl =
match cl with
| CApp (loc, (None, CRef ref), l) -> loc, ref, l
| CRef ref -> loc_of_reference ref, ref, []
| _ -> raise Not_found
let implicit_application env ?(allow_partial=true) f ty =
let is_class =
try
let (loc, r, _ as clapp) = destClassAppExpl ty in
let (loc, qid) = qualid_of_reference r in
let gr = Nametab.locate qid in
if Typeclasses.is_class gr then Some (clapp, gr) else None
with Not_found -> None
in
match is_class with
| None -> ty, env
| Some ((loc, id, par), gr) ->
let avoid = Idset.union env (ids_of_list (free_vars_of_constr_expr ty ~bound:env [])) in
let c, avoid =
let c = class_info gr in
let (ci, rd) = c.cl_context in
if not allow_partial then
begin
let applen = List.fold_left (fun acc (x, y) -> if y = None then succ acc else acc) 0 par in
let needlen = List.fold_left (fun acc x -> if x = None then succ acc else acc) 0 ci in
if needlen <> applen then
Typeclasses_errors.mismatched_ctx_inst (Global.env ()) Parameters (List.map fst par) rd
end;
let pars = List.rev (List.combine ci rd) in
let args, avoid = combine_params avoid f par pars in
CAppExpl (loc, (None, id), args), avoid
in c, avoid
let implicits_of_rawterm ?(with_products=true) l =
let rec aux i c =
let abs loc na bk t b =
let rest = aux (succ i) b in
if bk = Implicit then
let name =
match na with
| Name id -> Some id
| Anonymous -> None
in
(ExplByPos (i, name), (true, true, true)) :: rest
else rest
in
match c with
| RProd (loc, na, bk, t, b) ->
if with_products then abs loc na bk t b
else
(if bk = Implicit then
msg_warning (str "Ignoring implicit status of product binder " ++
pr_name na ++ str " and following binders");
[])
| RLambda (loc, na, bk, t, b) -> abs loc na bk t b
| RLetIn (loc, na, t, b) -> aux i b
| _ -> []
in aux 1 l
|
56e2f3f44d5af7635284e4981c69f4b35deb76df4def56ef10ba2b51051c9b9c | guibou/PyF | Class.hs | # LANGUAGE DataKinds #
# LANGUAGE DefaultSignatures #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
-- | You want to add formatting support for your custom type. This is the right module.
--
In PyF , formatters are in three categories :
--
-- - Integral numbers, which are numbers without fractional part
-- - Fractional numbers, which are numbers with a fractional part
-- - String, which represents text.
--
-- The formatting can be either explicit or implicit. For example:
--
> > > let x = 10 in [ fmt|{x}| ]
10
--
-- Is an implicit formatting to number, but:
--
> > > let x = 10 in [ fmt|{x : d}| ]
--
Is an explicit formatting to Integral numbers , using @d@.
--
Implicit formatting will only format to either Integral , Fractional or text ,
-- and this choice is done by the (open) type family `PyFCategory'.
--
This modules also provides 3 type class for formatting .
--
-- - 'PyfFormatFractional' and 'PyfFormatIntegral' are responsible for
-- formatting integral and fractional numbers. Default instances are provided
-- respectively for 'Real' and 'Integral'. 'PyFToString' is in charge of
-- formatting text.
module PyF.Class where
import qualified Data.ByteString
import qualified Data.ByteString.Lazy
import Data.Char (ord)
import Data.Int
import qualified Data.Ratio
import qualified Data.Text as SText
import qualified Data.Text.Encoding as E
import qualified Data.Text.Lazy as LText
import qualified Data.Time
import Data.Word
import Numeric.Natural
import PyF.Formatters
-- * Default formatting classification
| The three categories of formatting in ' PyF '
data PyFCategory
= -- | Format as an integral, no fractional part, precise value
PyFIntegral
| -- | Format as a fractional, approximate value with a fractional part
PyFFractional
| -- | Format as a string
PyFString
-- | Classify a type to a 'PyFCategory'
-- This classification will be used to decide which formatting to
-- use when no type specifier in provided.
type family PyFClassify t :: PyFCategory
type instance PyFClassify Integer = 'PyFIntegral
type instance PyFClassify Int = 'PyFIntegral
type instance PyFClassify Int8 = 'PyFIntegral
type instance PyFClassify Int16 = 'PyFIntegral
type instance PyFClassify Int32 = 'PyFIntegral
type instance PyFClassify Int64 = 'PyFIntegral
type instance PyFClassify Natural = 'PyFIntegral
type instance PyFClassify Word = 'PyFIntegral
type instance PyFClassify Word8 = 'PyFIntegral
type instance PyFClassify Word16 = 'PyFIntegral
type instance PyFClassify Word32 = 'PyFIntegral
type instance PyFClassify Word64 = 'PyFIntegral
-- Float numbers
type instance PyFClassify Float = 'PyFFractional
type instance PyFClassify Double = 'PyFFractional
type instance PyFClassify Data.Time.DiffTime = 'PyFFractional
type instance PyFClassify Data.Time.NominalDiffTime = 'PyFFractional
type instance PyFClassify (Data.Ratio.Ratio i) = 'PyFFractional
-- String
type instance PyFClassify String = 'PyFString
type instance PyFClassify LText.Text = 'PyFString
type instance PyFClassify SText.Text = 'PyFString
type instance PyFClassify Data.ByteString.ByteString = 'PyFString
type instance PyFClassify Data.ByteString.Lazy.ByteString = 'PyFString
type instance PyFClassify Char = 'PyFString
-- * String formatting
-- | Convert a type to string
-- This is used for the string formatting.
class PyFToString t where
pyfToString :: t -> String
instance PyFToString String where pyfToString = id
instance PyFToString LText.Text where pyfToString = LText.unpack
instance PyFToString SText.Text where pyfToString = SText.unpack
instance PyFToString Data.ByteString.ByteString where pyfToString = SText.unpack . E.decodeUtf8
instance PyFToString Data.ByteString.Lazy.ByteString where pyfToString = pyfToString . Data.ByteString.Lazy.toStrict
instance PyFToString Char where pyfToString c = [c]
-- | Default instance. Convert any type with a 'Show instance.
instance {-# OVERLAPPABLE #-} Show t => PyFToString t where pyfToString = show
-- * Real formatting (with optional fractional part)
-- | Apply a fractional formatting to any type.
--
-- A default instance for any 'Real' is provided which internally converts to
-- 'Double', which may not be efficient or results in rounding errors.
--
-- You can provide your own instance and internally use 'formatFractional'
-- which does have the same signatures as 'pyfFormatFractional' but with a
' RealFrac ' constraint .
class PyfFormatFractional a where
pyfFormatFractional ::
(Integral paddingWidth, Integral precision) =>
Format t t' 'Fractional ->
-- | Sign formatting
SignMode ->
-- | Padding
Maybe (paddingWidth, AlignMode k, Char) ->
-- | Grouping
Maybe (Int, Char) ->
-- | Precision
Maybe precision ->
a ->
String
-- | Default instance working for any 'Real'. Internally it converts the type to 'Double'.
instance {-# OVERLAPPABLE #-} Real t => PyfFormatFractional t where
pyfFormatFractional f s p g prec v = formatFractional f s p g prec (realToFrac @t @Double v)
-- | This instance does not do any conversion.
instance PyfFormatFractional Double where pyfFormatFractional = formatFractional
-- | This instance does not do any conversion.
instance PyfFormatFractional Float where pyfFormatFractional = formatFractional
-- * Integral formatting
-- | Apply an integral formatting to any type.
--
-- A default instance for any 'Integral' is provided.
--
-- You can provide your own instance and internally use 'formatIntegral'
-- which does have the same signatures as 'pyfFormatIntegral' but with an
-- 'Integral' constraint.
class PyfFormatIntegral i where
pyfFormatIntegral ::
Integral paddingWidth =>
Format t t' 'Integral ->
-- | Sign formatting
SignMode ->
-- | Padding
Maybe (paddingWidth, AlignMode k, Char) ->
-- | Grouping
Maybe (Int, Char) ->
i ->
String
-- | Default instance for any 'Integral'.
instance {-# OVERLAPPABLE #-} Integral t => PyfFormatIntegral t where
pyfFormatIntegral f s p g v = formatIntegral f s p g v
| Returns the numerical value of a ' '
-- >>> [fmt|{'a':d}|]
97
instance PyfFormatIntegral Char where
pyfFormatIntegral f s p g v = formatIntegral f s p g (ord v)
| null | https://raw.githubusercontent.com/guibou/PyF/ff1780e0567aacc4637834dda83499572e655a6d/src/PyF/Class.hs | haskell | | You want to add formatting support for your custom type. This is the right module.
- Integral numbers, which are numbers without fractional part
- Fractional numbers, which are numbers with a fractional part
- String, which represents text.
The formatting can be either explicit or implicit. For example:
Is an implicit formatting to number, but:
and this choice is done by the (open) type family `PyFCategory'.
- 'PyfFormatFractional' and 'PyfFormatIntegral' are responsible for
formatting integral and fractional numbers. Default instances are provided
respectively for 'Real' and 'Integral'. 'PyFToString' is in charge of
formatting text.
* Default formatting classification
| Format as an integral, no fractional part, precise value
| Format as a fractional, approximate value with a fractional part
| Format as a string
| Classify a type to a 'PyFCategory'
This classification will be used to decide which formatting to
use when no type specifier in provided.
Float numbers
String
* String formatting
| Convert a type to string
This is used for the string formatting.
| Default instance. Convert any type with a 'Show instance.
# OVERLAPPABLE #
* Real formatting (with optional fractional part)
| Apply a fractional formatting to any type.
A default instance for any 'Real' is provided which internally converts to
'Double', which may not be efficient or results in rounding errors.
You can provide your own instance and internally use 'formatFractional'
which does have the same signatures as 'pyfFormatFractional' but with a
| Sign formatting
| Padding
| Grouping
| Precision
| Default instance working for any 'Real'. Internally it converts the type to 'Double'.
# OVERLAPPABLE #
| This instance does not do any conversion.
| This instance does not do any conversion.
* Integral formatting
| Apply an integral formatting to any type.
A default instance for any 'Integral' is provided.
You can provide your own instance and internally use 'formatIntegral'
which does have the same signatures as 'pyfFormatIntegral' but with an
'Integral' constraint.
| Sign formatting
| Padding
| Grouping
| Default instance for any 'Integral'.
# OVERLAPPABLE #
>>> [fmt|{'a':d}|] | # LANGUAGE DataKinds #
# LANGUAGE DefaultSignatures #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
In PyF , formatters are in three categories :
> > > let x = 10 in [ fmt|{x}| ]
10
> > > let x = 10 in [ fmt|{x : d}| ]
Is an explicit formatting to Integral numbers , using @d@.
Implicit formatting will only format to either Integral , Fractional or text ,
This modules also provides 3 type class for formatting .
module PyF.Class where
import qualified Data.ByteString
import qualified Data.ByteString.Lazy
import Data.Char (ord)
import Data.Int
import qualified Data.Ratio
import qualified Data.Text as SText
import qualified Data.Text.Encoding as E
import qualified Data.Text.Lazy as LText
import qualified Data.Time
import Data.Word
import Numeric.Natural
import PyF.Formatters
| The three categories of formatting in ' PyF '
data PyFCategory
PyFIntegral
PyFFractional
PyFString
type family PyFClassify t :: PyFCategory
type instance PyFClassify Integer = 'PyFIntegral
type instance PyFClassify Int = 'PyFIntegral
type instance PyFClassify Int8 = 'PyFIntegral
type instance PyFClassify Int16 = 'PyFIntegral
type instance PyFClassify Int32 = 'PyFIntegral
type instance PyFClassify Int64 = 'PyFIntegral
type instance PyFClassify Natural = 'PyFIntegral
type instance PyFClassify Word = 'PyFIntegral
type instance PyFClassify Word8 = 'PyFIntegral
type instance PyFClassify Word16 = 'PyFIntegral
type instance PyFClassify Word32 = 'PyFIntegral
type instance PyFClassify Word64 = 'PyFIntegral
type instance PyFClassify Float = 'PyFFractional
type instance PyFClassify Double = 'PyFFractional
type instance PyFClassify Data.Time.DiffTime = 'PyFFractional
type instance PyFClassify Data.Time.NominalDiffTime = 'PyFFractional
type instance PyFClassify (Data.Ratio.Ratio i) = 'PyFFractional
type instance PyFClassify String = 'PyFString
type instance PyFClassify LText.Text = 'PyFString
type instance PyFClassify SText.Text = 'PyFString
type instance PyFClassify Data.ByteString.ByteString = 'PyFString
type instance PyFClassify Data.ByteString.Lazy.ByteString = 'PyFString
type instance PyFClassify Char = 'PyFString
class PyFToString t where
pyfToString :: t -> String
instance PyFToString String where pyfToString = id
instance PyFToString LText.Text where pyfToString = LText.unpack
instance PyFToString SText.Text where pyfToString = SText.unpack
instance PyFToString Data.ByteString.ByteString where pyfToString = SText.unpack . E.decodeUtf8
instance PyFToString Data.ByteString.Lazy.ByteString where pyfToString = pyfToString . Data.ByteString.Lazy.toStrict
instance PyFToString Char where pyfToString c = [c]
' RealFrac ' constraint .
class PyfFormatFractional a where
pyfFormatFractional ::
(Integral paddingWidth, Integral precision) =>
Format t t' 'Fractional ->
SignMode ->
Maybe (paddingWidth, AlignMode k, Char) ->
Maybe (Int, Char) ->
Maybe precision ->
a ->
String
pyfFormatFractional f s p g prec v = formatFractional f s p g prec (realToFrac @t @Double v)
instance PyfFormatFractional Double where pyfFormatFractional = formatFractional
instance PyfFormatFractional Float where pyfFormatFractional = formatFractional
class PyfFormatIntegral i where
pyfFormatIntegral ::
Integral paddingWidth =>
Format t t' 'Integral ->
SignMode ->
Maybe (paddingWidth, AlignMode k, Char) ->
Maybe (Int, Char) ->
i ->
String
pyfFormatIntegral f s p g v = formatIntegral f s p g v
| Returns the numerical value of a ' '
97
instance PyfFormatIntegral Char where
pyfFormatIntegral f s p g v = formatIntegral f s p g (ord v)
|
34374ad82fd5c030f257ede72d66bf11c8bf6183cfcfad5a8eb05c034e08fbe6 | haskell-mafia/tinfoil | Foreign.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
{-# LANGUAGE OverloadedStrings #-}
module Test.IO.Tinfoil.AEAD.AESGCM.Foreign where
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.Text as T
import Disorder.Core.IO (testIO)
import Disorder.Core.Property (failWith)
import Disorder.Core.Tripping (tripping)
import P
import System.IO
import Test.QuickCheck
import Test.Tinfoil.Arbitrary ()
import Test.Tinfoil.Gen
import Tinfoil.AEAD.AESGCM.Data
import Tinfoil.AEAD.AESGCM.Error
import Tinfoil.AEAD.AESGCM.Foreign
import Tinfoil.Data.Key
import Tinfoil.Internal.Sodium
import X.Control.Monad.Trans.Either (runEitherT)
testSodium :: (SodiumInitMarker -> Property) -> Property
testSodium p =
testIO $ (runEitherT initialiseSodium) >>= \x -> pure $ case x of
Right mark -> p mark
Left err -> failWith . T.pack $ show err
prop_aes256Gcm_encrypt :: AssociatedData -> SymmetricKey -> GcmIv -> Property
prop_aes256Gcm_encrypt ad sk iv = forAll (Cleartext <$> genByteStringWithin (16, 512)) $ \clear ->
testSodium $ \m ->
let
ct = aes256GcmEncrypt m clear ad sk iv
in
not (BS.null $ unCleartext clear) ==>
BS.isInfixOf (unCleartext clear) (unAuthenticatedCiphertext ct) === False
prop_aes256Gcm_decrypt :: ByteString -> AssociatedData -> SymmetricKey -> GcmIv -> Property
prop_aes256Gcm_decrypt ct ad sk iv =
testSodium $ \m ->
let
clear = aes256GcmDecrypt m (AuthenticatedCiphertext ct) ad sk iv
in
isLeft clear === True
prop_aes256Gcm_decrypt_short :: AssociatedData -> SymmetricKey -> GcmIv -> Property
prop_aes256Gcm_decrypt_short ad sk iv = forAll (genByteStringWithin (0, aes256GcmTagLength - 1)) $ \ct ->
testSodium $ \m ->
let
clear = aes256GcmDecrypt m (AuthenticatedCiphertext ct) ad sk iv
in
clear === Left MalformedCiphertext
prop_aes256Gcm :: Cleartext -> AssociatedData -> SymmetricKey -> GcmIv -> Property
prop_aes256Gcm clear ad sk iv =
testSodium $ \m ->
tripping (\msg -> aes256GcmEncrypt m msg ad sk iv) (\ct -> aes256GcmDecrypt m ct ad sk iv) $ clear
return []
tests :: IO Bool
tests = $forAllProperties $ quickCheckWithResult (stdArgs { maxSuccess = 1000 } )
| null | https://raw.githubusercontent.com/haskell-mafia/tinfoil/f46b2ea0b9984ac9a97073932b5584ce0a2e0554/test/Test/IO/Tinfoil/AEAD/AESGCM/Foreign.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
module Test.IO.Tinfoil.AEAD.AESGCM.Foreign where
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.Text as T
import Disorder.Core.IO (testIO)
import Disorder.Core.Property (failWith)
import Disorder.Core.Tripping (tripping)
import P
import System.IO
import Test.QuickCheck
import Test.Tinfoil.Arbitrary ()
import Test.Tinfoil.Gen
import Tinfoil.AEAD.AESGCM.Data
import Tinfoil.AEAD.AESGCM.Error
import Tinfoil.AEAD.AESGCM.Foreign
import Tinfoil.Data.Key
import Tinfoil.Internal.Sodium
import X.Control.Monad.Trans.Either (runEitherT)
testSodium :: (SodiumInitMarker -> Property) -> Property
testSodium p =
testIO $ (runEitherT initialiseSodium) >>= \x -> pure $ case x of
Right mark -> p mark
Left err -> failWith . T.pack $ show err
prop_aes256Gcm_encrypt :: AssociatedData -> SymmetricKey -> GcmIv -> Property
prop_aes256Gcm_encrypt ad sk iv = forAll (Cleartext <$> genByteStringWithin (16, 512)) $ \clear ->
testSodium $ \m ->
let
ct = aes256GcmEncrypt m clear ad sk iv
in
not (BS.null $ unCleartext clear) ==>
BS.isInfixOf (unCleartext clear) (unAuthenticatedCiphertext ct) === False
prop_aes256Gcm_decrypt :: ByteString -> AssociatedData -> SymmetricKey -> GcmIv -> Property
prop_aes256Gcm_decrypt ct ad sk iv =
testSodium $ \m ->
let
clear = aes256GcmDecrypt m (AuthenticatedCiphertext ct) ad sk iv
in
isLeft clear === True
prop_aes256Gcm_decrypt_short :: AssociatedData -> SymmetricKey -> GcmIv -> Property
prop_aes256Gcm_decrypt_short ad sk iv = forAll (genByteStringWithin (0, aes256GcmTagLength - 1)) $ \ct ->
testSodium $ \m ->
let
clear = aes256GcmDecrypt m (AuthenticatedCiphertext ct) ad sk iv
in
clear === Left MalformedCiphertext
prop_aes256Gcm :: Cleartext -> AssociatedData -> SymmetricKey -> GcmIv -> Property
prop_aes256Gcm clear ad sk iv =
testSodium $ \m ->
tripping (\msg -> aes256GcmEncrypt m msg ad sk iv) (\ct -> aes256GcmDecrypt m ct ad sk iv) $ clear
return []
tests :: IO Bool
tests = $forAllProperties $ quickCheckWithResult (stdArgs { maxSuccess = 1000 } )
|
c24293c620ce2f06ed9630ec1231fdf02a38e7b3c53383c62893a65b60833a8c | cyga/real-world-haskell | ParMap.hs | -- file: ch24/ParMap.hs
import Control.Parallel (par)
parallelMap :: (a -> b) -> [a] -> [b]
parallelMap f (x:xs) = let r = f x
in r `par` r : parallelMap f xs
parallelMap _ _ = []
-- file: ch24/ParMap.hs
forceList :: [a] -> ()
forceList (x:xs) = x `pseq` forceList xs
forceList _ = ()
-- file: ch24/ParMap.hs
stricterMap :: (a -> b) -> [a] -> [b]
stricterMap f xs = forceList xs `seq` map f xs
-- file: ch24/ParMap.hs
forceListAndElts :: (a -> ()) -> [a] -> ()
forceListAndElts forceElt (x:xs) =
forceElt x `seq` forceListAndElts forceElt xs
forceListAndElts _ _ = ()
| null | https://raw.githubusercontent.com/cyga/real-world-haskell/4ed581af5b96c6ef03f20d763b8de26be69d43d9/ch24/ParMap.hs | haskell | file: ch24/ParMap.hs
file: ch24/ParMap.hs
file: ch24/ParMap.hs
file: ch24/ParMap.hs | import Control.Parallel (par)
parallelMap :: (a -> b) -> [a] -> [b]
parallelMap f (x:xs) = let r = f x
in r `par` r : parallelMap f xs
parallelMap _ _ = []
forceList :: [a] -> ()
forceList (x:xs) = x `pseq` forceList xs
forceList _ = ()
stricterMap :: (a -> b) -> [a] -> [b]
stricterMap f xs = forceList xs `seq` map f xs
forceListAndElts :: (a -> ()) -> [a] -> ()
forceListAndElts forceElt (x:xs) =
forceElt x `seq` forceListAndElts forceElt xs
forceListAndElts _ _ = ()
|
9065d955507123ff904d1d346ed8c2f2f2e5fab3325d0236bafaf8c78df723fc | YoshikuniJujo/test_haskell | TH.hs | # LANGUAGE BlockArguments #
# OPTIONS_GHC -Wall -fno - warn - tabs #
module Data.Swizzle.TH (swizzle) where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Data.Maybe
import Data.List
import Data.Char
import Data.Swizzle.Class.Pkg
swizzle :: String -> DecsQ
swizzle nm = sequence [mkSwizzleSig i nm, mkSwizzleFun nm]
where i = maximum $ unalphabet <$> nm
mkSwizzleSig :: Int -> String -> Q Dec
mkSwizzleSig i nm = sigD (mkName nm) . forallT [] (mkSwizzleSigContext i)
$ varT (mkName "a") `arrT` mkSwizzleSigTup nm (mkName "a")
mkSwizzleSigContext :: Int -> CxtQ
mkSwizzleSigContext i = cxt [clsSwizzle i `appT` varT (mkName "a")]
mkSwizzleSigTup :: String -> Name -> TypeQ
mkSwizzleSigTup cs a = tupT $ (<$> cs) \c -> typX c `appT` varT a
clsSwizzle :: Int -> TypeQ
clsSwizzle = conT . mkNameG_tc swizzleClassPkg "Data.Swizzle.Class" . ("Swizzle" ++) . show
funX :: Char -> ExpQ
funX = varE . mkNameG_v swizzleClassPkg "Data.Swizzle.Class" . (: "")
typX :: Char -> TypeQ
typX = conT . mkNameG_tc swizzleClassPkg "Data.Swizzle.Class" . (: "") . toUpper
tupT :: [TypeQ] -> TypeQ
tupT ts = foldl appT (tupleT $ length ts) ts
unalphabet :: Char -> Int
unalphabet c = fromJust (elemIndex c $ ("xyz" ++ reverse ['a' .. 'w'])) + 1
arrT :: TypeQ -> TypeQ -> TypeQ
t1 `arrT` t2 = arrowT `appT` t1 `appT` t2
mkSwizzleFun :: String -> Q Dec
mkSwizzleFun nm = newName "a" >>= \a -> funD (mkName nm) [
clause [varP a] (normalB $ mkSwizzleFunTup nm a) [] ]
mkSwizzleFunTup :: String -> Name -> ExpQ
mkSwizzleFunTup nm a = tupE $ (<$> nm) \c -> funX c `appE` varE a
| null | https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/75d6f5df14aa0f254215c3ae700a35d1493910d5/themes/swizzle/try-swizzle/src/Data/Swizzle/TH.hs | haskell | # LANGUAGE BlockArguments #
# OPTIONS_GHC -Wall -fno - warn - tabs #
module Data.Swizzle.TH (swizzle) where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Data.Maybe
import Data.List
import Data.Char
import Data.Swizzle.Class.Pkg
swizzle :: String -> DecsQ
swizzle nm = sequence [mkSwizzleSig i nm, mkSwizzleFun nm]
where i = maximum $ unalphabet <$> nm
mkSwizzleSig :: Int -> String -> Q Dec
mkSwizzleSig i nm = sigD (mkName nm) . forallT [] (mkSwizzleSigContext i)
$ varT (mkName "a") `arrT` mkSwizzleSigTup nm (mkName "a")
mkSwizzleSigContext :: Int -> CxtQ
mkSwizzleSigContext i = cxt [clsSwizzle i `appT` varT (mkName "a")]
mkSwizzleSigTup :: String -> Name -> TypeQ
mkSwizzleSigTup cs a = tupT $ (<$> cs) \c -> typX c `appT` varT a
clsSwizzle :: Int -> TypeQ
clsSwizzle = conT . mkNameG_tc swizzleClassPkg "Data.Swizzle.Class" . ("Swizzle" ++) . show
funX :: Char -> ExpQ
funX = varE . mkNameG_v swizzleClassPkg "Data.Swizzle.Class" . (: "")
typX :: Char -> TypeQ
typX = conT . mkNameG_tc swizzleClassPkg "Data.Swizzle.Class" . (: "") . toUpper
tupT :: [TypeQ] -> TypeQ
tupT ts = foldl appT (tupleT $ length ts) ts
unalphabet :: Char -> Int
unalphabet c = fromJust (elemIndex c $ ("xyz" ++ reverse ['a' .. 'w'])) + 1
arrT :: TypeQ -> TypeQ -> TypeQ
t1 `arrT` t2 = arrowT `appT` t1 `appT` t2
mkSwizzleFun :: String -> Q Dec
mkSwizzleFun nm = newName "a" >>= \a -> funD (mkName nm) [
clause [varP a] (normalB $ mkSwizzleFunTup nm a) [] ]
mkSwizzleFunTup :: String -> Name -> ExpQ
mkSwizzleFunTup nm a = tupE $ (<$> nm) \c -> funX c `appE` varE a
| |
953b5a30d3a53f60c1d20618988dd81a4bd27c78da20574df3db1b17718226eb | liebke/avout | state.clj | (ns avout.state)
;; shared protocols
(defprotocol Identity
(getName [this])
(init [this])
(destroy [this]))
(defprotocol StateContainer
(initStateContainer [this])
(destroyStateContainer [this])
(getState [this])
(setState [this value]))
(defprotocol VersionedStateContainer
(initVersionedStateContainer [this])
(destroyVersionedStateContainer [this])
(getStateAt [this version])
(setStateAt [this value version])
(deleteStateAt [this version]))
(defprotocol StateCache
(setCache [this value])
(setCacheAt [this value version])
(getCache [this])
(cachedVersion [this])
(invalidateCache [this]))
| null | https://raw.githubusercontent.com/liebke/avout/06f3e00d63f487ebd01581343302e96b915f5b03/src/avout/state.clj | clojure | shared protocols | (ns avout.state)
(defprotocol Identity
(getName [this])
(init [this])
(destroy [this]))
(defprotocol StateContainer
(initStateContainer [this])
(destroyStateContainer [this])
(getState [this])
(setState [this value]))
(defprotocol VersionedStateContainer
(initVersionedStateContainer [this])
(destroyVersionedStateContainer [this])
(getStateAt [this version])
(setStateAt [this value version])
(deleteStateAt [this version]))
(defprotocol StateCache
(setCache [this value])
(setCacheAt [this value version])
(getCache [this])
(cachedVersion [this])
(invalidateCache [this]))
|
e12721785a7eb4863c73023d843a246e0adf89afd61cdf8aabf7bb945834f2aa | azimut/shiny | incudine.lisp | (in-package :shiny)
( dsp !
( ( buf buffer ) rate start - pos
( loop - p boolean ) attenuation rms ( ) )
(: defaults 0d0 -1 0 nil .00001 0 10 )
;; (with-samples
;; ((in (incudine.vug:buffer-play
buf rate start - pos loop - p # ' stop ) )
;; (inn (* in attenuation))
; ; ( inn ( incudine.vug : downsamp ) )
;; )
;; (out inn inn)))
( dsp !
( ( buf buffer ) rate start - pos
( loop - p boolean ) attenuation rms ( ) )
(: defaults 0d0 1 0 nil .00001 0 10 )
;; (with-samples
;; ((in (incudine.vug:buffer-play
buf rate start - pos loop - p # ' incudine : free ) )
;; (inn (* in attenuation))
;; (inn (+ inn
; ; ( incudine.vug : buzz 2 .1 2 )
; ; ( incudine.vug : downsamp 10 inn )
; ; ( incudine.vug : lpf inn 100 1 )
; ; ( incudine.vug : hpf inn 200 10 )
; ; ( incudine.vug : butter - hp inn 1000 )
;; ))
;; )
;; (out inn inn)))
( defvar * buf * ( make - buffer 512 : channels 1 ) )
;; From Music V family.
(define-vug rms (in hp)
(:defaults 0 10)
(with-samples ((b (- 2 (cos (* hp *twopi-div-sr*))))
(c2 (- b (sqrt (the non-negative-sample (1- (* b b))))))
(c1 (- 1 c2))
(in2 (* in in))
(q +sample-zero+))
(sqrt (the non-negative-sample (~ (+ (* c1 in2) (* c2 it)))))))
( dsp ! rms - master - out - test ( ( index fixnum ) )
;; (:defaults 0)
( setf ( aref - c * c - arr * index )
;; (coerce (audio-out 0) 'single-float))
( setf index
( mod ( 1 + index ) 512 ) ) )
( dsp ! rms - master - out - test ( ( index fixnum ) )
;; (:defaults 0)
( setf ( smp - ref ( incudine::buffer - base - data- * buf * ) index )
;; (rms (audio-out 0)))
( setf index
;; (mod (1+ index) (the fixnum (buffer-size *buf*)))))
(define-vug select (l)
(car (alexandria:shuffle l)))
(dsp! ambi (freq vol)
(:defaults 100 1)
(with-samples
((note (incudine.vug:lag 70 1))
(freq (midihz note))
(detune1 (incudine.vug:lag 12 1))
(detune2 (incudine.vug:lag 24 1))
(freq2 (midihz (+ note detune1)))
(freq3 (midihz (+ note detune2)))
(noise (select (list (pink-noise .002)
(white-noise .002))))
(in (+ (incudine.vug:ringz noise freq .2)
(incudine.vug:ringz noise freq .2)
(incudine.vug:ringz noise freq2 .2)
(incudine.vug:ringz noise freq3 .2)))
(in (tanh in))
(in (incudine.vug:lpf in 110 .1))
(in (* 100 in)))
(out in in)))
(ambi :id 2)
(incudine:free (node 2))
/
(bbuffer-load "/home/sendai/Downloads/sample/LOG0119.wav")
(bbuffer-load "/home/sendai/Downloads/sample/LOG0120.wav")
(put-phrase "joy" "LOG0120.wav" 5.5 3.7)
(put-phrase "apart" "LOG0120.wav" 9 4)
(put-phrase "separate" "LOG0120.wav" 13 .8)
(put-phrase "individual" "LOG0120.wav" 14.5 4)
(put-phrase "undo" "LOG0119.wav" 17 2.2)
(word-play "joy" :rate 1)
;;--------------------------------------------------
(bbuffer-load
"/home/sendai/projects/sonic-pi/etc/samples/guit_em9.flac")
(bbuffer-load
"/home/sendai/projects/sonic-pi/etc/samples/loop_garzul.flac")
(defun f (time)
(bbplay (gethash "ice.ogg" *buffers*)
: rate ( pick .25 .5 1 )
:beat-length 8
:attenuation .5
;; :id 2
)
( bbplay ( gethash " guit_em9.flac " * buffers * )
; ; : rate ( pick .25 .5 1 )
: beat - length 8
: attenuation .5
;; ;; :id 2
;; )
( bbplay ( gethash " loop_garzul.flac " * buffers * )
: rate ( pick .5 1 )
: attenuation 1
;; :id 3)
(aat (+ time #[8 b]) #'f it))
(defun f ())
(f (now))
(incudine:free (node 0))
;;--------------------------------------------------
(bbuffer-load "/home/sendai/Downloads/sample/EM0902-EM0902.wav")
(bplay (gethash "EM0902-EM0902.wav" *buffers*) 1 0 nil
:attenuation 1
:id 2)
(bbuffer-load "/home/sendai/Downloads/sample/LOG0106.wav")
(bbplay (gethash "LOG0106.wav" *buffers*)
:attenuation 1
:id 3
:loop-p nil)
(bbuffer-load "/home/sendai/Downloads/sample/EM0903.wav")
(bbplay (gethash "EM0903.wav" *buffers*)
:beat-length 8)
(bplay (gethash "EM0903.wav" *buffers*) 1 0 nil
:attenuation 1)
(put-phrase "nuisance" "EM0903.wav" 21 1)
(put-phrase "why" "EM0903.wav" 8.4 2)
(put-phrase "feel" "EM0903.wav" 10.5 3)
(word-play (pick "why" "nuisance" "feel")
:rate (pick 1 2 1.5)
:id (1+ (random 30)))
(word-play "why")
(word-play "nuisance" :beat-length 4)
(incudine:free (node 0))
(bbuffer-load "/home/sendai/whatever.wav")
(bplay (gethash "whatever.wav" *buffers*) 1 0 nil
:attenuation 1
:id 2)
(defun g ())
(defun g (time)
(let ((cfreq (drunk 60 5)))
(set-controls
2
:cfreq cfreq
:rate (funcall (pick '+ '+ '+ '- '+ '+ '+ '+)
(+ cfreq (pick 0 0 1 -1 -2)))))
(aat (+ time #[1 b]) #'g it))
(g (now))
(set-controls
2
:rate 1f0
:attenuation 1d0
:cfreq 1)
;;--------------------------------------------------
(make-instrument 'drum "/home/sendai/Downloads/sample/OH/")
(push-note 'drum *gm-kick* "kick_OH_F_9.wav")
(push-note 'drum *gm-side-stick* "snareStick_OH_F_9.wav")
(push-note 'drum *gm-snare* "snare_OH_FF_9.wav")
(push-note 'drum *gm-closed-hi-hat* "hihatClosed_OH_F_20.wav")
(push-note 'drum *gm-pedal-hi-hat* "hihatFoot_OH_MP_12.wav")
(push-note 'drum *gm-open-hi-hat* "hihatOpen_OH_FF_6.wav")
(push-note 'drum *gm-low-floor-tom* "loTom_OH_FF_8.wav")
(push-note 'drum *gm-hi-floor-tom* "hiTom_OH_FF_9.wav")
(push-note 'drum *gm-crash* "crash1_OH_FF_6.wav")
(push-note 'drum *gm-ride* "ride1_OH_FF_4.wav")
(push-note 'drum *gm-chinese* "china1_OH_FF_8.wav")
(push-note 'drum *gm-cowbell* "cowbell_FF_9.wav")
(push-note 'drum *gm-open-triangle* "bellchime_F_3.wav")
(push-note 'drum *gm-ride-bell* "ride1Bell_OH_F_6.wav")
(defun f (time dur &optional (beat 0))
(and (zmod beat 1) (bbplay (gethash "kick_OH_F_9.wav" *buffers*)
:attenuation 1d0
:left .1))
(and (zmod beat 3) (play-instrument 'drum *gm-snare* :dur dur :amp .4))
( and ( beat 2 ) ( play - instrument ' drum * gm - side - stick * dur .4 ) )
( and ( beat 2.5 ) ( play - instrument ' drum * gm - side - stick * dur .4 ) )
(aat (+ time #[dur b]) #'f it .5 (+ beat dur)))
(defun f ())
(f (now) 1)
(pat (now))
(defun pat ())
(defpattern pat ((get-pattern 'getup) .2)
(if (odds .5)
(bbplay (gethash "kick_OH_F_9.wav" *buffers*)
:attenuation 1d0
:left .1)
(bbplay (gethash "kick_OH_F_9.wav" *buffers*)
:attenuation 1d0
:right .1))
(bbplay (gethash "snareStick_OH_F_9.wav" *buffers*)
:attenuation 1d0)
(bbplay (gethash "hihatClosed_OH_F_20.wav" *buffers*)
:attenuation 1d0))
;;--------------------------------------------------
| null | https://raw.githubusercontent.com/azimut/shiny/774381a9bde21c4ec7e7092c7516dd13a5a50780/compositions/drafts/incudine.lisp | lisp | (with-samples
((in (incudine.vug:buffer-play
(inn (* in attenuation))
; ( inn ( incudine.vug : downsamp ) )
)
(out inn inn)))
(with-samples
((in (incudine.vug:buffer-play
(inn (* in attenuation))
(inn (+ inn
; ( incudine.vug : buzz 2 .1 2 )
; ( incudine.vug : downsamp 10 inn )
; ( incudine.vug : lpf inn 100 1 )
; ( incudine.vug : hpf inn 200 10 )
; ( incudine.vug : butter - hp inn 1000 )
))
)
(out inn inn)))
From Music V family.
(:defaults 0)
(coerce (audio-out 0) 'single-float))
(:defaults 0)
(rms (audio-out 0)))
(mod (1+ index) (the fixnum (buffer-size *buf*)))))
--------------------------------------------------
:id 2
; : rate ( pick .25 .5 1 )
;; :id 2
)
:id 3)
--------------------------------------------------
--------------------------------------------------
-------------------------------------------------- | (in-package :shiny)
( dsp !
( ( buf buffer ) rate start - pos
( loop - p boolean ) attenuation rms ( ) )
(: defaults 0d0 -1 0 nil .00001 0 10 )
buf rate start - pos loop - p # ' stop ) )
( dsp !
( ( buf buffer ) rate start - pos
( loop - p boolean ) attenuation rms ( ) )
(: defaults 0d0 1 0 nil .00001 0 10 )
buf rate start - pos loop - p # ' incudine : free ) )
( defvar * buf * ( make - buffer 512 : channels 1 ) )
(define-vug rms (in hp)
(:defaults 0 10)
(with-samples ((b (- 2 (cos (* hp *twopi-div-sr*))))
(c2 (- b (sqrt (the non-negative-sample (1- (* b b))))))
(c1 (- 1 c2))
(in2 (* in in))
(q +sample-zero+))
(sqrt (the non-negative-sample (~ (+ (* c1 in2) (* c2 it)))))))
( dsp ! rms - master - out - test ( ( index fixnum ) )
( setf ( aref - c * c - arr * index )
( setf index
( mod ( 1 + index ) 512 ) ) )
( dsp ! rms - master - out - test ( ( index fixnum ) )
( setf ( smp - ref ( incudine::buffer - base - data- * buf * ) index )
( setf index
(define-vug select (l)
(car (alexandria:shuffle l)))
(dsp! ambi (freq vol)
(:defaults 100 1)
(with-samples
((note (incudine.vug:lag 70 1))
(freq (midihz note))
(detune1 (incudine.vug:lag 12 1))
(detune2 (incudine.vug:lag 24 1))
(freq2 (midihz (+ note detune1)))
(freq3 (midihz (+ note detune2)))
(noise (select (list (pink-noise .002)
(white-noise .002))))
(in (+ (incudine.vug:ringz noise freq .2)
(incudine.vug:ringz noise freq .2)
(incudine.vug:ringz noise freq2 .2)
(incudine.vug:ringz noise freq3 .2)))
(in (tanh in))
(in (incudine.vug:lpf in 110 .1))
(in (* 100 in)))
(out in in)))
(ambi :id 2)
(incudine:free (node 2))
/
(bbuffer-load "/home/sendai/Downloads/sample/LOG0119.wav")
(bbuffer-load "/home/sendai/Downloads/sample/LOG0120.wav")
(put-phrase "joy" "LOG0120.wav" 5.5 3.7)
(put-phrase "apart" "LOG0120.wav" 9 4)
(put-phrase "separate" "LOG0120.wav" 13 .8)
(put-phrase "individual" "LOG0120.wav" 14.5 4)
(put-phrase "undo" "LOG0119.wav" 17 2.2)
(word-play "joy" :rate 1)
(bbuffer-load
"/home/sendai/projects/sonic-pi/etc/samples/guit_em9.flac")
(bbuffer-load
"/home/sendai/projects/sonic-pi/etc/samples/loop_garzul.flac")
(defun f (time)
(bbplay (gethash "ice.ogg" *buffers*)
: rate ( pick .25 .5 1 )
:beat-length 8
:attenuation .5
)
( bbplay ( gethash " guit_em9.flac " * buffers * )
: beat - length 8
: attenuation .5
( bbplay ( gethash " loop_garzul.flac " * buffers * )
: rate ( pick .5 1 )
: attenuation 1
(aat (+ time #[8 b]) #'f it))
(defun f ())
(f (now))
(incudine:free (node 0))
(bbuffer-load "/home/sendai/Downloads/sample/EM0902-EM0902.wav")
(bplay (gethash "EM0902-EM0902.wav" *buffers*) 1 0 nil
:attenuation 1
:id 2)
(bbuffer-load "/home/sendai/Downloads/sample/LOG0106.wav")
(bbplay (gethash "LOG0106.wav" *buffers*)
:attenuation 1
:id 3
:loop-p nil)
(bbuffer-load "/home/sendai/Downloads/sample/EM0903.wav")
(bbplay (gethash "EM0903.wav" *buffers*)
:beat-length 8)
(bplay (gethash "EM0903.wav" *buffers*) 1 0 nil
:attenuation 1)
(put-phrase "nuisance" "EM0903.wav" 21 1)
(put-phrase "why" "EM0903.wav" 8.4 2)
(put-phrase "feel" "EM0903.wav" 10.5 3)
(word-play (pick "why" "nuisance" "feel")
:rate (pick 1 2 1.5)
:id (1+ (random 30)))
(word-play "why")
(word-play "nuisance" :beat-length 4)
(incudine:free (node 0))
(bbuffer-load "/home/sendai/whatever.wav")
(bplay (gethash "whatever.wav" *buffers*) 1 0 nil
:attenuation 1
:id 2)
(defun g ())
(defun g (time)
(let ((cfreq (drunk 60 5)))
(set-controls
2
:cfreq cfreq
:rate (funcall (pick '+ '+ '+ '- '+ '+ '+ '+)
(+ cfreq (pick 0 0 1 -1 -2)))))
(aat (+ time #[1 b]) #'g it))
(g (now))
(set-controls
2
:rate 1f0
:attenuation 1d0
:cfreq 1)
(make-instrument 'drum "/home/sendai/Downloads/sample/OH/")
(push-note 'drum *gm-kick* "kick_OH_F_9.wav")
(push-note 'drum *gm-side-stick* "snareStick_OH_F_9.wav")
(push-note 'drum *gm-snare* "snare_OH_FF_9.wav")
(push-note 'drum *gm-closed-hi-hat* "hihatClosed_OH_F_20.wav")
(push-note 'drum *gm-pedal-hi-hat* "hihatFoot_OH_MP_12.wav")
(push-note 'drum *gm-open-hi-hat* "hihatOpen_OH_FF_6.wav")
(push-note 'drum *gm-low-floor-tom* "loTom_OH_FF_8.wav")
(push-note 'drum *gm-hi-floor-tom* "hiTom_OH_FF_9.wav")
(push-note 'drum *gm-crash* "crash1_OH_FF_6.wav")
(push-note 'drum *gm-ride* "ride1_OH_FF_4.wav")
(push-note 'drum *gm-chinese* "china1_OH_FF_8.wav")
(push-note 'drum *gm-cowbell* "cowbell_FF_9.wav")
(push-note 'drum *gm-open-triangle* "bellchime_F_3.wav")
(push-note 'drum *gm-ride-bell* "ride1Bell_OH_F_6.wav")
(defun f (time dur &optional (beat 0))
(and (zmod beat 1) (bbplay (gethash "kick_OH_F_9.wav" *buffers*)
:attenuation 1d0
:left .1))
(and (zmod beat 3) (play-instrument 'drum *gm-snare* :dur dur :amp .4))
( and ( beat 2 ) ( play - instrument ' drum * gm - side - stick * dur .4 ) )
( and ( beat 2.5 ) ( play - instrument ' drum * gm - side - stick * dur .4 ) )
(aat (+ time #[dur b]) #'f it .5 (+ beat dur)))
(defun f ())
(f (now) 1)
(pat (now))
(defun pat ())
(defpattern pat ((get-pattern 'getup) .2)
(if (odds .5)
(bbplay (gethash "kick_OH_F_9.wav" *buffers*)
:attenuation 1d0
:left .1)
(bbplay (gethash "kick_OH_F_9.wav" *buffers*)
:attenuation 1d0
:right .1))
(bbplay (gethash "snareStick_OH_F_9.wav" *buffers*)
:attenuation 1d0)
(bbplay (gethash "hihatClosed_OH_F_20.wav" *buffers*)
:attenuation 1d0))
|
20ef3b9cc6d0e5418de1266c5a7e9cb1aa239f79aee4fb0d2029534c43c5c977 | michiakig/LispInSmallPieces | reflisp.scm | $ I d : reflisp.scm , v 1.6 2006/11/24 18:37:22
;;;(((((((((((((((((((((((((((((((( L i S P ))))))))))))))))))))))))))))))))
;;; This file is part of the files that accompany the book:
LISP Implantation Semantique Programmation ( InterEditions , France )
By Christian Queinnec < >
;;; Newest version may be retrieved from:
( IP 128.93.2.54 ) ftp.inria.fr : INRIA / Projects / icsla / Books / LiSP*.tar.gz
;;; Check the README file before using this file.
;;;(((((((((((((((((((((((((((((((( L i S P ))))))))))))))))))))))))))))))))
;;; A reflective interpreter with non-systematically reified
;;; continuation and environment. These can be obtained through the-environment
;;; and call/cc. Special forms are coded as fexprs.
Bytecode size roughly 1 K bytes ( actually 1362 bytes )
cons - size : 583 .
(apply
(lambda (make-toplevel make-flambda flambda? flambda-apply)
(set! make-toplevel
(lambda (prompt-in prompt-out)
(call/cc
(lambda (exit)
(monitor (lambda (c b) (exit b))
((lambda (it extend error global-env
toplevel eval evlis eprogn reference )
(set! extend
(lambda (env names values)
(if (pair? names)
(if (pair? values)
((lambda (newenv)
(begin
(set-variable-value!
(car names)
newenv
(car values) )
(extend newenv (cdr names)
(cdr values) ) ) )
(enrich env (car names)) )
(error "Too few arguments" names) )
(if (symbol? names)
((lambda (newenv)
(begin
(set-variable-value!
names newenv values )
newenv ) )
(enrich env names) )
(if (null? names)
(if (null? values)
env
(error
"Too much arguments"
values ) )
env ) ) ) ) )
(set! error (lambda (msg hint)
(exit (list msg hint)) ))
(set! toplevel
(lambda (genv)
(set! global-env genv)
(display prompt-in)
((lambda (result)
(set! it result)
(display prompt-out)
(display result)
(newline) )
((lambda (e)
(if (eof-object? e)
(exit e)
(eval e global-env) ) )
(read) ) )
(toplevel global-env) ) )
(set! eval
(lambda (e r)
(if (pair? e)
((lambda (f)
(if (flambda? f)
(flambda-apply f r (cdr e))
(apply f (evlis (cdr e) r)) ) )
(eval (car e) r) )
(if (symbol? e)
(reference e r)
e ) ) ) )
(set! evlis
(lambda (e* r)
(if (pair? e*)
((lambda (v)
(cons v (evlis (cdr e*) r)) )
(eval (car e*) r) )
'() ) ) )
(set! eprogn
(lambda (e+ r)
(if (pair? (cdr e+))
(begin (eval (car e+) r)
(eprogn (cdr e+) r) )
(eval (car e+) r) ) ) )
(set! reference
(lambda (name r)
(if (variable-defined? name r)
(variable-value name r)
(if (variable-defined? name global-env)
(variable-value name global-env)
(error "No such variable"
name ) ) ) ) )
((lambda (quote if set! lambda flambda monitor)
(toplevel (the-environment)) )
(make-flambda
(lambda (r quotation) quotation) )
(make-flambda
(lambda (r condition then else)
(eval (if (eval condition r) then else) r) ) )
(make-flambda
(lambda (r name form)
((lambda (v)
(if (variable-defined? name r)
(set-variable-value! name r v)
(if (variable-defined? name global-env)
(set-variable-value!
name global-env v )
(error "No such variable"
name ) ) ))
(eval form r) ) ) )
(make-flambda
(lambda (r variables . body)
(lambda values
(eprogn body
(extend r variables values) ) ) ) )
(make-flambda
(lambda (r variables . body)
(make-flambda
(lambda (rr . parameters)
(eprogn body
(extend r variables
(cons rr
parameters
) ) ) ) ) ) )
(make-flambda
(lambda (r handler . body)
(monitor (eval handler r)
(eprogn body r) ) ) ) ) )
'it 'extend 'error 'global-env
'toplevel 'eval 'evlis 'eprogn 'reference ) ) ) ) ) )
(make-toplevel "?? " "== ") )
'make-toplevel
((lambda (flambda-tag)
(list (lambda (behavior) (cons flambda-tag behavior))
(lambda (o) (if (pair? o) (= (car o) flambda-tag) #f))
(lambda (f r parms) (apply (cdr f) r parms)) ) )
98127634 ) )
;;; end of chap8j.scm
| null | https://raw.githubusercontent.com/michiakig/LispInSmallPieces/0a2762d539a5f4c7488fffe95722790ac475c2ea/si/reflisp.scm | scheme | (((((((((((((((((((((((((((((((( L i S P ))))))))))))))))))))))))))))))))
This file is part of the files that accompany the book:
Newest version may be retrieved from:
Check the README file before using this file.
(((((((((((((((((((((((((((((((( L i S P ))))))))))))))))))))))))))))))))
A reflective interpreter with non-systematically reified
continuation and environment. These can be obtained through the-environment
and call/cc. Special forms are coded as fexprs.
end of chap8j.scm | $ I d : reflisp.scm , v 1.6 2006/11/24 18:37:22
LISP Implantation Semantique Programmation ( InterEditions , France )
By Christian Queinnec < >
( IP 128.93.2.54 ) ftp.inria.fr : INRIA / Projects / icsla / Books / LiSP*.tar.gz
Bytecode size roughly 1 K bytes ( actually 1362 bytes )
cons - size : 583 .
(apply
(lambda (make-toplevel make-flambda flambda? flambda-apply)
(set! make-toplevel
(lambda (prompt-in prompt-out)
(call/cc
(lambda (exit)
(monitor (lambda (c b) (exit b))
((lambda (it extend error global-env
toplevel eval evlis eprogn reference )
(set! extend
(lambda (env names values)
(if (pair? names)
(if (pair? values)
((lambda (newenv)
(begin
(set-variable-value!
(car names)
newenv
(car values) )
(extend newenv (cdr names)
(cdr values) ) ) )
(enrich env (car names)) )
(error "Too few arguments" names) )
(if (symbol? names)
((lambda (newenv)
(begin
(set-variable-value!
names newenv values )
newenv ) )
(enrich env names) )
(if (null? names)
(if (null? values)
env
(error
"Too much arguments"
values ) )
env ) ) ) ) )
(set! error (lambda (msg hint)
(exit (list msg hint)) ))
(set! toplevel
(lambda (genv)
(set! global-env genv)
(display prompt-in)
((lambda (result)
(set! it result)
(display prompt-out)
(display result)
(newline) )
((lambda (e)
(if (eof-object? e)
(exit e)
(eval e global-env) ) )
(read) ) )
(toplevel global-env) ) )
(set! eval
(lambda (e r)
(if (pair? e)
((lambda (f)
(if (flambda? f)
(flambda-apply f r (cdr e))
(apply f (evlis (cdr e) r)) ) )
(eval (car e) r) )
(if (symbol? e)
(reference e r)
e ) ) ) )
(set! evlis
(lambda (e* r)
(if (pair? e*)
((lambda (v)
(cons v (evlis (cdr e*) r)) )
(eval (car e*) r) )
'() ) ) )
(set! eprogn
(lambda (e+ r)
(if (pair? (cdr e+))
(begin (eval (car e+) r)
(eprogn (cdr e+) r) )
(eval (car e+) r) ) ) )
(set! reference
(lambda (name r)
(if (variable-defined? name r)
(variable-value name r)
(if (variable-defined? name global-env)
(variable-value name global-env)
(error "No such variable"
name ) ) ) ) )
((lambda (quote if set! lambda flambda monitor)
(toplevel (the-environment)) )
(make-flambda
(lambda (r quotation) quotation) )
(make-flambda
(lambda (r condition then else)
(eval (if (eval condition r) then else) r) ) )
(make-flambda
(lambda (r name form)
((lambda (v)
(if (variable-defined? name r)
(set-variable-value! name r v)
(if (variable-defined? name global-env)
(set-variable-value!
name global-env v )
(error "No such variable"
name ) ) ))
(eval form r) ) ) )
(make-flambda
(lambda (r variables . body)
(lambda values
(eprogn body
(extend r variables values) ) ) ) )
(make-flambda
(lambda (r variables . body)
(make-flambda
(lambda (rr . parameters)
(eprogn body
(extend r variables
(cons rr
parameters
) ) ) ) ) ) )
(make-flambda
(lambda (r handler . body)
(monitor (eval handler r)
(eprogn body r) ) ) ) ) )
'it 'extend 'error 'global-env
'toplevel 'eval 'evlis 'eprogn 'reference ) ) ) ) ) )
(make-toplevel "?? " "== ") )
'make-toplevel
((lambda (flambda-tag)
(list (lambda (behavior) (cons flambda-tag behavior))
(lambda (o) (if (pair? o) (= (car o) flambda-tag) #f))
(lambda (f r parms) (apply (cdr f) r parms)) ) )
98127634 ) )
|
adff2bd1a5ca6dfceb871602d21407b35940d59cc16bfebc90574adfb836b993 | LennMars/algorithms_in_OCaml | util.ml | include UtilPervasives
module List = struct
include List
include UtilList
end
module Array = struct
include Array
include UtilArray
end
| null | https://raw.githubusercontent.com/LennMars/algorithms_in_OCaml/f7fb8ca9f497883d86be3167bfc98a4a28ac73c9/util/util.ml | ocaml | include UtilPervasives
module List = struct
include List
include UtilList
end
module Array = struct
include Array
include UtilArray
end
| |
eee477b602cbe19986ed667423e493ac18b4a06b04fdf60e02b4ade8192acb96 | georgjz/raylib-gambit-scheme | npatchinfo.scm | ;;;-----------------------------------------------------------------------------
This file is the interface to the struct RenderNPatchInfo in .
;;;-----------------------------------------------------------------------------
(c-declare #<<c-declare-end
#include "raylib.h"
NPatchInfo MakeNPatchInfo( Rectangle sourceRec,
int left, int top,
int right, int bottom,
int type )
{
return (NPatchInfo){ sourceRec, left, top, right, bottom, type };
}
___SCMOBJ SCMOBJ_to_NPATCHINFO( ___PSD ___SCMOBJ src, NPatchInfo *dst, int arg_num )
{
___SCMOBJ ___err = ___FIX( ___NO_ERR );
if ( !___PAIRP( src ) )
___err = ___FIX( ___UNKNOWN_ERR );
else
{
___SCMOBJ source_rec = ___CAR( src );
___SCMOBJ left = ___CADR( src );
___SCMOBJ top = ___CADDR( src );
___SCMOBJ right = ___CADDDR( src );
___SCMOBJ bottom = ___CAR( ___CDDDDR( src ) );
___SCMOBJ type = ___CADR( ___CDDDDR( src ) );
___BEGIN_CFUN_SCMOBJ_to_RECTANGLE( source_rec, dst->sourceRec, arg_num )
___BEGIN_CFUN_SCMOBJ_TO_INT( left, dst->left, arg_num )
___BEGIN_CFUN_SCMOBJ_TO_INT( top, dst->top, arg_num )
___BEGIN_CFUN_SCMOBJ_TO_INT( right, dst->right, arg_num )
___BEGIN_CFUN_SCMOBJ_TO_INT( bottom, dst->bottom, arg_num )
___BEGIN_CFUN_SCMOBJ_TO_INT( type, dst->type, arg_num )
___END_CFUN_SCMOBJ_TO_INT( bottom, dst->bottom, arg_num )
___END_CFUN_SCMOBJ_TO_INT( right, dst->right, arg_num )
___END_CFUN_SCMOBJ_TO_INT( top, dst->top, arg_num )
___END_CFUN_SCMOBJ_TO_INT( type, dst->type, arg_num )
___END_CFUN_SCMOBJ_TO_INT( left, dst->left, arg_num )
___END_CFUN_SCMOBJ_to_RECTANGLE( source_rec, dst->sourceRec, arg_num )
}
return ___err;
}
___SCMOBJ NPATCHINFO_to_SCMOBJ( ___processor_state ___ps, NPatchInfo src, ___SCMOBJ *dst, int arg_num )
{
___SCMOBJ ___err = ___FIX( ___NO_ERR );
___SCMOBJ source_rec_obj;
___SCMOBJ left_obj;
___SCMOBJ top_obj;
___SCMOBJ right_obj;
___SCMOBJ bottom_obj;
___SCMOBJ type_obj;
___BEGIN_SFUN_RECTANGLE_to_SCMOBJ( src.sourceRec, source_rec_obj, arg_num )
___BEGIN_SFUN_INT_TO_SCMOBJ( src.left, left_obj, arg_num )
___BEGIN_SFUN_INT_TO_SCMOBJ( src.top, top_obj, arg_num )
___BEGIN_SFUN_INT_TO_SCMOBJ( src.right, right_obj, arg_num )
___BEGIN_SFUN_INT_TO_SCMOBJ( src.bottom, bottom_obj, arg_num )
___BEGIN_SFUN_INT_TO_SCMOBJ( src.type, type_obj, arg_num )
type_obj = ___EXT( ___make_pair ) ( ___ps, type_obj, ___NUL );
bottom_obj = ___EXT( ___make_pair ) ( ___ps, bottom_obj, type_obj );
right_obj = ___EXT( ___make_pair ) ( ___ps, right_obj, bottom_obj );
top_obj = ___EXT( ___make_pair ) ( ___ps, top_obj, right_obj );
*dst = ___EXT( ___make_pair ) ( ___ps, left_obj, top_obj );
___END_SFUN_INT_TO_SCMOBJ( src.type, type_obj, arg_num )
___END_SFUN_INT_TO_SCMOBJ( src.bottom, bottom_obj, arg_num )
___END_SFUN_INT_TO_SCMOBJ( src.right, right_obj, arg_num )
___END_SFUN_INT_TO_SCMOBJ( src.top, top_obj, arg_num )
___END_SFUN_INT_TO_SCMOBJ( src.left, left_obj, arg_num )
___END_SFUN_RECTANGLE_to_SCMOBJ( src.sourceRec, source_rec_obj, arg_num )
if ( ___FIXNUMP( *dst ) )
___err = *dst; /* return allocation error */
return ___err;
}
#define ___BEGIN_CFUN_SCMOBJ_to_NPATCHINFO(src,dst,i) \
if ((___err = SCMOBJ_to_NPATCHINFO (___PSP src, &dst, i)) == ___FIX(___NO_ERR)) {
#define ___END_CFUN_SCMOBJ_to_NPATCHINFO(src,dst,i) }
#define ___BEGIN_CFUN_NPATCHINFO_to_SCMOBJ(src,dst) \
if ((___err = NPATCHINFO_to_SCMOBJ (___ps, src, &dst, ___RETURN_POS)) == ___FIX(___NO_ERR)) {
#define ___END_CFUN_NPATCHINFO_to_SCMOBJ(src,dst) \
___EXT(___release_scmobj) (dst); }
#define ___BEGIN_SFUN_NPATCHINFO_to_SCMOBJ(src,dst,i) \
if ((___err = NPATCHINFO_to_SCMOBJ (___ps, src, &dst, i)) == ___FIX(___NO_ERR)) {
#define ___END_SFUN_NPATCHINFO_to_SCMOBJ(src,dst,i) \
___EXT(___release_scmobj) (dst); }
#define ___BEGIN_SFUN_SCMOBJ_to_NPATCHINFO(src,dst) \
{ ___err = SCMOBJ_to_NPATCHINFO (___PSP src, &dst, ___RETURN_POS);
#define ___END_SFUN_SCMOBJ_to_NPATCHINFO(src,dst) }
c-declare-end
)
(c-define-type n-patch-info "NPatchInfo" "NPATCHINFO_to_SCMOBJ" "SCMOBJ_to_NPATCHINFO" #f)
(define make-n-patch-info
(c-lambda (rectangle int int int int int)
n-patch-info "MakeNPatchInfo"))
| null | https://raw.githubusercontent.com/georgjz/raylib-gambit-scheme/df7ea6db54a3196d13c66dac4909c64cea6e5a88/src/raylibbinding/structs/npatchinfo.scm | scheme | -----------------------------------------------------------------------------
-----------------------------------------------------------------------------
/* return allocation error */
}
}
| This file is the interface to the struct RenderNPatchInfo in .
(c-declare #<<c-declare-end
#include "raylib.h"
NPatchInfo MakeNPatchInfo( Rectangle sourceRec,
int left, int top,
int right, int bottom,
int type )
{
}
___SCMOBJ SCMOBJ_to_NPATCHINFO( ___PSD ___SCMOBJ src, NPatchInfo *dst, int arg_num )
{
if ( !___PAIRP( src ) )
else
{
___BEGIN_CFUN_SCMOBJ_to_RECTANGLE( source_rec, dst->sourceRec, arg_num )
___BEGIN_CFUN_SCMOBJ_TO_INT( left, dst->left, arg_num )
___BEGIN_CFUN_SCMOBJ_TO_INT( top, dst->top, arg_num )
___BEGIN_CFUN_SCMOBJ_TO_INT( right, dst->right, arg_num )
___BEGIN_CFUN_SCMOBJ_TO_INT( bottom, dst->bottom, arg_num )
___BEGIN_CFUN_SCMOBJ_TO_INT( type, dst->type, arg_num )
___END_CFUN_SCMOBJ_TO_INT( bottom, dst->bottom, arg_num )
___END_CFUN_SCMOBJ_TO_INT( right, dst->right, arg_num )
___END_CFUN_SCMOBJ_TO_INT( top, dst->top, arg_num )
___END_CFUN_SCMOBJ_TO_INT( type, dst->type, arg_num )
___END_CFUN_SCMOBJ_TO_INT( left, dst->left, arg_num )
___END_CFUN_SCMOBJ_to_RECTANGLE( source_rec, dst->sourceRec, arg_num )
}
}
___SCMOBJ NPATCHINFO_to_SCMOBJ( ___processor_state ___ps, NPatchInfo src, ___SCMOBJ *dst, int arg_num )
{
___BEGIN_SFUN_RECTANGLE_to_SCMOBJ( src.sourceRec, source_rec_obj, arg_num )
___BEGIN_SFUN_INT_TO_SCMOBJ( src.left, left_obj, arg_num )
___BEGIN_SFUN_INT_TO_SCMOBJ( src.top, top_obj, arg_num )
___BEGIN_SFUN_INT_TO_SCMOBJ( src.right, right_obj, arg_num )
___BEGIN_SFUN_INT_TO_SCMOBJ( src.bottom, bottom_obj, arg_num )
___BEGIN_SFUN_INT_TO_SCMOBJ( src.type, type_obj, arg_num )
___END_SFUN_INT_TO_SCMOBJ( src.type, type_obj, arg_num )
___END_SFUN_INT_TO_SCMOBJ( src.bottom, bottom_obj, arg_num )
___END_SFUN_INT_TO_SCMOBJ( src.right, right_obj, arg_num )
___END_SFUN_INT_TO_SCMOBJ( src.top, top_obj, arg_num )
___END_SFUN_INT_TO_SCMOBJ( src.left, left_obj, arg_num )
___END_SFUN_RECTANGLE_to_SCMOBJ( src.sourceRec, source_rec_obj, arg_num )
if ( ___FIXNUMP( *dst ) )
}
#define ___BEGIN_CFUN_SCMOBJ_to_NPATCHINFO(src,dst,i) \
if ((___err = SCMOBJ_to_NPATCHINFO (___PSP src, &dst, i)) == ___FIX(___NO_ERR)) {
#define ___END_CFUN_SCMOBJ_to_NPATCHINFO(src,dst,i) }
#define ___BEGIN_CFUN_NPATCHINFO_to_SCMOBJ(src,dst) \
if ((___err = NPATCHINFO_to_SCMOBJ (___ps, src, &dst, ___RETURN_POS)) == ___FIX(___NO_ERR)) {
#define ___END_CFUN_NPATCHINFO_to_SCMOBJ(src,dst) \
#define ___BEGIN_SFUN_NPATCHINFO_to_SCMOBJ(src,dst,i) \
if ((___err = NPATCHINFO_to_SCMOBJ (___ps, src, &dst, i)) == ___FIX(___NO_ERR)) {
#define ___END_SFUN_NPATCHINFO_to_SCMOBJ(src,dst,i) \
#define ___BEGIN_SFUN_SCMOBJ_to_NPATCHINFO(src,dst) \
#define ___END_SFUN_SCMOBJ_to_NPATCHINFO(src,dst) }
c-declare-end
)
(c-define-type n-patch-info "NPatchInfo" "NPATCHINFO_to_SCMOBJ" "SCMOBJ_to_NPATCHINFO" #f)
(define make-n-patch-info
(c-lambda (rectangle int int int int int)
n-patch-info "MakeNPatchInfo"))
|
d0b101fd51358e7c2a67d6998c386b8fabb8ad0bd4da6f8846a93952850f1e26 | scrintal/heroicons-reagent | clipboard_document.cljs | (ns com.scrintal.heroicons.solid.clipboard-document)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 24 24"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M17.663 3.118c.225.015.45.032.673.05C19.876 3.298 21 4.604 21 6.109v9.642a3 3 0 01-3 3V16.5c0-5.922-4.576-10.775-10.384-11.217.324-1.132 1.3-2.01 2.548-2.114.224-.019.448-.036.673-.051A3 3 0 0113.5 1.5H15a3 3 0 012.663 1.618zM12 4.5A1.5 1.5 0 0113.5 3H15a1.5 1.5 0 011.5 1.5H12z"
:clipRule "evenodd"}]
[:path {:d "M3 8.625c0-1.036.84-1.875 1.875-1.875h.375A3.75 3.75 0 019 10.5v1.875c0 1.036.84 1.875 1.875 1.875h1.875A3.75 3.75 0 0116.5 18v2.625c0 1.035-.84 1.875-1.875 1.875h-9.75A1.875 1.875 0 013 20.625v-12z"}]
[:path {:d "M10.5 10.5a5.23 5.23 0 00-1.279-3.434 9.768 9.768 0 016.963 6.963 5.23 5.23 0 00-3.434-1.279h-1.875a.375.375 0 01-.375-.375V10.5z"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/solid/clipboard_document.cljs | clojure | (ns com.scrintal.heroicons.solid.clipboard-document)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 24 24"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M17.663 3.118c.225.015.45.032.673.05C19.876 3.298 21 4.604 21 6.109v9.642a3 3 0 01-3 3V16.5c0-5.922-4.576-10.775-10.384-11.217.324-1.132 1.3-2.01 2.548-2.114.224-.019.448-.036.673-.051A3 3 0 0113.5 1.5H15a3 3 0 012.663 1.618zM12 4.5A1.5 1.5 0 0113.5 3H15a1.5 1.5 0 011.5 1.5H12z"
:clipRule "evenodd"}]
[:path {:d "M3 8.625c0-1.036.84-1.875 1.875-1.875h.375A3.75 3.75 0 019 10.5v1.875c0 1.036.84 1.875 1.875 1.875h1.875A3.75 3.75 0 0116.5 18v2.625c0 1.035-.84 1.875-1.875 1.875h-9.75A1.875 1.875 0 013 20.625v-12z"}]
[:path {:d "M10.5 10.5a5.23 5.23 0 00-1.279-3.434 9.768 9.768 0 016.963 6.963 5.23 5.23 0 00-3.434-1.279h-1.875a.375.375 0 01-.375-.375V10.5z"}]]) | |
4ef19da7926b5a42a200dbffd6b884efec74387ba899a5e81c487f32947770bd | mu-chaco/ReWire | ToVHDL.hs | module ReWire.Core.Transformations.ToVHDL where
import ReWire.Scoping
import ReWire.Core.Syntax
import ReWire.Core.Transformations.Monad
import ReWire.Core.Transformations.CheckNF
import ReWire.Core.Transformations.Types
import qualified Data.Map.Strict as Map
import Data.Map.Strict (Map)
import Data.List (intercalate,findIndex,find,nub,foldl',isPrefixOf)
import Data.Maybe (fromJust,catMaybes)
import Data.Tuple (swap)
import Control.Monad.State
import Control.Monad.Reader
import Control.Monad.Identity
import Debug.Trace (trace)
import Control.DeepSeq
type Declaration = (String,Int)
data Bit = Zero | One deriving (Eq,Show)
data Condition = CondEq AssignmentRHS AssignmentRHS | CondAnd Condition Condition | CondTrue deriving (Eq,Show)
type Assignment = (String,AssignmentRHS)
data AssignmentRHS = FunCall String [AssignmentRHS]
| LocalVariable String
| Concat [AssignmentRHS]
| BitConst [Bit]
| Slice AssignmentRHS Int Int
| Conditional [(Condition,AssignmentRHS)]
deriving (Eq,Show)
data VMState = VMState { assignments :: [Assignment],
declarations :: [Declaration],
signalCounter :: Int,
tyWidthCache :: Map RWCTy Int,
inputWidthCache :: Maybe Int,
outputWidthCache :: Maybe Int,
stateWidthCache :: Maybe Int,
stateTagWidthCache :: Maybe Int } deriving Show
data VMEnv = VMEnv { bindings :: Map (Id RWCExp) NameInfo } deriving Show
type VM = RWT (ReaderT VMEnv (StateT VMState Identity))
data NameInfo = BoundK Int | BoundVar String | BoundFun String | BoundPrim String | NotBound deriving (Eq,Show)
getSignalCounter = get >>= return . signalCounter
modifySignalCounter f = modify (\ s -> s { signalCounter = f (signalCounter s) })
putSignalCounter = modifySignalCounter . const
getAssignments = get >>= return . assignments
modifyAssignments f = modify (\ s -> s { assignments = f (assignments s) })
putAssignments = modifyAssignments . const
getDeclarations = get >>= return . declarations
modifyDeclarations f = modify (\ s -> s { declarations = f (declarations s) })
putDeclarations = modifyDeclarations . const
getTyWidthCache = get >>= return . tyWidthCache
modifyTyWidthCache f = modify (\ s -> s { tyWidthCache = f (tyWidthCache s) })
putTyWidthCache = modifyTyWidthCache .
getOutputWidthCache = get >>= return . outputWidthCache
modifyOutputWidthCache f = modify (\ s -> s { outputWidthCache = f (outputWidthCache s) })
putOutputWidthCache = modifyOutputWidthCache . const
getInputWidthCache = get >>= return . inputWidthCache
modifyInputWidthCache f = modify (\ s -> s { inputWidthCache = f (inputWidthCache s) })
putInputWidthCache = modifyInputWidthCache . const
getStateWidthCache = get >>= return . stateWidthCache
modifyStateWidthCache f = modify (\ s -> s { stateWidthCache = f (stateWidthCache s) })
putStateWidthCache = modifyStateWidthCache . const
getStateTagWidthCache = get >>= return . stateTagWidthCache
modifyStateTagWidthCache f = modify (\ s -> s { stateTagWidthCache = f (stateTagWidthCache s) })
putStateTagWidthCache = modifyStateTagWidthCache . const
tellAssignments o = modifyAssignments (o++)
tellDeclarations o = modifyDeclarations (o++)
askBindings :: VM (Map (Id RWCExp) NameInfo)
askBindings = ask >>= return . bindings
localBindings :: (Map (Id RWCExp) NameInfo -> Map (Id RWCExp) NameInfo) -> VM a -> VM a
localBindings f = local (\ e -> e { bindings = f (bindings e) })
askNameInfo :: Id RWCExp -> VM NameInfo
askNameInfo n = do bindings <- askBindings
return $ maybe NotBound id (Map.lookup n bindings)
freshName :: String -> VM String
freshName n = do ctr <- getSignalCounter
putSignalCounter (ctr+1)
return (n++"_"++show ctr)
freshTmp :: String -> Int -> VM String
freshTmp n 0 = return "NIL" -- FIXME: hack hack hack?
freshTmp n i = do sn <- freshName n
emitDeclaration (sn,i)
return sn
freshTmpTy :: String -> RWCTy -> VM String
freshTmpTy n = freshTmp n <=< tyWidth
--isNil = (=="\"\"")
removeNils : : AssignmentRHS - >
--removeNils (FunCall f ss) = FunCall f (filter (not . isNil) ss)
--removeNils (LocalVariable v) = LocalVariable v
removeNils ( Concat ss ) = Concat ( filter ( not . isNil ) ss )
removeNils ( BitConst bs ) = bs
--removeNils (Slice s i j) = Slice s i j
--removeNils (Conditional cs) = Conditional (map removeNilsCase cs)
--removeNilsCase :: (Condition,String) -> (Condition,String)
--removeNilsCase (c,s) = (removeNilsCond c,s)
--removeNilsCond :: Condition -> Condition
removeNilsCond ( CondEq s1 s2 ) | isNil s1 & & isNil s2 = CondTrue
-- | otherwise = CondEq s1 s2
--removeNilsCond (CondAnd c1 c2) = CondAnd (removeNilsCond c1) (removeNilsCond c2)
--removeNilsCond CondTrue = CondTrue
emitAssignment :: Assignment -> VM ()
emitAssignment ("NIL",_) = return ()
emitAssignment (s,rhs) = tellAssignments [(s,rhs)]
emitDeclaration :: Declaration -> VM ()
emitDeclaration d = tellDeclarations [d]
--genBittyLiteral :: RWCLit -> VM String
--genBittyLiteral (RWCLitInteger
getStateTagWidth :: VM Int
getStateTagWidth = do mc <- getStateTagWidthCache
case mc of
Just n -> return n
Nothing -> do bdgs <- askBindings
let nstates = length [() | (_,BoundK _) <- Map.toList bdgs]
n = nBits (nstates-1)
putStateTagWidthCache (Just n)
return n
getThisStateWidth :: Id RWCExp -> VM Int
getThisStateWidth n = do Just (RWCDefn n (tvs :-> t) e) <- queryG n
let (targs,_) = flattenArrow t
-- Last argument is the input, not part of state, hence init
liftM (sum . init) $ mapM tyWidth targs
getThisOutputWidth :: Id RWCExp -> VM Int
getThisOutputWidth n = do Just (RWCDefn n (tvs :-> t) e) <- queryG n
let (_,tres) = flattenArrow t
case tres of
(RWCTyApp (RWCTyApp (RWCTyApp (RWCTyCon (TyConId "React")) _) t) _) -> tyWidth t
_ -> fail $ "getThisOutputWidth: malformed result type for state (shouldn't happen)"
getOutputWidth :: VM Int
getOutputWidth = do mc <- getOutputWidthCache
case mc of
Just n -> return n
Nothing -> do bdgs <- askBindings
let sns = [n | (n,BoundK _) <- Map.toList bdgs]
ows <- mapM getThisOutputWidth sns
case nub ows of
[] -> fail $ "getOutputWidth: no states defined?"
[n] -> putOutputWidthCache (Just n) >> return n
_ -> fail $ "getOutputWidth: inconsistent output widths (shouldn't happen)"
getThisInputWidth :: Id RWCExp -> VM Int
getThisInputWidth n = do Just (RWCDefn n (tvs :-> t) e) <- queryG n
let (_,tres) = flattenArrow t
case tres of
(RWCTyApp (RWCTyApp (RWCTyApp (RWCTyCon (TyConId "React")) t) _) _) -> tyWidth t
_ -> fail $ "getThisInputWidth: malformed result type for state (shouldn't happen)"
getInputWidth :: VM Int
getInputWidth = do mc <- getInputWidthCache
case mc of
Just n -> return n
Nothing -> do bdgs <- askBindings
let sns = [n | (n,BoundK _) <- Map.toList bdgs]
ows <- mapM getThisInputWidth sns
case nub ows of
[] -> fail $ "getInputWidth: no states defined?"
[n] -> putInputWidthCache (Just n) >> return n
_ -> fail $ "getInputWidth: inconsistent intput widths (shouldn't happen)"
getStateWidth :: VM Int
getStateWidth = do mc <- getStateWidthCache
case mc of
Just n -> return n
Nothing -> do ow <- getOutputWidth
tw <- getStateTagWidth
bdgs <- askBindings
let sns = [n | (n,BoundK _) <- Map.toList bdgs]
sws <- mapM getThisStateWidth sns
let n = ow+tw+maximum sws
putStateWidthCache (Just n)
return n
getStateTag :: Int -> VM [Bit]
getStateTag n = do tw <- getStateTagWidth
return (bitConstFromIntegral tw n)
genExp :: RWCExp -> VM String
genExp e@(RWCApp _ _) = let (ef:es) = flattenApp e
t = typeOf e
in case ef of
RWCCon (DataConId "P") _ -> case es of
[eo,ek] -> do s_o <- genExp eo
s_k <- genExp ek
w <- getStateWidth
s <- freshTmp "P" w
emitAssignment (s,Concat [LocalVariable s_o,LocalVariable s_k])
return s
_ -> fail $ "genExp: malformed pause expression"
RWCVar i _ -> do n_i <- askNameInfo i
case n_i of
BoundK n -> do tag <- getStateTag n
tagWidth <- getStateTagWidth
s_tag <- freshTmp "tag" tagWidth
emitAssignment (s_tag,BitConst tag)
s_es <- mapM genExp es
sw <- getStateWidth
ow <- getOutputWidth
let kw = sw-ow
s <- freshTmp "k" kw
emitAssignment (s,Concat (LocalVariable s_tag:map LocalVariable s_es))
return s
BoundFun n -> do s_es <- mapM genExp es
s <- freshTmpTy "funcall" t
emitAssignment (s,FunCall n (map LocalVariable s_es))
return s
BoundVar _ -> fail $ "genExp: locally bound variable is applied as function: " ++ show i
BoundPrim n -> do s_es <- mapM genExp es
s <- freshTmpTy "primcall" t
emitAssignment (s,FunCall n (map LocalVariable s_es))
return s
NotBound -> fail $ "genExp@RWCApp: unbound variable: " ++ show i
RWCCon i _ -> do tci <- getDataConTyCon i
tagWidth <- getTagWidth tci
s_tag <- freshTmp "tag" tagWidth
tag <- getTag i
emitAssignment (s_tag,BitConst tag)
s <- freshTmpTy "conapp" t
s_es <- mapM genExp es
emitAssignment (s,Concat (LocalVariable s_tag:map LocalVariable s_es))
return s
_ -> fail $ "genExp: malformed application head: " ++ show e
genExp (RWCCon i t) = do tag <- getTag i
s <- freshTmpTy "con" t
emitAssignment (s,BitConst tag)
return s
genExp (RWCVar i t) = do n_i <- askNameInfo i
case n_i of
BoundK n -> do tag <- getStateTag n
tagWidth <- getStateTagWidth
s_tag <- freshTmp "k" tagWidth
emitAssignment (s_tag,BitConst tag)
return s_tag
BoundFun n -> do s <- freshTmpTy "funcall" t
emitAssignment (s,FunCall n [])
return s
BoundVar n -> do s <- freshTmpTy "var" t
emitAssignment (s,LocalVariable n)
return s
BoundPrim n -> do s <- freshTmpTy "primcall" t
emitAssignment (s,FunCall n [])
return s
NotBound -> fail $ "genExp@RWCVar: unbound variable: " ++ show i
--genExp (RWCLiteral _ l) = genBittyLiteral l
genExp e_@(RWCCase e alts) = do s_scrut <- genExp e
scond_alts <- mapM (genBittyAlt s_scrut (typeOf e)) alts
s <- freshTmpTy "case" (typeOf e_)
emitAssignment (s,Conditional scond_alts)
return s
genExp e = fail $ "genExp: malformed bitty expression: " ++ show e
getTagWidth :: TyConId -> VM Int
getTagWidth i = do Just (TyConInfo (RWCData _ _ cs)) <- queryT i
return (nBits (length cs-1))
nBits 0 = 0
nBits n = nBits (n `quot` 2) + 1
getDataConTyCon :: DataConId -> VM TyConId
getDataConTyCon dci = do Just (DataConInfo n _) <- queryD dci
return n
breakData :: DataConId -> String -> RWCTy -> [Bool] -> VM (String,[(String,RWCTy)])
breakData i s_scrut t_scrut used = do tci <- getDataConTyCon i
tagWidth <- getTagWidth tci
s_tag <- freshTmp "tag" tagWidth
emitAssignment (s_tag,Slice (LocalVariable s_scrut) 0 (tagWidth-1))
fieldTys <- getFieldTys i t_scrut
fieldWidths <- mapM tyWidth fieldTys
let mkField False _ = return ""
mkField True w = freshTmp "field" w
s_fields <- zipWithM mkField used fieldWidths
let fieldOffsets = scanl (+) tagWidth fieldWidths
ranges [] = []
ranges [n] = []
ranges (n:m:ns) = (n,m-1) : ranges (m:ns)
fieldRanges = ranges fieldOffsets
emitOne "" _ = return ()
emitOne s (l,h) = emitAssignment (s,Slice (LocalVariable s_scrut) l h)
fieldRanges `deepseq` zipWithM_ emitOne s_fields fieldRanges
return (s_tag,zip s_fields fieldTys)
bitConstFromIntegral :: Integral a => Int -> a -> [Bit]
bitConstFromIntegral 0 _ = []
bitConstFromIntegral width n = bitConstFromIntegral (width-1) (n`div`2) ++ thisBit where thisBit = if odd n then [One] else [Zero]
getTag :: DataConId -> VM [Bit]
getTag i = do tci <- getDataConTyCon i
Just (TyConInfo dd) <- queryT tci
tagWidth <- getTagWidth tci
case findIndex (\ (RWCDataCon i' _) -> i==i') (dataCons dd) of
Just pos -> return (bitConstFromIntegral tagWidth pos)
Nothing -> fail $ "getTag: unknown constructor " ++ deDataConId i
NB : This will not terminate if called on a recursive type ! ( Could fix
-- that...)
tyWidth :: RWCTy -> VM Int
tyWidth (RWCTyVar _) = fail $ "tyWidth: type variable encountered"
tyWidth t = do twc <- getTyWidthCache
case Map.lookup t twc of
Just size -> return size
Nothing -> do
let (th:_) = flattenTyApp t
case th of
RWCTyCon (TyConId "React") -> getStateWidth
RWCTyVar _ -> fail $ "tyWidth: type variable encountered"
RWCTyCon i -> do
Just (TyConInfo (RWCData _ _ dcs)) <- queryT i
tagWidth <- getTagWidth i
cws <- mapM (dataConWidth i) dcs
let size = tagWidth + maximum cws
modifyTyWidthCache (Map.insert t size)
return size
where dataConWidth di (RWCDataCon i _) = do
fts <- getFieldTys i t
liftM sum (mapM tyWidth fts)
getFieldTys :: DataConId -> RWCTy -> VM [RWCTy]
getFieldTys i t = do Just (DataConInfo tci _) <- queryD i
Just (TyConInfo (RWCData _ tvs dcs)) <- queryT tci
let pt = foldl' RWCTyApp (RWCTyCon tci) (map RWCTyVar tvs)
msub = matchty Map.empty pt t
case msub of
Nothing -> fail $ "getFieldTys: type matching failed (type was " ++ show t ++ " and datacon was " ++ deDataConId i ++ ")"
Just sub -> do let (RWCDataCon _ targs) = fromJust $ find (\(RWCDataCon i' _) -> i==i') dcs
return (subst sub targs)
zipWithM3 :: Monad m => (a -> b -> c -> m d) -> [a] -> [b] -> [c] -> m [d]
zipWithM3 _ [] _ _ = return []
zipWithM3 _ _ [] _ = return []
zipWithM3 _ _ _ [] = return []
zipWithM3 f (a:as) (b:bs) (c:cs) = do d <- f a b c
ds <- zipWithM3 f as bs cs
return (d:ds)
genBittyAlt :: String -> RWCTy -> RWCAlt -> VM (Condition,AssignmentRHS)
genBittyAlt s_scrut t_scrut a = inAlt a $ \ p e -> do
(cond,bdgs) <- genBittyPat s_scrut t_scrut p
s <- localBindings (Map.union bdgs) $ genExp e
return (cond,LocalVariable s)
isWild RWCPatWild = True
isWild _ = False
genBittyPat :: String -> RWCTy -> RWCPat -> VM (Condition,Map (Id RWCExp) NameInfo) -- (condition for match, resulting bindings)
genBittyPat s_scrut t_scrut (RWCPatCon i pats) = do let used = map (not . isWild) pats
(s_tag,st_fields) <- used `deepseq` breakData i s_scrut t_scrut used
let s_fields = map fst st_fields
t_fields = map snd st_fields
tagValue <- getTag i
condbinds_pats <- s_fields `deepseq` t_fields `deepseq` zipWithM3 genBittyPat s_fields t_fields pats
let cond_pats = map fst condbinds_pats
binds_pats = map snd condbinds_pats
tci <- getDataConTyCon i
tagWidth <- getTagWidth tci
s_tagtest <- freshTmp "test" tagWidth
emitAssignment (s_tagtest,BitConst tagValue)
return (foldr CondAnd (CondEq (LocalVariable s_tag) (LocalVariable s_tagtest)) cond_pats,
foldr Map.union Map.empty binds_pats)
genBittyPat ( RWCPatLiteral l ) =
genBittyPat s_scrut t_scrut (RWCPatVar n _) = do s <- freshTmpTy "patvar" t_scrut
emitAssignment (s,LocalVariable s_scrut)
return (CondTrue,Map.singleton n (BoundVar s))
genBittyPat _ _ RWCPatWild = return (CondTrue,Map.empty)
bitToChar Zero = '0'
bitToChar One = '1'
renderRHS (FunCall f []) = f
renderRHS (FunCall f rs) = f ++ "(" ++ intercalate "," (map renderRHS rs) ++ ")"
renderRHS (LocalVariable x) = x
renderRHS (Concat rs) = "(" ++ intercalate " & " (map renderRHS rs) ++ ")"
renderRHS (BitConst bs) = "\"" ++ map bitToChar bs ++ "\""
renderRHS (Slice t l h) = "(" ++ renderRHS t ++ "(" ++ show l ++ " to " ++ show h ++ "))"
renderRHS r@(Conditional _) = error $ "renderRHS: encountered nested condition: " ++ show r
renderAssignmentForVariables :: Assignment -> String
renderAssignmentForVariables (s,Conditional []) = s ++ " := (others => '0');" -- shouldn't happen
renderAssignmentForVariables (s,Conditional cs) = let (b:bs) = map renderOneCase cs
in b ++ concatMap (" els"++) bs ++ " else " ++ s ++ " := (others => '0'); end if;"
where renderOneCase :: (Condition,AssignmentRHS) -> String
renderOneCase (c,sc) = "if " ++ renderCond c ++ " then " ++ s ++ " := " ++ renderRHS sc ++ ";"
renderCond (CondEq s1 s2) = "(" ++ renderRHS s1 ++ " = " ++ renderRHS s2 ++ ")"
renderCond (CondAnd c1 c2) = "(" ++ renderCond c1 ++ " and " ++ renderCond c2 ++ ")"
renderCond CondTrue = "true"
renderAssignmentForVariables (s,r) = s ++ " := " ++ renderRHS r ++ ";"
renderAssignmentForSignals :: Assignment -> String
renderAssignmentForSignals (s,Conditional []) = s ++ " <= (others => '0');"
renderAssignmentForSignals (s,Conditional cs) = s ++ " <= " ++ concatMap renderOneCase cs ++ "(others => '0');"
where renderOneCase (c,sc) = renderRHS sc ++ " when " ++ renderCond c ++ " else "
renderCond (CondEq s1 s2) = "(" ++ renderRHS s1 ++ " = " ++ renderRHS s2 ++ ")"
renderCond (CondAnd c1 c2) = "(" ++ renderCond c1 ++ " and " ++ renderCond c2 ++ ")"
renderCond CondTrue = "true"
renderAssignmentForSignals (s,r) = s ++ " <= " ++ renderRHS r ++ ";"
renderDeclarationForVariables :: Declaration -> String
renderDeclarationForVariables (s,i) = "variable " ++ s ++ " : std_logic_vector(0 to " ++ show (i-1) ++ ") := (others => '0');"
renderDeclarationForSignals :: Declaration -> String
renderDeclarationForSignals (s,i) = "signal " ++ s ++ " : std_logic_vector(0 to " ++ show (i-1) ++ ") := (others => '0');"
-- FIXME: Lots of duplicated code here (genBittyDefn).
genStart :: VM String
genStart =
do md <- queryG (mkId "start")
case md of
Just (RWCDefn n (tvs :-> t) e) ->
hideAssignments $ hideDeclarations $
do wr <- tyWidth (typeOf e)
s <- genExp e
s_ret <- freshTmp "ret" wr
emitAssignment (s_ret,LocalVariable s)
optimize
as <- getAssignments
ds <- getDeclarations
return (" pure function sm_state_initial\n" ++
" return std_logic_vector\n" ++
" is\n" ++
concatMap ((" "++) . (++"\n") . renderDeclarationForVariables) (reverse ds) ++
" begin\n" ++
concatMap ((" "++) . (++"\n") . renderAssignmentForVariables) (reverse as) ++
" return " ++ s_ret ++ ";\n" ++
" end sm_state_initial;\n")
Nothing -> fail $ "genStart: No definition for start"
genBittyDefn :: RWCDefn -> VM String
genBittyDefn (RWCDefn n_ (tvs :-> t) e_) =
hideAssignments $ hideDeclarations $
inLambdas e_ $ \ nts e ->
do (BoundFun n) <- askNameInfo n_
let freshArgumentTy pos (n,t) = do let s = "arg_" ++ show pos
ws <- tyWidth t
sUse <- freshTmp "arg_use" ws
emitAssignment (sUse,LocalVariable s)
return ((n,BoundVar sUse),s ++ " : std_logic_vector")
wr <- tyWidth (typeOf e)
bps <- zipWithM freshArgumentTy [0..] nts
let (bdgs,ps) = unzip bps
s <- localBindings (Map.union $ Map.fromList bdgs) (genExp e)
s_r <- freshTmp "ret" wr
emitAssignment (s_r,LocalVariable s)
optimize
as <- getAssignments
ds <- getDeclarations
return (" -- bitty: " ++ deId n_ ++ "\n" ++
" pure function " ++ n ++ (if null ps then "" else "(" ++ intercalate " ; " ps ++ ")") ++ "\n" ++
" return std_logic_vector\n" ++
" is\n" ++
concatMap ((" "++) . (++"\n") . renderDeclarationForVariables) (reverse ds) ++
" begin\n" ++
concatMap ((" "++) . (++"\n") . renderAssignmentForVariables) (reverse as) ++
" return " ++ s_r ++ ";\n" ++
" end " ++ n ++ ";\n")
genBittyDefnProto :: RWCDefn -> VM String
genBittyDefnProto (RWCDefn n_ (tvs :-> t) e_) =
hideAssignments $ hideDeclarations $
inLambdas e_ $ \ nts e ->
do (BoundFun n) <- askNameInfo n_
let freshArgumentTy pos (n,t) = let s = "arg_" ++ show pos in return ((n,BoundVar s),s ++ " : std_logic_vector")
wr <- tyWidth (typeOf e)
bps <- zipWithM freshArgumentTy [0..] nts
let (bdgs,ps) = unzip bps
return (" -- bitty: " ++ deId n_ ++ "\n" ++
" pure function " ++ n ++ (if null ps then "" else "(" ++ intercalate " ; " ps ++ ")") ++ "\n" ++
" return std_logic_vector;\n")
genBittyPrimProto :: RWCPrim -> VM String
genBittyPrimProto (RWCPrim n_ t vname) =
return (" -- prim: " ++ deId n_ ++ "\n")
genContDefn :: RWCDefn -> VM ()
genContDefn (RWCDefn n_ (tvs :-> t) e_) =
inLambdas e_ $ \ nts_ e ->
trace ("genContDefn: " ++ show n_) $
do (BoundK nk) <- askNameInfo n_
let nts = init nts_
(nin,tin) = last nts_
tagWidth <- getStateTagWidth
outputWidth <- getOutputWidth
fieldWidths <- mapM (tyWidth . snd) nts
s_fields <- mapM (freshTmp "statefield") fieldWidths
let fieldOffsets = scanl (+) (tagWidth+outputWidth) fieldWidths
ranges [] = []
ranges [n] = []
ranges (n:m:ns) = (n,m-1) : ranges (m:ns)
fieldRanges = ranges fieldOffsets
emitOne s (l,h) = emitAssignment (s,Slice (LocalVariable "sm_state") l h)
zipWithM_ emitOne s_fields fieldRanges
let mkNI n s = (n,BoundVar s)
bdgs_ = zipWith mkNI (map fst nts) s_fields
let bdgs = (nin,BoundVar "sm_input"):bdgs_
s <- localBindings (Map.union $ Map.fromList bdgs) (genExp e)
stateWidth <- getStateWidth
s_ret <- freshTmp "ret" stateWidth
emitAssignment (s_ret,LocalVariable s)
let decl = ("next_state_"++show nk,stateWidth)
emitDeclaration decl
let assignment = ("next_state_"++show nk,LocalVariable s_ret)
emitAssignment ("next_state_"++show nk,LocalVariable s_ret)
hideAssignments :: VM a -> VM a
hideAssignments m = do as <- getAssignments
putAssignments []
v <- m
putAssignments as
return v
hideDeclarations :: VM a -> VM a
hideDeclarations m = do ds <- getDeclarations
putDeclarations []
v <- m
putDeclarations ds
return v
-- Note: here we can't use the fresh name supply for conts because the
synth . tools need them numbered 0 and up in order for FSM to be
-- recognized. (I think. I may be totally wrong about that.)
initBindings :: Map (Id RWCExp) DefnSort -> VM (Map (Id RWCExp) NameInfo)
initBindings m = do let kvs = Map.toList m
sns = [0..]
kvs' <- doEm sns kvs
return (Map.fromList kvs')
where doEm sns ((k,DefnPrim):kvs) = do rest <- doEm sns kvs
mp <- queryP k
case mp of
Just (RWCPrim _ _ vname) -> return ((k,BoundPrim vname):rest)
_ -> error $ "initBindings: encountered unbound primitive " ++ show k
doEm sns ((k,DefnBitty):kvs) = do n <- freshName "func"
rest <- doEm sns kvs
return ((k,BoundFun n):rest)
doEm (n:sns) ((k,DefnCont):kvs) = do rest <- doEm sns kvs
return ((k,BoundK n):rest)
doEm _ [] = return []
nextstate_sig_assign :: (a,NameInfo) -> VM [String]
nextstate_sig_assign (_,BoundK n) = do tag <- getStateTag n
ss <- getOutputWidth
sw <- getStateTagWidth
special case when only one state !
if sw==0
then return $ ["if true then sm_state <= next_state_" ++ show n ++ ";"]
else return $ ["if sm_state(" ++ show ss ++ " to " ++ show (ss+sw-1) ++ ") = \"" ++ map bitToChar tag ++ "\" then sm_state <= next_state_" ++ show n ++ ";"]
nextstate_sig_assign _ = return []
optimize :: VM ()
optimize = do as <- liftM reverse getAssignments
as' <- op (Map.singleton "NIL" (BitConst [])) as
putAssignments (reverse as')
where op :: Map String AssignmentRHS -> [Assignment] -> VM [Assignment]
op m ((s,r):as) | isSimple r && not (isSpecial s) =
do unDecl s
let m' = Map.map (applymap (Map.singleton s r)) m
m'' = Map.insert s r m'
op m'' as
| otherwise = do let r' = simplifyRHS (applymap m r)
if r'==r then do rest <- op m as
return ((s,r'):rest)
else op m ((s,r'):as)
op _ [] = return []
isSpecial s = "ret_" `isPrefixOf` s || "next_state" `isPrefixOf` s || "sm_" `isPrefixOf` s || "P" `isPrefixOf` s || "k_" `isPrefixOf` s || "arg_use_" `isPrefixOf` s
isSimple (FunCall _ []) = True
isSimple (FunCall _ _) = False
isSimple (LocalVariable _) = True
isSimple (Concat rs) = all isSimple rs
isSimple (BitConst _) = True
isSimple (Slice _ _ _) = False
isSimple (Conditional _) = False
unDecl s = modifyDeclarations (filter ((/= s) . fst))
applymap m (FunCall s rs) = FunCall s (map (applymap m) rs)
applymap m (LocalVariable s) = case Map.lookup s m of
Just r -> let r' = applymap m r in if r==r' then r' else applymap m r'
Nothing -> LocalVariable s
applymap m (Concat rs) = Concat (map (applymap m) rs)
applymap m (BitConst bs) = BitConst bs
applymap m (Slice r l h) = Slice (applymap m r) l h
applymap m (Conditional cs) = Conditional $ map (\ (c,r) -> (applymapC m c,applymap m r)) cs
applymapC m (CondEq r1 r2) = CondEq (applymap m r1) (applymap m r2)
applymapC m (CondAnd c1 c2) = CondAnd (applymapC m c1) (applymapC m c2)
applymapC m CondTrue = CondTrue
simplifyRHS (FunCall s rs) = FunCall s (map simplifyRHS rs)
simplifyRHS (LocalVariable s) = LocalVariable s
simplifyRHS r@(Concat rs) = let rs' = map simplifyRHS rs
rs'' = smashConcat rs'
r' = case rs'' of
[] -> BitConst []
[r] -> r
_ -> Concat rs''
in if r == r' then r' else simplifyRHS r'
simplifyRHS (BitConst bs) = BitConst bs
simplifyRHS (Slice (BitConst bs) l h) = simplifyRHS $ BitConst $ reverse $ drop (length bs - (h+1)) $ reverse $ drop l bs
simplifyRHS (Slice r l h) = let r' = simplifyRHS r
in if r /= r' then simplifyRHS (Slice r' l h)
else Slice r' l h
simplifyRHS (Conditional [(CondTrue,r)]) = simplifyRHS r
simplifyRHS (Conditional cs) = let trimCs ((CondTrue,r):cs) = [(CondTrue,r)]
trimCs ((c,r):cs) | necessarilyFalse c = trimCs cs
| otherwise = (c,r) : trimCs cs
trimCs [] = []
cs' = trimCs cs
cs'' = map (\ (c,r) -> (simplifyCond c,simplifyRHS r)) cs'
in if cs'' == cs then Conditional cs''
else simplifyRHS $ Conditional cs''
simplifyCond c@(CondEq r1 r2) | r1 == r2 = CondTrue
| otherwise = let c' = CondEq (simplifyRHS r1) (simplifyRHS r2)
in if c' /= c then simplifyCond c' else c'
simplifyCond (CondAnd c CondTrue) = simplifyCond c
simplifyCond (CondAnd CondTrue c) = simplifyCond c
simplifyCond c@(CondAnd c1 c2) = let c' = CondAnd (simplifyCond c1) (simplifyCond c2)
in if c' /= c then simplifyCond c' else c'
simplifyCond CondTrue = CondTrue
necessarilyFalse (CondEq (BitConst b1) (BitConst b2)) | b1 /= b2 = True
necessarilyFalse _ = False
smashConcat (BitConst bs1:BitConst bs2:rs) = smashConcat (BitConst (bs1++bs2):rs)
smashConcat (BitConst []:rs) = smashConcat rs
smashConcat (Concat rs:rs') = smashConcat (rs++rs')
smashConcat (r:rs) = r:smashConcat rs
smashConcat [] = []
genProg :: Map (Id RWCExp) DefnSort -> VM String
genProg m = do bdgs <- initBindings m
trace (show bdgs) $ localBindings (Map.union bdgs) $ do
v_start <- genStart
sw <- getStateWidth
iw <- getInputWidth
ow <- getOutputWidth
let kts = Map.toList m
v_funs <- mapM genOne kts
optimize
as <- getAssignments
ds <- getDeclarations
let any_prims = any ((==DefnPrim) . snd) kts
(assn:assns) <- liftM concat $ mapM nextstate_sig_assign (Map.toList bdgs)
let entity_name = "rewire" -- FIXME: customizable?
v_protos <- mapM genOneProto kts
return ("library ieee;\n" ++
"use ieee.std_logic_1164.all;\n" ++
(if any_prims then "use prims.all;\n" else "") ++
"entity " ++ entity_name ++ " is\n" ++
" port (clk : in std_logic;\n" ++
" sm_input : in std_logic_vector(0 to " ++ show (iw-1) ++ ");\n" ++
" sm_output : out std_logic_vector(0 to " ++ show (ow-1) ++ "));\n" ++
"end rewire;\n" ++
"architecture behavioral of " ++ entity_name ++ " is\n" ++
concat v_protos ++
v_start ++
concat v_funs ++
" signal sm_state : std_logic_vector(0 to " ++ show (sw-1) ++ ") := sm_state_initial;\n" ++
concatMap ((" "++) . (++"\n") . renderDeclarationForSignals) (reverse ds) ++
"begin\n" ++
" sm_output <= sm_state(0 to " ++ show (ow-1) ++ ");\n" ++
concatMap ((" "++) . (++"\n") . renderAssignmentForSignals) (reverse as) ++
" process(clk)\n" ++
" begin\n" ++
" if rising_edge(clk) then\n" ++
" " ++ assn ++ concatMap (" els"++) assns ++ " else sm_state <= sm_state_initial; end if;\n" ++
" end if;\n" ++
" end process;\n" ++
"end behavioral;\n")
where genOne (k,DefnBitty) = do md <- queryG k
case md of
Just d -> genBittyDefn d
Nothing -> fail $ "genProg: No definition for bitty function " ++ show k
genOne (k,DefnCont) = do md <- queryG k
case md of
Just d -> genContDefn d >> return ""
Nothing -> fail $ "genProg: No definition for cont function " ++ show k
genOne (k,DefnPrim) = return ""
genOneProto (k,DefnBitty) = do md <- queryG k
case md of
Just d -> genBittyDefnProto d
Nothing -> fail $ "genProg: No definition for bitty function " ++ show k
genOneProto (k,DefnPrim) = do mp <- queryP k
case mp of
Just p -> genBittyPrimProto p
Nothing -> fail $ "genProg: No definition for bitty primitive " ++ show k
genOneProto _ = return ""
runVM :: RWCProg -> VM a -> (a,VMState)
runVM p phi = runIdentity $
runStateT (runReaderT (runRWT p phi) env0) state0
where state0 = VMState { signalCounter = 0,
assignments = [],
declarations = [],
tyWidthCache = Map.empty,
inputWidthCache = Nothing,
outputWidthCache = Nothing,
stateWidthCache = Nothing,
stateTagWidthCache = Nothing }
env0 = VMEnv { bindings = Map.empty }
cmdToVHDL :: TransCommand
cmdToVHDL _ p = case checkProg' p of
Left e -> (Nothing,Just $ "failed normal-form check: " ++ show e)
Right m -> (Nothing,Just $ fst $ runVM p (genProg m))
| null | https://raw.githubusercontent.com/mu-chaco/ReWire/a8dcea6ab0989474988a758179a1d876e2c32370/cruft/ToVHDL.hs | haskell | FIXME: hack hack hack?
isNil = (=="\"\"")
removeNils (FunCall f ss) = FunCall f (filter (not . isNil) ss)
removeNils (LocalVariable v) = LocalVariable v
removeNils (Slice s i j) = Slice s i j
removeNils (Conditional cs) = Conditional (map removeNilsCase cs)
removeNilsCase :: (Condition,String) -> (Condition,String)
removeNilsCase (c,s) = (removeNilsCond c,s)
removeNilsCond :: Condition -> Condition
| otherwise = CondEq s1 s2
removeNilsCond (CondAnd c1 c2) = CondAnd (removeNilsCond c1) (removeNilsCond c2)
removeNilsCond CondTrue = CondTrue
genBittyLiteral :: RWCLit -> VM String
genBittyLiteral (RWCLitInteger
Last argument is the input, not part of state, hence init
genExp (RWCLiteral _ l) = genBittyLiteral l
that...)
(condition for match, resulting bindings)
shouldn't happen
FIXME: Lots of duplicated code here (genBittyDefn).
Note: here we can't use the fresh name supply for conts because the
recognized. (I think. I may be totally wrong about that.)
FIXME: customizable? | module ReWire.Core.Transformations.ToVHDL where
import ReWire.Scoping
import ReWire.Core.Syntax
import ReWire.Core.Transformations.Monad
import ReWire.Core.Transformations.CheckNF
import ReWire.Core.Transformations.Types
import qualified Data.Map.Strict as Map
import Data.Map.Strict (Map)
import Data.List (intercalate,findIndex,find,nub,foldl',isPrefixOf)
import Data.Maybe (fromJust,catMaybes)
import Data.Tuple (swap)
import Control.Monad.State
import Control.Monad.Reader
import Control.Monad.Identity
import Debug.Trace (trace)
import Control.DeepSeq
type Declaration = (String,Int)
data Bit = Zero | One deriving (Eq,Show)
data Condition = CondEq AssignmentRHS AssignmentRHS | CondAnd Condition Condition | CondTrue deriving (Eq,Show)
type Assignment = (String,AssignmentRHS)
data AssignmentRHS = FunCall String [AssignmentRHS]
| LocalVariable String
| Concat [AssignmentRHS]
| BitConst [Bit]
| Slice AssignmentRHS Int Int
| Conditional [(Condition,AssignmentRHS)]
deriving (Eq,Show)
data VMState = VMState { assignments :: [Assignment],
declarations :: [Declaration],
signalCounter :: Int,
tyWidthCache :: Map RWCTy Int,
inputWidthCache :: Maybe Int,
outputWidthCache :: Maybe Int,
stateWidthCache :: Maybe Int,
stateTagWidthCache :: Maybe Int } deriving Show
data VMEnv = VMEnv { bindings :: Map (Id RWCExp) NameInfo } deriving Show
type VM = RWT (ReaderT VMEnv (StateT VMState Identity))
data NameInfo = BoundK Int | BoundVar String | BoundFun String | BoundPrim String | NotBound deriving (Eq,Show)
getSignalCounter = get >>= return . signalCounter
modifySignalCounter f = modify (\ s -> s { signalCounter = f (signalCounter s) })
putSignalCounter = modifySignalCounter . const
getAssignments = get >>= return . assignments
modifyAssignments f = modify (\ s -> s { assignments = f (assignments s) })
putAssignments = modifyAssignments . const
getDeclarations = get >>= return . declarations
modifyDeclarations f = modify (\ s -> s { declarations = f (declarations s) })
putDeclarations = modifyDeclarations . const
getTyWidthCache = get >>= return . tyWidthCache
modifyTyWidthCache f = modify (\ s -> s { tyWidthCache = f (tyWidthCache s) })
putTyWidthCache = modifyTyWidthCache .
getOutputWidthCache = get >>= return . outputWidthCache
modifyOutputWidthCache f = modify (\ s -> s { outputWidthCache = f (outputWidthCache s) })
putOutputWidthCache = modifyOutputWidthCache . const
getInputWidthCache = get >>= return . inputWidthCache
modifyInputWidthCache f = modify (\ s -> s { inputWidthCache = f (inputWidthCache s) })
putInputWidthCache = modifyInputWidthCache . const
getStateWidthCache = get >>= return . stateWidthCache
modifyStateWidthCache f = modify (\ s -> s { stateWidthCache = f (stateWidthCache s) })
putStateWidthCache = modifyStateWidthCache . const
getStateTagWidthCache = get >>= return . stateTagWidthCache
modifyStateTagWidthCache f = modify (\ s -> s { stateTagWidthCache = f (stateTagWidthCache s) })
putStateTagWidthCache = modifyStateTagWidthCache . const
tellAssignments o = modifyAssignments (o++)
tellDeclarations o = modifyDeclarations (o++)
askBindings :: VM (Map (Id RWCExp) NameInfo)
askBindings = ask >>= return . bindings
localBindings :: (Map (Id RWCExp) NameInfo -> Map (Id RWCExp) NameInfo) -> VM a -> VM a
localBindings f = local (\ e -> e { bindings = f (bindings e) })
askNameInfo :: Id RWCExp -> VM NameInfo
askNameInfo n = do bindings <- askBindings
return $ maybe NotBound id (Map.lookup n bindings)
freshName :: String -> VM String
freshName n = do ctr <- getSignalCounter
putSignalCounter (ctr+1)
return (n++"_"++show ctr)
freshTmp :: String -> Int -> VM String
freshTmp n i = do sn <- freshName n
emitDeclaration (sn,i)
return sn
freshTmpTy :: String -> RWCTy -> VM String
freshTmpTy n = freshTmp n <=< tyWidth
removeNils : : AssignmentRHS - >
removeNils ( Concat ss ) = Concat ( filter ( not . isNil ) ss )
removeNils ( BitConst bs ) = bs
removeNilsCond ( CondEq s1 s2 ) | isNil s1 & & isNil s2 = CondTrue
emitAssignment :: Assignment -> VM ()
emitAssignment ("NIL",_) = return ()
emitAssignment (s,rhs) = tellAssignments [(s,rhs)]
emitDeclaration :: Declaration -> VM ()
emitDeclaration d = tellDeclarations [d]
getStateTagWidth :: VM Int
getStateTagWidth = do mc <- getStateTagWidthCache
case mc of
Just n -> return n
Nothing -> do bdgs <- askBindings
let nstates = length [() | (_,BoundK _) <- Map.toList bdgs]
n = nBits (nstates-1)
putStateTagWidthCache (Just n)
return n
getThisStateWidth :: Id RWCExp -> VM Int
getThisStateWidth n = do Just (RWCDefn n (tvs :-> t) e) <- queryG n
let (targs,_) = flattenArrow t
liftM (sum . init) $ mapM tyWidth targs
getThisOutputWidth :: Id RWCExp -> VM Int
getThisOutputWidth n = do Just (RWCDefn n (tvs :-> t) e) <- queryG n
let (_,tres) = flattenArrow t
case tres of
(RWCTyApp (RWCTyApp (RWCTyApp (RWCTyCon (TyConId "React")) _) t) _) -> tyWidth t
_ -> fail $ "getThisOutputWidth: malformed result type for state (shouldn't happen)"
getOutputWidth :: VM Int
getOutputWidth = do mc <- getOutputWidthCache
case mc of
Just n -> return n
Nothing -> do bdgs <- askBindings
let sns = [n | (n,BoundK _) <- Map.toList bdgs]
ows <- mapM getThisOutputWidth sns
case nub ows of
[] -> fail $ "getOutputWidth: no states defined?"
[n] -> putOutputWidthCache (Just n) >> return n
_ -> fail $ "getOutputWidth: inconsistent output widths (shouldn't happen)"
getThisInputWidth :: Id RWCExp -> VM Int
getThisInputWidth n = do Just (RWCDefn n (tvs :-> t) e) <- queryG n
let (_,tres) = flattenArrow t
case tres of
(RWCTyApp (RWCTyApp (RWCTyApp (RWCTyCon (TyConId "React")) t) _) _) -> tyWidth t
_ -> fail $ "getThisInputWidth: malformed result type for state (shouldn't happen)"
getInputWidth :: VM Int
getInputWidth = do mc <- getInputWidthCache
case mc of
Just n -> return n
Nothing -> do bdgs <- askBindings
let sns = [n | (n,BoundK _) <- Map.toList bdgs]
ows <- mapM getThisInputWidth sns
case nub ows of
[] -> fail $ "getInputWidth: no states defined?"
[n] -> putInputWidthCache (Just n) >> return n
_ -> fail $ "getInputWidth: inconsistent intput widths (shouldn't happen)"
getStateWidth :: VM Int
getStateWidth = do mc <- getStateWidthCache
case mc of
Just n -> return n
Nothing -> do ow <- getOutputWidth
tw <- getStateTagWidth
bdgs <- askBindings
let sns = [n | (n,BoundK _) <- Map.toList bdgs]
sws <- mapM getThisStateWidth sns
let n = ow+tw+maximum sws
putStateWidthCache (Just n)
return n
getStateTag :: Int -> VM [Bit]
getStateTag n = do tw <- getStateTagWidth
return (bitConstFromIntegral tw n)
genExp :: RWCExp -> VM String
genExp e@(RWCApp _ _) = let (ef:es) = flattenApp e
t = typeOf e
in case ef of
RWCCon (DataConId "P") _ -> case es of
[eo,ek] -> do s_o <- genExp eo
s_k <- genExp ek
w <- getStateWidth
s <- freshTmp "P" w
emitAssignment (s,Concat [LocalVariable s_o,LocalVariable s_k])
return s
_ -> fail $ "genExp: malformed pause expression"
RWCVar i _ -> do n_i <- askNameInfo i
case n_i of
BoundK n -> do tag <- getStateTag n
tagWidth <- getStateTagWidth
s_tag <- freshTmp "tag" tagWidth
emitAssignment (s_tag,BitConst tag)
s_es <- mapM genExp es
sw <- getStateWidth
ow <- getOutputWidth
let kw = sw-ow
s <- freshTmp "k" kw
emitAssignment (s,Concat (LocalVariable s_tag:map LocalVariable s_es))
return s
BoundFun n -> do s_es <- mapM genExp es
s <- freshTmpTy "funcall" t
emitAssignment (s,FunCall n (map LocalVariable s_es))
return s
BoundVar _ -> fail $ "genExp: locally bound variable is applied as function: " ++ show i
BoundPrim n -> do s_es <- mapM genExp es
s <- freshTmpTy "primcall" t
emitAssignment (s,FunCall n (map LocalVariable s_es))
return s
NotBound -> fail $ "genExp@RWCApp: unbound variable: " ++ show i
RWCCon i _ -> do tci <- getDataConTyCon i
tagWidth <- getTagWidth tci
s_tag <- freshTmp "tag" tagWidth
tag <- getTag i
emitAssignment (s_tag,BitConst tag)
s <- freshTmpTy "conapp" t
s_es <- mapM genExp es
emitAssignment (s,Concat (LocalVariable s_tag:map LocalVariable s_es))
return s
_ -> fail $ "genExp: malformed application head: " ++ show e
genExp (RWCCon i t) = do tag <- getTag i
s <- freshTmpTy "con" t
emitAssignment (s,BitConst tag)
return s
genExp (RWCVar i t) = do n_i <- askNameInfo i
case n_i of
BoundK n -> do tag <- getStateTag n
tagWidth <- getStateTagWidth
s_tag <- freshTmp "k" tagWidth
emitAssignment (s_tag,BitConst tag)
return s_tag
BoundFun n -> do s <- freshTmpTy "funcall" t
emitAssignment (s,FunCall n [])
return s
BoundVar n -> do s <- freshTmpTy "var" t
emitAssignment (s,LocalVariable n)
return s
BoundPrim n -> do s <- freshTmpTy "primcall" t
emitAssignment (s,FunCall n [])
return s
NotBound -> fail $ "genExp@RWCVar: unbound variable: " ++ show i
genExp e_@(RWCCase e alts) = do s_scrut <- genExp e
scond_alts <- mapM (genBittyAlt s_scrut (typeOf e)) alts
s <- freshTmpTy "case" (typeOf e_)
emitAssignment (s,Conditional scond_alts)
return s
genExp e = fail $ "genExp: malformed bitty expression: " ++ show e
getTagWidth :: TyConId -> VM Int
getTagWidth i = do Just (TyConInfo (RWCData _ _ cs)) <- queryT i
return (nBits (length cs-1))
nBits 0 = 0
nBits n = nBits (n `quot` 2) + 1
getDataConTyCon :: DataConId -> VM TyConId
getDataConTyCon dci = do Just (DataConInfo n _) <- queryD dci
return n
breakData :: DataConId -> String -> RWCTy -> [Bool] -> VM (String,[(String,RWCTy)])
breakData i s_scrut t_scrut used = do tci <- getDataConTyCon i
tagWidth <- getTagWidth tci
s_tag <- freshTmp "tag" tagWidth
emitAssignment (s_tag,Slice (LocalVariable s_scrut) 0 (tagWidth-1))
fieldTys <- getFieldTys i t_scrut
fieldWidths <- mapM tyWidth fieldTys
let mkField False _ = return ""
mkField True w = freshTmp "field" w
s_fields <- zipWithM mkField used fieldWidths
let fieldOffsets = scanl (+) tagWidth fieldWidths
ranges [] = []
ranges [n] = []
ranges (n:m:ns) = (n,m-1) : ranges (m:ns)
fieldRanges = ranges fieldOffsets
emitOne "" _ = return ()
emitOne s (l,h) = emitAssignment (s,Slice (LocalVariable s_scrut) l h)
fieldRanges `deepseq` zipWithM_ emitOne s_fields fieldRanges
return (s_tag,zip s_fields fieldTys)
bitConstFromIntegral :: Integral a => Int -> a -> [Bit]
bitConstFromIntegral 0 _ = []
bitConstFromIntegral width n = bitConstFromIntegral (width-1) (n`div`2) ++ thisBit where thisBit = if odd n then [One] else [Zero]
getTag :: DataConId -> VM [Bit]
getTag i = do tci <- getDataConTyCon i
Just (TyConInfo dd) <- queryT tci
tagWidth <- getTagWidth tci
case findIndex (\ (RWCDataCon i' _) -> i==i') (dataCons dd) of
Just pos -> return (bitConstFromIntegral tagWidth pos)
Nothing -> fail $ "getTag: unknown constructor " ++ deDataConId i
NB : This will not terminate if called on a recursive type ! ( Could fix
tyWidth :: RWCTy -> VM Int
tyWidth (RWCTyVar _) = fail $ "tyWidth: type variable encountered"
tyWidth t = do twc <- getTyWidthCache
case Map.lookup t twc of
Just size -> return size
Nothing -> do
let (th:_) = flattenTyApp t
case th of
RWCTyCon (TyConId "React") -> getStateWidth
RWCTyVar _ -> fail $ "tyWidth: type variable encountered"
RWCTyCon i -> do
Just (TyConInfo (RWCData _ _ dcs)) <- queryT i
tagWidth <- getTagWidth i
cws <- mapM (dataConWidth i) dcs
let size = tagWidth + maximum cws
modifyTyWidthCache (Map.insert t size)
return size
where dataConWidth di (RWCDataCon i _) = do
fts <- getFieldTys i t
liftM sum (mapM tyWidth fts)
getFieldTys :: DataConId -> RWCTy -> VM [RWCTy]
getFieldTys i t = do Just (DataConInfo tci _) <- queryD i
Just (TyConInfo (RWCData _ tvs dcs)) <- queryT tci
let pt = foldl' RWCTyApp (RWCTyCon tci) (map RWCTyVar tvs)
msub = matchty Map.empty pt t
case msub of
Nothing -> fail $ "getFieldTys: type matching failed (type was " ++ show t ++ " and datacon was " ++ deDataConId i ++ ")"
Just sub -> do let (RWCDataCon _ targs) = fromJust $ find (\(RWCDataCon i' _) -> i==i') dcs
return (subst sub targs)
zipWithM3 :: Monad m => (a -> b -> c -> m d) -> [a] -> [b] -> [c] -> m [d]
zipWithM3 _ [] _ _ = return []
zipWithM3 _ _ [] _ = return []
zipWithM3 _ _ _ [] = return []
zipWithM3 f (a:as) (b:bs) (c:cs) = do d <- f a b c
ds <- zipWithM3 f as bs cs
return (d:ds)
genBittyAlt :: String -> RWCTy -> RWCAlt -> VM (Condition,AssignmentRHS)
genBittyAlt s_scrut t_scrut a = inAlt a $ \ p e -> do
(cond,bdgs) <- genBittyPat s_scrut t_scrut p
s <- localBindings (Map.union bdgs) $ genExp e
return (cond,LocalVariable s)
isWild RWCPatWild = True
isWild _ = False
genBittyPat s_scrut t_scrut (RWCPatCon i pats) = do let used = map (not . isWild) pats
(s_tag,st_fields) <- used `deepseq` breakData i s_scrut t_scrut used
let s_fields = map fst st_fields
t_fields = map snd st_fields
tagValue <- getTag i
condbinds_pats <- s_fields `deepseq` t_fields `deepseq` zipWithM3 genBittyPat s_fields t_fields pats
let cond_pats = map fst condbinds_pats
binds_pats = map snd condbinds_pats
tci <- getDataConTyCon i
tagWidth <- getTagWidth tci
s_tagtest <- freshTmp "test" tagWidth
emitAssignment (s_tagtest,BitConst tagValue)
return (foldr CondAnd (CondEq (LocalVariable s_tag) (LocalVariable s_tagtest)) cond_pats,
foldr Map.union Map.empty binds_pats)
genBittyPat ( RWCPatLiteral l ) =
genBittyPat s_scrut t_scrut (RWCPatVar n _) = do s <- freshTmpTy "patvar" t_scrut
emitAssignment (s,LocalVariable s_scrut)
return (CondTrue,Map.singleton n (BoundVar s))
genBittyPat _ _ RWCPatWild = return (CondTrue,Map.empty)
bitToChar Zero = '0'
bitToChar One = '1'
renderRHS (FunCall f []) = f
renderRHS (FunCall f rs) = f ++ "(" ++ intercalate "," (map renderRHS rs) ++ ")"
renderRHS (LocalVariable x) = x
renderRHS (Concat rs) = "(" ++ intercalate " & " (map renderRHS rs) ++ ")"
renderRHS (BitConst bs) = "\"" ++ map bitToChar bs ++ "\""
renderRHS (Slice t l h) = "(" ++ renderRHS t ++ "(" ++ show l ++ " to " ++ show h ++ "))"
renderRHS r@(Conditional _) = error $ "renderRHS: encountered nested condition: " ++ show r
renderAssignmentForVariables :: Assignment -> String
renderAssignmentForVariables (s,Conditional cs) = let (b:bs) = map renderOneCase cs
in b ++ concatMap (" els"++) bs ++ " else " ++ s ++ " := (others => '0'); end if;"
where renderOneCase :: (Condition,AssignmentRHS) -> String
renderOneCase (c,sc) = "if " ++ renderCond c ++ " then " ++ s ++ " := " ++ renderRHS sc ++ ";"
renderCond (CondEq s1 s2) = "(" ++ renderRHS s1 ++ " = " ++ renderRHS s2 ++ ")"
renderCond (CondAnd c1 c2) = "(" ++ renderCond c1 ++ " and " ++ renderCond c2 ++ ")"
renderCond CondTrue = "true"
renderAssignmentForVariables (s,r) = s ++ " := " ++ renderRHS r ++ ";"
renderAssignmentForSignals :: Assignment -> String
renderAssignmentForSignals (s,Conditional []) = s ++ " <= (others => '0');"
renderAssignmentForSignals (s,Conditional cs) = s ++ " <= " ++ concatMap renderOneCase cs ++ "(others => '0');"
where renderOneCase (c,sc) = renderRHS sc ++ " when " ++ renderCond c ++ " else "
renderCond (CondEq s1 s2) = "(" ++ renderRHS s1 ++ " = " ++ renderRHS s2 ++ ")"
renderCond (CondAnd c1 c2) = "(" ++ renderCond c1 ++ " and " ++ renderCond c2 ++ ")"
renderCond CondTrue = "true"
renderAssignmentForSignals (s,r) = s ++ " <= " ++ renderRHS r ++ ";"
renderDeclarationForVariables :: Declaration -> String
renderDeclarationForVariables (s,i) = "variable " ++ s ++ " : std_logic_vector(0 to " ++ show (i-1) ++ ") := (others => '0');"
renderDeclarationForSignals :: Declaration -> String
renderDeclarationForSignals (s,i) = "signal " ++ s ++ " : std_logic_vector(0 to " ++ show (i-1) ++ ") := (others => '0');"
genStart :: VM String
genStart =
do md <- queryG (mkId "start")
case md of
Just (RWCDefn n (tvs :-> t) e) ->
hideAssignments $ hideDeclarations $
do wr <- tyWidth (typeOf e)
s <- genExp e
s_ret <- freshTmp "ret" wr
emitAssignment (s_ret,LocalVariable s)
optimize
as <- getAssignments
ds <- getDeclarations
return (" pure function sm_state_initial\n" ++
" return std_logic_vector\n" ++
" is\n" ++
concatMap ((" "++) . (++"\n") . renderDeclarationForVariables) (reverse ds) ++
" begin\n" ++
concatMap ((" "++) . (++"\n") . renderAssignmentForVariables) (reverse as) ++
" return " ++ s_ret ++ ";\n" ++
" end sm_state_initial;\n")
Nothing -> fail $ "genStart: No definition for start"
genBittyDefn :: RWCDefn -> VM String
genBittyDefn (RWCDefn n_ (tvs :-> t) e_) =
hideAssignments $ hideDeclarations $
inLambdas e_ $ \ nts e ->
do (BoundFun n) <- askNameInfo n_
let freshArgumentTy pos (n,t) = do let s = "arg_" ++ show pos
ws <- tyWidth t
sUse <- freshTmp "arg_use" ws
emitAssignment (sUse,LocalVariable s)
return ((n,BoundVar sUse),s ++ " : std_logic_vector")
wr <- tyWidth (typeOf e)
bps <- zipWithM freshArgumentTy [0..] nts
let (bdgs,ps) = unzip bps
s <- localBindings (Map.union $ Map.fromList bdgs) (genExp e)
s_r <- freshTmp "ret" wr
emitAssignment (s_r,LocalVariable s)
optimize
as <- getAssignments
ds <- getDeclarations
return (" -- bitty: " ++ deId n_ ++ "\n" ++
" pure function " ++ n ++ (if null ps then "" else "(" ++ intercalate " ; " ps ++ ")") ++ "\n" ++
" return std_logic_vector\n" ++
" is\n" ++
concatMap ((" "++) . (++"\n") . renderDeclarationForVariables) (reverse ds) ++
" begin\n" ++
concatMap ((" "++) . (++"\n") . renderAssignmentForVariables) (reverse as) ++
" return " ++ s_r ++ ";\n" ++
" end " ++ n ++ ";\n")
genBittyDefnProto :: RWCDefn -> VM String
genBittyDefnProto (RWCDefn n_ (tvs :-> t) e_) =
hideAssignments $ hideDeclarations $
inLambdas e_ $ \ nts e ->
do (BoundFun n) <- askNameInfo n_
let freshArgumentTy pos (n,t) = let s = "arg_" ++ show pos in return ((n,BoundVar s),s ++ " : std_logic_vector")
wr <- tyWidth (typeOf e)
bps <- zipWithM freshArgumentTy [0..] nts
let (bdgs,ps) = unzip bps
return (" -- bitty: " ++ deId n_ ++ "\n" ++
" pure function " ++ n ++ (if null ps then "" else "(" ++ intercalate " ; " ps ++ ")") ++ "\n" ++
" return std_logic_vector;\n")
genBittyPrimProto :: RWCPrim -> VM String
genBittyPrimProto (RWCPrim n_ t vname) =
return (" -- prim: " ++ deId n_ ++ "\n")
genContDefn :: RWCDefn -> VM ()
genContDefn (RWCDefn n_ (tvs :-> t) e_) =
inLambdas e_ $ \ nts_ e ->
trace ("genContDefn: " ++ show n_) $
do (BoundK nk) <- askNameInfo n_
let nts = init nts_
(nin,tin) = last nts_
tagWidth <- getStateTagWidth
outputWidth <- getOutputWidth
fieldWidths <- mapM (tyWidth . snd) nts
s_fields <- mapM (freshTmp "statefield") fieldWidths
let fieldOffsets = scanl (+) (tagWidth+outputWidth) fieldWidths
ranges [] = []
ranges [n] = []
ranges (n:m:ns) = (n,m-1) : ranges (m:ns)
fieldRanges = ranges fieldOffsets
emitOne s (l,h) = emitAssignment (s,Slice (LocalVariable "sm_state") l h)
zipWithM_ emitOne s_fields fieldRanges
let mkNI n s = (n,BoundVar s)
bdgs_ = zipWith mkNI (map fst nts) s_fields
let bdgs = (nin,BoundVar "sm_input"):bdgs_
s <- localBindings (Map.union $ Map.fromList bdgs) (genExp e)
stateWidth <- getStateWidth
s_ret <- freshTmp "ret" stateWidth
emitAssignment (s_ret,LocalVariable s)
let decl = ("next_state_"++show nk,stateWidth)
emitDeclaration decl
let assignment = ("next_state_"++show nk,LocalVariable s_ret)
emitAssignment ("next_state_"++show nk,LocalVariable s_ret)
hideAssignments :: VM a -> VM a
hideAssignments m = do as <- getAssignments
putAssignments []
v <- m
putAssignments as
return v
hideDeclarations :: VM a -> VM a
hideDeclarations m = do ds <- getDeclarations
putDeclarations []
v <- m
putDeclarations ds
return v
synth . tools need them numbered 0 and up in order for FSM to be
initBindings :: Map (Id RWCExp) DefnSort -> VM (Map (Id RWCExp) NameInfo)
initBindings m = do let kvs = Map.toList m
sns = [0..]
kvs' <- doEm sns kvs
return (Map.fromList kvs')
where doEm sns ((k,DefnPrim):kvs) = do rest <- doEm sns kvs
mp <- queryP k
case mp of
Just (RWCPrim _ _ vname) -> return ((k,BoundPrim vname):rest)
_ -> error $ "initBindings: encountered unbound primitive " ++ show k
doEm sns ((k,DefnBitty):kvs) = do n <- freshName "func"
rest <- doEm sns kvs
return ((k,BoundFun n):rest)
doEm (n:sns) ((k,DefnCont):kvs) = do rest <- doEm sns kvs
return ((k,BoundK n):rest)
doEm _ [] = return []
nextstate_sig_assign :: (a,NameInfo) -> VM [String]
nextstate_sig_assign (_,BoundK n) = do tag <- getStateTag n
ss <- getOutputWidth
sw <- getStateTagWidth
special case when only one state !
if sw==0
then return $ ["if true then sm_state <= next_state_" ++ show n ++ ";"]
else return $ ["if sm_state(" ++ show ss ++ " to " ++ show (ss+sw-1) ++ ") = \"" ++ map bitToChar tag ++ "\" then sm_state <= next_state_" ++ show n ++ ";"]
nextstate_sig_assign _ = return []
optimize :: VM ()
optimize = do as <- liftM reverse getAssignments
as' <- op (Map.singleton "NIL" (BitConst [])) as
putAssignments (reverse as')
where op :: Map String AssignmentRHS -> [Assignment] -> VM [Assignment]
op m ((s,r):as) | isSimple r && not (isSpecial s) =
do unDecl s
let m' = Map.map (applymap (Map.singleton s r)) m
m'' = Map.insert s r m'
op m'' as
| otherwise = do let r' = simplifyRHS (applymap m r)
if r'==r then do rest <- op m as
return ((s,r'):rest)
else op m ((s,r'):as)
op _ [] = return []
isSpecial s = "ret_" `isPrefixOf` s || "next_state" `isPrefixOf` s || "sm_" `isPrefixOf` s || "P" `isPrefixOf` s || "k_" `isPrefixOf` s || "arg_use_" `isPrefixOf` s
isSimple (FunCall _ []) = True
isSimple (FunCall _ _) = False
isSimple (LocalVariable _) = True
isSimple (Concat rs) = all isSimple rs
isSimple (BitConst _) = True
isSimple (Slice _ _ _) = False
isSimple (Conditional _) = False
unDecl s = modifyDeclarations (filter ((/= s) . fst))
applymap m (FunCall s rs) = FunCall s (map (applymap m) rs)
applymap m (LocalVariable s) = case Map.lookup s m of
Just r -> let r' = applymap m r in if r==r' then r' else applymap m r'
Nothing -> LocalVariable s
applymap m (Concat rs) = Concat (map (applymap m) rs)
applymap m (BitConst bs) = BitConst bs
applymap m (Slice r l h) = Slice (applymap m r) l h
applymap m (Conditional cs) = Conditional $ map (\ (c,r) -> (applymapC m c,applymap m r)) cs
applymapC m (CondEq r1 r2) = CondEq (applymap m r1) (applymap m r2)
applymapC m (CondAnd c1 c2) = CondAnd (applymapC m c1) (applymapC m c2)
applymapC m CondTrue = CondTrue
simplifyRHS (FunCall s rs) = FunCall s (map simplifyRHS rs)
simplifyRHS (LocalVariable s) = LocalVariable s
simplifyRHS r@(Concat rs) = let rs' = map simplifyRHS rs
rs'' = smashConcat rs'
r' = case rs'' of
[] -> BitConst []
[r] -> r
_ -> Concat rs''
in if r == r' then r' else simplifyRHS r'
simplifyRHS (BitConst bs) = BitConst bs
simplifyRHS (Slice (BitConst bs) l h) = simplifyRHS $ BitConst $ reverse $ drop (length bs - (h+1)) $ reverse $ drop l bs
simplifyRHS (Slice r l h) = let r' = simplifyRHS r
in if r /= r' then simplifyRHS (Slice r' l h)
else Slice r' l h
simplifyRHS (Conditional [(CondTrue,r)]) = simplifyRHS r
simplifyRHS (Conditional cs) = let trimCs ((CondTrue,r):cs) = [(CondTrue,r)]
trimCs ((c,r):cs) | necessarilyFalse c = trimCs cs
| otherwise = (c,r) : trimCs cs
trimCs [] = []
cs' = trimCs cs
cs'' = map (\ (c,r) -> (simplifyCond c,simplifyRHS r)) cs'
in if cs'' == cs then Conditional cs''
else simplifyRHS $ Conditional cs''
simplifyCond c@(CondEq r1 r2) | r1 == r2 = CondTrue
| otherwise = let c' = CondEq (simplifyRHS r1) (simplifyRHS r2)
in if c' /= c then simplifyCond c' else c'
simplifyCond (CondAnd c CondTrue) = simplifyCond c
simplifyCond (CondAnd CondTrue c) = simplifyCond c
simplifyCond c@(CondAnd c1 c2) = let c' = CondAnd (simplifyCond c1) (simplifyCond c2)
in if c' /= c then simplifyCond c' else c'
simplifyCond CondTrue = CondTrue
necessarilyFalse (CondEq (BitConst b1) (BitConst b2)) | b1 /= b2 = True
necessarilyFalse _ = False
smashConcat (BitConst bs1:BitConst bs2:rs) = smashConcat (BitConst (bs1++bs2):rs)
smashConcat (BitConst []:rs) = smashConcat rs
smashConcat (Concat rs:rs') = smashConcat (rs++rs')
smashConcat (r:rs) = r:smashConcat rs
smashConcat [] = []
genProg :: Map (Id RWCExp) DefnSort -> VM String
genProg m = do bdgs <- initBindings m
trace (show bdgs) $ localBindings (Map.union bdgs) $ do
v_start <- genStart
sw <- getStateWidth
iw <- getInputWidth
ow <- getOutputWidth
let kts = Map.toList m
v_funs <- mapM genOne kts
optimize
as <- getAssignments
ds <- getDeclarations
let any_prims = any ((==DefnPrim) . snd) kts
(assn:assns) <- liftM concat $ mapM nextstate_sig_assign (Map.toList bdgs)
v_protos <- mapM genOneProto kts
return ("library ieee;\n" ++
"use ieee.std_logic_1164.all;\n" ++
(if any_prims then "use prims.all;\n" else "") ++
"entity " ++ entity_name ++ " is\n" ++
" port (clk : in std_logic;\n" ++
" sm_input : in std_logic_vector(0 to " ++ show (iw-1) ++ ");\n" ++
" sm_output : out std_logic_vector(0 to " ++ show (ow-1) ++ "));\n" ++
"end rewire;\n" ++
"architecture behavioral of " ++ entity_name ++ " is\n" ++
concat v_protos ++
v_start ++
concat v_funs ++
" signal sm_state : std_logic_vector(0 to " ++ show (sw-1) ++ ") := sm_state_initial;\n" ++
concatMap ((" "++) . (++"\n") . renderDeclarationForSignals) (reverse ds) ++
"begin\n" ++
" sm_output <= sm_state(0 to " ++ show (ow-1) ++ ");\n" ++
concatMap ((" "++) . (++"\n") . renderAssignmentForSignals) (reverse as) ++
" process(clk)\n" ++
" begin\n" ++
" if rising_edge(clk) then\n" ++
" " ++ assn ++ concatMap (" els"++) assns ++ " else sm_state <= sm_state_initial; end if;\n" ++
" end if;\n" ++
" end process;\n" ++
"end behavioral;\n")
where genOne (k,DefnBitty) = do md <- queryG k
case md of
Just d -> genBittyDefn d
Nothing -> fail $ "genProg: No definition for bitty function " ++ show k
genOne (k,DefnCont) = do md <- queryG k
case md of
Just d -> genContDefn d >> return ""
Nothing -> fail $ "genProg: No definition for cont function " ++ show k
genOne (k,DefnPrim) = return ""
genOneProto (k,DefnBitty) = do md <- queryG k
case md of
Just d -> genBittyDefnProto d
Nothing -> fail $ "genProg: No definition for bitty function " ++ show k
genOneProto (k,DefnPrim) = do mp <- queryP k
case mp of
Just p -> genBittyPrimProto p
Nothing -> fail $ "genProg: No definition for bitty primitive " ++ show k
genOneProto _ = return ""
runVM :: RWCProg -> VM a -> (a,VMState)
runVM p phi = runIdentity $
runStateT (runReaderT (runRWT p phi) env0) state0
where state0 = VMState { signalCounter = 0,
assignments = [],
declarations = [],
tyWidthCache = Map.empty,
inputWidthCache = Nothing,
outputWidthCache = Nothing,
stateWidthCache = Nothing,
stateTagWidthCache = Nothing }
env0 = VMEnv { bindings = Map.empty }
cmdToVHDL :: TransCommand
cmdToVHDL _ p = case checkProg' p of
Left e -> (Nothing,Just $ "failed normal-form check: " ++ show e)
Right m -> (Nothing,Just $ fst $ runVM p (genProg m))
|
9e15767ef5dd6fab7b2f3b95085d113573bb508b49f62a9476fb5b4531c3e45d | processone/xmpp | xep0158.erl | Created automatically by XML generator ( fxml_gen.erl )
%% Source: xmpp_codec.spec
-module(xep0158).
-compile(export_all).
do_decode(<<"captcha">>, <<"urn:xmpp:captcha">>, El,
Opts) ->
decode_captcha(<<"urn:xmpp:captcha">>, Opts, El);
do_decode(Name, <<>>, _, _) ->
erlang:error({xmpp_codec, {missing_tag_xmlns, Name}});
do_decode(Name, XMLNS, _, _) ->
erlang:error({xmpp_codec, {unknown_tag, Name, XMLNS}}).
tags() -> [{<<"captcha">>, <<"urn:xmpp:captcha">>}].
do_encode({xcaptcha, _} = Captcha, TopXMLNS) ->
encode_captcha(Captcha, TopXMLNS).
do_get_name({xcaptcha, _}) -> <<"captcha">>.
do_get_ns({xcaptcha, _}) -> <<"urn:xmpp:captcha">>.
pp(xcaptcha, 1) -> [xdata];
pp(_, _) -> no.
records() -> [{xcaptcha, 1}].
decode_captcha(__TopXMLNS, __Opts,
{xmlel, <<"captcha">>, _attrs, _els}) ->
Xdata = decode_captcha_els(__TopXMLNS,
__Opts,
_els,
error),
{xcaptcha, Xdata}.
decode_captcha_els(__TopXMLNS, __Opts, [], Xdata) ->
case Xdata of
error ->
erlang:error({xmpp_codec,
{missing_tag, <<"x">>, __TopXMLNS}});
{value, Xdata1} -> Xdata1
end;
decode_captcha_els(__TopXMLNS, __Opts,
[{xmlel, <<"x">>, _attrs, _} = _el | _els], Xdata) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"jabber:x:data">> ->
decode_captcha_els(__TopXMLNS,
__Opts,
_els,
{value,
xep0004:decode_xdata(<<"jabber:x:data">>,
__Opts,
_el)});
_ -> decode_captcha_els(__TopXMLNS, __Opts, _els, Xdata)
end;
decode_captcha_els(__TopXMLNS, __Opts, [_ | _els],
Xdata) ->
decode_captcha_els(__TopXMLNS, __Opts, _els, Xdata).
encode_captcha({xcaptcha, Xdata}, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:captcha">>,
[],
__TopXMLNS),
_els = lists:reverse('encode_captcha_$xdata'(Xdata,
__NewTopXMLNS,
[])),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"captcha">>, _attrs, _els}.
'encode_captcha_$xdata'(Xdata, __TopXMLNS, _acc) ->
[xep0004:encode_xdata(Xdata, __TopXMLNS) | _acc].
| null | https://raw.githubusercontent.com/processone/xmpp/88c43c3cf5843a8a0f76eac390980a3a39c972dd/src/xep0158.erl | erlang | Source: xmpp_codec.spec | Created automatically by XML generator ( fxml_gen.erl )
-module(xep0158).
-compile(export_all).
do_decode(<<"captcha">>, <<"urn:xmpp:captcha">>, El,
Opts) ->
decode_captcha(<<"urn:xmpp:captcha">>, Opts, El);
do_decode(Name, <<>>, _, _) ->
erlang:error({xmpp_codec, {missing_tag_xmlns, Name}});
do_decode(Name, XMLNS, _, _) ->
erlang:error({xmpp_codec, {unknown_tag, Name, XMLNS}}).
tags() -> [{<<"captcha">>, <<"urn:xmpp:captcha">>}].
do_encode({xcaptcha, _} = Captcha, TopXMLNS) ->
encode_captcha(Captcha, TopXMLNS).
do_get_name({xcaptcha, _}) -> <<"captcha">>.
do_get_ns({xcaptcha, _}) -> <<"urn:xmpp:captcha">>.
pp(xcaptcha, 1) -> [xdata];
pp(_, _) -> no.
records() -> [{xcaptcha, 1}].
decode_captcha(__TopXMLNS, __Opts,
{xmlel, <<"captcha">>, _attrs, _els}) ->
Xdata = decode_captcha_els(__TopXMLNS,
__Opts,
_els,
error),
{xcaptcha, Xdata}.
decode_captcha_els(__TopXMLNS, __Opts, [], Xdata) ->
case Xdata of
error ->
erlang:error({xmpp_codec,
{missing_tag, <<"x">>, __TopXMLNS}});
{value, Xdata1} -> Xdata1
end;
decode_captcha_els(__TopXMLNS, __Opts,
[{xmlel, <<"x">>, _attrs, _} = _el | _els], Xdata) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"jabber:x:data">> ->
decode_captcha_els(__TopXMLNS,
__Opts,
_els,
{value,
xep0004:decode_xdata(<<"jabber:x:data">>,
__Opts,
_el)});
_ -> decode_captcha_els(__TopXMLNS, __Opts, _els, Xdata)
end;
decode_captcha_els(__TopXMLNS, __Opts, [_ | _els],
Xdata) ->
decode_captcha_els(__TopXMLNS, __Opts, _els, Xdata).
encode_captcha({xcaptcha, Xdata}, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:captcha">>,
[],
__TopXMLNS),
_els = lists:reverse('encode_captcha_$xdata'(Xdata,
__NewTopXMLNS,
[])),
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"captcha">>, _attrs, _els}.
'encode_captcha_$xdata'(Xdata, __TopXMLNS, _acc) ->
[xep0004:encode_xdata(Xdata, __TopXMLNS) | _acc].
|
08f683e4204e85bd3378ad7354091858ec5e5ffdb73c0b71196440e6332b2b0f | softwarelanguageslab/maf | R5RS_scp1_polynome-4.scm | ; Changes:
* removed : 0
* added : 1
* swaps : 0
* negated predicates : 1
; * swapped branches: 0
* calls to i d fun : 2
(letrec ((make-point (lambda (x y)
(letrec ((dispatch (lambda (msg)
(if (eq? msg 'x-value)
x
(if (eq? msg 'y-value) y (error "wrong message"))))))
dispatch)))
(make-segment (lambda (start end)
(letrec ((midpoint (lambda ()
(make-point (/ (+ (start 'x-value) (end 'x-value)) 2) (/ (+ (start 'y-value) (end 'y-value)) 2))))
(dispatch (lambda (msg)
(if (eq? msg 'start-point)
start
(if (eq? msg 'end-point)
end
(if (eq? msg 'midpoint)
(midpoint)
(error "wrong message")))))))
dispatch)))
(make-w-vector (lambda args
(letrec ((dimension (lambda ()
(<change>
()
args)
(length args)))
(coordinate (lambda (n)
(if (let ((__or_res (< n 1))) (if __or_res __or_res (> n (dimension))))
(error "coordinate is out of range")
(list-ref args (- n 1)))))
(add (lambda (w-vector)
(letrec ((loop (lambda (ctr res)
(if (= ctr 0)
(apply make-w-vector res)
(loop (- ctr 1) (cons (+ (coordinate ctr) ((w-vector 'coordinate) ctr)) res))))))
(loop (dimension) ()))))
(dispatch (lambda (msg)
(if (eq? msg 'dimension)
(dimension)
(if (eq? msg 'coordinate)
coordinate
(if (eq? msg 'add) add (error "wrong message")))))))
(<change>
dispatch
((lambda (x) x) dispatch)))))
(make-polynome (lambda coefficients
(<change>
(let ((polynome (apply make-w-vector coefficients)))
(letrec ((coefficient (lambda (index)
((polynome 'coordinate) index)))
(order (lambda ()
(- (polynome 'dimension) 1)))
(dispatch (lambda (msg)
(if (eq? msg 'order)
(order)
(if (eq? msg 'coefficient)
coefficient
(error "wrong message"))))))
dispatch))
((lambda (x) x)
(let ((polynome (apply make-w-vector coefficients)))
(letrec ((coefficient (lambda (index)
((polynome 'coordinate) index)))
(order (lambda ()
(- (polynome 'dimension) 1)))
(dispatch (lambda (msg)
(if (eq? msg 'order)
(order)
(if (eq? msg 'coefficient)
coefficient
(error "wrong message"))))))
dispatch))))))
(point1 (make-point 6 10))
(point2 (make-point 10 20))
(segment (make-segment point1 point2))
(midpoint (segment 'midpoint))
(w-vector1 (make-w-vector 1 2 3))
(w-vector2 (make-w-vector 4 5 6))
(polynome (make-polynome 1 2 3)))
(if (= (point1 'x-value) 6)
(if (= ((segment 'start-point) 'y-value) 10)
(if (= (midpoint 'x-value) 8)
(if (= ((w-vector1 'coordinate) 2) 2)
(if (<change> (= ((w-vector2 'coordinate) 1) 4) (not (= ((w-vector2 'coordinate) 1) 4)))
(if (= ((((w-vector1 'add) w-vector2) 'coordinate) 1) 5)
(if (= (polynome 'order) 2)
(= ((polynome 'coefficient) 2) 2)
#f)
#f)
#f)
#f)
#f)
#f)
#f)) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_scp1_polynome-4.scm | scheme | Changes:
* swapped branches: 0 | * removed : 0
* added : 1
* swaps : 0
* negated predicates : 1
* calls to i d fun : 2
(letrec ((make-point (lambda (x y)
(letrec ((dispatch (lambda (msg)
(if (eq? msg 'x-value)
x
(if (eq? msg 'y-value) y (error "wrong message"))))))
dispatch)))
(make-segment (lambda (start end)
(letrec ((midpoint (lambda ()
(make-point (/ (+ (start 'x-value) (end 'x-value)) 2) (/ (+ (start 'y-value) (end 'y-value)) 2))))
(dispatch (lambda (msg)
(if (eq? msg 'start-point)
start
(if (eq? msg 'end-point)
end
(if (eq? msg 'midpoint)
(midpoint)
(error "wrong message")))))))
dispatch)))
(make-w-vector (lambda args
(letrec ((dimension (lambda ()
(<change>
()
args)
(length args)))
(coordinate (lambda (n)
(if (let ((__or_res (< n 1))) (if __or_res __or_res (> n (dimension))))
(error "coordinate is out of range")
(list-ref args (- n 1)))))
(add (lambda (w-vector)
(letrec ((loop (lambda (ctr res)
(if (= ctr 0)
(apply make-w-vector res)
(loop (- ctr 1) (cons (+ (coordinate ctr) ((w-vector 'coordinate) ctr)) res))))))
(loop (dimension) ()))))
(dispatch (lambda (msg)
(if (eq? msg 'dimension)
(dimension)
(if (eq? msg 'coordinate)
coordinate
(if (eq? msg 'add) add (error "wrong message")))))))
(<change>
dispatch
((lambda (x) x) dispatch)))))
(make-polynome (lambda coefficients
(<change>
(let ((polynome (apply make-w-vector coefficients)))
(letrec ((coefficient (lambda (index)
((polynome 'coordinate) index)))
(order (lambda ()
(- (polynome 'dimension) 1)))
(dispatch (lambda (msg)
(if (eq? msg 'order)
(order)
(if (eq? msg 'coefficient)
coefficient
(error "wrong message"))))))
dispatch))
((lambda (x) x)
(let ((polynome (apply make-w-vector coefficients)))
(letrec ((coefficient (lambda (index)
((polynome 'coordinate) index)))
(order (lambda ()
(- (polynome 'dimension) 1)))
(dispatch (lambda (msg)
(if (eq? msg 'order)
(order)
(if (eq? msg 'coefficient)
coefficient
(error "wrong message"))))))
dispatch))))))
(point1 (make-point 6 10))
(point2 (make-point 10 20))
(segment (make-segment point1 point2))
(midpoint (segment 'midpoint))
(w-vector1 (make-w-vector 1 2 3))
(w-vector2 (make-w-vector 4 5 6))
(polynome (make-polynome 1 2 3)))
(if (= (point1 'x-value) 6)
(if (= ((segment 'start-point) 'y-value) 10)
(if (= (midpoint 'x-value) 8)
(if (= ((w-vector1 'coordinate) 2) 2)
(if (<change> (= ((w-vector2 'coordinate) 1) 4) (not (= ((w-vector2 'coordinate) 1) 4)))
(if (= ((((w-vector1 'add) w-vector2) 'coordinate) 1) 5)
(if (= (polynome 'order) 2)
(= ((polynome 'coefficient) 2) 2)
#f)
#f)
#f)
#f)
#f)
#f)
#f)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.