_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
d2b9fdecfc74dfcfb93eeeb492209efa8a7a7b3a6b3f3391af81a8cfea24c34f
bschwb/cis194-solutions
Lecture.hs
# OPTIONS_GHC -Wall # module Lecture where import Control.Applicative type Name = String data Employee = Employee { name :: Name , phone :: String } deriving Show {-instance Applicative Maybe where-} {-pure = Just-} {-Nothing <*> _ = Nothing-} {-_ <*> Nothing = Nothing-} {-Just f <*> Just x = Just (f x)-} m_name1, m_name2 :: Maybe Name m_name1 = Nothing m_name2 = Just "Brent" m_phone1, m_phone2 :: Maybe String m_phone1 = Nothing m_phone2 = Just "555-1234" ex01 = Employee <$> m_name1 <*> m_phone1 ex02 = Employee <$> m_name1 <*> m_phone2 ex03 = Employee <$> m_name2 <*> m_phone1 ex04 = Employee <$> m_name2 <*> m_phone2
null
https://raw.githubusercontent.com/bschwb/cis194-solutions/e79f96083b6edbfed18a2adbc749c41d196d8ff7/10-applicative-functors-part1/Lecture.hs
haskell
instance Applicative Maybe where pure = Just Nothing <*> _ = Nothing _ <*> Nothing = Nothing Just f <*> Just x = Just (f x)
# OPTIONS_GHC -Wall # module Lecture where import Control.Applicative type Name = String data Employee = Employee { name :: Name , phone :: String } deriving Show m_name1, m_name2 :: Maybe Name m_name1 = Nothing m_name2 = Just "Brent" m_phone1, m_phone2 :: Maybe String m_phone1 = Nothing m_phone2 = Just "555-1234" ex01 = Employee <$> m_name1 <*> m_phone1 ex02 = Employee <$> m_name1 <*> m_phone2 ex03 = Employee <$> m_name2 <*> m_phone1 ex04 = Employee <$> m_name2 <*> m_phone2
3977eba8a6f9c0229be218abaefb60a58605f6c067881b60c515751ce32a8db3
zkat/sheeple
reply-dispatch.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;;; ;;;; This file is part of Sheeple ;;;; tests/reply-dispatch.lisp ;;;; ;;;; Unit tests for reply-dispatch and replies ;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :sheeple) (def-suite reply-combination :in messages) (in-suite reply-combination) (defmacro with-flag-stack (&body body) (with-gensyms (stack) `(let (,stack) (declare (ignorable ,stack)) (flet ((flag (tag) (nconcf ,stack (list tag))) (check (reason &rest stack) (is (equal stack ,stack) reason) (setf ,stack nil))) (declare (ignorable (function flag) (function check))) ,@body)))) (defmacro with-dummy-message (message-arglist &body body) (let ((message-name (gensym))) `(with-test-message ,message-name (macrolet ((define-dummy-reply (qualifiers specializers &body body) `(defreply ,',message-name ,@qualifiers ,(mapcar 'list ',message-arglist specializers) ,@body))) (flet ((call-dummy-message (,@message-arglist) (,message-name ,@message-arglist))) (defmessage ,message-name ,message-arglist) ,@body))))) (test standard-combination-primary (with-object-hierarchy (a (b a)) (with-dummy-message (x y) (with-flag-stack (define-dummy-reply nil (a =t=) (flag :a)) (call-dummy-message a nil) (check "Single reply" :a))) (with-dummy-message (x y) (with-flag-stack (define-dummy-reply nil (a =t=) (flag :a)) (define-dummy-reply nil (b =t=) (flag :b) (call-next-reply)) (call-dummy-message b nil) (check "Two replies, linked with CALL-NEXT-REPLY" :b :a))))) (test standard-combination-before (with-object-hierarchy (a (b a)) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:before) (a) (flag :a-before)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message a) (check "One primary, one :before, specialized on the same object" :a-before :a))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:before) (b) (flag :b-before)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message b) (check "One primary and one :before specialized on a child" :b-before :a))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:before) (b) (flag :b-before)) (define-dummy-reply (:before) (a) (flag :a-before)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message b) (check "One primary, one :before specialized on the same object, and ~@ one :before specialized on its child" :b-before :a-before :a))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:before) (b) (flag :b-before)) (define-dummy-reply (:before) (a) (flag :a-before)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message a) (check "One primary, one :before specialized on the same object, and ~@ one :before which shouldn't be running" :a-before :a))))) (test standard-combination-after (with-object-hierarchy (a (b a)) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:after) (a) (flag :a-after)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message a) (check "One primary, one :after, specialized on the same object" :a :a-after))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:after) (b) (flag :b-after)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message b) (check "One primary and one :after specialized on a child" :a :b-after))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:after) (b) (flag :b-after)) (define-dummy-reply (:after) (a) (flag :a-after)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message b) (check "One primary, one :after specialized on the same object, and ~@ one :after specialized on its child" :a :a-after :b-after))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:after) (b) (flag :b-after)) (define-dummy-reply (:after) (a) (flag :a-after)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message a) (check "One primary, one :after specialized on the same object, and ~@ one :after which shouldn't be running" :a :a-after))))) (test standard-combination-around (with-object-hierarchy (a (b a)) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:around) (a) (flag :around-entry) (call-next-reply) (flag :around-exit)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message a) (check "One primary, and one :around wrapping it" :around-entry :a :around-exit))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:around) (b) (flag :poop)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message a) (check "One primary, and an :around which shouldn't be running" :a))))) (def-suite reply-dispatch :in messages) (in-suite reply-dispatch) (test primary-reply-p (is (primary-reply-p (%%make-reply :qualifiers nil))) (is (not (primary-reply-p (%%make-reply :qualifiers '(:before))))) (is (not (primary-reply-p (%%make-reply :qualifiers '(:after))))) (is (not (primary-reply-p (%%make-reply :qualifiers '(:around))))) (is (not (primary-reply-p (%%make-reply :qualifiers '(:oogly :boogly)))))) (test before-reply-p (is (not (before-reply-p (%%make-reply :qualifiers nil)))) (is (before-reply-p (%%make-reply :qualifiers '(:before)))) (is (before-reply-p (%%make-reply :qualifiers '(:before :another)))) (is (not (before-reply-p (%%make-reply :qualifiers '(:after))))) (is (not (before-reply-p (%%make-reply :qualifiers '(:around))))) (is (not (before-reply-p (%%make-reply :qualifiers '(:oogly :boogly)))))) (test after-reply-p (is (not (after-reply-p (%%make-reply :qualifiers nil)))) (is (not (after-reply-p (%%make-reply :qualifiers '(:before))))) (is (after-reply-p (%%make-reply :qualifiers '(:after)))) (is (after-reply-p (%%make-reply :qualifiers '(:after :another)))) (is (not (after-reply-p (%%make-reply :qualifiers '(:around))))) (is (not (after-reply-p (%%make-reply :qualifiers '(:oogly :boogly)))))) (test around-reply-p (is (not (around-reply-p (%%make-reply :qualifiers nil)))) (is (not (around-reply-p (%%make-reply :qualifiers '(:before))))) (is (not (around-reply-p (%%make-reply :qualifiers '(:after))))) (is (around-reply-p (%%make-reply :qualifiers '(:around)))) (is (around-reply-p (%%make-reply :qualifiers '(:around :another)))) (is (not (around-reply-p (%%make-reply :qualifiers '(:oogly :boogly)))))) (test apply-replies) (test next-reply-p) (test call-next-reply) (test compute-effective-reply-function) (test compute-primary-erfun) (test find-applicable-replies) ;; other dispatch stuff (test sort-applicable-replies) (test contain-reply) (test unbox-replies) (test fully-specified-p) (test calculate-rank-score) (test reply-specialized-portion)
null
https://raw.githubusercontent.com/zkat/sheeple/5393c74737ccf22c3fd5f390076b75c38453cb04/tests/reply-dispatch.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- This file is part of Sheeple tests/reply-dispatch.lisp Unit tests for reply-dispatch and replies other dispatch stuff
(in-package :sheeple) (def-suite reply-combination :in messages) (in-suite reply-combination) (defmacro with-flag-stack (&body body) (with-gensyms (stack) `(let (,stack) (declare (ignorable ,stack)) (flet ((flag (tag) (nconcf ,stack (list tag))) (check (reason &rest stack) (is (equal stack ,stack) reason) (setf ,stack nil))) (declare (ignorable (function flag) (function check))) ,@body)))) (defmacro with-dummy-message (message-arglist &body body) (let ((message-name (gensym))) `(with-test-message ,message-name (macrolet ((define-dummy-reply (qualifiers specializers &body body) `(defreply ,',message-name ,@qualifiers ,(mapcar 'list ',message-arglist specializers) ,@body))) (flet ((call-dummy-message (,@message-arglist) (,message-name ,@message-arglist))) (defmessage ,message-name ,message-arglist) ,@body))))) (test standard-combination-primary (with-object-hierarchy (a (b a)) (with-dummy-message (x y) (with-flag-stack (define-dummy-reply nil (a =t=) (flag :a)) (call-dummy-message a nil) (check "Single reply" :a))) (with-dummy-message (x y) (with-flag-stack (define-dummy-reply nil (a =t=) (flag :a)) (define-dummy-reply nil (b =t=) (flag :b) (call-next-reply)) (call-dummy-message b nil) (check "Two replies, linked with CALL-NEXT-REPLY" :b :a))))) (test standard-combination-before (with-object-hierarchy (a (b a)) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:before) (a) (flag :a-before)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message a) (check "One primary, one :before, specialized on the same object" :a-before :a))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:before) (b) (flag :b-before)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message b) (check "One primary and one :before specialized on a child" :b-before :a))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:before) (b) (flag :b-before)) (define-dummy-reply (:before) (a) (flag :a-before)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message b) (check "One primary, one :before specialized on the same object, and ~@ one :before specialized on its child" :b-before :a-before :a))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:before) (b) (flag :b-before)) (define-dummy-reply (:before) (a) (flag :a-before)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message a) (check "One primary, one :before specialized on the same object, and ~@ one :before which shouldn't be running" :a-before :a))))) (test standard-combination-after (with-object-hierarchy (a (b a)) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:after) (a) (flag :a-after)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message a) (check "One primary, one :after, specialized on the same object" :a :a-after))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:after) (b) (flag :b-after)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message b) (check "One primary and one :after specialized on a child" :a :b-after))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:after) (b) (flag :b-after)) (define-dummy-reply (:after) (a) (flag :a-after)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message b) (check "One primary, one :after specialized on the same object, and ~@ one :after specialized on its child" :a :a-after :b-after))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:after) (b) (flag :b-after)) (define-dummy-reply (:after) (a) (flag :a-after)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message a) (check "One primary, one :after specialized on the same object, and ~@ one :after which shouldn't be running" :a :a-after))))) (test standard-combination-around (with-object-hierarchy (a (b a)) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:around) (a) (flag :around-entry) (call-next-reply) (flag :around-exit)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message a) (check "One primary, and one :around wrapping it" :around-entry :a :around-exit))) (with-dummy-message (x) (with-flag-stack (define-dummy-reply (:around) (b) (flag :poop)) (define-dummy-reply nil (a) (flag :a)) (call-dummy-message a) (check "One primary, and an :around which shouldn't be running" :a))))) (def-suite reply-dispatch :in messages) (in-suite reply-dispatch) (test primary-reply-p (is (primary-reply-p (%%make-reply :qualifiers nil))) (is (not (primary-reply-p (%%make-reply :qualifiers '(:before))))) (is (not (primary-reply-p (%%make-reply :qualifiers '(:after))))) (is (not (primary-reply-p (%%make-reply :qualifiers '(:around))))) (is (not (primary-reply-p (%%make-reply :qualifiers '(:oogly :boogly)))))) (test before-reply-p (is (not (before-reply-p (%%make-reply :qualifiers nil)))) (is (before-reply-p (%%make-reply :qualifiers '(:before)))) (is (before-reply-p (%%make-reply :qualifiers '(:before :another)))) (is (not (before-reply-p (%%make-reply :qualifiers '(:after))))) (is (not (before-reply-p (%%make-reply :qualifiers '(:around))))) (is (not (before-reply-p (%%make-reply :qualifiers '(:oogly :boogly)))))) (test after-reply-p (is (not (after-reply-p (%%make-reply :qualifiers nil)))) (is (not (after-reply-p (%%make-reply :qualifiers '(:before))))) (is (after-reply-p (%%make-reply :qualifiers '(:after)))) (is (after-reply-p (%%make-reply :qualifiers '(:after :another)))) (is (not (after-reply-p (%%make-reply :qualifiers '(:around))))) (is (not (after-reply-p (%%make-reply :qualifiers '(:oogly :boogly)))))) (test around-reply-p (is (not (around-reply-p (%%make-reply :qualifiers nil)))) (is (not (around-reply-p (%%make-reply :qualifiers '(:before))))) (is (not (around-reply-p (%%make-reply :qualifiers '(:after))))) (is (around-reply-p (%%make-reply :qualifiers '(:around)))) (is (around-reply-p (%%make-reply :qualifiers '(:around :another)))) (is (not (around-reply-p (%%make-reply :qualifiers '(:oogly :boogly)))))) (test apply-replies) (test next-reply-p) (test call-next-reply) (test compute-effective-reply-function) (test compute-primary-erfun) (test find-applicable-replies) (test sort-applicable-replies) (test contain-reply) (test unbox-replies) (test fully-specified-p) (test calculate-rank-score) (test reply-specialized-portion)
eb6921e1f77fd9c6246127faf2b3c95e811494be9fc0c180d3e2ca90e16f241d
scrintal/heroicons-reagent
inbox_stack.cljs
(ns com.scrintal.heroicons.solid.inbox-stack) (defn render [] [:svg {:xmlns "" :viewBox "0 0 24 24" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M1.5 9.832v1.793c0 1.036.84 1.875 1.875 1.875h17.25c1.035 0 1.875-.84 1.875-1.875V9.832a3 3 0 00-.722-1.952l-3.285-3.832A3 3 0 0016.215 3h-8.43a3 3 0 00-2.278 1.048L2.222 7.88A3 3 0 001.5 9.832zM7.785 4.5a1.5 1.5 0 00-1.139.524L3.881 8.25h3.165a3 3 0 012.496 1.336l.164.246a1.5 1.5 0 001.248.668h2.092a1.5 1.5 0 001.248-.668l.164-.246a3 3 0 012.496-1.336h3.165l-2.765-3.226a1.5 1.5 0 00-1.139-.524h-8.43z" :clipRule "evenodd"}] [:path {:d "M2.813 15c-.725 0-1.313.588-1.313 1.313V18a3 3 0 003 3h15a3 3 0 003-3v-1.688c0-.724-.588-1.312-1.313-1.312h-4.233a3 3 0 00-2.496 1.336l-.164.246a1.5 1.5 0 01-1.248.668h-2.092a1.5 1.5 0 01-1.248-.668l-.164-.246A3 3 0 007.046 15H2.812z"}]])
null
https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/solid/inbox_stack.cljs
clojure
(ns com.scrintal.heroicons.solid.inbox-stack) (defn render [] [:svg {:xmlns "" :viewBox "0 0 24 24" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M1.5 9.832v1.793c0 1.036.84 1.875 1.875 1.875h17.25c1.035 0 1.875-.84 1.875-1.875V9.832a3 3 0 00-.722-1.952l-3.285-3.832A3 3 0 0016.215 3h-8.43a3 3 0 00-2.278 1.048L2.222 7.88A3 3 0 001.5 9.832zM7.785 4.5a1.5 1.5 0 00-1.139.524L3.881 8.25h3.165a3 3 0 012.496 1.336l.164.246a1.5 1.5 0 001.248.668h2.092a1.5 1.5 0 001.248-.668l.164-.246a3 3 0 012.496-1.336h3.165l-2.765-3.226a1.5 1.5 0 00-1.139-.524h-8.43z" :clipRule "evenodd"}] [:path {:d "M2.813 15c-.725 0-1.313.588-1.313 1.313V18a3 3 0 003 3h15a3 3 0 003-3v-1.688c0-.724-.588-1.312-1.313-1.312h-4.233a3 3 0 00-2.496 1.336l-.164.246a1.5 1.5 0 01-1.248.668h-2.092a1.5 1.5 0 01-1.248-.668l-.164-.246A3 3 0 007.046 15H2.812z"}]])
7b7862d836b32069a92465a204c4ceb9ff158203e2924ee79e47f8f223835a44
input-output-hk/plutus-apps
Types.hs
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DerivingVia #-} # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE LambdaCase # {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # {-# LANGUAGE Strict #-} # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # OPTIONS_GHC -Wno - orphans # {-| Misc. types used in this package -} module Plutus.ChainIndex.Types( ChainIndexTx(..) , ChainIndexTxOutputs(..) , ChainIndexTxOut(..) , ReferenceScript(..) , BlockId(..) , blockId , Tip(..) , Point(..) , pointsToTip , tipAsPoint , _PointAtGenesis , _Point , TxValidity(..) , TxStatus , TxOutStatus , RollbackState(..) , TxOutState(..) , liftTxOutStatus , txOutStatusTxOutState , BlockNumber(..) , Depth(..) , Diagnostics(..) , TxConfirmedState(..) , TxStatusFailure(..) , TxIdState(..) , TxUtxoBalance(..) , tubUnspentOutputs , tubUnmatchedSpentInputs , TxOutBalance(..) , tobUnspentOutputs , tobSpentOutputs , ChainSyncBlock(..) , TxProcessOption(..) -- ** Lenses , citxTxId , citxInputs , citxOutputs , citxValidRange , citxData , citxRedeemers , citxScripts , citxCardanoTx , _InvalidTx , _ValidTx , fromReferenceScript ) where import Cardano.Api qualified as C import Codec.Serialise (Serialise) import Codec.Serialise qualified as CBOR import Codec.Serialise.Class (Serialise (decode, encode)) import Codec.Serialise.Decoding (decodeListLen, decodeWord) import Codec.Serialise.Encoding (encodeListLen, encodeWord) import Control.Lens (makeLenses, makePrisms, (&), (.~), (?~)) import Control.Monad (void) import Crypto.Hash (SHA256, hash) import Data.Aeson (FromJSON (parseJSON), ToJSON (toJSON), object, (.!=), (.:), (.:?), (.=)) import Data.Aeson qualified as Aeson import Data.Aeson.KeyMap qualified as Aeson import Data.ByteArray qualified as BA import Data.ByteString.Lazy qualified as BSL import Data.Default (Default (..)) import Data.HashMap.Strict.InsOrd qualified as InsOrdMap import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map import Data.Monoid (Last (..), Sum (..)) import Data.OpenApi (NamedSchema (NamedSchema), OpenApiType (OpenApiObject), byteSchema, declareSchemaRef, properties, required, sketchSchema, type_) import Data.OpenApi qualified as OpenApi import Data.Semigroup.Generic (GenericSemigroupMonoid (..)) import Data.Set (Set) import Data.Set qualified as Set import Data.Typeable (Proxy (Proxy), Typeable) import Data.Word (Word64) import GHC.Generics (Generic) import Ledger (CardanoAddress, CardanoTx, Language, SlotRange, TxIn (..), TxInType (..), TxOutRef (..), Versioned, toPlutusAddress) import Ledger.Blockchain (BlockId (..)) import Ledger.Blockchain qualified as Ledger import Ledger.Slot (Slot (Slot)) import Ledger.Tx.CardanoAPI (fromCardanoScriptInAnyLang) import Plutus.V1.Ledger.Scripts (Datum (Datum), DatumHash (DatumHash), Script, ScriptHash (..)) import Plutus.V1.Ledger.Tx (RedeemerPtr, Redeemers, ScriptTag, TxId (TxId)) import Plutus.V2.Ledger.Api (CurrencySymbol (CurrencySymbol), Extended, Interval (..), LowerBound, OutputDatum (..), Redeemer (Redeemer), TokenName (TokenName), UpperBound, Validator (Validator), Value (..)) import PlutusCore.Data import PlutusTx.AssocMap qualified as AssocMap import PlutusTx.Builtins.Internal (BuiltinData (..)) import PlutusTx.Lattice (MeetSemiLattice (..)) import PlutusTx.Prelude qualified as PlutusTx import Prettyprinter import Prettyprinter.Extras (PrettyShow (..)) data ReferenceScript = ReferenceScriptNone | ReferenceScriptInAnyLang C.ScriptInAnyLang deriving (Eq, Show, Generic, Serialise, OpenApi.ToSchema) instance ToJSON ReferenceScript where toJSON (ReferenceScriptInAnyLang s) = object ["referenceScript" .= s] toJSON ReferenceScriptNone = Aeson.Null instance FromJSON ReferenceScript where parseJSON = Aeson.withObject "ReferenceScript" $ \o -> case Aeson.lookup "referenceScript" o of Nothing -> pure ReferenceScriptNone Just refScript -> ReferenceScriptInAnyLang <$> parseJSON refScript instance Serialise C.ScriptInAnyLang where encode (C.ScriptInAnyLang lang script) = let -- Since lang is a GADT we have to encode the script in all branches other = case lang of C.SimpleScriptLanguage C.SimpleScriptV1 -> encodeWord 0 <> encode (C.serialiseToCBOR script) C.SimpleScriptLanguage C.SimpleScriptV2 -> encodeWord 1 <> encode (C.serialiseToCBOR script) C.PlutusScriptLanguage C.PlutusScriptV1 -> encodeWord 2 <> encode (C.serialiseToCBOR script) C.PlutusScriptLanguage C.PlutusScriptV2 -> encodeWord 3 <> encode (C.serialiseToCBOR script) in encodeListLen 2 <> other decode = do len <- decodeListLen langWord <- decodeWord script <- decode case (len, langWord) of (2, 0) -> do let decoded = either (error "Failed to deserialise AsSimpleScriptV1 from CBOR ") id (C.deserialiseFromCBOR (C.AsScript C.AsSimpleScriptV1) script) pure $ C.ScriptInAnyLang (C.SimpleScriptLanguage C.SimpleScriptV1) decoded (2, 1) -> do let decoded = either (error "Failed to deserialise AsSimpleScriptV2 from CBOR ") id (C.deserialiseFromCBOR (C.AsScript C.AsSimpleScriptV2) script) pure $ C.ScriptInAnyLang (C.SimpleScriptLanguage C.SimpleScriptV2) decoded (2, 2) -> do let decoded = either (error "Failed to deserialise AsPlutusScriptV1 from CBOR ") id (C.deserialiseFromCBOR (C.AsScript C.AsPlutusScriptV1) script) pure $ C.ScriptInAnyLang (C.PlutusScriptLanguage C.PlutusScriptV1) decoded (2, 3) -> do let decoded = either (error "Failed to deserialise AsPlutusScriptV2 from CBOR ") id (C.deserialiseFromCBOR (C.AsScript C.AsPlutusScriptV2) script) pure $ C.ScriptInAnyLang (C.PlutusScriptLanguage C.PlutusScriptV2) decoded _ -> fail "Invalid ScriptInAnyLang encoding" instance OpenApi.ToSchema C.ScriptInAnyLang where declareNamedSchema _ = pure $ OpenApi.NamedSchema (Just "ScriptInAnyLang") mempty fromReferenceScript :: ReferenceScript -> Maybe (Versioned Script) fromReferenceScript ReferenceScriptNone = Nothing fromReferenceScript (ReferenceScriptInAnyLang sial) = fromCardanoScriptInAnyLang sial instance OpenApi.ToSchema (C.AddressInEra C.BabbageEra) where declareNamedSchema _ = pure $ OpenApi.NamedSchema (Just "AddressInBabbageEra") mempty instance OpenApi.ToSchema Data where declareNamedSchema _ = do integerSchema <- OpenApi.declareSchemaRef (Proxy :: Proxy Integer) constrArgsSchema <- OpenApi.declareSchemaRef (Proxy :: Proxy (Integer, [Data])) mapArgsSchema <- OpenApi.declareSchemaRef (Proxy :: Proxy [(Data, Data)]) listArgsSchema <- OpenApi.declareSchemaRef (Proxy :: Proxy [Data]) bytestringSchema <- OpenApi.declareSchemaRef (Proxy :: Proxy String) return $ OpenApi.NamedSchema (Just "Data") $ mempty & OpenApi.type_ ?~ OpenApi.OpenApiObject & OpenApi.properties .~ InsOrdMap.fromList [ ("Constr", constrArgsSchema) , ("Map", mapArgsSchema) , ("List", listArgsSchema) , ("I", integerSchema) , ("B", bytestringSchema) ] deriving instance OpenApi.ToSchema BuiltinData instance OpenApi.ToSchema PlutusTx.BuiltinByteString where declareNamedSchema _ = pure $ OpenApi.NamedSchema (Just "Bytes") mempty deriving newtype instance OpenApi.ToSchema TokenName deriving newtype instance OpenApi.ToSchema Value deriving instance OpenApi.ToSchema a => OpenApi.ToSchema (Extended a) deriving instance OpenApi.ToSchema a => OpenApi.ToSchema (Interval a) deriving instance OpenApi.ToSchema a => OpenApi.ToSchema (LowerBound a) deriving instance OpenApi.ToSchema a => OpenApi.ToSchema (UpperBound a) deriving instance OpenApi.ToSchema Language deriving instance OpenApi.ToSchema script => OpenApi.ToSchema (Versioned script) deriving anyclass instance OpenApi . C.TxId deriving newtype instance OpenApi.ToSchema TxId deriving instance OpenApi.ToSchema ScriptTag deriving newtype instance OpenApi.ToSchema Validator deriving instance OpenApi.ToSchema TxInType deriving instance OpenApi.ToSchema TxIn deriving newtype instance OpenApi.ToSchema Slot deriving anyclass instance (OpenApi.ToSchema k, OpenApi.ToSchema v) => OpenApi.ToSchema (AssocMap.Map k v) deriving anyclass instance OpenApi.ToSchema OutputDatum instance OpenApi.ToSchema C.Value where declareNamedSchema _ = pure $ OpenApi.NamedSchema (Just "Value") $ OpenApi.toSchema (Proxy @[(String, Integer)]) data ChainIndexTxOut = ChainIndexTxOut ^ We ca n't use AddressInAnyEra here because of missing FromJson instance for era , citoValue :: C.Value , citoDatum :: OutputDatum , citoRefScript :: ReferenceScript } deriving (Eq, Show, Generic, Serialise, OpenApi.ToSchema) instance ToJSON ChainIndexTxOut where toJSON ChainIndexTxOut{..} = object [ "address" .= toJSON citoAddress , "value" .= toJSON citoValue , "datum" .= toJSON citoDatum , "refScript" .= toJSON citoRefScript ] instance FromJSON ChainIndexTxOut where parseJSON = Aeson.withObject "ChainIndexTxOut" $ \obj -> ChainIndexTxOut <$> obj .: "address" <*> obj .: "value" <*> obj .: "datum" <*> obj .:? "refScript" .!= ReferenceScriptNone instance Pretty ChainIndexTxOut where pretty ChainIndexTxOut {citoAddress, citoValue} = hang 2 $ vsep ["-" <+> pretty citoValue <+> "addressed to", pretty (toPlutusAddress citoAddress)] -- | List of outputs of a transaction. There is only an optional collateral output -- if the transaction is invalid. data ChainIndexTxOutputs = InvalidTx (Maybe ChainIndexTxOut) -- ^ The transaction is invalid so there is maybe a collateral output. | ValidTx [ChainIndexTxOut] deriving (Show, Eq, Generic, ToJSON, FromJSON, Serialise, OpenApi.ToSchema) makePrisms ''ChainIndexTxOutputs deriving instance OpenApi.ToSchema TxOutRef deriving instance OpenApi.ToSchema RedeemerPtr deriving newtype instance OpenApi.ToSchema Redeemer deriving newtype instance OpenApi.ToSchema ScriptHash instance OpenApi.ToSchema Script where declareNamedSchema _ = pure $ OpenApi.NamedSchema (Just "Script") (OpenApi.toSchema (Proxy :: Proxy String)) deriving newtype instance OpenApi.ToSchema CurrencySymbol deriving newtype instance OpenApi.ToSchema Datum deriving newtype instance OpenApi.ToSchema DatumHash instance (Typeable era, Typeable mode) => OpenApi.ToSchema (C.EraInMode era mode) where declareNamedSchema _ = do return $ NamedSchema (Just "EraInMode") $ sketchSchema C.BabbageEraInCardanoMode instance (Typeable era) => OpenApi.ToSchema (C.Tx era) where declareNamedSchema _ = do return $ NamedSchema (Just "Tx") byteSchema instance OpenApi.ToSchema CardanoTx where declareNamedSchema _ = do txSchema <- declareSchemaRef (Proxy :: Proxy (C.Tx C.BabbageEra)) eraInModeSchema <- declareSchemaRef (Proxy :: Proxy (C.EraInMode C.BabbageEra C.CardanoMode)) return $ NamedSchema (Just "CardanoTx") $ mempty & type_ ?~ OpenApiObject & properties .~ InsOrdMap.fromList [ ("tx", txSchema) , ("eraInMode", eraInModeSchema) ] & required .~ [ "tx", "eraInMode" ] data ChainIndexTx = ChainIndexTx { _citxTxId :: TxId, -- ^ The id of this transaction. _citxInputs :: [TxIn], -- ^ The inputs to this transaction. _citxOutputs :: ChainIndexTxOutputs, -- ^ The outputs of this transaction, ordered so they can be referenced by index. _citxValidRange :: !SlotRange, ^ The ' SlotRange ' during which this transaction may be validated . _citxData :: Map DatumHash Datum, ^ Datum objects recorded on this transaction . _citxRedeemers :: Redeemers, -- ^ Redeemers of the minting scripts. _citxScripts :: Map ScriptHash (Versioned Script), ^ The scripts ( validator , stake validator or minting ) part of . _citxCardanoTx :: Maybe CardanoTx ^ The full Cardano API tx which was used to populate the rest of the -- 'ChainIndexTx' fields. Useful because 'ChainIndexTx' doesn't have all the details of the tx , so we keep it as a safety net . Might be Nothing if we -- are in the emulator. } deriving (Show, Eq, Generic, ToJSON, FromJSON, Serialise, OpenApi.ToSchema) makeLenses ''ChainIndexTx instance Pretty ChainIndexTx where pretty ChainIndexTx{_citxTxId, _citxInputs, _citxOutputs = ValidTx outputs, _citxValidRange, _citxData, _citxRedeemers, _citxScripts} = let lines' = [ hang 2 (vsep ("inputs:" : fmap pretty _citxInputs)) , hang 2 (vsep ("outputs:" : fmap pretty outputs)) , hang 2 (vsep ("scripts hashes:": fmap (pretty . fst) (Map.toList _citxScripts))) , "validity range:" <+> viaShow _citxValidRange , hang 2 (vsep ("data:": fmap (pretty . snd) (Map.toList _citxData) )) , hang 2 (vsep ("redeemers:": fmap (pretty . snd) (Map.toList _citxRedeemers) )) ] in nest 2 $ vsep ["Valid tx" <+> pretty _citxTxId <> colon, braces (vsep lines')] pretty ChainIndexTx{_citxTxId, _citxInputs, _citxOutputs = InvalidTx mOutput, _citxValidRange, _citxData, _citxRedeemers, _citxScripts} = let lines' = [ hang 2 (vsep ("inputs:" : fmap pretty _citxInputs)) , hang 2 (vsep ["collateral output:", maybe "-" pretty mOutput]) , hang 2 (vsep ("scripts hashes:": fmap (pretty . fst) (Map.toList _citxScripts))) , "validity range:" <+> viaShow _citxValidRange , hang 2 (vsep ("data:": fmap (pretty . snd) (Map.toList _citxData) )) , hang 2 (vsep ("redeemers:": fmap (pretty . snd) (Map.toList _citxRedeemers) )) ] in nest 2 $ vsep ["Invalid tx" <+> pretty _citxTxId <> colon, braces (vsep lines')] -- | Compute a hash of the block's contents. blockId :: Ledger.Block -> BlockId blockId = BlockId . BA.convert . hash @_ @SHA256 . BSL.toStrict . CBOR.serialise newtype BlockNumber = BlockNumber { unBlockNumber :: Word64 } deriving stock (Eq, Ord, Show, Generic) deriving newtype (Num, Real, Enum, Integral, ToJSON, FromJSON, OpenApi.ToSchema) instance Pretty BlockNumber where pretty (BlockNumber blockNumber) = "BlockNumber " <> pretty blockNumber instance OpenApi.ToSchema BlockId where declareNamedSchema _ = OpenApi.declareNamedSchema (Proxy @String) -- | The tip of the chain index. data Tip = TipAtGenesis | Tip { tipSlot :: Slot -- ^ Last slot , tipBlockId :: BlockId -- ^ Last block ID , tipBlockNo :: BlockNumber -- ^ Last block number } deriving stock (Eq, Show, Generic) deriving anyclass (ToJSON, FromJSON, OpenApi.ToSchema) makePrisms ''Tip -- | When performing a rollback the chain sync protocol does not provide a block -- number where to resume from. data Point = PointAtGenesis | Point { pointSlot :: Slot -- ^ Slot number , pointBlockId :: BlockId -- ^ Block number } deriving stock (Eq, Show, Generic) deriving anyclass (ToJSON, FromJSON) makePrisms ''Point instance Ord Point where PointAtGenesis <= _ = True _ <= PointAtGenesis = False (Point ls _) <= (Point rs _) = ls <= rs instance Pretty Point where pretty PointAtGenesis = "PointAtGenesis" pretty Point {pointSlot, pointBlockId} = "Point(" <> pretty pointSlot <> comma <+> pretty pointBlockId <> ")" tipAsPoint :: Tip -> Point tipAsPoint TipAtGenesis = PointAtGenesis tipAsPoint (Tip tSlot tBlockId _) = Point { pointSlot = tSlot , pointBlockId = tBlockId } pointsToTip :: Point -> Tip -> Bool pointsToTip PointAtGenesis TipAtGenesis = True pointsToTip (Point pSlot pBlockId) (Tip tSlot tBlockId _) | tSlot == pSlot && tBlockId == pBlockId = True pointsToTip _ _ = False -- | This mirrors the previously defined Tip which used the Last monoid definition. instance Semigroup Tip where t <> TipAtGenesis = t _ <> t = t instance Semigroup Point where t <> PointAtGenesis = t _ <> t = t instance Monoid Tip where mempty = TipAtGenesis instance Monoid Point where mempty = PointAtGenesis instance Ord Tip where compare TipAtGenesis TipAtGenesis = EQ compare TipAtGenesis _ = LT compare _ TipAtGenesis = GT compare (Tip ls _ lb) (Tip rs _ rb) = compare ls rs <> compare lb rb instance Pretty Tip where pretty TipAtGenesis = "TipAtGenesis" pretty Tip {tipSlot, tipBlockId, tipBlockNo} = "Tip(" <> pretty tipSlot <> comma <+> pretty tipBlockId <> comma <+> pretty tipBlockNo <> ")" -- | Validity of a transaction that has been added to the ledger data TxValidity = TxValid | TxInvalid | UnknownValidity deriving stock (Eq, Ord, Show, Generic) deriving anyclass (ToJSON, FromJSON) deriving Pretty via (PrettyShow TxValidity) instance MeetSemiLattice TxValidity where TxValid /\ TxValid = TxValid TxInvalid /\ TxInvalid = TxInvalid _ /\ _ = UnknownValidity | How many blocks deep the tx is on the chain newtype Depth = Depth { unDepth :: Int } deriving stock (Eq, Ord, Show, Generic) deriving newtype (Num, Real, Enum, Integral, Pretty, ToJSON, FromJSON) instance MeetSemiLattice Depth where Depth a /\ Depth b = Depth (max a b) Note [ TxStatus state machine ] The status of a transaction is described by the following state machine . Current state | Next state(s ) ----------------------------------------------------- Unknown | OnChain OnChain | OnChain , Unknown , Committed Committed | - The initial state after submitting the transaction is Unknown . The status of a transaction is described by the following state machine. Current state | Next state(s) ----------------------------------------------------- Unknown | OnChain OnChain | OnChain, Unknown, Committed Committed | - The initial state after submitting the transaction is Unknown. -} -- | The status of a Cardano transaction type TxStatus = RollbackState () -- | The rollback state of a Cardano transaction data RollbackState a = Unknown -- ^ The transaction is not on the chain. That's all we can say. | TentativelyConfirmed Depth TxValidity a -- ^ The transaction is on the chain, n blocks deep. It can still be rolled -- back. | Committed TxValidity a -- ^ The transaction is on the chain. It cannot be rolled back anymore. deriving stock (Eq, Ord, Show, Generic, Functor) deriving anyclass (ToJSON, FromJSON) deriving Pretty via (PrettyShow (RollbackState a)) instance MeetSemiLattice a => MeetSemiLattice (RollbackState a) where Unknown /\ a = a a /\ Unknown = a TentativelyConfirmed d1 v1 a1 /\ TentativelyConfirmed d2 v2 a2 = TentativelyConfirmed (d1 /\ d2) (v1 /\ v2) (a1 /\ a2) TentativelyConfirmed _ v1 a1 /\ Committed v2 a2 = Committed (v1 /\ v2) (a1 /\ a2) Committed v1 a1 /\ TentativelyConfirmed _ v2 a2 = Committed (v1 /\ v2) (a1 /\ a2) Committed v1 a1 /\ Committed v2 a2 = Committed (v1 /\ v2) (a1 /\ a2) Note [ TxOutStatus state machine ] The status of a transaction output is described by the following state machine . Current state | Next state(s ) ----------------------------------------------------- TxOutUnknown | TxOutTentativelyUnspent TxOutTentativelyUnspent | TxOutUnknown , TxOutTentativelySpent , TxOutConfirmedUnspent TxOutTentativelySpent | TxOutUnknown , TxOutConfirmedSpent TxOutConfirmedUnspent | TxOutConfirmedSpent TxOutConfirmedSpent | - The initial state after submitting the transaction is ' TxOutUnknown ' . The status of a transaction output is described by the following state machine. Current state | Next state(s) ----------------------------------------------------- TxOutUnknown | TxOutTentativelyUnspent TxOutTentativelyUnspent | TxOutUnknown, TxOutTentativelySpent, TxOutConfirmedUnspent TxOutTentativelySpent | TxOutUnknown, TxOutConfirmedSpent TxOutConfirmedUnspent | TxOutConfirmedSpent TxOutConfirmedSpent | - The initial state after submitting the transaction is 'TxOutUnknown'. -} type TxOutStatus = RollbackState TxOutState data TxOutState = Spent TxId -- Spent by this transaction | Unspent deriving stock (Eq, Ord, Show, Generic) deriving anyclass (ToJSON, FromJSON) deriving Pretty via (PrettyShow TxOutState) | Maybe extract the ' TxOutState ' ( Spent or Unspent ) of a ' TxOutStatus ' . txOutStatusTxOutState :: TxOutStatus -> Maybe TxOutState txOutStatusTxOutState Unknown = Nothing txOutStatusTxOutState (TentativelyConfirmed _ _ s) = Just s txOutStatusTxOutState (Committed _ s) = Just s | Converts a ' TxOutStatus ' to a ' TxStatus ' . Possible since a transaction -- output belongs to a transaction. -- Note , however , that we ca n't convert a ' TxStatus ' to a ' TxOutStatus ' . liftTxOutStatus :: TxOutStatus -> TxStatus liftTxOutStatus = void data Diagnostics = Diagnostics { numTransactions :: Integer , numScripts :: Integer , numAddresses :: Integer , numAssetClasses :: Integer , numUnspentOutputs :: Int , numUnmatchedInputs :: Int , someTransactions :: [TxId] , unspentTxOuts :: [ChainIndexTxOut] } deriving stock (Eq, Show, Generic) deriving anyclass (ToJSON, FromJSON, OpenApi.ToSchema) | Datatype returned when we could n't get the state of a tx or a tx output . data TxStatusFailure | We could n't return the status because the ' TxIdState ' was in a ... -- state ... that we didn't know how to decode in ' . ChainIndex . TxIdState.transactionStatus ' . = TxIdStateInvalid BlockNumber TxId TxIdState | We could n't return the status because the ' ' does not contain the target tx output . | TxOutBalanceStateInvalid BlockNumber TxOutRef TxOutBalance | InvalidRollbackAttempt BlockNumber TxId TxIdState deriving (Show, Eq) data TxIdState = TxIdState { txnsConfirmed :: Map TxId TxConfirmedState -- ^ Number of times this transaction has been added as well as other -- necessary metadata. , txnsDeleted :: Map TxId (Sum Int) -- ^ Number of times this transaction has been deleted. } deriving stock (Eq, Generic, Show) A semigroup instance that merges the two maps , instead of taking the -- leftmost one. instance Semigroup TxIdState where TxIdState{txnsConfirmed=c, txnsDeleted=d} <> TxIdState{txnsConfirmed=c', txnsDeleted=d'} = TxIdState { txnsConfirmed = Map.unionWith (<>) c c' , txnsDeleted = Map.unionWith (<>) d d' } instance Monoid TxIdState where mappend = (<>) mempty = TxIdState { txnsConfirmed=mempty, txnsDeleted=mempty } data TxConfirmedState = TxConfirmedState { timesConfirmed :: Sum Int , blockAdded :: Last BlockNumber , validity :: Last TxValidity } deriving stock (Eq, Generic, Show) deriving (Monoid) via (GenericSemigroupMonoid TxConfirmedState) instance Semigroup TxConfirmedState where (TxConfirmedState tc ba v) <> (TxConfirmedState tc' ba' v') = TxConfirmedState (tc <> tc') (ba <> ba') (v <> v') | The effect of a transaction ( or a number of them ) on the tx output set . data TxOutBalance = TxOutBalance { _tobUnspentOutputs :: Set TxOutRef -- ^ Outputs newly added by the transaction(s) , _tobSpentOutputs :: Map TxOutRef TxId ^ Outputs spent by the transaction(s ) along with the tx i d that spent it } deriving stock (Eq, Show, Generic) deriving anyclass (FromJSON, ToJSON) instance Semigroup TxOutBalance where l <> r = TxOutBalance { _tobUnspentOutputs = _tobUnspentOutputs r <> (_tobUnspentOutputs l `Set.difference` Map.keysSet (_tobSpentOutputs r)) , _tobSpentOutputs = _tobSpentOutputs l <> _tobSpentOutputs r } instance Monoid TxOutBalance where mappend = (<>) mempty = TxOutBalance mempty mempty makeLenses ''TxOutBalance | The effect of a transaction ( or a number of them ) on the set . data TxUtxoBalance = TxUtxoBalance { _tubUnspentOutputs :: Set TxOutRef -- ^ Outputs newly added by the transaction(s) , _tubUnmatchedSpentInputs :: Set TxOutRef -- ^ Outputs spent by the transaction(s) that have no matching unspent output } deriving stock (Eq, Show, Generic) deriving anyclass (FromJSON, ToJSON, Serialise) makeLenses ''TxUtxoBalance instance Semigroup TxUtxoBalance where l <> r = TxUtxoBalance { _tubUnspentOutputs = _tubUnspentOutputs r <> (_tubUnspentOutputs l `Set.difference` _tubUnmatchedSpentInputs r) , _tubUnmatchedSpentInputs = (_tubUnmatchedSpentInputs r `Set.difference` _tubUnspentOutputs l) <> _tubUnmatchedSpentInputs l } instance Monoid TxUtxoBalance where mappend = (<>) mempty = TxUtxoBalance mempty mempty -- | User-customizable options to process a transaction. See # 73 for more motivations . newtype TxProcessOption = TxProcessOption { tpoStoreTx :: Bool -- ^ Should the chain index store this transaction or not. -- If not, only handle the UTXOs. -- This, for example, allows applications to skip unwanted pre-Alonzo transactions. } deriving (Show) -- We should think twice when setting the default option. -- For now, it should store all data to avoid weird non-backward-compatible bugs in the future. instance Default TxProcessOption where def = TxProcessOption { tpoStoreTx = True } -- | A block of transactions to be synced. data ChainSyncBlock = Block { blockTip :: Tip , blockTxs :: [(ChainIndexTx, TxProcessOption)] } deriving (Show)
null
https://raw.githubusercontent.com/input-output-hk/plutus-apps/b80116b9dd97e83b61f016924f83ad4284212796/plutus-chain-index-core/src/Plutus/ChainIndex/Types.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE DerivingVia # # LANGUAGE GADTs # # LANGUAGE NamedFieldPuns # # LANGUAGE OverloadedStrings # # LANGUAGE Strict # | Misc. types used in this package ** Lenses Since lang is a GADT we have to encode the script in all branches | List of outputs of a transaction. There is only an optional collateral output if the transaction is invalid. ^ The transaction is invalid so there is maybe a collateral output. ^ The id of this transaction. ^ The inputs to this transaction. ^ The outputs of this transaction, ordered so they can be referenced by index. ^ Redeemers of the minting scripts. 'ChainIndexTx' fields. Useful because 'ChainIndexTx' doesn't have all the are in the emulator. | Compute a hash of the block's contents. | The tip of the chain index. ^ Last slot ^ Last block ID ^ Last block number | When performing a rollback the chain sync protocol does not provide a block number where to resume from. ^ Slot number ^ Block number | This mirrors the previously defined Tip which used the Last monoid definition. | Validity of a transaction that has been added to the ledger --------------------------------------------------- --------------------------------------------------- | The status of a Cardano transaction | The rollback state of a Cardano transaction ^ The transaction is not on the chain. That's all we can say. ^ The transaction is on the chain, n blocks deep. It can still be rolled back. ^ The transaction is on the chain. It cannot be rolled back anymore. --------------------------------------------------- --------------------------------------------------- Spent by this transaction output belongs to a transaction. state ... that we didn't know how to decode in ^ Number of times this transaction has been added as well as other necessary metadata. ^ Number of times this transaction has been deleted. leftmost one. ^ Outputs newly added by the transaction(s) ^ Outputs newly added by the transaction(s) ^ Outputs spent by the transaction(s) that have no matching unspent output | User-customizable options to process a transaction. ^ Should the chain index store this transaction or not. If not, only handle the UTXOs. This, for example, allows applications to skip unwanted pre-Alonzo transactions. We should think twice when setting the default option. For now, it should store all data to avoid weird non-backward-compatible bugs in the future. | A block of transactions to be synced.
# LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # OPTIONS_GHC -Wno - orphans # module Plutus.ChainIndex.Types( ChainIndexTx(..) , ChainIndexTxOutputs(..) , ChainIndexTxOut(..) , ReferenceScript(..) , BlockId(..) , blockId , Tip(..) , Point(..) , pointsToTip , tipAsPoint , _PointAtGenesis , _Point , TxValidity(..) , TxStatus , TxOutStatus , RollbackState(..) , TxOutState(..) , liftTxOutStatus , txOutStatusTxOutState , BlockNumber(..) , Depth(..) , Diagnostics(..) , TxConfirmedState(..) , TxStatusFailure(..) , TxIdState(..) , TxUtxoBalance(..) , tubUnspentOutputs , tubUnmatchedSpentInputs , TxOutBalance(..) , tobUnspentOutputs , tobSpentOutputs , ChainSyncBlock(..) , TxProcessOption(..) , citxTxId , citxInputs , citxOutputs , citxValidRange , citxData , citxRedeemers , citxScripts , citxCardanoTx , _InvalidTx , _ValidTx , fromReferenceScript ) where import Cardano.Api qualified as C import Codec.Serialise (Serialise) import Codec.Serialise qualified as CBOR import Codec.Serialise.Class (Serialise (decode, encode)) import Codec.Serialise.Decoding (decodeListLen, decodeWord) import Codec.Serialise.Encoding (encodeListLen, encodeWord) import Control.Lens (makeLenses, makePrisms, (&), (.~), (?~)) import Control.Monad (void) import Crypto.Hash (SHA256, hash) import Data.Aeson (FromJSON (parseJSON), ToJSON (toJSON), object, (.!=), (.:), (.:?), (.=)) import Data.Aeson qualified as Aeson import Data.Aeson.KeyMap qualified as Aeson import Data.ByteArray qualified as BA import Data.ByteString.Lazy qualified as BSL import Data.Default (Default (..)) import Data.HashMap.Strict.InsOrd qualified as InsOrdMap import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map import Data.Monoid (Last (..), Sum (..)) import Data.OpenApi (NamedSchema (NamedSchema), OpenApiType (OpenApiObject), byteSchema, declareSchemaRef, properties, required, sketchSchema, type_) import Data.OpenApi qualified as OpenApi import Data.Semigroup.Generic (GenericSemigroupMonoid (..)) import Data.Set (Set) import Data.Set qualified as Set import Data.Typeable (Proxy (Proxy), Typeable) import Data.Word (Word64) import GHC.Generics (Generic) import Ledger (CardanoAddress, CardanoTx, Language, SlotRange, TxIn (..), TxInType (..), TxOutRef (..), Versioned, toPlutusAddress) import Ledger.Blockchain (BlockId (..)) import Ledger.Blockchain qualified as Ledger import Ledger.Slot (Slot (Slot)) import Ledger.Tx.CardanoAPI (fromCardanoScriptInAnyLang) import Plutus.V1.Ledger.Scripts (Datum (Datum), DatumHash (DatumHash), Script, ScriptHash (..)) import Plutus.V1.Ledger.Tx (RedeemerPtr, Redeemers, ScriptTag, TxId (TxId)) import Plutus.V2.Ledger.Api (CurrencySymbol (CurrencySymbol), Extended, Interval (..), LowerBound, OutputDatum (..), Redeemer (Redeemer), TokenName (TokenName), UpperBound, Validator (Validator), Value (..)) import PlutusCore.Data import PlutusTx.AssocMap qualified as AssocMap import PlutusTx.Builtins.Internal (BuiltinData (..)) import PlutusTx.Lattice (MeetSemiLattice (..)) import PlutusTx.Prelude qualified as PlutusTx import Prettyprinter import Prettyprinter.Extras (PrettyShow (..)) data ReferenceScript = ReferenceScriptNone | ReferenceScriptInAnyLang C.ScriptInAnyLang deriving (Eq, Show, Generic, Serialise, OpenApi.ToSchema) instance ToJSON ReferenceScript where toJSON (ReferenceScriptInAnyLang s) = object ["referenceScript" .= s] toJSON ReferenceScriptNone = Aeson.Null instance FromJSON ReferenceScript where parseJSON = Aeson.withObject "ReferenceScript" $ \o -> case Aeson.lookup "referenceScript" o of Nothing -> pure ReferenceScriptNone Just refScript -> ReferenceScriptInAnyLang <$> parseJSON refScript instance Serialise C.ScriptInAnyLang where encode (C.ScriptInAnyLang lang script) = let other = case lang of C.SimpleScriptLanguage C.SimpleScriptV1 -> encodeWord 0 <> encode (C.serialiseToCBOR script) C.SimpleScriptLanguage C.SimpleScriptV2 -> encodeWord 1 <> encode (C.serialiseToCBOR script) C.PlutusScriptLanguage C.PlutusScriptV1 -> encodeWord 2 <> encode (C.serialiseToCBOR script) C.PlutusScriptLanguage C.PlutusScriptV2 -> encodeWord 3 <> encode (C.serialiseToCBOR script) in encodeListLen 2 <> other decode = do len <- decodeListLen langWord <- decodeWord script <- decode case (len, langWord) of (2, 0) -> do let decoded = either (error "Failed to deserialise AsSimpleScriptV1 from CBOR ") id (C.deserialiseFromCBOR (C.AsScript C.AsSimpleScriptV1) script) pure $ C.ScriptInAnyLang (C.SimpleScriptLanguage C.SimpleScriptV1) decoded (2, 1) -> do let decoded = either (error "Failed to deserialise AsSimpleScriptV2 from CBOR ") id (C.deserialiseFromCBOR (C.AsScript C.AsSimpleScriptV2) script) pure $ C.ScriptInAnyLang (C.SimpleScriptLanguage C.SimpleScriptV2) decoded (2, 2) -> do let decoded = either (error "Failed to deserialise AsPlutusScriptV1 from CBOR ") id (C.deserialiseFromCBOR (C.AsScript C.AsPlutusScriptV1) script) pure $ C.ScriptInAnyLang (C.PlutusScriptLanguage C.PlutusScriptV1) decoded (2, 3) -> do let decoded = either (error "Failed to deserialise AsPlutusScriptV2 from CBOR ") id (C.deserialiseFromCBOR (C.AsScript C.AsPlutusScriptV2) script) pure $ C.ScriptInAnyLang (C.PlutusScriptLanguage C.PlutusScriptV2) decoded _ -> fail "Invalid ScriptInAnyLang encoding" instance OpenApi.ToSchema C.ScriptInAnyLang where declareNamedSchema _ = pure $ OpenApi.NamedSchema (Just "ScriptInAnyLang") mempty fromReferenceScript :: ReferenceScript -> Maybe (Versioned Script) fromReferenceScript ReferenceScriptNone = Nothing fromReferenceScript (ReferenceScriptInAnyLang sial) = fromCardanoScriptInAnyLang sial instance OpenApi.ToSchema (C.AddressInEra C.BabbageEra) where declareNamedSchema _ = pure $ OpenApi.NamedSchema (Just "AddressInBabbageEra") mempty instance OpenApi.ToSchema Data where declareNamedSchema _ = do integerSchema <- OpenApi.declareSchemaRef (Proxy :: Proxy Integer) constrArgsSchema <- OpenApi.declareSchemaRef (Proxy :: Proxy (Integer, [Data])) mapArgsSchema <- OpenApi.declareSchemaRef (Proxy :: Proxy [(Data, Data)]) listArgsSchema <- OpenApi.declareSchemaRef (Proxy :: Proxy [Data]) bytestringSchema <- OpenApi.declareSchemaRef (Proxy :: Proxy String) return $ OpenApi.NamedSchema (Just "Data") $ mempty & OpenApi.type_ ?~ OpenApi.OpenApiObject & OpenApi.properties .~ InsOrdMap.fromList [ ("Constr", constrArgsSchema) , ("Map", mapArgsSchema) , ("List", listArgsSchema) , ("I", integerSchema) , ("B", bytestringSchema) ] deriving instance OpenApi.ToSchema BuiltinData instance OpenApi.ToSchema PlutusTx.BuiltinByteString where declareNamedSchema _ = pure $ OpenApi.NamedSchema (Just "Bytes") mempty deriving newtype instance OpenApi.ToSchema TokenName deriving newtype instance OpenApi.ToSchema Value deriving instance OpenApi.ToSchema a => OpenApi.ToSchema (Extended a) deriving instance OpenApi.ToSchema a => OpenApi.ToSchema (Interval a) deriving instance OpenApi.ToSchema a => OpenApi.ToSchema (LowerBound a) deriving instance OpenApi.ToSchema a => OpenApi.ToSchema (UpperBound a) deriving instance OpenApi.ToSchema Language deriving instance OpenApi.ToSchema script => OpenApi.ToSchema (Versioned script) deriving anyclass instance OpenApi . C.TxId deriving newtype instance OpenApi.ToSchema TxId deriving instance OpenApi.ToSchema ScriptTag deriving newtype instance OpenApi.ToSchema Validator deriving instance OpenApi.ToSchema TxInType deriving instance OpenApi.ToSchema TxIn deriving newtype instance OpenApi.ToSchema Slot deriving anyclass instance (OpenApi.ToSchema k, OpenApi.ToSchema v) => OpenApi.ToSchema (AssocMap.Map k v) deriving anyclass instance OpenApi.ToSchema OutputDatum instance OpenApi.ToSchema C.Value where declareNamedSchema _ = pure $ OpenApi.NamedSchema (Just "Value") $ OpenApi.toSchema (Proxy @[(String, Integer)]) data ChainIndexTxOut = ChainIndexTxOut ^ We ca n't use AddressInAnyEra here because of missing FromJson instance for era , citoValue :: C.Value , citoDatum :: OutputDatum , citoRefScript :: ReferenceScript } deriving (Eq, Show, Generic, Serialise, OpenApi.ToSchema) instance ToJSON ChainIndexTxOut where toJSON ChainIndexTxOut{..} = object [ "address" .= toJSON citoAddress , "value" .= toJSON citoValue , "datum" .= toJSON citoDatum , "refScript" .= toJSON citoRefScript ] instance FromJSON ChainIndexTxOut where parseJSON = Aeson.withObject "ChainIndexTxOut" $ \obj -> ChainIndexTxOut <$> obj .: "address" <*> obj .: "value" <*> obj .: "datum" <*> obj .:? "refScript" .!= ReferenceScriptNone instance Pretty ChainIndexTxOut where pretty ChainIndexTxOut {citoAddress, citoValue} = hang 2 $ vsep ["-" <+> pretty citoValue <+> "addressed to", pretty (toPlutusAddress citoAddress)] data ChainIndexTxOutputs = | ValidTx [ChainIndexTxOut] deriving (Show, Eq, Generic, ToJSON, FromJSON, Serialise, OpenApi.ToSchema) makePrisms ''ChainIndexTxOutputs deriving instance OpenApi.ToSchema TxOutRef deriving instance OpenApi.ToSchema RedeemerPtr deriving newtype instance OpenApi.ToSchema Redeemer deriving newtype instance OpenApi.ToSchema ScriptHash instance OpenApi.ToSchema Script where declareNamedSchema _ = pure $ OpenApi.NamedSchema (Just "Script") (OpenApi.toSchema (Proxy :: Proxy String)) deriving newtype instance OpenApi.ToSchema CurrencySymbol deriving newtype instance OpenApi.ToSchema Datum deriving newtype instance OpenApi.ToSchema DatumHash instance (Typeable era, Typeable mode) => OpenApi.ToSchema (C.EraInMode era mode) where declareNamedSchema _ = do return $ NamedSchema (Just "EraInMode") $ sketchSchema C.BabbageEraInCardanoMode instance (Typeable era) => OpenApi.ToSchema (C.Tx era) where declareNamedSchema _ = do return $ NamedSchema (Just "Tx") byteSchema instance OpenApi.ToSchema CardanoTx where declareNamedSchema _ = do txSchema <- declareSchemaRef (Proxy :: Proxy (C.Tx C.BabbageEra)) eraInModeSchema <- declareSchemaRef (Proxy :: Proxy (C.EraInMode C.BabbageEra C.CardanoMode)) return $ NamedSchema (Just "CardanoTx") $ mempty & type_ ?~ OpenApiObject & properties .~ InsOrdMap.fromList [ ("tx", txSchema) , ("eraInMode", eraInModeSchema) ] & required .~ [ "tx", "eraInMode" ] data ChainIndexTx = ChainIndexTx { _citxTxId :: TxId, _citxInputs :: [TxIn], _citxOutputs :: ChainIndexTxOutputs, _citxValidRange :: !SlotRange, ^ The ' SlotRange ' during which this transaction may be validated . _citxData :: Map DatumHash Datum, ^ Datum objects recorded on this transaction . _citxRedeemers :: Redeemers, _citxScripts :: Map ScriptHash (Versioned Script), ^ The scripts ( validator , stake validator or minting ) part of . _citxCardanoTx :: Maybe CardanoTx ^ The full Cardano API tx which was used to populate the rest of the details of the tx , so we keep it as a safety net . Might be Nothing if we } deriving (Show, Eq, Generic, ToJSON, FromJSON, Serialise, OpenApi.ToSchema) makeLenses ''ChainIndexTx instance Pretty ChainIndexTx where pretty ChainIndexTx{_citxTxId, _citxInputs, _citxOutputs = ValidTx outputs, _citxValidRange, _citxData, _citxRedeemers, _citxScripts} = let lines' = [ hang 2 (vsep ("inputs:" : fmap pretty _citxInputs)) , hang 2 (vsep ("outputs:" : fmap pretty outputs)) , hang 2 (vsep ("scripts hashes:": fmap (pretty . fst) (Map.toList _citxScripts))) , "validity range:" <+> viaShow _citxValidRange , hang 2 (vsep ("data:": fmap (pretty . snd) (Map.toList _citxData) )) , hang 2 (vsep ("redeemers:": fmap (pretty . snd) (Map.toList _citxRedeemers) )) ] in nest 2 $ vsep ["Valid tx" <+> pretty _citxTxId <> colon, braces (vsep lines')] pretty ChainIndexTx{_citxTxId, _citxInputs, _citxOutputs = InvalidTx mOutput, _citxValidRange, _citxData, _citxRedeemers, _citxScripts} = let lines' = [ hang 2 (vsep ("inputs:" : fmap pretty _citxInputs)) , hang 2 (vsep ["collateral output:", maybe "-" pretty mOutput]) , hang 2 (vsep ("scripts hashes:": fmap (pretty . fst) (Map.toList _citxScripts))) , "validity range:" <+> viaShow _citxValidRange , hang 2 (vsep ("data:": fmap (pretty . snd) (Map.toList _citxData) )) , hang 2 (vsep ("redeemers:": fmap (pretty . snd) (Map.toList _citxRedeemers) )) ] in nest 2 $ vsep ["Invalid tx" <+> pretty _citxTxId <> colon, braces (vsep lines')] blockId :: Ledger.Block -> BlockId blockId = BlockId . BA.convert . hash @_ @SHA256 . BSL.toStrict . CBOR.serialise newtype BlockNumber = BlockNumber { unBlockNumber :: Word64 } deriving stock (Eq, Ord, Show, Generic) deriving newtype (Num, Real, Enum, Integral, ToJSON, FromJSON, OpenApi.ToSchema) instance Pretty BlockNumber where pretty (BlockNumber blockNumber) = "BlockNumber " <> pretty blockNumber instance OpenApi.ToSchema BlockId where declareNamedSchema _ = OpenApi.declareNamedSchema (Proxy @String) data Tip = TipAtGenesis | Tip } deriving stock (Eq, Show, Generic) deriving anyclass (ToJSON, FromJSON, OpenApi.ToSchema) makePrisms ''Tip data Point = PointAtGenesis | Point } deriving stock (Eq, Show, Generic) deriving anyclass (ToJSON, FromJSON) makePrisms ''Point instance Ord Point where PointAtGenesis <= _ = True _ <= PointAtGenesis = False (Point ls _) <= (Point rs _) = ls <= rs instance Pretty Point where pretty PointAtGenesis = "PointAtGenesis" pretty Point {pointSlot, pointBlockId} = "Point(" <> pretty pointSlot <> comma <+> pretty pointBlockId <> ")" tipAsPoint :: Tip -> Point tipAsPoint TipAtGenesis = PointAtGenesis tipAsPoint (Tip tSlot tBlockId _) = Point { pointSlot = tSlot , pointBlockId = tBlockId } pointsToTip :: Point -> Tip -> Bool pointsToTip PointAtGenesis TipAtGenesis = True pointsToTip (Point pSlot pBlockId) (Tip tSlot tBlockId _) | tSlot == pSlot && tBlockId == pBlockId = True pointsToTip _ _ = False instance Semigroup Tip where t <> TipAtGenesis = t _ <> t = t instance Semigroup Point where t <> PointAtGenesis = t _ <> t = t instance Monoid Tip where mempty = TipAtGenesis instance Monoid Point where mempty = PointAtGenesis instance Ord Tip where compare TipAtGenesis TipAtGenesis = EQ compare TipAtGenesis _ = LT compare _ TipAtGenesis = GT compare (Tip ls _ lb) (Tip rs _ rb) = compare ls rs <> compare lb rb instance Pretty Tip where pretty TipAtGenesis = "TipAtGenesis" pretty Tip {tipSlot, tipBlockId, tipBlockNo} = "Tip(" <> pretty tipSlot <> comma <+> pretty tipBlockId <> comma <+> pretty tipBlockNo <> ")" data TxValidity = TxValid | TxInvalid | UnknownValidity deriving stock (Eq, Ord, Show, Generic) deriving anyclass (ToJSON, FromJSON) deriving Pretty via (PrettyShow TxValidity) instance MeetSemiLattice TxValidity where TxValid /\ TxValid = TxValid TxInvalid /\ TxInvalid = TxInvalid _ /\ _ = UnknownValidity | How many blocks deep the tx is on the chain newtype Depth = Depth { unDepth :: Int } deriving stock (Eq, Ord, Show, Generic) deriving newtype (Num, Real, Enum, Integral, Pretty, ToJSON, FromJSON) instance MeetSemiLattice Depth where Depth a /\ Depth b = Depth (max a b) Note [ TxStatus state machine ] The status of a transaction is described by the following state machine . Current state | Next state(s ) Unknown | OnChain OnChain | OnChain , Unknown , Committed Committed | - The initial state after submitting the transaction is Unknown . The status of a transaction is described by the following state machine. Current state | Next state(s) Unknown | OnChain OnChain | OnChain, Unknown, Committed Committed | - The initial state after submitting the transaction is Unknown. -} type TxStatus = RollbackState () data RollbackState a = Unknown | TentativelyConfirmed Depth TxValidity a | Committed TxValidity a deriving stock (Eq, Ord, Show, Generic, Functor) deriving anyclass (ToJSON, FromJSON) deriving Pretty via (PrettyShow (RollbackState a)) instance MeetSemiLattice a => MeetSemiLattice (RollbackState a) where Unknown /\ a = a a /\ Unknown = a TentativelyConfirmed d1 v1 a1 /\ TentativelyConfirmed d2 v2 a2 = TentativelyConfirmed (d1 /\ d2) (v1 /\ v2) (a1 /\ a2) TentativelyConfirmed _ v1 a1 /\ Committed v2 a2 = Committed (v1 /\ v2) (a1 /\ a2) Committed v1 a1 /\ TentativelyConfirmed _ v2 a2 = Committed (v1 /\ v2) (a1 /\ a2) Committed v1 a1 /\ Committed v2 a2 = Committed (v1 /\ v2) (a1 /\ a2) Note [ TxOutStatus state machine ] The status of a transaction output is described by the following state machine . Current state | Next state(s ) TxOutUnknown | TxOutTentativelyUnspent TxOutTentativelyUnspent | TxOutUnknown , TxOutTentativelySpent , TxOutConfirmedUnspent TxOutTentativelySpent | TxOutUnknown , TxOutConfirmedSpent TxOutConfirmedUnspent | TxOutConfirmedSpent TxOutConfirmedSpent | - The initial state after submitting the transaction is ' TxOutUnknown ' . The status of a transaction output is described by the following state machine. Current state | Next state(s) TxOutUnknown | TxOutTentativelyUnspent TxOutTentativelyUnspent | TxOutUnknown, TxOutTentativelySpent, TxOutConfirmedUnspent TxOutTentativelySpent | TxOutUnknown, TxOutConfirmedSpent TxOutConfirmedUnspent | TxOutConfirmedSpent TxOutConfirmedSpent | - The initial state after submitting the transaction is 'TxOutUnknown'. -} type TxOutStatus = RollbackState TxOutState | Unspent deriving stock (Eq, Ord, Show, Generic) deriving anyclass (ToJSON, FromJSON) deriving Pretty via (PrettyShow TxOutState) | Maybe extract the ' TxOutState ' ( Spent or Unspent ) of a ' TxOutStatus ' . txOutStatusTxOutState :: TxOutStatus -> Maybe TxOutState txOutStatusTxOutState Unknown = Nothing txOutStatusTxOutState (TentativelyConfirmed _ _ s) = Just s txOutStatusTxOutState (Committed _ s) = Just s | Converts a ' TxOutStatus ' to a ' TxStatus ' . Possible since a transaction Note , however , that we ca n't convert a ' TxStatus ' to a ' TxOutStatus ' . liftTxOutStatus :: TxOutStatus -> TxStatus liftTxOutStatus = void data Diagnostics = Diagnostics { numTransactions :: Integer , numScripts :: Integer , numAddresses :: Integer , numAssetClasses :: Integer , numUnspentOutputs :: Int , numUnmatchedInputs :: Int , someTransactions :: [TxId] , unspentTxOuts :: [ChainIndexTxOut] } deriving stock (Eq, Show, Generic) deriving anyclass (ToJSON, FromJSON, OpenApi.ToSchema) | Datatype returned when we could n't get the state of a tx or a tx output . data TxStatusFailure | We could n't return the status because the ' TxIdState ' was in a ... ' . ChainIndex . TxIdState.transactionStatus ' . = TxIdStateInvalid BlockNumber TxId TxIdState | We could n't return the status because the ' ' does not contain the target tx output . | TxOutBalanceStateInvalid BlockNumber TxOutRef TxOutBalance | InvalidRollbackAttempt BlockNumber TxId TxIdState deriving (Show, Eq) data TxIdState = TxIdState { txnsConfirmed :: Map TxId TxConfirmedState , txnsDeleted :: Map TxId (Sum Int) } deriving stock (Eq, Generic, Show) A semigroup instance that merges the two maps , instead of taking the instance Semigroup TxIdState where TxIdState{txnsConfirmed=c, txnsDeleted=d} <> TxIdState{txnsConfirmed=c', txnsDeleted=d'} = TxIdState { txnsConfirmed = Map.unionWith (<>) c c' , txnsDeleted = Map.unionWith (<>) d d' } instance Monoid TxIdState where mappend = (<>) mempty = TxIdState { txnsConfirmed=mempty, txnsDeleted=mempty } data TxConfirmedState = TxConfirmedState { timesConfirmed :: Sum Int , blockAdded :: Last BlockNumber , validity :: Last TxValidity } deriving stock (Eq, Generic, Show) deriving (Monoid) via (GenericSemigroupMonoid TxConfirmedState) instance Semigroup TxConfirmedState where (TxConfirmedState tc ba v) <> (TxConfirmedState tc' ba' v') = TxConfirmedState (tc <> tc') (ba <> ba') (v <> v') | The effect of a transaction ( or a number of them ) on the tx output set . data TxOutBalance = TxOutBalance { _tobUnspentOutputs :: Set TxOutRef , _tobSpentOutputs :: Map TxOutRef TxId ^ Outputs spent by the transaction(s ) along with the tx i d that spent it } deriving stock (Eq, Show, Generic) deriving anyclass (FromJSON, ToJSON) instance Semigroup TxOutBalance where l <> r = TxOutBalance { _tobUnspentOutputs = _tobUnspentOutputs r <> (_tobUnspentOutputs l `Set.difference` Map.keysSet (_tobSpentOutputs r)) , _tobSpentOutputs = _tobSpentOutputs l <> _tobSpentOutputs r } instance Monoid TxOutBalance where mappend = (<>) mempty = TxOutBalance mempty mempty makeLenses ''TxOutBalance | The effect of a transaction ( or a number of them ) on the set . data TxUtxoBalance = TxUtxoBalance { _tubUnspentOutputs :: Set TxOutRef , _tubUnmatchedSpentInputs :: Set TxOutRef } deriving stock (Eq, Show, Generic) deriving anyclass (FromJSON, ToJSON, Serialise) makeLenses ''TxUtxoBalance instance Semigroup TxUtxoBalance where l <> r = TxUtxoBalance { _tubUnspentOutputs = _tubUnspentOutputs r <> (_tubUnspentOutputs l `Set.difference` _tubUnmatchedSpentInputs r) , _tubUnmatchedSpentInputs = (_tubUnmatchedSpentInputs r `Set.difference` _tubUnspentOutputs l) <> _tubUnmatchedSpentInputs l } instance Monoid TxUtxoBalance where mappend = (<>) mempty = TxUtxoBalance mempty mempty See # 73 for more motivations . newtype TxProcessOption = TxProcessOption { tpoStoreTx :: Bool } deriving (Show) instance Default TxProcessOption where def = TxProcessOption { tpoStoreTx = True } data ChainSyncBlock = Block { blockTip :: Tip , blockTxs :: [(ChainIndexTx, TxProcessOption)] } deriving (Show)
8f59f2cf228a2b7c3c981aff715571e53765687d476b4d1fc4b9d56f093b8b05
buildsome/buildsome
SyncMap.hs
# LANGUAGE TupleSections # module Lib.SyncMap ( SyncMap , Inserted(..) , Result , toMap , tryInsert , insert , new ) where import Prelude.Compat import Control.Concurrent.MVar import qualified Control.Exception as E import Control.Monad (join) import Data.IORef import qualified Data.Map as M import Data.Map (Map) type Result = Either E.SomeException newtype SyncMap k a = SyncMap (IORef (Map k (MVar (Result a)))) data Inserted = Inserted | Old toMap :: SyncMap k a -> IO (Map k (Result a)) toMap (SyncMap ioRefMap) = readIORef ioRefMap >>= traverse readMVar | Safely insert ( or update ) a value into a SyncMap . -- Uses masking internally to ensure one of two outcomes : -- 1 . The map is updated : if the key is missing from the map , the given action is run , and the resulting value is inserted 2 . The map is not updated : if the key exists , returns the old value . -- -- If an exception occurred during the synchronous update, it will be returned in the `Result`. -- -- If blocking operations are used in the action, it is the user's responsibility to use uninterruptibleMask or accept an async -- exception as a result! -- tryInsert :: Ord k => SyncMap k a -> k -> IO a -> IO (Inserted, Result a) tryInsert (SyncMap refMap) key action = do mvar <- newEmptyMVar let fillMVar x = do putMVar mvar x pure (Inserted, x) E.mask_ . join $ atomicModifyIORef refMap $ \oldMap -> case M.lookup key oldMap of Just oldMVar -> (oldMap, (Old,) <$> readMVar oldMVar) Nothing -> ( M.insert key mvar oldMap , E.try action >>= fillMVar ) | Version of that throws exceptions instead of returning them in a ` Result ` , and also discards the ` Inserted ` value insert :: Ord k => SyncMap k a -> k -> IO a -> IO a insert syncMap key action = do (_, res) <- tryInsert syncMap key action either E.throwIO pure res new :: IO (SyncMap k v) new = SyncMap <$> newIORef M.empty
null
https://raw.githubusercontent.com/buildsome/buildsome/479b92bb74a474a5f0c3292b79202cc850bd8653/src/Lib/SyncMap.hs
haskell
If an exception occurred during the synchronous update, it will be returned in the `Result`. If blocking operations are used in the action, it is the user's exception as a result!
# LANGUAGE TupleSections # module Lib.SyncMap ( SyncMap , Inserted(..) , Result , toMap , tryInsert , insert , new ) where import Prelude.Compat import Control.Concurrent.MVar import qualified Control.Exception as E import Control.Monad (join) import Data.IORef import qualified Data.Map as M import Data.Map (Map) type Result = Either E.SomeException newtype SyncMap k a = SyncMap (IORef (Map k (MVar (Result a)))) data Inserted = Inserted | Old toMap :: SyncMap k a -> IO (Map k (Result a)) toMap (SyncMap ioRefMap) = readIORef ioRefMap >>= traverse readMVar | Safely insert ( or update ) a value into a SyncMap . Uses masking internally to ensure one of two outcomes : 1 . The map is updated : if the key is missing from the map , the given action is run , and the resulting value is inserted 2 . The map is not updated : if the key exists , returns the old value . responsibility to use uninterruptibleMask or accept an async tryInsert :: Ord k => SyncMap k a -> k -> IO a -> IO (Inserted, Result a) tryInsert (SyncMap refMap) key action = do mvar <- newEmptyMVar let fillMVar x = do putMVar mvar x pure (Inserted, x) E.mask_ . join $ atomicModifyIORef refMap $ \oldMap -> case M.lookup key oldMap of Just oldMVar -> (oldMap, (Old,) <$> readMVar oldMVar) Nothing -> ( M.insert key mvar oldMap , E.try action >>= fillMVar ) | Version of that throws exceptions instead of returning them in a ` Result ` , and also discards the ` Inserted ` value insert :: Ord k => SyncMap k a -> k -> IO a -> IO a insert syncMap key action = do (_, res) <- tryInsert syncMap key action either E.throwIO pure res new :: IO (SyncMap k v) new = SyncMap <$> newIORef M.empty
6c2b577ea1277f4398d03a790c4aeba3ebe9404b066a6466fa602250d8545d5d
lfe/lfe
lfe_io_pretty.erl
Copyright ( c ) 2008 - 2021 %% 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. %% File : lfe_io_pretty.erl Author : Purpose : Pretty printer for Lisp Flavoured Erlang . -module(lfe_io_pretty). %% The basic API. -export([term/1,term/2,term/3,term/4]). %% These might be useful somewhere else. -export([newline/1,newline/2,last_length/1,last_length/2]). %% -compile(export_all). -import(lists, [reverse/1,reverse/2,flatlength/1]). -include("lfe.hrl"). -define(MAPVIND, 2). %Extra indentation of map value term(Sexpr [ , Depth [ , Indentation [ , ] ] ] ) - > [ char ( ) ] . %% A relatively simple pretty print function, but with some %% customisation. N.B. We know about the standard character macros %% and use them instead of their expanded forms. term(S) -> term(S, -1, 0, 80). term(S, D) -> term(S, D, 0, 80). term(S, D, I) -> term(S, D, I, 80). term(_, 0, _, _) -> "..."; term(Symb, _, _, _) when is_atom(Symb) -> lfe_io_write:symbol(Symb); term(Numb, _, _, _) when is_integer(Numb) -> integer_to_list(Numb); term(Numb, _, _, _) when is_float(Numb) -> io_lib_format:fwrite_g(Numb); %% Handle some default special cases, standard character macros. These %% don't increase depth as they really should. term([quote,E], D, I, L) -> ["'",term(E, D, I+1, L)]; term([backquote,E], D, I, L) -> ["`",term(E, D, I+1, L)]; term([comma,E], D, I, L) -> [",",term(E, D, I+1, L)]; term(['comma-at',E], D, I, L) -> [",@",term(E, D, I+2, L)]; term([Car|_]=List, D, I, L) -> %% Handle printable lists specially. case io_lib:printable_unicode_list(List) of true -> lfe_io_write:string(List, $"); %" false -> case list_max(List, D-1, I+1, L-1) of {yes,Print} -> ["(",Print,")"]; no -> %% Customise printing of lists. case indent_type(Car) of none -> %Normal lists. ["(",list(List, D-1, I+1, L-1),")"]; defun -> %Special case for defuns defun(List, D, I, L); Special N first elements type(List, D, I, L, N) end end end; term([], _, _, _) -> "()"; term({}, _, _, _) -> "#()"; term(Tup, D, I, L) when is_tuple(Tup) -> Es = tuple_to_list(Tup), case list_max(Es, D-1, I+2, L-1) of {yes,Print} -> ["#(",Print,")"]; no -> ["#(",list(Es, D-1, I+2, L),")"] end; term(Bit, D, _, _) when is_bitstring(Bit) -> First D bytes term(Map, D, I, L) when ?IS_MAP(Map) -> %% Preserve kv pair ordering, the extra copying is trivial here. map(Map, D, I, L); term(Other, _, _, _) -> lfe_io_write:term(Other). %Use standard LFE for rest map(Map , Depth , Indentation , ) - > string ( ) . %% Print a map but specially detect structs. map(Map, D, I, L) -> case maps:is_key('__struct__', Map) of true -> struct(Map, D, I, L); false -> %% Preserve kv pair ordering, the extra copying is trivial here. Mkvs = maps:to_list(Map), Mcs = map_body(Mkvs, D, I+3, L), ["#M(",Mcs,$)] end. struct(Map , Depth , Indentation , ) - > string ( ) %% Print a struct from the map. struct(Map, D, I, L) -> {StructName,Struct} = maps:take('__struct__', Map), The struct kvs NameCs = lfe_io_write:symbol(StructName), NameLen = length(NameCs), Struct name is first " KV " so now we want the rest of them . Scs = map_rest(Skvs, I+3+NameLen, D-1, I+3, L), ["#S(",NameCs,Scs,$)]. %% bitstring(Bitstring, Depth) -> [char()] %% Print the bytes in a bitstring. Print bytes except for last which we add size field if not 8 bits big . bitstring(Bit, D) -> try Chars = unicode:characters_to_list(Bit, utf8), true = io_lib:printable_unicode_list(Chars), [$#|lfe_io_write:string(Chars, $")] catch _:_ -> lfe_io_write:bitstring(Bit, D) end. defun(List , Depth , Indentation , ) - > [ char ( ) ] . %% Print a defun depending on whether it is traditional or matching. defun([Def,Name,Args|Rest], D, I, L) when is_atom(Name), (D > 3) or (D < 0) -> Dcs = atom_to_list(Def), %Might not actually be defun Ncs = atom_to_list(Name), case lfe_lib:is_symb_list(Args) of true -> %Traditional Acs = term(Args, D-2, I + length(Dcs) + length(Ncs) + 3, L), Tcs = list_tail(Rest, D-3, I+2, L), ["(",Dcs," ",Ncs," ",Acs,Tcs,")"]; false -> %Matching Tcs = list_tail([Args|Rest], D-2, I+2, L), ["(",Dcs," ",Ncs,Tcs,")"] end; defun(List, D, I, L) -> %% Too short to get worked up about, or not a "proper" defun or %% not enough depth. ["(",list(List, D-1, I+1, L),")"]. type(List , Depth , Indentation , , TypeCount ) - > [ char ( ) ] . Print a special type form indenting first TypeCount elements afer type and rest indented 2 steps . type([Car|Cdr], D, I, L, N) when (D > 2) or (D < 0) -> %% Handle special lists, we KNOW Car is an atom. Cs = atom_to_list(Car), NewI = I + length(Cs) + 2, {Spec,Rest} = split(N, Cdr), Tcs = [list(Spec, D-1, NewI, L), list_tail(Rest, D-2, I+2, L)], ["(" ++ Cs," ",Tcs,")"]; type(List, D, I, L, _) -> %% Too short to get worked up about or not enough depth. [$(,list(List, D-1, I+1, L),$)]. %% split(N, List) -> {List1,List2}. Split a list into two lists , the first containing the first N elements and the second the rest . Be tolerant of too few elements . split(0, L) -> {[],L}; split(_, []) -> {[],[]}; split(N, [H|T]) -> {H1,T1} = split(N-1, T), {[H|H1],T1}. list_max(List , Depth , Indentation , ) - > { yes , } | no . Maybe print a list on one line , but abort if it goes past . list_max([], _, _, _) -> {yes,[]}; list_max(_, 0, _, _) -> {yes,"..."}; list_max([Car|Cdr], D, I, L) -> Cs = term(Car, D, 0, 99999), %Never break the line tail_max(Cdr, D-1, I + flatlength(Cs), L, [Cs]). tail_max(Tail , Depth , Indentation , ) - > { yes , } | no . Maybe print the tail of a list on one line , but abort if it goes past . We know about dotted pairs . When we reach depth 0 %% we just quit as we know necessary "..." will have come from an %% earlier print1 at same depth. tail_max(_, _, I, L, _) when I >= L -> no; %No more room tail_max([], _, _, _, Acc) -> {yes,reverse(Acc)}; tail_max(_, 0, _, _, Acc) -> {yes,reverse(Acc, [" ..."])}; tail_max([Car|Cdr], D, I, L, Acc) -> Cs = term(Car, D, 0, 99999), %Never break the line tail_max(Cdr, D-1, I + flatlength(Cs) + 1, L, [Cs," "|Acc]); tail_max(S, D, I, L, Acc) -> Cs = term(S, D, 0, 99999), %Never break the line tail_max([], D-1, I + flatlength(Cs) + 3, L, [Cs," . "|Acc]). list(List , Depth , Indentation , ) Print a list , one element per line but print multiple atomic elements on one line . No leading / trailing ( ) . list([], _, _, _) -> []; list(_, 0, _, _) -> "..."; list([Car|Cdr], D, I, L) -> case list_element(Car, I, D, I, L) of {join,Ccs,Cl} -> %Atomic that fits [Ccs|list_tail(Cdr, I+Cl, D, I, L)]; {break,Ccs,_} -> %Atomic that does not fit [Ccs|list_tail(Cdr, L, D, I, L)]; {break,Ccs} -> %Non-atomic %% Force a break after not an atomic. [Ccs|list_tail(Cdr, L, D, I, L)] end. list_tail(Tail , Depth , Indentation , ) list_tail(Tail , CurrentLength , Depth , Indentation , ) %% Print the tail of a list decreasing the depth for each element. We print multiple atomic elements on one line and we know about %% dotted pairs. list_tail(Tail, D, I, L) -> list_tail(Tail, L, D, I, L). %Force a break list_tail([], _, _, _, _) -> ""; list_tail(_, _, 0, _, _) -> " ..."; list_tail([Car|Cdr], CurL, D, I, L) -> case list_element(Car, CurL+1, D, I, L) of {join,Ccs,Cl} -> %Atomic that fits [$\s,Ccs,list_tail(Cdr, CurL+1+Cl, D-1, I, L)]; {break,Ccs,Cl} -> %Atomic that does not fit [newline(I, Ccs),list_tail(Cdr, I+Cl, D-1, I, L)]; {break,Ccs} -> %Non-atomic %% Force a break after not an atomic. [newline(I, Ccs),list_tail(Cdr, L, D-1, I, L)] end; list_tail(Cdr, CurL, D, I, L) -> case list_element(Cdr, CurL+3, D, I, L) of {join,Ccs,_} -> [" . "|Ccs]; %Atomic that fits {break,Ccs,_} -> %Atomic that does not fit [" .\n",blanks(I, Ccs)]; {break,Ccs} -> %Non-atomic [" .\n",blanks(I, Ccs)] end. list_element(E, CurL, D, _, L) when is_number(E); is_atom(E); is_pid(E); is_reference(E); is_port(E); is_function(E); E =:= [] -> Ecs = lfe_io_write:term(E, D), El = flatlength(Ecs), if CurL+El =< L - 10 -> {join,Ecs,El}; %Don't make the line too wide true -> {break,Ecs,El} end; list_element(E, _, D, I, L) -> {break,term(E, D, I, L)}. blanks(N, Tail) -> string:chars($\s, N, Tail). newline(N) -> newline(N, []). newline(N, Tail) -> [$\n|blanks(N, Tail)]. %% indent_type(Form) -> N | none. Defines special indentation . None means default , N is number of %% sexprs in list which are indented *after* Form while all following %% that end up at indent+2. %% Old style forms. indent_type('define') -> 1; indent_type('define-syntax') -> 1; indent_type('define-record') -> 1; indent_type('begin') -> 0; indent_type('let-syntax') -> 1; indent_type('syntax-rules') -> 0; indent_type('macro') -> 0; %% New style forms. indent_type('defmodule') -> 1; indent_type('defun') -> defun; indent_type('defmacro') -> defun; indent_type('defsyntax') -> 1; indent_type('defrecord') -> 1; indent_type('deftest') -> 1; Core forms . indent_type('progn') -> 0; indent_type('lambda') -> 1; indent_type('match-lambda') -> 0; indent_type('let') -> 1; indent_type('let-function') -> 1; indent_type('letrec-function') -> 1; indent_type('let-macro') -> 1; indent_type('if') -> 1; indent_type('case') -> 1; indent_type('receive') -> 0; indent_type('catch') -> 0; indent_type('try') -> 1; indent_type('funcall') -> 1; indent_type('call') -> 2; indent_type('eval-when-compile') -> 0; indent_type('define-function') -> 1; indent_type('define-macro') -> 1; indent_type('define-module') -> 1; indent_type('extend-module') -> 0; indent_type('define-type') -> 1; indent_type('define-opaque-type') -> 1; indent_type('define-function-spec') -> 1; Core macros . indent_type(':') -> 2; indent_type('cond') -> 999; %All following forms indent_type('let*') -> 1; indent_type('flet') -> 1; indent_type('flet*') -> 1; indent_type('fletrec') -> 1; indent_type(macrolet) -> 1; indent_type(syntaxlet) -> 1; indent_type('do') -> 2; indent_type('lc') -> 1; %List comprehensions indent_type('list-comp') -> 1; indent_type('bc') -> 1; %Binary comprehensions indent_type('binary-comp') -> 1; indent_type('match-spec') -> 0; indent_type(_) -> none. map_body(KVs , Depth , Indentation , ) . map_body(KVs , CurrentLineIndent , Depth , Indentation , ) %% Don't include the start and end of the map as this is called from %% differenct functions. map_body(KVs, D, I, L) -> map_body(KVs, I, D, I, L-1). map_body([KV|KVs], CurL, D, I, L) -> case map_assoc(KV, CurL, D, I, L) of {curr_line,KVcs,KVl} -> %Both fit on current line [KVcs,map_rest(KVs, CurL+KVl, D-1, I, L)]; Both fit on one line [KVcs,map_rest(KVs, I+KVl, D-1, I, L)]; {sep_lines,Kcs,Vcs} -> %On separate lines %% Force a break after K/V split. [Kcs,newline(I+?MAPVIND, Vcs),map_rest(KVs, L, D-1, I, L)] end; map_body([], _CurL, _D, _I, _L) -> []. map_rest(KVs , CurrentLineIndent , Depth , Indentation , ) map_rest(_, _, 0, _, _) -> " ..."; %Reached our depth map_rest([KV|KVs], CurL, D, I, L) -> case map_assoc(KV, CurL+1, D, I, L) of {curr_line,KVcs,KVl} -> %Both fit on current line [$\s,KVcs,map_rest(KVs, CurL+KVl+1, D-1, I, L)]; Both fit on one line [newline(I, KVcs),map_rest(KVs, I+KVl, D-1, I, L)]; {sep_lines,Kcs,Vcs} -> %On separate lines %% Force a break after K/V split. [newline(I, Kcs),newline(I+?MAPVIND, Vcs), map_rest(KVs, L, D-1, I, L)] end; map_rest([], _CurL, _D, _I, _L) -> []. map_assoc({K,V}, CurL, D, I, L) -> Kcs = term(K, D, 0, 99999), %Never break the line Kl = flatlength(Kcs), Vcs = term(V, D, 0, 99999), %Never break the line Vl = flatlength(Vcs), if CurL+Kl+Vl < L-10 -> %Both fit on current line {curr_line,[Kcs,$\s,Vcs],Kl+1+Vl}; Both fit on one line {one_line,[Kcs,$\s,Vcs],Kl+1+Vl}; true -> %On separate lines Try to reuse flat prints if they fit on one line . Ks = if I+Kl < L-10 -> Kcs; true -> term(K, D, I, L) end, Vs = if I+Vl < L-10 -> Vcs; true -> term(V, D, I+?MAPVIND, L) end, {sep_lines,Ks,Vs} end. %% last_length(Chars) -> Length. last_length(Chars , CurrentLine ) - > Length . %% Return the length of the last line in the text. last_length(S) -> last_length(S, 0). last_length([H|T], L0) when is_list(H) -> L1 = last_length(H, L0), %Must go left-to-right last_length(T, L1); last_length([$\n|T], _) -> last_length(T, 0); last_length([_|T], L) -> last_length(T, L+1); last_length([], L) -> L.
null
https://raw.githubusercontent.com/lfe/lfe/c1c0364bbf4f69df56c961561835e08b53439c67/src/lfe_io_pretty.erl
erlang
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. File : lfe_io_pretty.erl The basic API. These might be useful somewhere else. -compile(export_all). Extra indentation of map value A relatively simple pretty print function, but with some customisation. N.B. We know about the standard character macros and use them instead of their expanded forms. Handle some default special cases, standard character macros. These don't increase depth as they really should. Handle printable lists specially. Customise printing of lists. Normal lists. Special case for defuns Preserve kv pair ordering, the extra copying is trivial here. Use standard LFE for rest Print a map but specially detect structs. Preserve kv pair ordering, the extra copying is trivial here. Print a struct from the map. bitstring(Bitstring, Depth) -> [char()] Print the bytes in a bitstring. Print bytes except for last which Print a defun depending on whether it is traditional or matching. Might not actually be defun Traditional Matching Too short to get worked up about, or not a "proper" defun or not enough depth. Handle special lists, we KNOW Car is an atom. Too short to get worked up about or not enough depth. split(N, List) -> {List1,List2}. Never break the line we just quit as we know necessary "..." will have come from an earlier print1 at same depth. No more room Never break the line Never break the line Atomic that fits Atomic that does not fit Non-atomic Force a break after not an atomic. Print the tail of a list decreasing the depth for each element. We dotted pairs. Force a break Atomic that fits Atomic that does not fit Non-atomic Force a break after not an atomic. Atomic that fits Atomic that does not fit Non-atomic Don't make the line too wide indent_type(Form) -> N | none. sexprs in list which are indented *after* Form while all following that end up at indent+2. Old style forms. New style forms. All following forms List comprehensions Binary comprehensions Don't include the start and end of the map as this is called from differenct functions. Both fit on current line On separate lines Force a break after K/V split. Reached our depth Both fit on current line On separate lines Force a break after K/V split. Never break the line Never break the line Both fit on current line On separate lines last_length(Chars) -> Length. Return the length of the last line in the text. Must go left-to-right
Copyright ( c ) 2008 - 2021 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , Author : Purpose : Pretty printer for Lisp Flavoured Erlang . -module(lfe_io_pretty). -export([term/1,term/2,term/3,term/4]). -export([newline/1,newline/2,last_length/1,last_length/2]). -import(lists, [reverse/1,reverse/2,flatlength/1]). -include("lfe.hrl"). term(Sexpr [ , Depth [ , Indentation [ , ] ] ] ) - > [ char ( ) ] . term(S) -> term(S, -1, 0, 80). term(S, D) -> term(S, D, 0, 80). term(S, D, I) -> term(S, D, I, 80). term(_, 0, _, _) -> "..."; term(Symb, _, _, _) when is_atom(Symb) -> lfe_io_write:symbol(Symb); term(Numb, _, _, _) when is_integer(Numb) -> integer_to_list(Numb); term(Numb, _, _, _) when is_float(Numb) -> io_lib_format:fwrite_g(Numb); term([quote,E], D, I, L) -> ["'",term(E, D, I+1, L)]; term([backquote,E], D, I, L) -> ["`",term(E, D, I+1, L)]; term([comma,E], D, I, L) -> [",",term(E, D, I+1, L)]; term(['comma-at',E], D, I, L) -> [",@",term(E, D, I+2, L)]; term([Car|_]=List, D, I, L) -> case io_lib:printable_unicode_list(List) of true -> lfe_io_write:string(List, $"); %" false -> case list_max(List, D-1, I+1, L-1) of {yes,Print} -> ["(",Print,")"]; no -> case indent_type(Car) of ["(",list(List, D-1, I+1, L-1),")"]; defun(List, D, I, L); Special N first elements type(List, D, I, L, N) end end end; term([], _, _, _) -> "()"; term({}, _, _, _) -> "#()"; term(Tup, D, I, L) when is_tuple(Tup) -> Es = tuple_to_list(Tup), case list_max(Es, D-1, I+2, L-1) of {yes,Print} -> ["#(",Print,")"]; no -> ["#(",list(Es, D-1, I+2, L),")"] end; term(Bit, D, _, _) when is_bitstring(Bit) -> First D bytes term(Map, D, I, L) when ?IS_MAP(Map) -> map(Map, D, I, L); term(Other, _, _, _) -> map(Map , Depth , Indentation , ) - > string ( ) . map(Map, D, I, L) -> case maps:is_key('__struct__', Map) of true -> struct(Map, D, I, L); false -> Mkvs = maps:to_list(Map), Mcs = map_body(Mkvs, D, I+3, L), ["#M(",Mcs,$)] end. struct(Map , Depth , Indentation , ) - > string ( ) struct(Map, D, I, L) -> {StructName,Struct} = maps:take('__struct__', Map), The struct kvs NameCs = lfe_io_write:symbol(StructName), NameLen = length(NameCs), Struct name is first " KV " so now we want the rest of them . Scs = map_rest(Skvs, I+3+NameLen, D-1, I+3, L), ["#S(",NameCs,Scs,$)]. we add size field if not 8 bits big . bitstring(Bit, D) -> try Chars = unicode:characters_to_list(Bit, utf8), true = io_lib:printable_unicode_list(Chars), [$#|lfe_io_write:string(Chars, $")] catch _:_ -> lfe_io_write:bitstring(Bit, D) end. defun(List , Depth , Indentation , ) - > [ char ( ) ] . defun([Def,Name,Args|Rest], D, I, L) when is_atom(Name), (D > 3) or (D < 0) -> Ncs = atom_to_list(Name), case lfe_lib:is_symb_list(Args) of Acs = term(Args, D-2, I + length(Dcs) + length(Ncs) + 3, L), Tcs = list_tail(Rest, D-3, I+2, L), ["(",Dcs," ",Ncs," ",Acs,Tcs,")"]; Tcs = list_tail([Args|Rest], D-2, I+2, L), ["(",Dcs," ",Ncs,Tcs,")"] end; defun(List, D, I, L) -> ["(",list(List, D-1, I+1, L),")"]. type(List , Depth , Indentation , , TypeCount ) - > [ char ( ) ] . Print a special type form indenting first TypeCount elements afer type and rest indented 2 steps . type([Car|Cdr], D, I, L, N) when (D > 2) or (D < 0) -> Cs = atom_to_list(Car), NewI = I + length(Cs) + 2, {Spec,Rest} = split(N, Cdr), Tcs = [list(Spec, D-1, NewI, L), list_tail(Rest, D-2, I+2, L)], ["(" ++ Cs," ",Tcs,")"]; type(List, D, I, L, _) -> [$(,list(List, D-1, I+1, L),$)]. Split a list into two lists , the first containing the first N elements and the second the rest . Be tolerant of too few elements . split(0, L) -> {[],L}; split(_, []) -> {[],[]}; split(N, [H|T]) -> {H1,T1} = split(N-1, T), {[H|H1],T1}. list_max(List , Depth , Indentation , ) - > { yes , } | no . Maybe print a list on one line , but abort if it goes past . list_max([], _, _, _) -> {yes,[]}; list_max(_, 0, _, _) -> {yes,"..."}; list_max([Car|Cdr], D, I, L) -> tail_max(Cdr, D-1, I + flatlength(Cs), L, [Cs]). tail_max(Tail , Depth , Indentation , ) - > { yes , } | no . Maybe print the tail of a list on one line , but abort if it goes past . We know about dotted pairs . When we reach depth 0 tail_max([], _, _, _, Acc) -> {yes,reverse(Acc)}; tail_max(_, 0, _, _, Acc) -> {yes,reverse(Acc, [" ..."])}; tail_max([Car|Cdr], D, I, L, Acc) -> tail_max(Cdr, D-1, I + flatlength(Cs) + 1, L, [Cs," "|Acc]); tail_max(S, D, I, L, Acc) -> tail_max([], D-1, I + flatlength(Cs) + 3, L, [Cs," . "|Acc]). list(List , Depth , Indentation , ) Print a list , one element per line but print multiple atomic elements on one line . No leading / trailing ( ) . list([], _, _, _) -> []; list(_, 0, _, _) -> "..."; list([Car|Cdr], D, I, L) -> case list_element(Car, I, D, I, L) of [Ccs|list_tail(Cdr, I+Cl, D, I, L)]; [Ccs|list_tail(Cdr, L, D, I, L)]; [Ccs|list_tail(Cdr, L, D, I, L)] end. list_tail(Tail , Depth , Indentation , ) list_tail(Tail , CurrentLength , Depth , Indentation , ) print multiple atomic elements on one line and we know about list_tail(Tail, D, I, L) -> list_tail([], _, _, _, _) -> ""; list_tail(_, _, 0, _, _) -> " ..."; list_tail([Car|Cdr], CurL, D, I, L) -> case list_element(Car, CurL+1, D, I, L) of [$\s,Ccs,list_tail(Cdr, CurL+1+Cl, D-1, I, L)]; [newline(I, Ccs),list_tail(Cdr, I+Cl, D-1, I, L)]; [newline(I, Ccs),list_tail(Cdr, L, D-1, I, L)] end; list_tail(Cdr, CurL, D, I, L) -> case list_element(Cdr, CurL+3, D, I, L) of [" .\n",blanks(I, Ccs)]; [" .\n",blanks(I, Ccs)] end. list_element(E, CurL, D, _, L) when is_number(E); is_atom(E); is_pid(E); is_reference(E); is_port(E); is_function(E); E =:= [] -> Ecs = lfe_io_write:term(E, D), El = flatlength(Ecs), true -> {break,Ecs,El} end; list_element(E, _, D, I, L) -> {break,term(E, D, I, L)}. blanks(N, Tail) -> string:chars($\s, N, Tail). newline(N) -> newline(N, []). newline(N, Tail) -> [$\n|blanks(N, Tail)]. Defines special indentation . None means default , N is number of indent_type('define') -> 1; indent_type('define-syntax') -> 1; indent_type('define-record') -> 1; indent_type('begin') -> 0; indent_type('let-syntax') -> 1; indent_type('syntax-rules') -> 0; indent_type('macro') -> 0; indent_type('defmodule') -> 1; indent_type('defun') -> defun; indent_type('defmacro') -> defun; indent_type('defsyntax') -> 1; indent_type('defrecord') -> 1; indent_type('deftest') -> 1; Core forms . indent_type('progn') -> 0; indent_type('lambda') -> 1; indent_type('match-lambda') -> 0; indent_type('let') -> 1; indent_type('let-function') -> 1; indent_type('letrec-function') -> 1; indent_type('let-macro') -> 1; indent_type('if') -> 1; indent_type('case') -> 1; indent_type('receive') -> 0; indent_type('catch') -> 0; indent_type('try') -> 1; indent_type('funcall') -> 1; indent_type('call') -> 2; indent_type('eval-when-compile') -> 0; indent_type('define-function') -> 1; indent_type('define-macro') -> 1; indent_type('define-module') -> 1; indent_type('extend-module') -> 0; indent_type('define-type') -> 1; indent_type('define-opaque-type') -> 1; indent_type('define-function-spec') -> 1; Core macros . indent_type(':') -> 2; indent_type('let*') -> 1; indent_type('flet') -> 1; indent_type('flet*') -> 1; indent_type('fletrec') -> 1; indent_type(macrolet) -> 1; indent_type(syntaxlet) -> 1; indent_type('do') -> 2; indent_type('list-comp') -> 1; indent_type('binary-comp') -> 1; indent_type('match-spec') -> 0; indent_type(_) -> none. map_body(KVs , Depth , Indentation , ) . map_body(KVs , CurrentLineIndent , Depth , Indentation , ) map_body(KVs, D, I, L) -> map_body(KVs, I, D, I, L-1). map_body([KV|KVs], CurL, D, I, L) -> case map_assoc(KV, CurL, D, I, L) of [KVcs,map_rest(KVs, CurL+KVl, D-1, I, L)]; Both fit on one line [KVcs,map_rest(KVs, I+KVl, D-1, I, L)]; [Kcs,newline(I+?MAPVIND, Vcs),map_rest(KVs, L, D-1, I, L)] end; map_body([], _CurL, _D, _I, _L) -> []. map_rest(KVs , CurrentLineIndent , Depth , Indentation , ) map_rest([KV|KVs], CurL, D, I, L) -> case map_assoc(KV, CurL+1, D, I, L) of [$\s,KVcs,map_rest(KVs, CurL+KVl+1, D-1, I, L)]; Both fit on one line [newline(I, KVcs),map_rest(KVs, I+KVl, D-1, I, L)]; [newline(I, Kcs),newline(I+?MAPVIND, Vcs), map_rest(KVs, L, D-1, I, L)] end; map_rest([], _CurL, _D, _I, _L) -> []. map_assoc({K,V}, CurL, D, I, L) -> Kl = flatlength(Kcs), Vl = flatlength(Vcs), {curr_line,[Kcs,$\s,Vcs],Kl+1+Vl}; Both fit on one line {one_line,[Kcs,$\s,Vcs],Kl+1+Vl}; Try to reuse flat prints if they fit on one line . Ks = if I+Kl < L-10 -> Kcs; true -> term(K, D, I, L) end, Vs = if I+Vl < L-10 -> Vcs; true -> term(V, D, I+?MAPVIND, L) end, {sep_lines,Ks,Vs} end. last_length(Chars , CurrentLine ) - > Length . last_length(S) -> last_length(S, 0). last_length([H|T], L0) when is_list(H) -> last_length(T, L1); last_length([$\n|T], _) -> last_length(T, 0); last_length([_|T], L) -> last_length(T, L+1); last_length([], L) -> L.
260bd1863921b0858bb3717585cae178cf511f06f7aa55f5232422a235708544
lispnik/cl-http
pre-cl-http.lisp
-*- Mode : LISP ; Syntax : Ansi - common - lisp ; Package : CL - USER ; Base : 10 -*- (in-package "CL-USER") (defparameter *private-patches-directory* (or #+LispWorks3.2 "~/LispWorks/private-patches/" #+(and LispWorks4.0 Harlequin-PC-Lisp) "z:/pcl-release/pcl/local/images/uninstalled-patches/" (pathname-location (current-pathname)) ; last chance guess )) (pushnew :CLIM-SYS *features*) MJS 27Oct99 : ca n't push : multi - threaded until load - time bugs fixed in logging and client ( : multi - threaded * features * ) #+unix (pushnew :lispworks-unix *features*) #-unix (pushnew :lispworks-pc *features*) (when (member :ccl *features*) (warn "************>>>>>>>>> removing CCL from features!") (setq *features* (remove :ccl *features*))) (load-all-patches) #+LispWorks3.2 (do-demand-pre-loads :comms) #+LispWorks4 (require "comm") #+(and compile-reverse LispWorks3.2) (defadvice (comm::create-socket-for-service-connection htons-the-port :around) (service port) (call-next-advice service (if (zerop port) port (+ (ash (logand port 255) 8) (logand (ash port -8) 255))))) #+LispWorks3.2 (let ((symbol (intern "IGNORABLE" "CL"))) (proclaim `(declaration ,symbol))) #+LispWorks3.2 (defun quit () (bye)) ( lw : ( ) ) (defmacro sct-defsystem (name options &rest module-list) (translate-to-lw-defsystem name options module-list)) (defun translate-to-lw-defsystem (name options module-list) (let ((new-options '()) (required-systems '())) (loop while options do (let ((option (pop options)) (value (pop options))) (ecase option (:pretty-name) (:journal-directory) (:initial-status) (:patchable) (:source-category) (:default-pathname (let ((pathname (pathname value))) (push option new-options) (push (if (typep pathname 'logical-pathname) (translate-logical-pathname pathname) (string-downcase (namestring pathname))) new-options))) (:required-systems (setq required-systems (append required-systems (loop for system in (if (listp value) value (list value)) collect `(,system :type :system)))))))) (let ((expanded-module-list '()) (submodules '())) (flet ((translate-module (module-spec) (let ((result '())) (loop (when (null module-spec) (return)) (let ((item (pop module-spec))) (cond ((symbolp item) (let ((submodule (assoc item submodules))) (if submodule (if (eq :system (second (assoc :type (cddr submodule)))) (progn (push `(,(car (second submodule)) :type :system) result) (setq submodules (delete item submodules :key 'car))) (error "~S does not name a system module.") #+comment (setq module-spec (append (second submodule) module-spec))) (error "Unknown submodule ~S" item)))) ((or (typep item 'logical-pathname) (and (stringp item) (typep (parse-namestring item) 'logical-pathname))) (push (namestring (translate-logical-pathname item)) result)) (t (push (string-downcase item) result))))) result))) (dolist (module-desc module-list) (cond ((eq (car module-desc) :serial) (setq expanded-module-list (append (translate-module (cdr module-desc)) expanded-module-list))) ((eq (car module-desc) :module) (let ((type (second (assoc :type (cdddr module-desc))))) (unless (eq type :lisp-example) (push (cdr module-desc) submodules) (unless (member type '(nil :system)) (warn "Unknown module type ~S" module-desc))) (push module-desc expanded-module-list))) (t (error "funny module-desc ~S" module-desc)))) (let ((new-module-list '())) (dolist (item expanded-module-list) (if (and (consp item) (eq (car item) :module)) (when-let (submodule (assoc (second item) submodules)) (setq new-module-list (nconc (reverse (translate-module (third item))) new-module-list)) (setq submodules (delete submodule submodules))) (push item new-module-list))) (when submodules (error "Unprocecessed submodules ~S" submodules)) `(lw:defsystem ,name ,(nreverse new-options) :members (,@required-systems ,@new-module-list) :rules ((:in-order-to :compile :all (:requires (:load :serial)))))))))) (sys::without-warning-on-redefinition (let ((dir (pathname-location (translate-logical-pathname (pathname *private-patches-directory*))))) #+LispWorks3.2 (loop for (name seqname minor) in '(("symbol-macrolet-nil" sys::compiler 37) ("unspecific-pathname-device" sys::system 86) ("select-output" sys::system 87) ("select-output-extra" sys::system 173) ("listen-buffered-pipe" sys::system 175) ("lw-external-lambda-lists" sys::system 89) ("buffered-tcp-output-streams" :comms 9) ("signal-continue-search-in-same-cluster" :conditions 2)) for seq = (and seqname (scm::find-patch-sequence seqname)) unless (and seq minor (>= (scm::ps-minor seq) minor)) do (load (merge-pathnames name dir))) #+LispWorks4 (loop for (file id) in #+(and LispWorks4.0 Harlequin-PC-Lisp) '(("defpackage-disjoint-allow-duplicates" :system-defpackage-disjoint-allow-duplicates) ("result-type-values" :compiler-result-type-values) ("setf-name-uninterned" :system-setf-name-uninterned) ("dynamic-extent-multiple-value-list" :compiler-dynamic-extent-multiple-value-list) ("with-stream-buffers" :buffered-stream-with-stream-buffers) ("special-operator-p" :system-special-operator-p) ("socket-check-bytes-before-eof" :comm-socket-check-bytes-before-eof) ("host-forces-unc-pathname" :system-host-forces-unc-pathname)) #-(and LispWorks4.0 Harlequin-PC-Lisp) '() unless (scm::patch-id-loaded-p id) do (load (merge-pathnames file dir)))))
null
https://raw.githubusercontent.com/lispnik/cl-http/84391892d88c505aed705762a153eb65befb6409/lw/pre-cl-http.lisp
lisp
Syntax : Ansi - common - lisp ; Package : CL - USER ; Base : 10 -*- last chance guess
(in-package "CL-USER") (defparameter *private-patches-directory* (or #+LispWorks3.2 "~/LispWorks/private-patches/" #+(and LispWorks4.0 Harlequin-PC-Lisp) "z:/pcl-release/pcl/local/images/uninstalled-patches/" )) (pushnew :CLIM-SYS *features*) MJS 27Oct99 : ca n't push : multi - threaded until load - time bugs fixed in logging and client ( : multi - threaded * features * ) #+unix (pushnew :lispworks-unix *features*) #-unix (pushnew :lispworks-pc *features*) (when (member :ccl *features*) (warn "************>>>>>>>>> removing CCL from features!") (setq *features* (remove :ccl *features*))) (load-all-patches) #+LispWorks3.2 (do-demand-pre-loads :comms) #+LispWorks4 (require "comm") #+(and compile-reverse LispWorks3.2) (defadvice (comm::create-socket-for-service-connection htons-the-port :around) (service port) (call-next-advice service (if (zerop port) port (+ (ash (logand port 255) 8) (logand (ash port -8) 255))))) #+LispWorks3.2 (let ((symbol (intern "IGNORABLE" "CL"))) (proclaim `(declaration ,symbol))) #+LispWorks3.2 (defun quit () (bye)) ( lw : ( ) ) (defmacro sct-defsystem (name options &rest module-list) (translate-to-lw-defsystem name options module-list)) (defun translate-to-lw-defsystem (name options module-list) (let ((new-options '()) (required-systems '())) (loop while options do (let ((option (pop options)) (value (pop options))) (ecase option (:pretty-name) (:journal-directory) (:initial-status) (:patchable) (:source-category) (:default-pathname (let ((pathname (pathname value))) (push option new-options) (push (if (typep pathname 'logical-pathname) (translate-logical-pathname pathname) (string-downcase (namestring pathname))) new-options))) (:required-systems (setq required-systems (append required-systems (loop for system in (if (listp value) value (list value)) collect `(,system :type :system)))))))) (let ((expanded-module-list '()) (submodules '())) (flet ((translate-module (module-spec) (let ((result '())) (loop (when (null module-spec) (return)) (let ((item (pop module-spec))) (cond ((symbolp item) (let ((submodule (assoc item submodules))) (if submodule (if (eq :system (second (assoc :type (cddr submodule)))) (progn (push `(,(car (second submodule)) :type :system) result) (setq submodules (delete item submodules :key 'car))) (error "~S does not name a system module.") #+comment (setq module-spec (append (second submodule) module-spec))) (error "Unknown submodule ~S" item)))) ((or (typep item 'logical-pathname) (and (stringp item) (typep (parse-namestring item) 'logical-pathname))) (push (namestring (translate-logical-pathname item)) result)) (t (push (string-downcase item) result))))) result))) (dolist (module-desc module-list) (cond ((eq (car module-desc) :serial) (setq expanded-module-list (append (translate-module (cdr module-desc)) expanded-module-list))) ((eq (car module-desc) :module) (let ((type (second (assoc :type (cdddr module-desc))))) (unless (eq type :lisp-example) (push (cdr module-desc) submodules) (unless (member type '(nil :system)) (warn "Unknown module type ~S" module-desc))) (push module-desc expanded-module-list))) (t (error "funny module-desc ~S" module-desc)))) (let ((new-module-list '())) (dolist (item expanded-module-list) (if (and (consp item) (eq (car item) :module)) (when-let (submodule (assoc (second item) submodules)) (setq new-module-list (nconc (reverse (translate-module (third item))) new-module-list)) (setq submodules (delete submodule submodules))) (push item new-module-list))) (when submodules (error "Unprocecessed submodules ~S" submodules)) `(lw:defsystem ,name ,(nreverse new-options) :members (,@required-systems ,@new-module-list) :rules ((:in-order-to :compile :all (:requires (:load :serial)))))))))) (sys::without-warning-on-redefinition (let ((dir (pathname-location (translate-logical-pathname (pathname *private-patches-directory*))))) #+LispWorks3.2 (loop for (name seqname minor) in '(("symbol-macrolet-nil" sys::compiler 37) ("unspecific-pathname-device" sys::system 86) ("select-output" sys::system 87) ("select-output-extra" sys::system 173) ("listen-buffered-pipe" sys::system 175) ("lw-external-lambda-lists" sys::system 89) ("buffered-tcp-output-streams" :comms 9) ("signal-continue-search-in-same-cluster" :conditions 2)) for seq = (and seqname (scm::find-patch-sequence seqname)) unless (and seq minor (>= (scm::ps-minor seq) minor)) do (load (merge-pathnames name dir))) #+LispWorks4 (loop for (file id) in #+(and LispWorks4.0 Harlequin-PC-Lisp) '(("defpackage-disjoint-allow-duplicates" :system-defpackage-disjoint-allow-duplicates) ("result-type-values" :compiler-result-type-values) ("setf-name-uninterned" :system-setf-name-uninterned) ("dynamic-extent-multiple-value-list" :compiler-dynamic-extent-multiple-value-list) ("with-stream-buffers" :buffered-stream-with-stream-buffers) ("special-operator-p" :system-special-operator-p) ("socket-check-bytes-before-eof" :comm-socket-check-bytes-before-eof) ("host-forces-unc-pathname" :system-host-forces-unc-pathname)) #-(and LispWorks4.0 Harlequin-PC-Lisp) '() unless (scm::patch-id-loaded-p id) do (load (merge-pathnames file dir)))))
be1a3a8e1a93ba0339afc2e2c99dab1f0dc0241bb3d7e02326564a859bb839b2
bcc32/advent-of-code
circle.ml
open! Core open! Async open! Import type 'a t = { value : 'a ; mutable prev : 'a t ; mutable next : 'a t } let create value = let rec t = { value; prev = t; next = t } in t ;; let insert_after t x = let node = { value = x; prev = t; next = t.next } in t.next.prev <- node; t.next <- node; node ;; let remove_and_get_next t = let t' = t.prev in assert (not (phys_equal t t')); t'.next <- t.next; t.next.prev <- t'; t.next ;;
null
https://raw.githubusercontent.com/bcc32/advent-of-code/653c0f130e2fb2f599d4e76804e02af54c9bb19f/2018/09/circle.ml
ocaml
open! Core open! Async open! Import type 'a t = { value : 'a ; mutable prev : 'a t ; mutable next : 'a t } let create value = let rec t = { value; prev = t; next = t } in t ;; let insert_after t x = let node = { value = x; prev = t; next = t.next } in t.next.prev <- node; t.next <- node; node ;; let remove_and_get_next t = let t' = t.prev in assert (not (phys_equal t t')); t'.next <- t.next; t.next.prev <- t'; t.next ;;
b01baa4c1388669c90be94d8f8ea0665102b3d4341c2701fb8c62b376ba75af5
ptal/AbSolute
interval_view_dbm.mli
Copyright 2019 This program is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *) open Bounds open Dbm * An octagon is a n - dimensional geometrical shape represented by the intersection of n n - dimensional boxes . It equips the DBM representation with functions to view elements in the DBM as intervals . It equips the DBM representation with functions to view elements in the DBM as intervals. *) * This module signature provides function to view DBM 's values as interval bounds . Rational : Conversion of an element in the DBM to an interval depends on the bound type . Rational: Conversion of an element in the DBM to an interval depends on the bound type. *) module type Interval_view_sig = functor (B: Bound_sig.S) -> sig module B: Bound_sig.S type bound = B.t * The bounds of the variable must be retrieved with ` DBM.project ` . val dbm_to_lb : dbm_var -> bound -> bound val dbm_to_ub : dbm_var -> bound -> bound val dbm_to_itv: dbm_interval -> (bound * bound) -> (bound * bound) val lb_to_dbm : dbm_var -> bound -> bound val ub_to_dbm : dbm_var -> bound -> bound end with module B=B module Interval_view : Interval_view_sig
null
https://raw.githubusercontent.com/ptal/AbSolute/469159d87e3a717499573c1e187e5cfa1b569829/src/domains/octagon/interval_view_dbm.mli
ocaml
Copyright 2019 This program is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *) open Bounds open Dbm * An octagon is a n - dimensional geometrical shape represented by the intersection of n n - dimensional boxes . It equips the DBM representation with functions to view elements in the DBM as intervals . It equips the DBM representation with functions to view elements in the DBM as intervals. *) * This module signature provides function to view DBM 's values as interval bounds . Rational : Conversion of an element in the DBM to an interval depends on the bound type . Rational: Conversion of an element in the DBM to an interval depends on the bound type. *) module type Interval_view_sig = functor (B: Bound_sig.S) -> sig module B: Bound_sig.S type bound = B.t * The bounds of the variable must be retrieved with ` DBM.project ` . val dbm_to_lb : dbm_var -> bound -> bound val dbm_to_ub : dbm_var -> bound -> bound val dbm_to_itv: dbm_interval -> (bound * bound) -> (bound * bound) val lb_to_dbm : dbm_var -> bound -> bound val ub_to_dbm : dbm_var -> bound -> bound end with module B=B module Interval_view : Interval_view_sig
c56197fcec453ff9350569908ea6e52100f1a68d0317e968f40bd2e3ab13f830
jarohen/simple-brepl
plugin.clj
(ns simple-brepl.plugin (:require [clojure.java.io :as io] [robert.hooke :refer [add-hook]] [leiningen.core.eval :as eval])) (defn with-core-dep [project] (update-in project [:dependencies] conj ['jarohen/simple-brepl-core (.trim (slurp (io/resource "simple_brepl/VERSION")))])) (defn with-piggieback-hook [project] (-> project (update-in [:repl-options :nrepl-middleware] conj 'cemerick.piggieback/wrap-cljs-repl))) (defn middleware [project] (-> project with-core-dep with-piggieback-hook)) (defn wrap-eval [eval-in-project project form & [init]] (let [{:keys [brepl-port] {:keys [ip port] :or {ip "127.0.0.1"}} :brepl} project] (when brepl-port (binding [*out* *err*] (println (format ":brepl-port is deprecated and will be removed in 0.2.0 - please change your project.clj to use {:brepl {:ip \"optional-ip\", :port %d}} instead." brepl-port)))) (eval-in-project project `(do (simple-brepl.service/load-brepl! ~ip ~(or port brepl-port 9001)) ~form) `(do (require 'simple-brepl.service) ~init)))) (defn hooks [] (add-hook #'eval/eval-in-project #'wrap-eval))
null
https://raw.githubusercontent.com/jarohen/simple-brepl/01169c5f650e768f8f65df238d452afa099537f7/simple-brepl/src/simple_brepl/plugin.clj
clojure
(ns simple-brepl.plugin (:require [clojure.java.io :as io] [robert.hooke :refer [add-hook]] [leiningen.core.eval :as eval])) (defn with-core-dep [project] (update-in project [:dependencies] conj ['jarohen/simple-brepl-core (.trim (slurp (io/resource "simple_brepl/VERSION")))])) (defn with-piggieback-hook [project] (-> project (update-in [:repl-options :nrepl-middleware] conj 'cemerick.piggieback/wrap-cljs-repl))) (defn middleware [project] (-> project with-core-dep with-piggieback-hook)) (defn wrap-eval [eval-in-project project form & [init]] (let [{:keys [brepl-port] {:keys [ip port] :or {ip "127.0.0.1"}} :brepl} project] (when brepl-port (binding [*out* *err*] (println (format ":brepl-port is deprecated and will be removed in 0.2.0 - please change your project.clj to use {:brepl {:ip \"optional-ip\", :port %d}} instead." brepl-port)))) (eval-in-project project `(do (simple-brepl.service/load-brepl! ~ip ~(or port brepl-port 9001)) ~form) `(do (require 'simple-brepl.service) ~init)))) (defn hooks [] (add-hook #'eval/eval-in-project #'wrap-eval))
3ca83a83aed03230333e5ac9625fadbbc548e0a738237e64237ba9f5560b8b9f
clojerl/clojerl
clojerl_String_SUITE.erl
-module(clojerl_String_SUITE). -include("clojerl.hrl"). -include("clj_test_utils.hrl"). -export([ all/0 , init_per_suite/1 , end_per_suite/1 ]). -export([ append/1 , count/1 , index_of/1 , is_whitespace/1 , last_index_of/1 , join/1 , to_lower/1 , to_upper/1 , seq/1 , str/1 , substring/1 , split/1 , replace/1 , complete_coverage/1 ]). -spec all() -> [atom()]. all() -> clj_test_utils:all(?MODULE). -spec init_per_suite(config()) -> config(). init_per_suite(Config) -> clj_test_utils:init_per_suite(Config). -spec end_per_suite(config()) -> config(). end_per_suite(Config) -> Config. %%------------------------------------------------------------------------------ %% Test Cases %%------------------------------------------------------------------------------ -spec append(config()) -> result(). append(_Config) -> <<"ab">> = 'clojerl.String':append(<<"a">>, <<"b">>), <<"hello world">> = 'clojerl.String':append(<<"hello ">>, <<"world">>), {comments, ""}. -spec count(config()) -> result(). count(_Config) -> 3 = clj_rt:count(<<"abc">>), 0 = clj_rt:count(<<>>), InvalidBinary = <<69, 82, 67, 80, 79, 0, 0, 0, 0, 0, 0, 0, 81, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 97, 0, 100, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 125, 0, 11, 29, 97, 29, 98, 29, 99, 29, 100, 114, 0, 11, 0>>, ok = try clj_rt:count(InvalidBinary), error catch _:_ -> ok end, {comments, ""}. -spec is_whitespace(config()) -> result(). is_whitespace(_Config) -> true = 'clojerl.String':is_whitespace(<<" ">>), true = 'clojerl.String':is_whitespace(<<"\t">>), true = 'clojerl.String':is_whitespace(<<"\n">>), true = 'clojerl.String':is_whitespace(<<"\r">>), false = 'clojerl.String':is_whitespace(<<"a">>), false = 'clojerl.String':is_whitespace(<<"A">>), false = 'clojerl.String':is_whitespace(<<"B">>), false = 'clojerl.String':is_whitespace(<<"b">>), {comments, ""}. -spec index_of(config()) -> result(). index_of(_Config) -> 1 = 'clojerl.String':index_of(<<"hello">>, <<"e">>), 2 = 'clojerl.String':index_of(<<"hello">>, <<"l">>), -1 = 'clojerl.String':index_of(<<"hello">>, <<"f">>), -1 = 'clojerl.String':index_of(<<>>, <<"f">>), 6 = 'clojerl.String':index_of(<<"foobarfoo">>, <<"f">>, 2), {comments, ""}. -spec last_index_of(config()) -> result(). last_index_of(_Config) -> 7 = 'clojerl.String':last_index_of(<<"hello world">>, <<"o">>), 3 = 'clojerl.String':last_index_of(<<"hello">>, <<"l">>), -1 = 'clojerl.String':last_index_of(<<"hello">>, <<"f">>), -1 = 'clojerl.String':last_index_of(<<>>, <<"f">>), {comments, ""}. -spec join(config()) -> result(). join(_Config) -> <<"1 and 2 and 3">> = 'clojerl.String':join([1, 2, 3], <<" and ">>), <<"42">> = 'clojerl.String':join([42], <<" and ">>), <<>> = 'clojerl.String':join([], <<" and ">>), {comments, ""}. -spec to_lower(config()) -> result(). to_lower(_Config) -> <<"foo faa">> = 'clojerl.String':to_lower(<<"fOO FaA">>), <<"hello world!">> = 'clojerl.String':to_lower(<<"Hello WoRld!">>), {comments, ""}. -spec to_upper(config()) -> result(). to_upper(_Config) -> <<"FOO FAA">> = 'clojerl.String':to_upper(<<"fOO FaA">>), <<"HELLO WORLD!">> = 'clojerl.String':to_upper(<<"Hello WoRld!">>), {comments, ""}. -spec str(config()) -> result(). str(_Config) -> <<"hello">> = clj_rt:str(<<"hello">>), <<>> = clj_rt:str(<<>>), {comments, ""}. -spec seq(config()) -> result(). seq(_Config) -> 5 = clj_rt:count(clj_rt:seq(<<"hello">>)), StringSeq = clj_rt:seq(<<"hello">>), StringSeq = 'clojerl.StringSeq':?CONSTRUCTOR(<<"hello">>), ?NIL = clj_rt:seq(<<>>), [<<"h">>, <<"e">>, <<"l">>, <<"l">>, <<"o">>] = clj_rt:to_list(<<"hello">>), {comments, ""}. -spec substring(config()) -> result(). substring(_Config) -> <<"h">> = 'clojerl.String':substring(<<"hello">>, 0, 1), <<"hel">> = 'clojerl.String':substring(<<"hello">>, 0, 3), <<"l">> = 'clojerl.String':substring(<<"hello">>, 3, 4), <<"">> = 'clojerl.String':substring(<<"hello">>, 4, 4), <<"o">> = 'clojerl.String':substring(<<"hello">>, 4, 5), <<>> = 'clojerl.String':substring(<<>>, 0, 1), <<"lo">> = 'clojerl.String':substring(<<"hello">>, 3), ok = try 'clojerl.String':substring(<<>>, 5, 4), error catch _:_ -> ok end, {comments, ""}. -spec split(config()) -> result(). split(_Config) -> [<<"h">>, <<"llo">>] = 'clojerl.String':split(<<"hello">>, <<"e">>), [<<"1">>, <<"2">>, <<"3">>] = 'clojerl.String':split(<<"1,2,3">>, <<",">>), {comments, ""}. -spec replace(config()) -> result(). replace(_Config) -> <<"faabarfaa">> = 'clojerl.String':replace(<<"foobarfoo">>, <<"o">>, <<"a">>), <<"fbarf">> = 'clojerl.String':replace(<<"foobarfoo">>, <<"oo">>, <<"">>), {comments, ""}. -spec complete_coverage(config()) -> result(). complete_coverage(_Config) -> true = 'clojerl.String':starts_with(<<>>, <<>>), true = 'clojerl.String':starts_with(<<"123456">>, <<"1">>), true = 'clojerl.String':starts_with(<<"123456">>, <<"12">>), true = 'clojerl.String':starts_with(<<"123456">>, <<"123">>), false = 'clojerl.String':starts_with(<<"123456">>, <<"a">>), true = 'clojerl.String':ends_with(<<>>, <<>>), true = 'clojerl.String':ends_with(<<"123456">>, <<"6">>), true = 'clojerl.String':ends_with(<<"123456">>, <<"56">>), true = 'clojerl.String':ends_with(<<"123456">>, <<"456">>), false = 'clojerl.String':ends_with(<<"123456">>, <<"789">>), false = 'clojerl.String':ends_with(<<"123456">>, <<"1234567">>), true = 'clojerl.String':contains(<<"123456">>, <<"234">>), true = 'clojerl.String':contains(<<"123456">>, <<"456">>), false = 'clojerl.String':contains(<<"123456">>, <<"354">>), false = 'clojerl.String':contains(<<"123456">>, <<"abc">>), <<"3">> = 'clojerl.String':char_at(<<"123456">>, 2), true = erlang:is_integer('clojerl.IHash':hash(<<"123456">>)), true = 'clojerl.String':is_printable(<<"123456">>), false = 'clojerl.String':is_printable(<<"123456", 0>>), {comments, ""}.
null
https://raw.githubusercontent.com/clojerl/clojerl/aa35847ca64e1c66224867ca4c31ca6de95bc898/test/clojerl_String_SUITE.erl
erlang
------------------------------------------------------------------------------ Test Cases ------------------------------------------------------------------------------
-module(clojerl_String_SUITE). -include("clojerl.hrl"). -include("clj_test_utils.hrl"). -export([ all/0 , init_per_suite/1 , end_per_suite/1 ]). -export([ append/1 , count/1 , index_of/1 , is_whitespace/1 , last_index_of/1 , join/1 , to_lower/1 , to_upper/1 , seq/1 , str/1 , substring/1 , split/1 , replace/1 , complete_coverage/1 ]). -spec all() -> [atom()]. all() -> clj_test_utils:all(?MODULE). -spec init_per_suite(config()) -> config(). init_per_suite(Config) -> clj_test_utils:init_per_suite(Config). -spec end_per_suite(config()) -> config(). end_per_suite(Config) -> Config. -spec append(config()) -> result(). append(_Config) -> <<"ab">> = 'clojerl.String':append(<<"a">>, <<"b">>), <<"hello world">> = 'clojerl.String':append(<<"hello ">>, <<"world">>), {comments, ""}. -spec count(config()) -> result(). count(_Config) -> 3 = clj_rt:count(<<"abc">>), 0 = clj_rt:count(<<>>), InvalidBinary = <<69, 82, 67, 80, 79, 0, 0, 0, 0, 0, 0, 0, 81, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 97, 0, 100, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 125, 0, 11, 29, 97, 29, 98, 29, 99, 29, 100, 114, 0, 11, 0>>, ok = try clj_rt:count(InvalidBinary), error catch _:_ -> ok end, {comments, ""}. -spec is_whitespace(config()) -> result(). is_whitespace(_Config) -> true = 'clojerl.String':is_whitespace(<<" ">>), true = 'clojerl.String':is_whitespace(<<"\t">>), true = 'clojerl.String':is_whitespace(<<"\n">>), true = 'clojerl.String':is_whitespace(<<"\r">>), false = 'clojerl.String':is_whitespace(<<"a">>), false = 'clojerl.String':is_whitespace(<<"A">>), false = 'clojerl.String':is_whitespace(<<"B">>), false = 'clojerl.String':is_whitespace(<<"b">>), {comments, ""}. -spec index_of(config()) -> result(). index_of(_Config) -> 1 = 'clojerl.String':index_of(<<"hello">>, <<"e">>), 2 = 'clojerl.String':index_of(<<"hello">>, <<"l">>), -1 = 'clojerl.String':index_of(<<"hello">>, <<"f">>), -1 = 'clojerl.String':index_of(<<>>, <<"f">>), 6 = 'clojerl.String':index_of(<<"foobarfoo">>, <<"f">>, 2), {comments, ""}. -spec last_index_of(config()) -> result(). last_index_of(_Config) -> 7 = 'clojerl.String':last_index_of(<<"hello world">>, <<"o">>), 3 = 'clojerl.String':last_index_of(<<"hello">>, <<"l">>), -1 = 'clojerl.String':last_index_of(<<"hello">>, <<"f">>), -1 = 'clojerl.String':last_index_of(<<>>, <<"f">>), {comments, ""}. -spec join(config()) -> result(). join(_Config) -> <<"1 and 2 and 3">> = 'clojerl.String':join([1, 2, 3], <<" and ">>), <<"42">> = 'clojerl.String':join([42], <<" and ">>), <<>> = 'clojerl.String':join([], <<" and ">>), {comments, ""}. -spec to_lower(config()) -> result(). to_lower(_Config) -> <<"foo faa">> = 'clojerl.String':to_lower(<<"fOO FaA">>), <<"hello world!">> = 'clojerl.String':to_lower(<<"Hello WoRld!">>), {comments, ""}. -spec to_upper(config()) -> result(). to_upper(_Config) -> <<"FOO FAA">> = 'clojerl.String':to_upper(<<"fOO FaA">>), <<"HELLO WORLD!">> = 'clojerl.String':to_upper(<<"Hello WoRld!">>), {comments, ""}. -spec str(config()) -> result(). str(_Config) -> <<"hello">> = clj_rt:str(<<"hello">>), <<>> = clj_rt:str(<<>>), {comments, ""}. -spec seq(config()) -> result(). seq(_Config) -> 5 = clj_rt:count(clj_rt:seq(<<"hello">>)), StringSeq = clj_rt:seq(<<"hello">>), StringSeq = 'clojerl.StringSeq':?CONSTRUCTOR(<<"hello">>), ?NIL = clj_rt:seq(<<>>), [<<"h">>, <<"e">>, <<"l">>, <<"l">>, <<"o">>] = clj_rt:to_list(<<"hello">>), {comments, ""}. -spec substring(config()) -> result(). substring(_Config) -> <<"h">> = 'clojerl.String':substring(<<"hello">>, 0, 1), <<"hel">> = 'clojerl.String':substring(<<"hello">>, 0, 3), <<"l">> = 'clojerl.String':substring(<<"hello">>, 3, 4), <<"">> = 'clojerl.String':substring(<<"hello">>, 4, 4), <<"o">> = 'clojerl.String':substring(<<"hello">>, 4, 5), <<>> = 'clojerl.String':substring(<<>>, 0, 1), <<"lo">> = 'clojerl.String':substring(<<"hello">>, 3), ok = try 'clojerl.String':substring(<<>>, 5, 4), error catch _:_ -> ok end, {comments, ""}. -spec split(config()) -> result(). split(_Config) -> [<<"h">>, <<"llo">>] = 'clojerl.String':split(<<"hello">>, <<"e">>), [<<"1">>, <<"2">>, <<"3">>] = 'clojerl.String':split(<<"1,2,3">>, <<",">>), {comments, ""}. -spec replace(config()) -> result(). replace(_Config) -> <<"faabarfaa">> = 'clojerl.String':replace(<<"foobarfoo">>, <<"o">>, <<"a">>), <<"fbarf">> = 'clojerl.String':replace(<<"foobarfoo">>, <<"oo">>, <<"">>), {comments, ""}. -spec complete_coverage(config()) -> result(). complete_coverage(_Config) -> true = 'clojerl.String':starts_with(<<>>, <<>>), true = 'clojerl.String':starts_with(<<"123456">>, <<"1">>), true = 'clojerl.String':starts_with(<<"123456">>, <<"12">>), true = 'clojerl.String':starts_with(<<"123456">>, <<"123">>), false = 'clojerl.String':starts_with(<<"123456">>, <<"a">>), true = 'clojerl.String':ends_with(<<>>, <<>>), true = 'clojerl.String':ends_with(<<"123456">>, <<"6">>), true = 'clojerl.String':ends_with(<<"123456">>, <<"56">>), true = 'clojerl.String':ends_with(<<"123456">>, <<"456">>), false = 'clojerl.String':ends_with(<<"123456">>, <<"789">>), false = 'clojerl.String':ends_with(<<"123456">>, <<"1234567">>), true = 'clojerl.String':contains(<<"123456">>, <<"234">>), true = 'clojerl.String':contains(<<"123456">>, <<"456">>), false = 'clojerl.String':contains(<<"123456">>, <<"354">>), false = 'clojerl.String':contains(<<"123456">>, <<"abc">>), <<"3">> = 'clojerl.String':char_at(<<"123456">>, 2), true = erlang:is_integer('clojerl.IHash':hash(<<"123456">>)), true = 'clojerl.String':is_printable(<<"123456">>), false = 'clojerl.String':is_printable(<<"123456", 0>>), {comments, ""}.
dc4e686658b21c0794855ad495b9b78b845669887f100c6a0db9b33f6e194ad5
hanshuebner/bos
import.lisp
(in-package :bos.m2) (defclass importer () ((sponsor :accessor importer-sponsor) (price :accessor importer-price) (date :accessor importer-date) (m2s :accessor importer-m2s) (area-active-p :accessor importer-area-active-p) (area-y :accessor importer-area-y) (area-vertices :accessor importer-area-vertices) (area :accessor importer-area))) (defun import-database (pathname) (cxml:parse-file pathname (cxml:make-recoder (make-instance 'importer)))) (defun string-or-nil (x) (if (zerop (length x)) nil x)) (defun getattribute (name attributes) (let ((a (find name attributes :key #'sax:attribute-qname :test #'string=))) (if a (string-or-nil (sax:attribute-value a)) nil))) (defun parse-iso-time (str) (let ((y (parse-integer str :start 0 :end 4)) (m (parse-integer str :start 5 :end 7)) (d (parse-integer str :start 8 :end 10)) (h (parse-integer str :start 11 :end 13)) (min (parse-integer str :start 14 :end 16)) (s (parse-integer str :start 17 :end 19))) (encode-universal-time s min h d m y 0))) (defmethod sax:start-element ((handler importer) namespace-uri local-name qname attrs) (declare (ignore namespace-uri local-name)) (cond ((string= qname "sponsor") (setf (importer-sponsor handler) (make-sponsor :login (getattribute "profile-id" attrs) :full-name (getattribute "full-name" attrs) :email-address (getattribute "email-address" attrs) :info-text (getattribute "info-text" attrs) :country (getattribute "country" attrs))) XXX Achtung , das Passwort nicht als schon Initarg uebergeben , die USER - Klasse es sonst fuer uns MD5 t. (change-slot-values (importer-sponsor handler) 'bknr.web::password (getattribute "password" attrs))) ((string= qname "contract") (setf (importer-price handler) (parse-integer (getattribute "price" attrs))) (setf (importer-date handler) (parse-iso-time (getattribute "date" attrs))) (setf (importer-m2s handler) '())) ((string= qname "m2") (let ((m2 (ensure-m2-with-num (parse-integer (getattribute "sqm-num" attrs)))) (x (getattribute "x" attrs)) (y (getattribute "y" attrs)) (utm-x (getattribute "utm-x" attrs)) (utm-y (getattribute "utm-y" attrs)) (*read-eval* nil)) (when x (assert (eql (parse-integer x) (m2-x m2)))) (when y (assert (eql (parse-integer y) (m2-y m2)))) (when utm-x (assert (= (read-from-string utm-x) (m2-utm-x m2)))) (when utm-y (assert (= (read-from-string utm-y) (m2-utm-y m2)))) (push m2 (importer-m2s handler)))) ((string= qname "allocation-area") (setf (importer-area-active-p handler) (equal (getattribute "active" attrs) "yes")) (setf (importer-area-y handler) (parse-integer (getattribute "y" attrs))) (setf (importer-area handler) nil) (setf (importer-area-vertices handler) nil)) ((string= qname "point") (push (cons (parse-integer (getattribute "x" attrs)) (parse-integer (getattribute "y" attrs))) (importer-area-vertices handler))))) (defmethod sax:end-element ((handler importer) namespace-uri local-name qname) (declare (ignore namespace-uri local-name)) (cond ((string= qname "contract") (make-contract (importer-sponsor handler) (importer-m2s handler) :date (importer-date handler)))))
null
https://raw.githubusercontent.com/hanshuebner/bos/ab5944cc46f4a5ff5a08fd8aa4d228c0f9cfc771/m2/import.lisp
lisp
(in-package :bos.m2) (defclass importer () ((sponsor :accessor importer-sponsor) (price :accessor importer-price) (date :accessor importer-date) (m2s :accessor importer-m2s) (area-active-p :accessor importer-area-active-p) (area-y :accessor importer-area-y) (area-vertices :accessor importer-area-vertices) (area :accessor importer-area))) (defun import-database (pathname) (cxml:parse-file pathname (cxml:make-recoder (make-instance 'importer)))) (defun string-or-nil (x) (if (zerop (length x)) nil x)) (defun getattribute (name attributes) (let ((a (find name attributes :key #'sax:attribute-qname :test #'string=))) (if a (string-or-nil (sax:attribute-value a)) nil))) (defun parse-iso-time (str) (let ((y (parse-integer str :start 0 :end 4)) (m (parse-integer str :start 5 :end 7)) (d (parse-integer str :start 8 :end 10)) (h (parse-integer str :start 11 :end 13)) (min (parse-integer str :start 14 :end 16)) (s (parse-integer str :start 17 :end 19))) (encode-universal-time s min h d m y 0))) (defmethod sax:start-element ((handler importer) namespace-uri local-name qname attrs) (declare (ignore namespace-uri local-name)) (cond ((string= qname "sponsor") (setf (importer-sponsor handler) (make-sponsor :login (getattribute "profile-id" attrs) :full-name (getattribute "full-name" attrs) :email-address (getattribute "email-address" attrs) :info-text (getattribute "info-text" attrs) :country (getattribute "country" attrs))) XXX Achtung , das Passwort nicht als schon Initarg uebergeben , die USER - Klasse es sonst fuer uns MD5 t. (change-slot-values (importer-sponsor handler) 'bknr.web::password (getattribute "password" attrs))) ((string= qname "contract") (setf (importer-price handler) (parse-integer (getattribute "price" attrs))) (setf (importer-date handler) (parse-iso-time (getattribute "date" attrs))) (setf (importer-m2s handler) '())) ((string= qname "m2") (let ((m2 (ensure-m2-with-num (parse-integer (getattribute "sqm-num" attrs)))) (x (getattribute "x" attrs)) (y (getattribute "y" attrs)) (utm-x (getattribute "utm-x" attrs)) (utm-y (getattribute "utm-y" attrs)) (*read-eval* nil)) (when x (assert (eql (parse-integer x) (m2-x m2)))) (when y (assert (eql (parse-integer y) (m2-y m2)))) (when utm-x (assert (= (read-from-string utm-x) (m2-utm-x m2)))) (when utm-y (assert (= (read-from-string utm-y) (m2-utm-y m2)))) (push m2 (importer-m2s handler)))) ((string= qname "allocation-area") (setf (importer-area-active-p handler) (equal (getattribute "active" attrs) "yes")) (setf (importer-area-y handler) (parse-integer (getattribute "y" attrs))) (setf (importer-area handler) nil) (setf (importer-area-vertices handler) nil)) ((string= qname "point") (push (cons (parse-integer (getattribute "x" attrs)) (parse-integer (getattribute "y" attrs))) (importer-area-vertices handler))))) (defmethod sax:end-element ((handler importer) namespace-uri local-name qname) (declare (ignore namespace-uri local-name)) (cond ((string= qname "contract") (make-contract (importer-sponsor handler) (importer-m2s handler) :date (importer-date handler)))))
c722c7a54be0ec0711306442e9707c06ab8518df80de966907a6905ed2d70b4b
xapi-project/xen-api
xapi_message.ml
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) 2006-2009 Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) (** Module that defines API functions for Message objects * @group XenAPI functions *) (** Message store *) (* We use a filesystem based 'database': * Base directory: /var/lib/xcp/blobs/messages * All messages go in there, filename=timestamp * * Symlinks are created to the messages for fast indexing: * /var/lib/xcp/blobs/messages/VM/<uuid>/<timestamp> -> message * /var/lib/xcp/blobs/messages/uuid/<message uuid> -> message * /var/lib/xcp/blobs/messages/ref/<message ref> -> message *) module Date = Xapi_stdext_date.Date module Encodings = Xapi_stdext_encodings.Encodings module Listext = Xapi_stdext_std.Listext module Pervasiveext = Xapi_stdext_pervasives.Pervasiveext module Unixext = Xapi_stdext_unix.Unixext let with_lock = Xapi_stdext_threads.Threadext.Mutex.execute module D = Debug.Make (struct let name = "xapi_message" end) open D let message_dir = Xapi_globs.xapi_blob_location ^ "/messages" let event_mutex = Mutex.create () let in_memory_cache = ref [] let in_memory_cache_mutex = Mutex.create () let in_memory_cache_length = ref 0 let in_memory_cache_length_max = 512 let in_memory_cache_length_default = 256 (* We use the timestamp to name the file. For consistency, use this function *) let timestamp_to_string f = Printf.sprintf "%0.5f" f (************* Marshalling/unmarshalling functions ************) let to_xml output _ref gen message = let tag n next () = Xmlm.output output (`El_start (("", n), [])) ; List.iter (fun x -> x ()) next ; Xmlm.output output `El_end in let data dat () = Xmlm.output output (`Data dat) in Xmlm.output output (`Dtd None) ; let message_subtags = [ tag "ref" [data (Ref.string_of _ref)] ; tag "name" [data message.API.message_name] ; tag "priority" [data (Int64.to_string message.API.message_priority)] ; tag "cls" [data (Record_util.class_to_string message.API.message_cls)] ; tag "obj_uuid" [data message.API.message_obj_uuid] ; tag "timestamp" [data (Date.to_string message.API.message_timestamp)] ; tag "uuid" [data message.API.message_uuid] ; tag "body" [data message.API.message_body] ] in let message_subtags = match gen with | Some g -> tag "generation" [data (Int64.to_string g)] :: message_subtags | None -> message_subtags in tag "message" message_subtags () let of_xml input = let current_elt = ref "" in let message = ref { API.message_name= "" ; API.message_priority= 0L ; API.message_cls= `VM ; API.message_obj_uuid= "" ; API.message_timestamp= Date.never ; API.message_body= "" ; API.message_uuid= "" } in let _ref = ref "" in let gen = ref 0L in let rec f () = match Xmlm.input input with | `El_start ((_, tag), _) -> current_elt := tag ; f () | `El_end -> current_elt := "" ; if Xmlm.eoi input then () else f () | `Data dat -> ( match !current_elt with | "name" -> message := {!message with API.message_name= dat} | "priority" -> message := {!message with API.message_priority= Int64.of_string dat} | "cls" -> message := {!message with API.message_cls= Record_util.string_to_class dat} | "obj_uuid" -> message := {!message with API.message_obj_uuid= dat} | "timestamp" -> message := {!message with API.message_timestamp= Date.of_string dat} | "uuid" -> message := {!message with API.message_uuid= dat} | "body" -> message := {!message with API.message_body= dat} | "generation" -> gen := Int64.of_string dat | "ref" -> _ref := dat | _ -> failwith "Bad XML!" ) ; f () | `Dtd _ -> f () in try f () ; (!gen, Ref.of_string !_ref, !message) with e -> Backtrace.is_important e ; raise e let export_xml messages = let size = 500 * List.length messages in let buf = Buffer.create size in let output = Xmlm.make_output (`Buffer buf) in List.iter (function r, m -> to_xml output r None m) messages ; Buffer.contents buf let import_xml xml_in = let split_xml = let ob = Buffer.create 600 in (* let i = Xmlm.make_input (`String (0, xml)) in *) let o = Xmlm.make_output (`Buffer ob) in let rec pull xml_in o depth = Xmlm.output o (Xmlm.peek xml_in) ; match Xmlm.input xml_in with | `El_start _ -> pull xml_in o (depth + 1) | `El_end -> if depth = 1 then () else pull xml_in o (depth - 1) | `Data _ -> pull xml_in o depth | `Dtd _ -> pull xml_in o depth in let out = ref [] in while not (Xmlm.eoi xml_in) do pull xml_in o 0 ; out := Buffer.contents ob :: !out ; Buffer.clear ob done ; !out in let rec loop = function | [] -> [] | m :: ms -> let im = Xmlm.make_input (`String (0, m)) in of_xml im :: loop ms in loop split_xml (********** Symlink functions *************) let class_symlink cls obj_uuid = let strcls = Record_util.class_to_string cls in Printf.sprintf "%s/%s/%s" message_dir strcls obj_uuid let uuid_symlink () = Printf.sprintf "%s/uuids" message_dir let ref_symlink () = Printf.sprintf "%s/refs" message_dir let gen_symlink () = Printf.sprintf "%s/gen" message_dir (** Returns a list of tuples - (directory, filename) *) let symlinks _ref gen message basefilename = let symlinks = [ (class_symlink message.API.message_cls message.API.message_obj_uuid, None) ; (uuid_symlink (), Some message.API.message_uuid) ; (ref_symlink (), Some (Ref.string_of _ref)) ] in let symlinks = match gen with | Some gen -> (gen_symlink (), Some (Int64.to_string gen)) :: symlinks | None -> symlinks in List.map (fun (dir, fnameopt) -> let newfname = match fnameopt with None -> basefilename | Some f -> f in (dir, dir ^ "/" ^ newfname) ) symlinks * Check to see if the UUID is valid . This should not use get_by_uuid as this causes spurious exceptions to be logged ... this causes spurious exceptions to be logged... *) let check_uuid ~__context ~cls ~uuid = try ( match cls with | `VM -> ignore (Db.VM.get_by_uuid ~__context ~uuid) | `Host -> ignore (Db.Host.get_by_uuid ~__context ~uuid) | `SR -> ignore (Db.SR.get_by_uuid ~__context ~uuid) | `Pool -> ignore (Db.Pool.get_by_uuid ~__context ~uuid) | `VMPP -> ignore (Db.VMPP.get_by_uuid ~__context ~uuid) | `VMSS -> ignore (Db.VMSS.get_by_uuid ~__context ~uuid) | `PVS_proxy -> ignore (Db.PVS_proxy.get_by_uuid ~__context ~uuid) | `VDI -> ignore (Db.VDI.get_by_uuid ~__context ~uuid) | `Certificate -> ignore (Db.Certificate.get_by_uuid ~__context ~uuid) ) ; true with _ -> false * * * * * * * * * * Thread_queue to exec the message script hook * * * * * * * * * * let queue_push = ref (fun (_ : string) (_ : string) -> false) let message_to_string (_ref, message) = let buffer = Buffer.create 10 in let output = Xmlm.make_output (`Buffer buffer) in to_xml output _ref None message ; Buffer.contents buffer let handle_message ~__context message = try if not (Pool_features.is_enabled ~__context Features.Email) then info "Email alerting is restricted by current license: not generating email" else if Sys.file_exists !Xapi_globs.xapi_message_script then let output, log = Forkhelpers.execute_command_get_output !Xapi_globs.xapi_message_script [message] in debug "Executed message hook: output='%s' log='%s'" output log else info "%s not found, skipping" !Xapi_globs.xapi_message_script with e -> error "Unexpected exception in message hook %s: %s" !Xapi_globs.xapi_message_script (ExnHelper.string_of_exn e) let start_message_hook_thread ~__context () = queue_push := (Thread_queue.make ~name:"email message queue" ~max_q_length:100 (handle_message ~__context) ) .Thread_queue.push_fn (********************************************************************) let cache_insert _ref message gen = with_lock in_memory_cache_mutex (fun () -> in_memory_cache := (gen, _ref, message) :: !in_memory_cache ; in_memory_cache_length := !in_memory_cache_length + 1 ; if !in_memory_cache_length > in_memory_cache_length_max then ( in_memory_cache := Listext.List.take in_memory_cache_length_default !in_memory_cache ; in_memory_cache_length := in_memory_cache_length_default ; debug "Pruning in-memory cache of messages: Length=%d (%d)" !in_memory_cache_length (List.length !in_memory_cache) ) ) let cache_remove _ref = with_lock in_memory_cache_mutex (fun () -> let to_delete, to_keep = List.partition (function _, _ref', _ -> _ref' = _ref) !in_memory_cache in if List.length to_delete > 1 then error "Internal error: Repeated reference in messages in_memory_cache" ; in_memory_cache := to_keep ; in_memory_cache_length := List.length to_keep ) (** Write: write message to disk. Returns boolean indicating whether message was written *) let write ~__context ~_ref ~message = (* Check if a message with _ref has already been written *) let message_exists () = let file = ref_symlink () ^ "/" ^ Ref.string_of _ref in try Unix.access file [Unix.F_OK] ; true with _ -> false in let message_gen () = let fn = ref_symlink () ^ "/" ^ Ref.string_of _ref in let ic = open_in fn in let xi = Xmlm.make_input (`Channel ic) in let gen, _, _ = Pervasiveext.finally (fun () -> of_xml xi) (fun () -> close_in ic) in gen in let gen = ref 0L in Db_lock.with_lock (fun () -> let t = Context.database_of __context in Db_ref.update_database t (fun db -> gen := Db_cache_types.Manifest.generation (Db_cache_types.Database.manifest db) ; Db_cache_types.Database.increment db ) ) ; Unixext.mkdir_rec message_dir 0o700 ; let timestamp = ref (Date.to_float message.API.message_timestamp) in if message_exists () then Some (message_gen ()) else try with_lock event_mutex (fun () -> let fd, basefilename, filename = Try 10 , no wait , 11 times to create message file let rec doit n = if n > 10 then failwith "Couldn't create a file" else let basefilename = timestamp_to_string !timestamp in let filename = message_dir ^ "/" ^ basefilename in try let fd = Unix.openfile filename [Unix.O_RDWR; Unix.O_CREAT; Unix.O_EXCL] 0o600 in (* Set file's timestamp to message timestamp *) Unix.utimes filename !timestamp !timestamp ; (fd, basefilename, filename) with _ -> (* We may be copying messages from another pool, in which case we may have filename collision (unlikely, but possible). So increment the filename and try again, but leave the original timestamp in the message untouched. *) timestamp := !timestamp +. 0.00001 ; doit (n + 1) in doit 0 in (* Write the message to file *) let oc = Unix.out_channel_of_descr fd in let output = Xmlm.make_output (`Channel oc) in to_xml output _ref (Some !gen) message ; close_out oc ; (* Message now written, let's symlink it in various places *) let symlinks = symlinks _ref (Some !gen) message basefilename in List.iter (fun (dir, newpath) -> Unixext.mkdir_rec dir 0o700 ; Unix.symlink filename newpath ) symlinks ; (* Insert a written message into in_memory_cache *) cache_insert _ref message !gen ; (* Emit a create event (with the old event API). If the message hasn't been written, we may want to also emit a del even, for consistency (since the reference for the message will never be valid again. *) let rpc = API.rpc_of_message_t message in Xapi_event.event_add ~snapshot:rpc "message" "add" (Ref.string_of _ref) ; let (_ : bool) = !queue_push message.API.message_name (message_to_string (_ref, message)) in (*Xapi_event.event_add ~snapshot:xml "message" "del" (Ref.string_of _ref);*) Some !gen ) with _ -> None (** create: Create a new message, and write to disk. Returns null ref if write failed, or message ref otherwise. *) let create ~__context ~name ~priority ~cls ~obj_uuid ~body = debug "Message.create %s %Ld %s %s" name priority (Record_util.class_to_string cls) obj_uuid ; if not (Encodings.UTF8_XML.is_valid body) then raise (Api_errors.Server_error (Api_errors.invalid_value, ["UTF8 expected"])) ; if not (check_uuid ~__context ~cls ~uuid:obj_uuid) then raise (Api_errors.Server_error (Api_errors.uuid_invalid, [Record_util.class_to_string cls; obj_uuid]) ) ; let _ref = Ref.make () in let uuid = Uuidx.to_string (Uuidx.make ()) in let timestamp = with_lock event_mutex (fun () -> Unix.gettimeofday ()) in (* During rolling upgrade, upgraded master might have a alerts grading system different from the not yet upgraded slaves, during that process we transform the priority of received messages as a special case. *) let priority = if Helpers.rolling_upgrade_in_progress ~__context && List.mem_assoc name !Api_messages.msgList then List.assoc name !Api_messages.msgList else priority in let message = { API.message_name= name ; API.message_uuid= uuid ; API.message_priority= priority ; API.message_cls= cls ; API.message_obj_uuid= obj_uuid ; API.message_timestamp= Date.of_float timestamp ; API.message_body= body } in (* Write the message to disk *) let gen = write ~__context ~_ref ~message in (* Return the message ref, or Ref.null if the message wasn't written *) match gen with Some _ -> _ref | None -> Ref.null let deleted : (Generation.t * API.ref_message) list ref = ref [(0L, Ref.null)] let ndeleted = ref 1 let deleted_mutex = Mutex.create () let destroy_real __context basefilename = let filename = message_dir ^ "/" ^ basefilename in let ic = open_in filename in let gen, _ref, message = Pervasiveext.finally (fun () -> of_xml (Xmlm.make_input (`Channel ic))) (fun () -> close_in ic) in let symlinks = symlinks _ref (Some gen) message basefilename in List.iter (fun (_, newpath) -> Unixext.unlink_safe newpath) symlinks ; Unixext.unlink_safe filename ; let rpc = API.rpc_of_message_t message in let gen = ref 0L in Db_lock.with_lock (fun () -> let t = Context.database_of __context in Db_ref.update_database t (fun db -> gen := Db_cache_types.Manifest.generation (Db_cache_types.Database.manifest db) ; Db_cache_types.Database.increment db ) ) ; with_lock event_mutex (fun () -> deleted := (!gen, _ref) :: !deleted ; ndeleted := !ndeleted + 1 ; if !ndeleted > 1024 then ( deleted := Listext.List.take 512 !deleted ; ndeleted := 512 ) ) ; cache_remove _ref ; Xapi_event.event_add ~snapshot:rpc "message" "del" (Ref.string_of _ref) let destroy ~__context ~self = (* Find the original message so we know where the symlinks will be *) let symlinkfname = ref_symlink () ^ "/" ^ Ref.string_of self in let fullpath = try Unix.readlink symlinkfname with _ -> ( let allfiles = List.map (fun file -> message_dir ^ "/" ^ file) (Array.to_list (Sys.readdir message_dir)) in let allmsgs = List.filter (fun file -> not (Sys.is_directory file)) allfiles in try List.find (fun msg_fname -> try let ic = open_in msg_fname in let _, _ref, _ = Pervasiveext.finally (fun () -> of_xml (Xmlm.make_input (`Channel ic))) (fun () -> close_in ic) in if _ref = self then true else false with _ -> false ) allmsgs with _ -> raise (Api_errors.Server_error ( Api_errors.handle_invalid , [Datamodel_common._message; Ref.string_of self] ) ) ) in let basefilename = List.hd (List.rev (String.split_on_char '/' fullpath)) in destroy_real __context basefilename let destroy_many ~__context ~messages = List.iter (fun self -> destroy ~__context ~self) messages (* Gc the messages - leave only the number of messages defined in 'Xapi_globs.message_limit' *) let gc ~__context = let message_limit = !Xapi_globs.message_limit in if try Unix.access message_dir [Unix.F_OK] ; true with _ -> false then let allmsg = List.filter_map (fun msg -> try Some (float_of_string msg, msg) with _ -> None) (Array.to_list (Sys.readdir message_dir)) in if List.length allmsg > message_limit then ( warn "Messages have reached over the limit %d" message_limit ; let sorted = List.sort (fun (t1, _) (t2, _) -> compare t1 t2) allmsg in let n = List.length sorted in let to_reap = n - message_limit in let rec reap_one i msgs = if i = to_reap then () else ( ( try destroy_real __context (snd (List.hd msgs)) with e -> debug "Failed to destroy message %s" (snd (List.hd msgs)) ; debug "Caught exception %s" (Printexc.to_string e) ) ; reap_one (i + 1) (List.tl msgs) ) in reap_one 0 sorted ) let get_real_inner dir filter name_filter = try let allmsgs = Array.to_list (Sys.readdir dir) in let messages = List.filter name_filter allmsgs in let messages = List.filter_map (fun msg_fname -> let filename = dir ^ "/" ^ msg_fname in try let ic = open_in filename in let gen, _ref, msg = Pervasiveext.finally (fun () -> of_xml (Xmlm.make_input (`Channel ic))) (fun () -> close_in ic) in if filter msg then Some (gen, _ref, msg) else None with _ -> None ) messages in List.sort (fun (t1, _, m1) (t2, _, m2) -> let r = compare t2 t1 in if r <> 0 then r else compare (Date.to_float m2.API.message_timestamp) (Date.to_float m1.API.message_timestamp) ) messages with _ -> [] (* Message directory missing *) let since_name_filter since name = try float_of_string name > since with _ -> false let get_from_generation gen = if gen > 0L then get_real_inner (gen_symlink ()) (fun _ -> true) (fun n -> try Int64.of_string n > gen with _ -> false) else get_real_inner message_dir (fun _ -> true) (fun n -> try ignore (float_of_string n) ; true with _ -> false ) let get_real dir filter since = List.map (fun (_, r, m) -> (r, m)) (get_real_inner dir filter (since_name_filter since)) let get ~__context ~cls ~obj_uuid ~since = (* Read in all the messages for a particular object *) let class_symlink = class_symlink cls obj_uuid in if not (check_uuid ~__context ~cls ~uuid:obj_uuid) then raise (Api_errors.Server_error (Api_errors.uuid_invalid, [])) ; let msg = get_real_inner class_symlink (fun msg -> Date.to_float msg.API.message_timestamp > Date.to_float since) (fun _ -> true) in List.map (fun (_, b, c) -> (b, c)) msg let get_since ~__context ~since = get_real message_dir (fun _ -> true) (Date.to_float since) let get_since_for_events ~__context since = let cached_result = with_lock in_memory_cache_mutex (fun () -> match List.rev !in_memory_cache with | (last_in_memory, _, _) :: _ when last_in_memory < since -> Some (List.filter_map (fun (gen, _ref, msg) -> if gen > since then Some (gen, Xapi_event.Message.Create (_ref, msg)) else None ) !in_memory_cache ) | (last_in_memory, _, _) :: _ -> debug "get_since_for_events: last_in_memory (%Ld) >= since (%Ld): \ Using slow message lookup" last_in_memory since ; None | _ -> warn "get_since_for_events: no in_memory_cache!" ; None ) in let result = match cached_result with | Some x -> x | None -> List.map (fun (ts, x, y) -> (ts, Xapi_event.Message.Create (x, y))) (get_from_generation since) in let delete_results = with_lock deleted_mutex (fun () -> let deleted = List.filter (fun (deltime, _ref) -> deltime > since) !deleted in List.map (fun (ts, _ref) -> (ts, Xapi_event.Message.Del _ref)) deleted ) in let all_results = result @ delete_results in let newsince = List.fold_left (fun acc (ts, _) -> max ts acc) since all_results in (newsince, List.map snd all_results) let get_by_uuid ~__context ~uuid = try let message_filename = uuid_symlink () ^ "/" ^ uuid in let ic = open_in message_filename in let _, _ref, _ = Pervasiveext.finally (fun () -> of_xml (Xmlm.make_input (`Channel ic))) (fun () -> close_in ic) in _ref with _ -> raise (Api_errors.Server_error (Api_errors.uuid_invalid, ["message"; uuid])) let get_all ~__context = try let allmsgs = Array.to_list (Sys.readdir (ref_symlink ())) in List.map (fun r -> Ref.of_string r) allmsgs with _ -> [] let get_record ~__context ~self = try let symlinkfname = ref_symlink () ^ "/" ^ Ref.string_of self in let fullpath = Unix.readlink symlinkfname in let ic = open_in fullpath in let _, _ref, message = Pervasiveext.finally (fun () -> of_xml (Xmlm.make_input (`Channel ic))) (fun () -> close_in ic) in message with _ -> raise (Api_errors.Server_error (Api_errors.handle_invalid, ["message"; Ref.string_of self]) ) let get_all_records ~__context = get_real message_dir (fun _ -> true) 0.0 let get_all_records_where ~__context ~expr:_ = get_real message_dir (fun _ -> true) 0.0 let repopulate_cache () = with_lock in_memory_cache_mutex (fun () -> let messages = get_real_inner message_dir (fun _ -> true) (fun n -> try ignore (float_of_string n) ; true with _ -> false ) in let last_256 = Listext.List.take 256 messages in in_memory_cache := last_256 ; let get_ts (ts, _, m) = Printf.sprintf "%Ld (%s)" ts (Date.to_string m.API.message_timestamp) in debug "Constructing in-memory-cache: most length=%d" (List.length last_256) ; ( try debug "newest=%s oldest=%s" (get_ts (List.hd last_256)) (get_ts (List.hd (List.rev last_256))) with _ -> () ) ; in_memory_cache_length := List.length !in_memory_cache ) let register_event_hook () = repopulate_cache () ; Xapi_event.Message.get_since_for_events := get_since_for_events * Handler for PUTing messages to a host . Query params : { cls=<obj class > , > } Query params: { cls=<obj class>, uuid=<obj uuid> } *) let handler (req : Http.Request.t) fd _ = let query = req.Http.Request.query in req.Http.Request.close <- true ; debug "Xapi_message.handler: receiving messages" ; let check_query param = if not (List.mem_assoc param query) then ( error "Xapi_message.handler: HTTP request for message lacked %s parameter" param ; Http_svr.headers fd (Http.http_400_badrequest ()) ; failwith (Printf.sprintf "Xapi_message.handler: Missing %s parameter" param) ) in (* Check query for required params *) check_query "uuid" ; check_query "cls" ; Xapi_http.with_context ~dummy:true "Xapi_message.handler" req fd (fun __context -> try (* Redirect if we're not master *) if not (Pool_role.is_master ()) then let url = Printf.sprintf "" (Http.Url.maybe_wrap_IPv6_literal (Pool_role.get_master_address ()) ) req.Http.Request.uri (String.concat "&" (List.map (fun (a, b) -> a ^ "=" ^ b) query)) in Http_svr.headers fd (Http.http_302_redirect url) else (* Get and check query parameters *) let uuid = List.assoc "uuid" query and cls = List.assoc "cls" query in let cls = try Record_util.string_to_class cls with _ -> failwith ("Xapi_message.handler: Bad class " ^ cls) in if not (check_uuid ~__context ~cls ~uuid) then failwith ("Xapi_message.handler: Bad uuid " ^ uuid) ; (* Tell client we're good to receive *) Http_svr.headers fd (Http.http_200_ok ()) ; (* Read messages in, and write to filesystem *) let xml_in = Xmlm.make_input (`Channel (Unix.in_channel_of_descr fd)) in let messages = import_xml xml_in in List.iter (function _, r, m -> ignore (write ~__context ~_ref:r ~message:m)) messages ; (* Flush cache and reload *) repopulate_cache () with e -> error "Xapi_message.handler: caught exception '%s'" (ExnHelper.string_of_exn e) ) (* Export messages and send to another host/pool over http. *) let send_messages ~__context ~cls ~obj_uuid ~session_id ~remote_address = let msgs = get ~__context ~cls ~obj_uuid ~since:(Date.of_float 0.0) in let body = export_xml msgs in let query = [ ("session_id", Ref.string_of session_id); ("cls", "VM"); ("uuid", obj_uuid) ] in let subtask_of = Context.string_of_task __context in let request = Xapi_http.http_request ~subtask_of ~query ~body Http.Put Constants.message_put_uri in let open Xmlrpc_client in let transport = SSL (SSL.make ~verify_cert:None (), remote_address, !Constants.https_port) in with_transport transport (with_http request (fun (rsp, _) -> if rsp.Http.Response.code <> "200" then error "Error transferring messages" ) )
null
https://raw.githubusercontent.com/xapi-project/xen-api/48cc1489fff0e344246ecf19fc1ebed6f09c7471/ocaml/xapi/xapi_message.ml
ocaml
* Module that defines API functions for Message objects * @group XenAPI functions * Message store We use a filesystem based 'database': * Base directory: /var/lib/xcp/blobs/messages * All messages go in there, filename=timestamp * * Symlinks are created to the messages for fast indexing: * /var/lib/xcp/blobs/messages/VM/<uuid>/<timestamp> -> message * /var/lib/xcp/blobs/messages/uuid/<message uuid> -> message * /var/lib/xcp/blobs/messages/ref/<message ref> -> message We use the timestamp to name the file. For consistency, use this function ************ Marshalling/unmarshalling functions *********** let i = Xmlm.make_input (`String (0, xml)) in ********* Symlink functions ************ * Returns a list of tuples - (directory, filename) ****************************************************************** * Write: write message to disk. Returns boolean indicating whether message was written Check if a message with _ref has already been written Set file's timestamp to message timestamp We may be copying messages from another pool, in which case we may have filename collision (unlikely, but possible). So increment the filename and try again, but leave the original timestamp in the message untouched. Write the message to file Message now written, let's symlink it in various places Insert a written message into in_memory_cache Emit a create event (with the old event API). If the message hasn't been written, we may want to also emit a del even, for consistency (since the reference for the message will never be valid again. Xapi_event.event_add ~snapshot:xml "message" "del" (Ref.string_of _ref); * create: Create a new message, and write to disk. Returns null ref if write failed, or message ref otherwise. During rolling upgrade, upgraded master might have a alerts grading system different from the not yet upgraded slaves, during that process we transform the priority of received messages as a special case. Write the message to disk Return the message ref, or Ref.null if the message wasn't written Find the original message so we know where the symlinks will be Gc the messages - leave only the number of messages defined in 'Xapi_globs.message_limit' Message directory missing Read in all the messages for a particular object Check query for required params Redirect if we're not master Get and check query parameters Tell client we're good to receive Read messages in, and write to filesystem Flush cache and reload Export messages and send to another host/pool over http.
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) 2006-2009 Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) module Date = Xapi_stdext_date.Date module Encodings = Xapi_stdext_encodings.Encodings module Listext = Xapi_stdext_std.Listext module Pervasiveext = Xapi_stdext_pervasives.Pervasiveext module Unixext = Xapi_stdext_unix.Unixext let with_lock = Xapi_stdext_threads.Threadext.Mutex.execute module D = Debug.Make (struct let name = "xapi_message" end) open D let message_dir = Xapi_globs.xapi_blob_location ^ "/messages" let event_mutex = Mutex.create () let in_memory_cache = ref [] let in_memory_cache_mutex = Mutex.create () let in_memory_cache_length = ref 0 let in_memory_cache_length_max = 512 let in_memory_cache_length_default = 256 let timestamp_to_string f = Printf.sprintf "%0.5f" f let to_xml output _ref gen message = let tag n next () = Xmlm.output output (`El_start (("", n), [])) ; List.iter (fun x -> x ()) next ; Xmlm.output output `El_end in let data dat () = Xmlm.output output (`Data dat) in Xmlm.output output (`Dtd None) ; let message_subtags = [ tag "ref" [data (Ref.string_of _ref)] ; tag "name" [data message.API.message_name] ; tag "priority" [data (Int64.to_string message.API.message_priority)] ; tag "cls" [data (Record_util.class_to_string message.API.message_cls)] ; tag "obj_uuid" [data message.API.message_obj_uuid] ; tag "timestamp" [data (Date.to_string message.API.message_timestamp)] ; tag "uuid" [data message.API.message_uuid] ; tag "body" [data message.API.message_body] ] in let message_subtags = match gen with | Some g -> tag "generation" [data (Int64.to_string g)] :: message_subtags | None -> message_subtags in tag "message" message_subtags () let of_xml input = let current_elt = ref "" in let message = ref { API.message_name= "" ; API.message_priority= 0L ; API.message_cls= `VM ; API.message_obj_uuid= "" ; API.message_timestamp= Date.never ; API.message_body= "" ; API.message_uuid= "" } in let _ref = ref "" in let gen = ref 0L in let rec f () = match Xmlm.input input with | `El_start ((_, tag), _) -> current_elt := tag ; f () | `El_end -> current_elt := "" ; if Xmlm.eoi input then () else f () | `Data dat -> ( match !current_elt with | "name" -> message := {!message with API.message_name= dat} | "priority" -> message := {!message with API.message_priority= Int64.of_string dat} | "cls" -> message := {!message with API.message_cls= Record_util.string_to_class dat} | "obj_uuid" -> message := {!message with API.message_obj_uuid= dat} | "timestamp" -> message := {!message with API.message_timestamp= Date.of_string dat} | "uuid" -> message := {!message with API.message_uuid= dat} | "body" -> message := {!message with API.message_body= dat} | "generation" -> gen := Int64.of_string dat | "ref" -> _ref := dat | _ -> failwith "Bad XML!" ) ; f () | `Dtd _ -> f () in try f () ; (!gen, Ref.of_string !_ref, !message) with e -> Backtrace.is_important e ; raise e let export_xml messages = let size = 500 * List.length messages in let buf = Buffer.create size in let output = Xmlm.make_output (`Buffer buf) in List.iter (function r, m -> to_xml output r None m) messages ; Buffer.contents buf let import_xml xml_in = let split_xml = let ob = Buffer.create 600 in let o = Xmlm.make_output (`Buffer ob) in let rec pull xml_in o depth = Xmlm.output o (Xmlm.peek xml_in) ; match Xmlm.input xml_in with | `El_start _ -> pull xml_in o (depth + 1) | `El_end -> if depth = 1 then () else pull xml_in o (depth - 1) | `Data _ -> pull xml_in o depth | `Dtd _ -> pull xml_in o depth in let out = ref [] in while not (Xmlm.eoi xml_in) do pull xml_in o 0 ; out := Buffer.contents ob :: !out ; Buffer.clear ob done ; !out in let rec loop = function | [] -> [] | m :: ms -> let im = Xmlm.make_input (`String (0, m)) in of_xml im :: loop ms in loop split_xml let class_symlink cls obj_uuid = let strcls = Record_util.class_to_string cls in Printf.sprintf "%s/%s/%s" message_dir strcls obj_uuid let uuid_symlink () = Printf.sprintf "%s/uuids" message_dir let ref_symlink () = Printf.sprintf "%s/refs" message_dir let gen_symlink () = Printf.sprintf "%s/gen" message_dir let symlinks _ref gen message basefilename = let symlinks = [ (class_symlink message.API.message_cls message.API.message_obj_uuid, None) ; (uuid_symlink (), Some message.API.message_uuid) ; (ref_symlink (), Some (Ref.string_of _ref)) ] in let symlinks = match gen with | Some gen -> (gen_symlink (), Some (Int64.to_string gen)) :: symlinks | None -> symlinks in List.map (fun (dir, fnameopt) -> let newfname = match fnameopt with None -> basefilename | Some f -> f in (dir, dir ^ "/" ^ newfname) ) symlinks * Check to see if the UUID is valid . This should not use get_by_uuid as this causes spurious exceptions to be logged ... this causes spurious exceptions to be logged... *) let check_uuid ~__context ~cls ~uuid = try ( match cls with | `VM -> ignore (Db.VM.get_by_uuid ~__context ~uuid) | `Host -> ignore (Db.Host.get_by_uuid ~__context ~uuid) | `SR -> ignore (Db.SR.get_by_uuid ~__context ~uuid) | `Pool -> ignore (Db.Pool.get_by_uuid ~__context ~uuid) | `VMPP -> ignore (Db.VMPP.get_by_uuid ~__context ~uuid) | `VMSS -> ignore (Db.VMSS.get_by_uuid ~__context ~uuid) | `PVS_proxy -> ignore (Db.PVS_proxy.get_by_uuid ~__context ~uuid) | `VDI -> ignore (Db.VDI.get_by_uuid ~__context ~uuid) | `Certificate -> ignore (Db.Certificate.get_by_uuid ~__context ~uuid) ) ; true with _ -> false * * * * * * * * * * Thread_queue to exec the message script hook * * * * * * * * * * let queue_push = ref (fun (_ : string) (_ : string) -> false) let message_to_string (_ref, message) = let buffer = Buffer.create 10 in let output = Xmlm.make_output (`Buffer buffer) in to_xml output _ref None message ; Buffer.contents buffer let handle_message ~__context message = try if not (Pool_features.is_enabled ~__context Features.Email) then info "Email alerting is restricted by current license: not generating email" else if Sys.file_exists !Xapi_globs.xapi_message_script then let output, log = Forkhelpers.execute_command_get_output !Xapi_globs.xapi_message_script [message] in debug "Executed message hook: output='%s' log='%s'" output log else info "%s not found, skipping" !Xapi_globs.xapi_message_script with e -> error "Unexpected exception in message hook %s: %s" !Xapi_globs.xapi_message_script (ExnHelper.string_of_exn e) let start_message_hook_thread ~__context () = queue_push := (Thread_queue.make ~name:"email message queue" ~max_q_length:100 (handle_message ~__context) ) .Thread_queue.push_fn let cache_insert _ref message gen = with_lock in_memory_cache_mutex (fun () -> in_memory_cache := (gen, _ref, message) :: !in_memory_cache ; in_memory_cache_length := !in_memory_cache_length + 1 ; if !in_memory_cache_length > in_memory_cache_length_max then ( in_memory_cache := Listext.List.take in_memory_cache_length_default !in_memory_cache ; in_memory_cache_length := in_memory_cache_length_default ; debug "Pruning in-memory cache of messages: Length=%d (%d)" !in_memory_cache_length (List.length !in_memory_cache) ) ) let cache_remove _ref = with_lock in_memory_cache_mutex (fun () -> let to_delete, to_keep = List.partition (function _, _ref', _ -> _ref' = _ref) !in_memory_cache in if List.length to_delete > 1 then error "Internal error: Repeated reference in messages in_memory_cache" ; in_memory_cache := to_keep ; in_memory_cache_length := List.length to_keep ) let write ~__context ~_ref ~message = let message_exists () = let file = ref_symlink () ^ "/" ^ Ref.string_of _ref in try Unix.access file [Unix.F_OK] ; true with _ -> false in let message_gen () = let fn = ref_symlink () ^ "/" ^ Ref.string_of _ref in let ic = open_in fn in let xi = Xmlm.make_input (`Channel ic) in let gen, _, _ = Pervasiveext.finally (fun () -> of_xml xi) (fun () -> close_in ic) in gen in let gen = ref 0L in Db_lock.with_lock (fun () -> let t = Context.database_of __context in Db_ref.update_database t (fun db -> gen := Db_cache_types.Manifest.generation (Db_cache_types.Database.manifest db) ; Db_cache_types.Database.increment db ) ) ; Unixext.mkdir_rec message_dir 0o700 ; let timestamp = ref (Date.to_float message.API.message_timestamp) in if message_exists () then Some (message_gen ()) else try with_lock event_mutex (fun () -> let fd, basefilename, filename = Try 10 , no wait , 11 times to create message file let rec doit n = if n > 10 then failwith "Couldn't create a file" else let basefilename = timestamp_to_string !timestamp in let filename = message_dir ^ "/" ^ basefilename in try let fd = Unix.openfile filename [Unix.O_RDWR; Unix.O_CREAT; Unix.O_EXCL] 0o600 in Unix.utimes filename !timestamp !timestamp ; (fd, basefilename, filename) with _ -> timestamp := !timestamp +. 0.00001 ; doit (n + 1) in doit 0 in let oc = Unix.out_channel_of_descr fd in let output = Xmlm.make_output (`Channel oc) in to_xml output _ref (Some !gen) message ; close_out oc ; let symlinks = symlinks _ref (Some !gen) message basefilename in List.iter (fun (dir, newpath) -> Unixext.mkdir_rec dir 0o700 ; Unix.symlink filename newpath ) symlinks ; cache_insert _ref message !gen ; let rpc = API.rpc_of_message_t message in Xapi_event.event_add ~snapshot:rpc "message" "add" (Ref.string_of _ref) ; let (_ : bool) = !queue_push message.API.message_name (message_to_string (_ref, message)) in Some !gen ) with _ -> None let create ~__context ~name ~priority ~cls ~obj_uuid ~body = debug "Message.create %s %Ld %s %s" name priority (Record_util.class_to_string cls) obj_uuid ; if not (Encodings.UTF8_XML.is_valid body) then raise (Api_errors.Server_error (Api_errors.invalid_value, ["UTF8 expected"])) ; if not (check_uuid ~__context ~cls ~uuid:obj_uuid) then raise (Api_errors.Server_error (Api_errors.uuid_invalid, [Record_util.class_to_string cls; obj_uuid]) ) ; let _ref = Ref.make () in let uuid = Uuidx.to_string (Uuidx.make ()) in let timestamp = with_lock event_mutex (fun () -> Unix.gettimeofday ()) in let priority = if Helpers.rolling_upgrade_in_progress ~__context && List.mem_assoc name !Api_messages.msgList then List.assoc name !Api_messages.msgList else priority in let message = { API.message_name= name ; API.message_uuid= uuid ; API.message_priority= priority ; API.message_cls= cls ; API.message_obj_uuid= obj_uuid ; API.message_timestamp= Date.of_float timestamp ; API.message_body= body } in let gen = write ~__context ~_ref ~message in match gen with Some _ -> _ref | None -> Ref.null let deleted : (Generation.t * API.ref_message) list ref = ref [(0L, Ref.null)] let ndeleted = ref 1 let deleted_mutex = Mutex.create () let destroy_real __context basefilename = let filename = message_dir ^ "/" ^ basefilename in let ic = open_in filename in let gen, _ref, message = Pervasiveext.finally (fun () -> of_xml (Xmlm.make_input (`Channel ic))) (fun () -> close_in ic) in let symlinks = symlinks _ref (Some gen) message basefilename in List.iter (fun (_, newpath) -> Unixext.unlink_safe newpath) symlinks ; Unixext.unlink_safe filename ; let rpc = API.rpc_of_message_t message in let gen = ref 0L in Db_lock.with_lock (fun () -> let t = Context.database_of __context in Db_ref.update_database t (fun db -> gen := Db_cache_types.Manifest.generation (Db_cache_types.Database.manifest db) ; Db_cache_types.Database.increment db ) ) ; with_lock event_mutex (fun () -> deleted := (!gen, _ref) :: !deleted ; ndeleted := !ndeleted + 1 ; if !ndeleted > 1024 then ( deleted := Listext.List.take 512 !deleted ; ndeleted := 512 ) ) ; cache_remove _ref ; Xapi_event.event_add ~snapshot:rpc "message" "del" (Ref.string_of _ref) let destroy ~__context ~self = let symlinkfname = ref_symlink () ^ "/" ^ Ref.string_of self in let fullpath = try Unix.readlink symlinkfname with _ -> ( let allfiles = List.map (fun file -> message_dir ^ "/" ^ file) (Array.to_list (Sys.readdir message_dir)) in let allmsgs = List.filter (fun file -> not (Sys.is_directory file)) allfiles in try List.find (fun msg_fname -> try let ic = open_in msg_fname in let _, _ref, _ = Pervasiveext.finally (fun () -> of_xml (Xmlm.make_input (`Channel ic))) (fun () -> close_in ic) in if _ref = self then true else false with _ -> false ) allmsgs with _ -> raise (Api_errors.Server_error ( Api_errors.handle_invalid , [Datamodel_common._message; Ref.string_of self] ) ) ) in let basefilename = List.hd (List.rev (String.split_on_char '/' fullpath)) in destroy_real __context basefilename let destroy_many ~__context ~messages = List.iter (fun self -> destroy ~__context ~self) messages let gc ~__context = let message_limit = !Xapi_globs.message_limit in if try Unix.access message_dir [Unix.F_OK] ; true with _ -> false then let allmsg = List.filter_map (fun msg -> try Some (float_of_string msg, msg) with _ -> None) (Array.to_list (Sys.readdir message_dir)) in if List.length allmsg > message_limit then ( warn "Messages have reached over the limit %d" message_limit ; let sorted = List.sort (fun (t1, _) (t2, _) -> compare t1 t2) allmsg in let n = List.length sorted in let to_reap = n - message_limit in let rec reap_one i msgs = if i = to_reap then () else ( ( try destroy_real __context (snd (List.hd msgs)) with e -> debug "Failed to destroy message %s" (snd (List.hd msgs)) ; debug "Caught exception %s" (Printexc.to_string e) ) ; reap_one (i + 1) (List.tl msgs) ) in reap_one 0 sorted ) let get_real_inner dir filter name_filter = try let allmsgs = Array.to_list (Sys.readdir dir) in let messages = List.filter name_filter allmsgs in let messages = List.filter_map (fun msg_fname -> let filename = dir ^ "/" ^ msg_fname in try let ic = open_in filename in let gen, _ref, msg = Pervasiveext.finally (fun () -> of_xml (Xmlm.make_input (`Channel ic))) (fun () -> close_in ic) in if filter msg then Some (gen, _ref, msg) else None with _ -> None ) messages in List.sort (fun (t1, _, m1) (t2, _, m2) -> let r = compare t2 t1 in if r <> 0 then r else compare (Date.to_float m2.API.message_timestamp) (Date.to_float m1.API.message_timestamp) ) messages with _ -> [] let since_name_filter since name = try float_of_string name > since with _ -> false let get_from_generation gen = if gen > 0L then get_real_inner (gen_symlink ()) (fun _ -> true) (fun n -> try Int64.of_string n > gen with _ -> false) else get_real_inner message_dir (fun _ -> true) (fun n -> try ignore (float_of_string n) ; true with _ -> false ) let get_real dir filter since = List.map (fun (_, r, m) -> (r, m)) (get_real_inner dir filter (since_name_filter since)) let get ~__context ~cls ~obj_uuid ~since = let class_symlink = class_symlink cls obj_uuid in if not (check_uuid ~__context ~cls ~uuid:obj_uuid) then raise (Api_errors.Server_error (Api_errors.uuid_invalid, [])) ; let msg = get_real_inner class_symlink (fun msg -> Date.to_float msg.API.message_timestamp > Date.to_float since) (fun _ -> true) in List.map (fun (_, b, c) -> (b, c)) msg let get_since ~__context ~since = get_real message_dir (fun _ -> true) (Date.to_float since) let get_since_for_events ~__context since = let cached_result = with_lock in_memory_cache_mutex (fun () -> match List.rev !in_memory_cache with | (last_in_memory, _, _) :: _ when last_in_memory < since -> Some (List.filter_map (fun (gen, _ref, msg) -> if gen > since then Some (gen, Xapi_event.Message.Create (_ref, msg)) else None ) !in_memory_cache ) | (last_in_memory, _, _) :: _ -> debug "get_since_for_events: last_in_memory (%Ld) >= since (%Ld): \ Using slow message lookup" last_in_memory since ; None | _ -> warn "get_since_for_events: no in_memory_cache!" ; None ) in let result = match cached_result with | Some x -> x | None -> List.map (fun (ts, x, y) -> (ts, Xapi_event.Message.Create (x, y))) (get_from_generation since) in let delete_results = with_lock deleted_mutex (fun () -> let deleted = List.filter (fun (deltime, _ref) -> deltime > since) !deleted in List.map (fun (ts, _ref) -> (ts, Xapi_event.Message.Del _ref)) deleted ) in let all_results = result @ delete_results in let newsince = List.fold_left (fun acc (ts, _) -> max ts acc) since all_results in (newsince, List.map snd all_results) let get_by_uuid ~__context ~uuid = try let message_filename = uuid_symlink () ^ "/" ^ uuid in let ic = open_in message_filename in let _, _ref, _ = Pervasiveext.finally (fun () -> of_xml (Xmlm.make_input (`Channel ic))) (fun () -> close_in ic) in _ref with _ -> raise (Api_errors.Server_error (Api_errors.uuid_invalid, ["message"; uuid])) let get_all ~__context = try let allmsgs = Array.to_list (Sys.readdir (ref_symlink ())) in List.map (fun r -> Ref.of_string r) allmsgs with _ -> [] let get_record ~__context ~self = try let symlinkfname = ref_symlink () ^ "/" ^ Ref.string_of self in let fullpath = Unix.readlink symlinkfname in let ic = open_in fullpath in let _, _ref, message = Pervasiveext.finally (fun () -> of_xml (Xmlm.make_input (`Channel ic))) (fun () -> close_in ic) in message with _ -> raise (Api_errors.Server_error (Api_errors.handle_invalid, ["message"; Ref.string_of self]) ) let get_all_records ~__context = get_real message_dir (fun _ -> true) 0.0 let get_all_records_where ~__context ~expr:_ = get_real message_dir (fun _ -> true) 0.0 let repopulate_cache () = with_lock in_memory_cache_mutex (fun () -> let messages = get_real_inner message_dir (fun _ -> true) (fun n -> try ignore (float_of_string n) ; true with _ -> false ) in let last_256 = Listext.List.take 256 messages in in_memory_cache := last_256 ; let get_ts (ts, _, m) = Printf.sprintf "%Ld (%s)" ts (Date.to_string m.API.message_timestamp) in debug "Constructing in-memory-cache: most length=%d" (List.length last_256) ; ( try debug "newest=%s oldest=%s" (get_ts (List.hd last_256)) (get_ts (List.hd (List.rev last_256))) with _ -> () ) ; in_memory_cache_length := List.length !in_memory_cache ) let register_event_hook () = repopulate_cache () ; Xapi_event.Message.get_since_for_events := get_since_for_events * Handler for PUTing messages to a host . Query params : { cls=<obj class > , > } Query params: { cls=<obj class>, uuid=<obj uuid> } *) let handler (req : Http.Request.t) fd _ = let query = req.Http.Request.query in req.Http.Request.close <- true ; debug "Xapi_message.handler: receiving messages" ; let check_query param = if not (List.mem_assoc param query) then ( error "Xapi_message.handler: HTTP request for message lacked %s parameter" param ; Http_svr.headers fd (Http.http_400_badrequest ()) ; failwith (Printf.sprintf "Xapi_message.handler: Missing %s parameter" param) ) in check_query "uuid" ; check_query "cls" ; Xapi_http.with_context ~dummy:true "Xapi_message.handler" req fd (fun __context -> try if not (Pool_role.is_master ()) then let url = Printf.sprintf "" (Http.Url.maybe_wrap_IPv6_literal (Pool_role.get_master_address ()) ) req.Http.Request.uri (String.concat "&" (List.map (fun (a, b) -> a ^ "=" ^ b) query)) in Http_svr.headers fd (Http.http_302_redirect url) let uuid = List.assoc "uuid" query and cls = List.assoc "cls" query in let cls = try Record_util.string_to_class cls with _ -> failwith ("Xapi_message.handler: Bad class " ^ cls) in if not (check_uuid ~__context ~cls ~uuid) then failwith ("Xapi_message.handler: Bad uuid " ^ uuid) ; Http_svr.headers fd (Http.http_200_ok ()) ; let xml_in = Xmlm.make_input (`Channel (Unix.in_channel_of_descr fd)) in let messages = import_xml xml_in in List.iter (function _, r, m -> ignore (write ~__context ~_ref:r ~message:m)) messages ; repopulate_cache () with e -> error "Xapi_message.handler: caught exception '%s'" (ExnHelper.string_of_exn e) ) let send_messages ~__context ~cls ~obj_uuid ~session_id ~remote_address = let msgs = get ~__context ~cls ~obj_uuid ~since:(Date.of_float 0.0) in let body = export_xml msgs in let query = [ ("session_id", Ref.string_of session_id); ("cls", "VM"); ("uuid", obj_uuid) ] in let subtask_of = Context.string_of_task __context in let request = Xapi_http.http_request ~subtask_of ~query ~body Http.Put Constants.message_put_uri in let open Xmlrpc_client in let transport = SSL (SSL.make ~verify_cert:None (), remote_address, !Constants.https_port) in with_transport transport (with_http request (fun (rsp, _) -> if rsp.Http.Response.code <> "200" then error "Error transferring messages" ) )
dbdf1e9f4c17d6a255a44b81b2eafb61536775808403b70a0afa183f1b955aac
herd/herdtools7
CParseTest.mli
(****************************************************************************) (* the diy toolsuite *) (* *) , University College London , UK . , INRIA Paris - Rocquencourt , France . (* *) Copyright 2023 - present Institut National de Recherche en Informatique et (* en Automatique and the authors. All rights reserved. *) (* *) This software is governed by the CeCILL - B license under French law and (* abiding by the rules of distribution of free software. You can use, *) modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . (****************************************************************************) module Make : functor(Conf:RunTest.Config) -> functor(ModelConfig:CMem.Config) -> sig val run : RunTest.runfun end
null
https://raw.githubusercontent.com/herd/herdtools7/574c59e111deda09afbba1f2bdd94353f437faaf/herd/CParseTest.mli
ocaml
************************************************************************** the diy toolsuite en Automatique and the authors. All rights reserved. abiding by the rules of distribution of free software. You can use, **************************************************************************
, University College London , UK . , INRIA Paris - Rocquencourt , France . Copyright 2023 - present Institut National de Recherche en Informatique et This software is governed by the CeCILL - B license under French law and modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . module Make : functor(Conf:RunTest.Config) -> functor(ModelConfig:CMem.Config) -> sig val run : RunTest.runfun end
bcd97b91c7d699da5fb592ec47c9fe5a4b542e1d309e923da2da5688508a701d
bobzhang/fan
fors.ml
for a = 3 to 10 do let u = 4; print_int a; print_int u; done; let a = ref 3; while !a >0 do let u = 3; decr a; print_int u; print_newline (); done;
null
https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/todoml/testr/fors.ml
ocaml
for a = 3 to 10 do let u = 4; print_int a; print_int u; done; let a = ref 3; while !a >0 do let u = 3; decr a; print_int u; print_newline (); done;
9782ca7cfe38af500f9657ffb8dfb5ee07af5f32431dbab57321c93f37156404
elastic/eui-cljs
icon_pause.cljs
(ns eui.icon-pause (:require ["@elastic/eui/lib/components/icon/assets/pause.js" :as eui])) (def pause eui/icon)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/icon_pause.cljs
clojure
(ns eui.icon-pause (:require ["@elastic/eui/lib/components/icon/assets/pause.js" :as eui])) (def pause eui/icon)
445aab171afdf312e923ca013796ae3a00f0d745b446a69d7288971342a692d1
zeniuseducation/poly-euler
five.clj
(ns alfa.five (:require [clojure.string :as cs] [alfa.common :refer :all] [clojure.set :refer [intersection difference]])) (defn run [f & args] (dotimes [i 5] (let [res (time (apply f args))] (println res)))) (defn ^long p50 [^long lim] (let [refs (boolean-array lim true) llim (inc (int (Math/sqrt lim))) primes (sieve lim)] (loop [i (int 2)] (if (aget refs i) (when (<= i llim) (do (loop [j (int (* i i))] (when (< j lim) (aset refs j false) (recur (+ j i)))) (recur (+ i 1)))) (recur (+ i 1)))) (->> primes (iterate rest) (take-while not-empty) (mapcat #(->> (iterate butlast %) (take-while not-empty) (keep (fn [x] (let [res (reduce + x)] (when (< res lim) [(count x) res])))))) (filter #(aget refs (second %))) (apply max-key first))))
null
https://raw.githubusercontent.com/zeniuseducation/poly-euler/734fdcf1ddd096a8730600b684bf7398d071d499/Alfa/src/alfa/five.clj
clojure
(ns alfa.five (:require [clojure.string :as cs] [alfa.common :refer :all] [clojure.set :refer [intersection difference]])) (defn run [f & args] (dotimes [i 5] (let [res (time (apply f args))] (println res)))) (defn ^long p50 [^long lim] (let [refs (boolean-array lim true) llim (inc (int (Math/sqrt lim))) primes (sieve lim)] (loop [i (int 2)] (if (aget refs i) (when (<= i llim) (do (loop [j (int (* i i))] (when (< j lim) (aset refs j false) (recur (+ j i)))) (recur (+ i 1)))) (recur (+ i 1)))) (->> primes (iterate rest) (take-while not-empty) (mapcat #(->> (iterate butlast %) (take-while not-empty) (keep (fn [x] (let [res (reduce + x)] (when (< res lim) [(count x) res])))))) (filter #(aget refs (second %))) (apply max-key first))))
0781c57ce79526179644a03e54221133384ef0c98594e010f36f0c9458e4ecd3
yav/hobbit
Ents.hs
module ModSys.Ents ( Entity(..),owns,isCon -- for module system (only need Entity type) , EntType(..), origName, isType -- for compiler ) where import AST.Type import qualified Data.Set as Set -- interface of the module system to the concrete type of entities data Entity = Entity { definedIn :: ModName , name :: Name , entType :: EntType } deriving Eq data EntType = Value | Constr | Type (Set.Set Entity) owns e = case entType e of Type cs -> cs _ -> Set.empty isCon e = case entType e of Constr -> True _ -> False isType e = case entType e of Type _ -> True _ -> False instance Show EntType where show Value = "V" show Constr = "C" show (Type _) = "T" instance Eq EntType where x == y = compare x y == EQ instance Ord EntType where compare Value Value = EQ compare Constr Constr = EQ compare (Type _) (Type _) = EQ compare Value _ = LT compare (Type _) _ = GT compare Constr y = compare y Constr instance Show Entity where + + " ( " + + show ( entType x ) + + " ) " instance Ord Entity where compare e1 e2 = case compare (definedIn e1) (definedIn e2) of LT -> LT EQ -> case compare (name e1) (name e2) of LT -> LT EQ -> compare (entType e1) (entType e2) GT -> GT GT -> GT origName :: Entity -> Name origName e = Qual (definedIn e) (name e)
null
https://raw.githubusercontent.com/yav/hobbit/31414ba1188f4b39620c2553b45b9e4d4aa40169/src/ModSys/Ents.hs
haskell
for module system (only need Entity type) for compiler interface of the module system to the concrete type of entities
module ModSys.Ents ) where import AST.Type import qualified Data.Set as Set data Entity = Entity { definedIn :: ModName , name :: Name , entType :: EntType } deriving Eq data EntType = Value | Constr | Type (Set.Set Entity) owns e = case entType e of Type cs -> cs _ -> Set.empty isCon e = case entType e of Constr -> True _ -> False isType e = case entType e of Type _ -> True _ -> False instance Show EntType where show Value = "V" show Constr = "C" show (Type _) = "T" instance Eq EntType where x == y = compare x y == EQ instance Ord EntType where compare Value Value = EQ compare Constr Constr = EQ compare (Type _) (Type _) = EQ compare Value _ = LT compare (Type _) _ = GT compare Constr y = compare y Constr instance Show Entity where + + " ( " + + show ( entType x ) + + " ) " instance Ord Entity where compare e1 e2 = case compare (definedIn e1) (definedIn e2) of LT -> LT EQ -> case compare (name e1) (name e2) of LT -> LT EQ -> compare (entType e1) (entType e2) GT -> GT GT -> GT origName :: Entity -> Name origName e = Qual (definedIn e) (name e)
57399d1521d1344298ab25e342cefc308cdc06f832f464225c9ef63859e06afb
cac-t-u-s/om-sharp
midi-out.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ; ;============================================================================ File author : ;============================================================================ (in-package :om) ;=================== PITCHBEND & PITCHWHEEL ;=================== (defmethod* pitchwheel ((val number) (chans number) &optional port) :icon :midi-out :indoc '("pitch wheel value(s)" "MIDI channel(s) (1-16)" "output port number") :initvals '(8192 1 nil) :doc "Sends one or more MIDI pitch wheel message(s) of <vals> in the MIDI channel(s) <chans>. <values> and <chans> can be single numbers or lists. The range of pitch wheel is between 0 and 16383 (inclusive). 8192 (default) means no bend. " (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :PitchBend :chan chans :port aport :fields (val2lsbmsb val)))) (om-midi::midi-send-evt event) ))) (defmethod* pitchwheel ((vals number) (chans list) &optional port) (loop for item in chans do (pitchwheel vals item port))) (defmethod* pitchwheel ((vals list) (chans list) &optional port) (loop for item in chans for item1 in vals do (pitchwheel item1 item port))) (defmethod* pitchwheel ((vals list) (chans number) &optional port) (loop for chan from chans for val in vals do (pitchwheel val chan port))) (defmethod* pitchbend ((val number) (chan number) &optional port) :icon :midi-out :indoc '("pitch bend value(s)" "MIDI channel(s) (1-16)" "output port number") :initvals '(64 1 nil) :doc "Sends one or more MIDI pitch bend message(s) of <vals> in the MIDI channel(s) <chans>. <values> and <chans> can be single numbers or lists. The range of pitch bend is between 0 and 127. 64 (default) means no bend. [COMPATIBILITY: PITCHBEND strictly equivalent to PITCHWHEEL with less precision.] " (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :PitchBend :chan chan :port aport :fields (list 0 val)))) (om-midi::midi-send-evt event) ))) (defmethod* pitchbend ((vals number) (chans list) &optional port) (loop for item in chans do (pitchbend vals item port))) (defmethod* pitchbend ((vals list) (chans list) &optional port) (loop for item in chans for item1 in vals do (pitchbend item1 item port))) ;=================== ; PROGRAM CHANGE ;=================== (defmethod* pgmout ((progm integer) (chans integer) &optional port) :icon :midi-out :indoc '("program number" "MIDI channel(s)" "output port number") :initvals '(2 1 nil) :doc "Sends a program change event with program number <progm> to channel(s) <chans>. <progm> and <chans> can be single numbers or lists." (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :ProgChange :chan chans :port aport :fields (list progm)))) (when event (om-midi::midi-send-evt event) t)))) (defmethod* pgmout ((progm number) (chans list) &optional port) (loop for item in chans do (pgmout progm item port))) (defmethod* pgmout ((progm list) (chans list) &optional port) (if (or (null port) (integerp port)) (loop for item in chans for item1 in progm do (pgmout item1 item port)) (loop for item in chans for item1 in progm for item2 in port do (pgmout item1 item item2)))) ;=================== ; POLY KEY PRESSURE ;=================== (defmethod* polyKeypres ((val integer) (pitch integer) (chans integer) &optional port) :icon :midi-out :indoc '("pressure value" "target pitch" "MIDI channel (1-16)" "output port number") :initvals '(100 6000 1 nil) :doc " Sends a key pressure event with pressure <values> and <pitch> on channel <cahns> and port <port>. Arguments can be single numbers or lists. " (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :KeyPress :chan chans :port aport :fields (list (round pitch 100) val)))) (when event (om-midi::midi-send-evt event))) )) (defmethod* polyKeypres ((vals list) (pitch list) (chans list) &optional port) (loop for item in pitch for val in vals for chan in chans do (polyKeypres val item chan port))) (defmethod* polyKeypres ((val integer) (pitch list) (chans integer) &optional port) (loop for item in pitch do (polyKeypres val item chans port))) (defmethod* polyKeypres ((val integer) (pitch list) (chans list) &optional port) (loop for item in pitch for chan in chans do (polyKeypres val item chan port))) (defmethod* polyKeypres ((vals list) (pitch integer) (chans list) &optional port) (loop for val in vals for chan in chans do (polyKeypres val pitch chan port))) (defmethod* polyKeypres ((vals list) (pitch integer) (chans integer) &optional port) (loop for val in vals do (polyKeypres val pitch chans port))) (defmethod* polyKeypres ((vals list) (pitch list) (chans integer) &optional port) (loop for item in pitch for val in vals do (polyKeypres val item chans port))) ;=================== ; AFTER TOUCH ;=================== (defmethod* aftertouch ((val integer) (chans integer) &optional port) :icon :midi-out :indoc '("pressurev value" "MIDI channel (1-16)" "output port number") :initvals '(100 1 nil) :doc "Sends an after touch event of <val> to channel <chans> and port <port>. Arguments can be can be single numbers or lists. " (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :ChanPress :chan chans :port aport :fields (list val)))) (when event (om-midi::midi-send-evt event))) )) (defmethod* aftertouch ((vals number) (chans list) &optional port) (loop for item in chans do (aftertouch vals item port))) (defmethod* aftertouch ((vals list) (chans list) &optional port) (if (or (null port) (integerp port)) (loop for item in vals for val in chans do (aftertouch item val port)) (loop for item in vals for val in chans for item2 in port do (aftertouch item val item2)))) ;=================== ; CONTROL CHANGE ;=================== (defmethod* ctrlchg ((ctrlnum integer) (val integer) (chans integer) &optional port) :icon :midi-out :indoc '("control number" "value" "MIDI channel (1-16)" "output port number") :initvals '(7 100 1 nil) :doc "Sends a control change event with control number <ctrlnum> and value <val> to channel <chans> (and port <port>)." (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan chans :port aport :fields (list ctrlnum val)))) (when event (om-midi::midi-send-evt event))))) (defmethod* ctrlchg ((ctrlnum integer) (val integer) (chans list) &optional port) (loop for item in chans do (ctrlchg ctrlnum val item port))) (defmethod* ctrlchg ((ctrlnum list) (val list) (chans list) &optional port) (loop for ctrl in ctrlnum for item in chans for aval in val do (ctrlchg ctrl aval item port))) (defmethod* ctrlchg ((ctrlnum list) (val list) (chans integer) &optional port) (loop for ctrl in ctrlnum for aval in val do (ctrlchg ctrl aval chans port))) (defmethod* ctrlchg ((ctrlnum list) (val integer) (chans integer) &optional port) (loop for ctrl in ctrlnum do (ctrlchg ctrl val chans port))) (defmethod* ctrlchg ((ctrlnum list) (val integer) (chans list) &optional port) (loop for ctrl in ctrlnum for item in chans do (ctrlchg ctrl val item port))) (defmethod* ctrlchg ((ctrlnum integer) (val list) (chans list) &optional port) (loop for item in chans for aval in val do (ctrlchg ctrlnum aval item port))) ;=================== ; VOLUME ;=================== (defmethod* volume ((vol integer) (chans integer) &optional port) :icon :midi-out :indoc '("value" "MIDI channel (1-16)" "output port number") :initvals '(100 1 nil) :doc "Sends MIDI volume message(s) to channel(s) <chans> and port <port>. Arguments can be numbers or lists. The range of volume values is 0-127. " (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan chans :port aport :fields (list 7 vol)))) (when event (om-midi::midi-send-evt event))))) (defmethod* volume ((volume number) (chans list) &optional port) (loop for item in chans do (volume volume item port))) (defmethod* volume ((volume list) (chans list) &optional port) (if (or (null port) (integerp port)) (loop for item in volume for val in chans do (volume item val port)) (loop for item in volume for val in chans for item2 in port do (volume item val item2)))) ;=================== ; ALL NOTES OFF ;=================== (defmethod* midi-allnotesoff (&optional port) :icon :midi-out :indoc '("output port number") :initvals '(nil) :doc "Turns all notes off on all channels" (unless port (setf port (get-pref-value :midi :out-port))) (loop for aport in (list! port) do (loop for c from 1 to 16 do (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan c :port aport :fields (list 120 0)))) (when event (om-midi::midi-send-evt event))) )) t) ;=================== ; RESET ;=================== (defmethod* midi-reset (port) :icon :midi-out :indoc '("ouput MIDI port") :initvals '(0) :doc "Sends a MIDI Reset message on port <port>." (loop for chan from 1 to 16 do (let ((event (om-midi::make-midi-evt :type :CtrlChange :port (or port (get-pref-value :midi :out-port)) :chan chan :fields '(121 0)))) (when event (om-midi::midi-send-evt event)))) t) ;=================== ; SEND FREE BYTES ;=================== ;;; THIS FUNCTION WILL PROBABLY NOT WORK ;;; LOW-LEVEL API SHOULD HANDLE THIS TYPE OF EVENTS... OR NOT (defmethod* midi-o ((bytes list) &optional port) :icon :midi-out :indoc '("data bytes" "output port number") :initvals '((144 60 64) nil) :doc "Sends <bytes> out of the port number <port>. " (when bytes (unless port (setf port (get-pref-value :midi :out-port))) (if (list-subtypep bytes 'list) ;;; bytes is a list of lists (if (integerp port) send all lists one by one to port (loop for item in bytes do (midi-o item port)) ;;; send all lists, one to each port (loop for item in bytes for item1 in port do (midi-o item item1))) ;;; send the bytes list (loop for aport in (list! port) do (om-midi::midi-send-bytes bytes aport)) ) t)) (defmethod* sysex ((databytes list) &optional port) :icon :midi-out :indoc '("data bytes (ID data)" "output port number") :initvals '((1 1) nil) :doc "Sends a system exclusive MIDI message on <port> with any number of data bytes. The data will be framed between SysEx begin/end messages (F0/F7)." (when databytes (unless port (setf port (get-pref-value :midi :out-port))) (if (list-subtypep databytes 'list) (if (integerp port) (loop for item in databytes do (sysex item port)) (loop for item in databytes for item1 in port do (sysex item item1))) (loop for aport in (list! port) do (om-midi::midi-send-bytes (cons #xF0 databytes) aport) (om-midi::midi-send-bytes (cons #xF7 '(0 0)) aport) )) t)) ;=================== ; SEND ONE NOTE ;=================== (defmethod! send-midi-note (port chan pitch vel dur) :icon :midi-out :initvals '(0 1 60 100 1000) :doc "Sends a MIDI note on port <port>, channel <chan>, key <pitch>, with velocity <vel>, and duration <dur>." (let ((note (make-midinote :port port :chan chan :pitch pitch :vel vel :dur dur))) (funcall (get-frame-action note)))) ( send - midi - note 0 1 60 100 1000 )
null
https://raw.githubusercontent.com/cac-t-u-s/om-sharp/deafab18e2f08d39244706dc355bc6e941449a7c/src/packages/midi/tools/midi-out.lisp
lisp
============================================================================ om#: visual programming language for computer-assisted music composition ============================================================================ This program is free software. For information on usage and redistribution, see the "LICENSE" file in this distribution. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ============================================================================ ============================================================================ =================== =================== =================== PROGRAM CHANGE =================== =================== POLY KEY PRESSURE =================== =================== AFTER TOUCH =================== =================== CONTROL CHANGE =================== =================== VOLUME =================== =================== ALL NOTES OFF =================== =================== RESET =================== =================== SEND FREE BYTES =================== THIS FUNCTION WILL PROBABLY NOT WORK LOW-LEVEL API SHOULD HANDLE THIS TYPE OF EVENTS... OR NOT bytes is a list of lists send all lists, one to each port send the bytes list =================== SEND ONE NOTE ===================
File author : (in-package :om) PITCHBEND & PITCHWHEEL (defmethod* pitchwheel ((val number) (chans number) &optional port) :icon :midi-out :indoc '("pitch wheel value(s)" "MIDI channel(s) (1-16)" "output port number") :initvals '(8192 1 nil) :doc "Sends one or more MIDI pitch wheel message(s) of <vals> in the MIDI channel(s) <chans>. <values> and <chans> can be single numbers or lists. The range of pitch wheel is between 0 and 16383 (inclusive). 8192 (default) means no bend. " (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :PitchBend :chan chans :port aport :fields (val2lsbmsb val)))) (om-midi::midi-send-evt event) ))) (defmethod* pitchwheel ((vals number) (chans list) &optional port) (loop for item in chans do (pitchwheel vals item port))) (defmethod* pitchwheel ((vals list) (chans list) &optional port) (loop for item in chans for item1 in vals do (pitchwheel item1 item port))) (defmethod* pitchwheel ((vals list) (chans number) &optional port) (loop for chan from chans for val in vals do (pitchwheel val chan port))) (defmethod* pitchbend ((val number) (chan number) &optional port) :icon :midi-out :indoc '("pitch bend value(s)" "MIDI channel(s) (1-16)" "output port number") :initvals '(64 1 nil) :doc "Sends one or more MIDI pitch bend message(s) of <vals> in the MIDI channel(s) <chans>. <values> and <chans> can be single numbers or lists. The range of pitch bend is between 0 and 127. 64 (default) means no bend. [COMPATIBILITY: PITCHBEND strictly equivalent to PITCHWHEEL with less precision.] " (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :PitchBend :chan chan :port aport :fields (list 0 val)))) (om-midi::midi-send-evt event) ))) (defmethod* pitchbend ((vals number) (chans list) &optional port) (loop for item in chans do (pitchbend vals item port))) (defmethod* pitchbend ((vals list) (chans list) &optional port) (loop for item in chans for item1 in vals do (pitchbend item1 item port))) (defmethod* pgmout ((progm integer) (chans integer) &optional port) :icon :midi-out :indoc '("program number" "MIDI channel(s)" "output port number") :initvals '(2 1 nil) :doc "Sends a program change event with program number <progm> to channel(s) <chans>. <progm> and <chans> can be single numbers or lists." (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :ProgChange :chan chans :port aport :fields (list progm)))) (when event (om-midi::midi-send-evt event) t)))) (defmethod* pgmout ((progm number) (chans list) &optional port) (loop for item in chans do (pgmout progm item port))) (defmethod* pgmout ((progm list) (chans list) &optional port) (if (or (null port) (integerp port)) (loop for item in chans for item1 in progm do (pgmout item1 item port)) (loop for item in chans for item1 in progm for item2 in port do (pgmout item1 item item2)))) (defmethod* polyKeypres ((val integer) (pitch integer) (chans integer) &optional port) :icon :midi-out :indoc '("pressure value" "target pitch" "MIDI channel (1-16)" "output port number") :initvals '(100 6000 1 nil) :doc " Sends a key pressure event with pressure <values> and <pitch> on channel <cahns> and port <port>. Arguments can be single numbers or lists. " (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :KeyPress :chan chans :port aport :fields (list (round pitch 100) val)))) (when event (om-midi::midi-send-evt event))) )) (defmethod* polyKeypres ((vals list) (pitch list) (chans list) &optional port) (loop for item in pitch for val in vals for chan in chans do (polyKeypres val item chan port))) (defmethod* polyKeypres ((val integer) (pitch list) (chans integer) &optional port) (loop for item in pitch do (polyKeypres val item chans port))) (defmethod* polyKeypres ((val integer) (pitch list) (chans list) &optional port) (loop for item in pitch for chan in chans do (polyKeypres val item chan port))) (defmethod* polyKeypres ((vals list) (pitch integer) (chans list) &optional port) (loop for val in vals for chan in chans do (polyKeypres val pitch chan port))) (defmethod* polyKeypres ((vals list) (pitch integer) (chans integer) &optional port) (loop for val in vals do (polyKeypres val pitch chans port))) (defmethod* polyKeypres ((vals list) (pitch list) (chans integer) &optional port) (loop for item in pitch for val in vals do (polyKeypres val item chans port))) (defmethod* aftertouch ((val integer) (chans integer) &optional port) :icon :midi-out :indoc '("pressurev value" "MIDI channel (1-16)" "output port number") :initvals '(100 1 nil) :doc "Sends an after touch event of <val> to channel <chans> and port <port>. Arguments can be can be single numbers or lists. " (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :ChanPress :chan chans :port aport :fields (list val)))) (when event (om-midi::midi-send-evt event))) )) (defmethod* aftertouch ((vals number) (chans list) &optional port) (loop for item in chans do (aftertouch vals item port))) (defmethod* aftertouch ((vals list) (chans list) &optional port) (if (or (null port) (integerp port)) (loop for item in vals for val in chans do (aftertouch item val port)) (loop for item in vals for val in chans for item2 in port do (aftertouch item val item2)))) (defmethod* ctrlchg ((ctrlnum integer) (val integer) (chans integer) &optional port) :icon :midi-out :indoc '("control number" "value" "MIDI channel (1-16)" "output port number") :initvals '(7 100 1 nil) :doc "Sends a control change event with control number <ctrlnum> and value <val> to channel <chans> (and port <port>)." (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan chans :port aport :fields (list ctrlnum val)))) (when event (om-midi::midi-send-evt event))))) (defmethod* ctrlchg ((ctrlnum integer) (val integer) (chans list) &optional port) (loop for item in chans do (ctrlchg ctrlnum val item port))) (defmethod* ctrlchg ((ctrlnum list) (val list) (chans list) &optional port) (loop for ctrl in ctrlnum for item in chans for aval in val do (ctrlchg ctrl aval item port))) (defmethod* ctrlchg ((ctrlnum list) (val list) (chans integer) &optional port) (loop for ctrl in ctrlnum for aval in val do (ctrlchg ctrl aval chans port))) (defmethod* ctrlchg ((ctrlnum list) (val integer) (chans integer) &optional port) (loop for ctrl in ctrlnum do (ctrlchg ctrl val chans port))) (defmethod* ctrlchg ((ctrlnum list) (val integer) (chans list) &optional port) (loop for ctrl in ctrlnum for item in chans do (ctrlchg ctrl val item port))) (defmethod* ctrlchg ((ctrlnum integer) (val list) (chans list) &optional port) (loop for item in chans for aval in val do (ctrlchg ctrlnum aval item port))) (defmethod* volume ((vol integer) (chans integer) &optional port) :icon :midi-out :indoc '("value" "MIDI channel (1-16)" "output port number") :initvals '(100 1 nil) :doc "Sends MIDI volume message(s) to channel(s) <chans> and port <port>. Arguments can be numbers or lists. The range of volume values is 0-127. " (unless port (setf port (get-pref-value :midi :out-port))) (setf port (list! port)) (loop for aport in port do (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan chans :port aport :fields (list 7 vol)))) (when event (om-midi::midi-send-evt event))))) (defmethod* volume ((volume number) (chans list) &optional port) (loop for item in chans do (volume volume item port))) (defmethod* volume ((volume list) (chans list) &optional port) (if (or (null port) (integerp port)) (loop for item in volume for val in chans do (volume item val port)) (loop for item in volume for val in chans for item2 in port do (volume item val item2)))) (defmethod* midi-allnotesoff (&optional port) :icon :midi-out :indoc '("output port number") :initvals '(nil) :doc "Turns all notes off on all channels" (unless port (setf port (get-pref-value :midi :out-port))) (loop for aport in (list! port) do (loop for c from 1 to 16 do (let ((event (om-midi::make-midi-evt :type :CtrlChange :chan c :port aport :fields (list 120 0)))) (when event (om-midi::midi-send-evt event))) )) t) (defmethod* midi-reset (port) :icon :midi-out :indoc '("ouput MIDI port") :initvals '(0) :doc "Sends a MIDI Reset message on port <port>." (loop for chan from 1 to 16 do (let ((event (om-midi::make-midi-evt :type :CtrlChange :port (or port (get-pref-value :midi :out-port)) :chan chan :fields '(121 0)))) (when event (om-midi::midi-send-evt event)))) t) (defmethod* midi-o ((bytes list) &optional port) :icon :midi-out :indoc '("data bytes" "output port number") :initvals '((144 60 64) nil) :doc "Sends <bytes> out of the port number <port>. " (when bytes (unless port (setf port (get-pref-value :midi :out-port))) (if (list-subtypep bytes 'list) (if (integerp port) send all lists one by one to port (loop for item in bytes do (midi-o item port)) (loop for item in bytes for item1 in port do (midi-o item item1))) (loop for aport in (list! port) do (om-midi::midi-send-bytes bytes aport)) ) t)) (defmethod* sysex ((databytes list) &optional port) :icon :midi-out :indoc '("data bytes (ID data)" "output port number") :initvals '((1 1) nil) :doc "Sends a system exclusive MIDI message on <port> with any number of data bytes. The data will be framed between SysEx begin/end messages (F0/F7)." (when databytes (unless port (setf port (get-pref-value :midi :out-port))) (if (list-subtypep databytes 'list) (if (integerp port) (loop for item in databytes do (sysex item port)) (loop for item in databytes for item1 in port do (sysex item item1))) (loop for aport in (list! port) do (om-midi::midi-send-bytes (cons #xF0 databytes) aport) (om-midi::midi-send-bytes (cons #xF7 '(0 0)) aport) )) t)) (defmethod! send-midi-note (port chan pitch vel dur) :icon :midi-out :initvals '(0 1 60 100 1000) :doc "Sends a MIDI note on port <port>, channel <chan>, key <pitch>, with velocity <vel>, and duration <dur>." (let ((note (make-midinote :port port :chan chan :pitch pitch :vel vel :dur dur))) (funcall (get-frame-action note)))) ( send - midi - note 0 1 60 100 1000 )
fa71c93495194e2e9450916db2ca3fccc85dffbf0aefbd939ee27d32ef0edd53
alanz/ghc-exactprint
Dump.hs
Temporary copy of the GHC.Hs . Dump module , modified to show DeltaPos hacked into a SrcSpan . Temporary copy of the GHC.Hs.Dump module, modified to show DeltaPos hacked into a SrcSpan. -} {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # module Language.Haskell.GHC.ExactPrint.Dump ( -- * Dumping ASTs showAstData, BlankSrcSpan(..), BlankEpAnnotations(..), ) where import Prelude () import GHC.Prelude import GHC.Hs hiding ( ann, anns, deltaPos, realSrcSpan ) import GHC.Core.DataCon import GHC.Data.Bag import GHC.Data.FastString import GHC.Types.Name.Set import GHC.Types.Name hiding ( occName ) import GHC.Types.SrcLoc import GHC.Types.Var import GHC.Types.SourceText import GHC.Unit.Module hiding ( moduleName ) import GHC.Utils.Outputable import Data.Data hiding (Fixity) import qualified Data.ByteString as B import Data.Generics (extQ, ext1Q, ext2Q) import Language.Haskell.GHC.ExactPrint.Utils data BlankSrcSpan = BlankSrcSpan | BlankSrcSpanFile | NoBlankSrcSpan deriving (Eq,Show) data BlankEpAnnotations = BlankEpAnnotations | NoBlankEpAnnotations deriving (Eq,Show) | Show a GHC syntax tree . This parameterised because it is also used for comparing ASTs in ppr roundtripping tests , where the SrcSpan 's are blanked -- out, to avoid comparing locations, only structure showAstData :: Data a => BlankSrcSpan -> BlankEpAnnotations -> a -> SDoc showAstData bs ba a0 = blankLine $$ showAstData' a0 where showAstData' :: Data a => a -> SDoc showAstData' = generic `ext1Q` list `extQ` string `extQ` fastString `extQ` srcSpan `extQ` realSrcSpan `extQ` annotation `extQ` annotationModule `extQ` annotationAddEpAnn `extQ` annotationGrhsAnn `extQ` annotationEpAnnHsCase `extQ` annotationAnnList `extQ` annotationEpAnnImportDecl `extQ` annotationAnnParen `extQ` annotationTrailingAnn `extQ` annotationEpaLocation `extQ` addEpAnn `extQ` lit `extQ` litr `extQ` litt `extQ` sourceText `extQ` deltaPos `extQ` epaAnchor `extQ` bytestring `extQ` name `extQ` occName `extQ` moduleName `extQ` var `extQ` dataCon `extQ` bagName `extQ` bagRdrName `extQ` bagVar `extQ` nameSet `extQ` fixity `ext2Q` located `extQ` srcSpanAnnA `extQ` srcSpanAnnL `extQ` srcSpanAnnP `extQ` srcSpanAnnC `extQ` srcSpanAnnN where generic :: Data a => a -> SDoc generic t = parens $ text (showConstr (toConstr t)) $$ vcat (gmapQ showAstData' t) string :: String -> SDoc string = text . normalize_newlines . show fastString :: FastString -> SDoc fastString s = braces $ text "FastString:" <+> text (normalize_newlines . show $ s) bytestring :: B.ByteString -> SDoc bytestring = text . normalize_newlines . show list [] = brackets empty list [x] = brackets (showAstData' x) list (x1 : x2 : xs) = (text "[" <> showAstData' x1) $$ go x2 xs where go y [] = text "," <> showAstData' y <> text "]" go y1 (y2 : ys) = (text "," <> showAstData' y1) $$ go y2 ys -- Eliminate word-size dependence lit :: HsLit GhcPs -> SDoc lit (HsWordPrim s x) = numericLit "HsWord{64}Prim" x s lit (HsWord64Prim s x) = numericLit "HsWord{64}Prim" x s lit (HsIntPrim s x) = numericLit "HsInt{64}Prim" x s lit (HsInt64Prim s x) = numericLit "HsInt{64}Prim" x s lit l = generic l litr :: HsLit GhcRn -> SDoc litr (HsWordPrim s x) = numericLit "HsWord{64}Prim" x s litr (HsWord64Prim s x) = numericLit "HsWord{64}Prim" x s litr (HsIntPrim s x) = numericLit "HsInt{64}Prim" x s litr (HsInt64Prim s x) = numericLit "HsInt{64}Prim" x s litr l = generic l litt :: HsLit GhcTc -> SDoc litt (HsWordPrim s x) = numericLit "HsWord{64}Prim" x s litt (HsWord64Prim s x) = numericLit "HsWord{64}Prim" x s litt (HsIntPrim s x) = numericLit "HsInt{64}Prim" x s litt (HsInt64Prim s x) = numericLit "HsInt{64}Prim" x s litt l = generic l numericLit :: String -> Integer -> SourceText -> SDoc numericLit tag x s = braces $ hsep [ text tag , generic x , generic s ] sourceText :: SourceText -> SDoc sourceText NoSourceText = parens $ text "NoSourceText" sourceText (SourceText src) = case bs of NoBlankSrcSpan -> parens $ text "SourceText" <+> text src BlankSrcSpanFile -> parens $ text "SourceText" <+> text src _ -> parens $ text "SourceText" <+> text "blanked" epaAnchor :: EpaLocation -> SDoc epaAnchor (EpaSpan r) = parens $ text "EpaSpan" <+> realSrcSpan r epaAnchor (EpaDelta d cs) = case ba of NoBlankEpAnnotations -> parens $ text "EpaDelta" <+> deltaPos d <+> showAstData' cs BlankEpAnnotations -> parens $ text "EpaDelta" <+> deltaPos d <+> text "blanked" deltaPos :: DeltaPos -> SDoc deltaPos (SameLine c) = parens $ text "SameLine" <+> ppr c deltaPos (DifferentLine l c) = parens $ text "DifferentLine" <+> ppr l <+> ppr c name :: Name -> SDoc name nm = braces $ text "Name:" <+> ppr nm occName n = braces $ text "OccName:" <+> text (occNameString n) moduleName :: ModuleName -> SDoc moduleName m = braces $ text "ModuleName:" <+> ppr m srcSpan :: SrcSpan -> SDoc srcSpan ss = case bs of BlankSrcSpan -> text "{ ss }" NoBlankSrcSpan -> braces $ char ' ' <> (hang (pprSrcSpanWithAnchor ss) 1 (text "")) BlankSrcSpanFile -> braces $ char ' ' <> (hang (pprUserSpan False ss) 1 (text "")) realSrcSpan :: RealSrcSpan -> SDoc realSrcSpan ss = case bs of BlankSrcSpan -> text "{ ss }" NoBlankSrcSpan -> braces $ char ' ' <> (hang (ppr ss) 1 (text "")) BlankSrcSpanFile -> braces $ char ' ' <> (hang (pprUserRealSpan False ss) 1 (text "")) addEpAnn :: AddEpAnn -> SDoc addEpAnn (AddEpAnn a s) = case ba of BlankEpAnnotations -> parens $ text "blanked:" <+> text "AddEpAnn" NoBlankEpAnnotations -> parens $ text "AddEpAnn" <+> ppr a <+> epaAnchor s var :: Var -> SDoc var v = braces $ text "Var:" <+> ppr v dataCon :: DataCon -> SDoc dataCon c = braces $ text "DataCon:" <+> ppr c bagRdrName:: Bag (LocatedA (HsBind GhcPs)) -> SDoc bagRdrName bg = braces $ text "Bag(LocatedA (HsBind GhcPs)):" $$ (list . bagToList $ bg) bagName :: Bag (LocatedA (HsBind GhcRn)) -> SDoc bagName bg = braces $ text "Bag(LocatedA (HsBind Name)):" $$ (list . bagToList $ bg) bagVar :: Bag (LocatedA (HsBind GhcTc)) -> SDoc bagVar bg = braces $ text "Bag(LocatedA (HsBind Var)):" $$ (list . bagToList $ bg) nameSet ns = braces $ text "NameSet:" $$ (list . nameSetElemsStable $ ns) fixity :: Fixity -> SDoc fixity fx = braces $ text "Fixity:" <+> ppr fx located :: (Data a, Data b) => GenLocated a b -> SDoc located (L ss a) = parens (text "L" $$ vcat [showAstData' ss, showAstData' a]) -- ------------------------- annotation :: EpAnn [AddEpAnn] -> SDoc annotation = annotation' (text "EpAnn [AddEpAnn]") annotationModule :: EpAnn AnnsModule -> SDoc annotationModule = annotation' (text "EpAnn AnnsModule") annotationAddEpAnn :: EpAnn AddEpAnn -> SDoc annotationAddEpAnn = annotation' (text "EpAnn AddEpAnn") annotationGrhsAnn :: EpAnn GrhsAnn -> SDoc annotationGrhsAnn = annotation' (text "EpAnn GrhsAnn") annotationEpAnnHsCase :: EpAnn EpAnnHsCase -> SDoc annotationEpAnnHsCase = annotation' (text "EpAnn EpAnnHsCase") annotationAnnList :: EpAnn AnnList -> SDoc annotationAnnList = annotation' (text "EpAnn AnnList") annotationEpAnnImportDecl :: EpAnn EpAnnImportDecl -> SDoc annotationEpAnnImportDecl = annotation' (text "EpAnn EpAnnImportDecl") annotationAnnParen :: EpAnn AnnParen -> SDoc annotationAnnParen = annotation' (text "EpAnn AnnParen") annotationTrailingAnn :: EpAnn TrailingAnn -> SDoc annotationTrailingAnn = annotation' (text "EpAnn TrailingAnn") annotationEpaLocation :: EpAnn EpaLocation -> SDoc annotationEpaLocation = annotation' (text "EpAnn EpaLocation") annotation' :: forall a .(Data a) => SDoc -> EpAnn a -> SDoc annotation' tag anns = case ba of BlankEpAnnotations -> parens (text "blanked:" <+> tag) NoBlankEpAnnotations -> parens $ text (showConstr (toConstr anns)) $$ vcat (gmapQ showAstData' anns) -- ------------------------- srcSpanAnnA :: SrcSpanAnn' (EpAnn AnnListItem) -> SDoc srcSpanAnnA = locatedAnn'' (text "SrcSpanAnnA") srcSpanAnnL :: SrcSpanAnn' (EpAnn AnnList) -> SDoc srcSpanAnnL = locatedAnn'' (text "SrcSpanAnnL") srcSpanAnnP :: SrcSpanAnn' (EpAnn AnnPragma) -> SDoc srcSpanAnnP = locatedAnn'' (text "SrcSpanAnnP") srcSpanAnnC :: SrcSpanAnn' (EpAnn AnnContext) -> SDoc srcSpanAnnC = locatedAnn'' (text "SrcSpanAnnC") srcSpanAnnN :: SrcSpanAnn' (EpAnn NameAnn) -> SDoc srcSpanAnnN = locatedAnn'' (text "SrcSpanAnnN") locatedAnn'' :: forall a. (Data a) => SDoc -> SrcSpanAnn' a -> SDoc locatedAnn'' tag ss = parens $ case cast ss of Just ((SrcSpanAnn ann s) :: SrcSpanAnn' a) -> case ba of BlankEpAnnotations -> parens (text "blanked:" <+> tag) NoBlankEpAnnotations -> text "SrcSpanAnn" <+> showAstData' ann <+> srcSpan s Nothing -> text "locatedAnn:unmatched" <+> tag <+> (parens $ text (showConstr (toConstr ss))) normalize_newlines :: String -> String normalize_newlines ('\\':'r':'\\':'n':xs) = '\\':'n':normalize_newlines xs normalize_newlines (x:xs) = x:normalize_newlines xs normalize_newlines [] = [] pprSrcSpanWithAnchor :: SrcSpan -> SDoc pprSrcSpanWithAnchor ss@(UnhelpfulSpan _) = ppr ss pprSrcSpanWithAnchor ss = ppr ss <+> parens (ppr (hackSrcSpanToAnchor ss))
null
https://raw.githubusercontent.com/alanz/ghc-exactprint/3b36f5d0a498e31d882fe111304b2cf5ca6cad22/src/Language/Haskell/GHC/ExactPrint/Dump.hs
haskell
# LANGUAGE RankNTypes # * Dumping ASTs out, to avoid comparing locations, only structure Eliminate word-size dependence ------------------------- -------------------------
Temporary copy of the GHC.Hs . Dump module , modified to show DeltaPos hacked into a SrcSpan . Temporary copy of the GHC.Hs.Dump module, modified to show DeltaPos hacked into a SrcSpan. -} # LANGUAGE ScopedTypeVariables # module Language.Haskell.GHC.ExactPrint.Dump ( showAstData, BlankSrcSpan(..), BlankEpAnnotations(..), ) where import Prelude () import GHC.Prelude import GHC.Hs hiding ( ann, anns, deltaPos, realSrcSpan ) import GHC.Core.DataCon import GHC.Data.Bag import GHC.Data.FastString import GHC.Types.Name.Set import GHC.Types.Name hiding ( occName ) import GHC.Types.SrcLoc import GHC.Types.Var import GHC.Types.SourceText import GHC.Unit.Module hiding ( moduleName ) import GHC.Utils.Outputable import Data.Data hiding (Fixity) import qualified Data.ByteString as B import Data.Generics (extQ, ext1Q, ext2Q) import Language.Haskell.GHC.ExactPrint.Utils data BlankSrcSpan = BlankSrcSpan | BlankSrcSpanFile | NoBlankSrcSpan deriving (Eq,Show) data BlankEpAnnotations = BlankEpAnnotations | NoBlankEpAnnotations deriving (Eq,Show) | Show a GHC syntax tree . This parameterised because it is also used for comparing ASTs in ppr roundtripping tests , where the SrcSpan 's are blanked showAstData :: Data a => BlankSrcSpan -> BlankEpAnnotations -> a -> SDoc showAstData bs ba a0 = blankLine $$ showAstData' a0 where showAstData' :: Data a => a -> SDoc showAstData' = generic `ext1Q` list `extQ` string `extQ` fastString `extQ` srcSpan `extQ` realSrcSpan `extQ` annotation `extQ` annotationModule `extQ` annotationAddEpAnn `extQ` annotationGrhsAnn `extQ` annotationEpAnnHsCase `extQ` annotationAnnList `extQ` annotationEpAnnImportDecl `extQ` annotationAnnParen `extQ` annotationTrailingAnn `extQ` annotationEpaLocation `extQ` addEpAnn `extQ` lit `extQ` litr `extQ` litt `extQ` sourceText `extQ` deltaPos `extQ` epaAnchor `extQ` bytestring `extQ` name `extQ` occName `extQ` moduleName `extQ` var `extQ` dataCon `extQ` bagName `extQ` bagRdrName `extQ` bagVar `extQ` nameSet `extQ` fixity `ext2Q` located `extQ` srcSpanAnnA `extQ` srcSpanAnnL `extQ` srcSpanAnnP `extQ` srcSpanAnnC `extQ` srcSpanAnnN where generic :: Data a => a -> SDoc generic t = parens $ text (showConstr (toConstr t)) $$ vcat (gmapQ showAstData' t) string :: String -> SDoc string = text . normalize_newlines . show fastString :: FastString -> SDoc fastString s = braces $ text "FastString:" <+> text (normalize_newlines . show $ s) bytestring :: B.ByteString -> SDoc bytestring = text . normalize_newlines . show list [] = brackets empty list [x] = brackets (showAstData' x) list (x1 : x2 : xs) = (text "[" <> showAstData' x1) $$ go x2 xs where go y [] = text "," <> showAstData' y <> text "]" go y1 (y2 : ys) = (text "," <> showAstData' y1) $$ go y2 ys lit :: HsLit GhcPs -> SDoc lit (HsWordPrim s x) = numericLit "HsWord{64}Prim" x s lit (HsWord64Prim s x) = numericLit "HsWord{64}Prim" x s lit (HsIntPrim s x) = numericLit "HsInt{64}Prim" x s lit (HsInt64Prim s x) = numericLit "HsInt{64}Prim" x s lit l = generic l litr :: HsLit GhcRn -> SDoc litr (HsWordPrim s x) = numericLit "HsWord{64}Prim" x s litr (HsWord64Prim s x) = numericLit "HsWord{64}Prim" x s litr (HsIntPrim s x) = numericLit "HsInt{64}Prim" x s litr (HsInt64Prim s x) = numericLit "HsInt{64}Prim" x s litr l = generic l litt :: HsLit GhcTc -> SDoc litt (HsWordPrim s x) = numericLit "HsWord{64}Prim" x s litt (HsWord64Prim s x) = numericLit "HsWord{64}Prim" x s litt (HsIntPrim s x) = numericLit "HsInt{64}Prim" x s litt (HsInt64Prim s x) = numericLit "HsInt{64}Prim" x s litt l = generic l numericLit :: String -> Integer -> SourceText -> SDoc numericLit tag x s = braces $ hsep [ text tag , generic x , generic s ] sourceText :: SourceText -> SDoc sourceText NoSourceText = parens $ text "NoSourceText" sourceText (SourceText src) = case bs of NoBlankSrcSpan -> parens $ text "SourceText" <+> text src BlankSrcSpanFile -> parens $ text "SourceText" <+> text src _ -> parens $ text "SourceText" <+> text "blanked" epaAnchor :: EpaLocation -> SDoc epaAnchor (EpaSpan r) = parens $ text "EpaSpan" <+> realSrcSpan r epaAnchor (EpaDelta d cs) = case ba of NoBlankEpAnnotations -> parens $ text "EpaDelta" <+> deltaPos d <+> showAstData' cs BlankEpAnnotations -> parens $ text "EpaDelta" <+> deltaPos d <+> text "blanked" deltaPos :: DeltaPos -> SDoc deltaPos (SameLine c) = parens $ text "SameLine" <+> ppr c deltaPos (DifferentLine l c) = parens $ text "DifferentLine" <+> ppr l <+> ppr c name :: Name -> SDoc name nm = braces $ text "Name:" <+> ppr nm occName n = braces $ text "OccName:" <+> text (occNameString n) moduleName :: ModuleName -> SDoc moduleName m = braces $ text "ModuleName:" <+> ppr m srcSpan :: SrcSpan -> SDoc srcSpan ss = case bs of BlankSrcSpan -> text "{ ss }" NoBlankSrcSpan -> braces $ char ' ' <> (hang (pprSrcSpanWithAnchor ss) 1 (text "")) BlankSrcSpanFile -> braces $ char ' ' <> (hang (pprUserSpan False ss) 1 (text "")) realSrcSpan :: RealSrcSpan -> SDoc realSrcSpan ss = case bs of BlankSrcSpan -> text "{ ss }" NoBlankSrcSpan -> braces $ char ' ' <> (hang (ppr ss) 1 (text "")) BlankSrcSpanFile -> braces $ char ' ' <> (hang (pprUserRealSpan False ss) 1 (text "")) addEpAnn :: AddEpAnn -> SDoc addEpAnn (AddEpAnn a s) = case ba of BlankEpAnnotations -> parens $ text "blanked:" <+> text "AddEpAnn" NoBlankEpAnnotations -> parens $ text "AddEpAnn" <+> ppr a <+> epaAnchor s var :: Var -> SDoc var v = braces $ text "Var:" <+> ppr v dataCon :: DataCon -> SDoc dataCon c = braces $ text "DataCon:" <+> ppr c bagRdrName:: Bag (LocatedA (HsBind GhcPs)) -> SDoc bagRdrName bg = braces $ text "Bag(LocatedA (HsBind GhcPs)):" $$ (list . bagToList $ bg) bagName :: Bag (LocatedA (HsBind GhcRn)) -> SDoc bagName bg = braces $ text "Bag(LocatedA (HsBind Name)):" $$ (list . bagToList $ bg) bagVar :: Bag (LocatedA (HsBind GhcTc)) -> SDoc bagVar bg = braces $ text "Bag(LocatedA (HsBind Var)):" $$ (list . bagToList $ bg) nameSet ns = braces $ text "NameSet:" $$ (list . nameSetElemsStable $ ns) fixity :: Fixity -> SDoc fixity fx = braces $ text "Fixity:" <+> ppr fx located :: (Data a, Data b) => GenLocated a b -> SDoc located (L ss a) = parens (text "L" $$ vcat [showAstData' ss, showAstData' a]) annotation :: EpAnn [AddEpAnn] -> SDoc annotation = annotation' (text "EpAnn [AddEpAnn]") annotationModule :: EpAnn AnnsModule -> SDoc annotationModule = annotation' (text "EpAnn AnnsModule") annotationAddEpAnn :: EpAnn AddEpAnn -> SDoc annotationAddEpAnn = annotation' (text "EpAnn AddEpAnn") annotationGrhsAnn :: EpAnn GrhsAnn -> SDoc annotationGrhsAnn = annotation' (text "EpAnn GrhsAnn") annotationEpAnnHsCase :: EpAnn EpAnnHsCase -> SDoc annotationEpAnnHsCase = annotation' (text "EpAnn EpAnnHsCase") annotationAnnList :: EpAnn AnnList -> SDoc annotationAnnList = annotation' (text "EpAnn AnnList") annotationEpAnnImportDecl :: EpAnn EpAnnImportDecl -> SDoc annotationEpAnnImportDecl = annotation' (text "EpAnn EpAnnImportDecl") annotationAnnParen :: EpAnn AnnParen -> SDoc annotationAnnParen = annotation' (text "EpAnn AnnParen") annotationTrailingAnn :: EpAnn TrailingAnn -> SDoc annotationTrailingAnn = annotation' (text "EpAnn TrailingAnn") annotationEpaLocation :: EpAnn EpaLocation -> SDoc annotationEpaLocation = annotation' (text "EpAnn EpaLocation") annotation' :: forall a .(Data a) => SDoc -> EpAnn a -> SDoc annotation' tag anns = case ba of BlankEpAnnotations -> parens (text "blanked:" <+> tag) NoBlankEpAnnotations -> parens $ text (showConstr (toConstr anns)) $$ vcat (gmapQ showAstData' anns) srcSpanAnnA :: SrcSpanAnn' (EpAnn AnnListItem) -> SDoc srcSpanAnnA = locatedAnn'' (text "SrcSpanAnnA") srcSpanAnnL :: SrcSpanAnn' (EpAnn AnnList) -> SDoc srcSpanAnnL = locatedAnn'' (text "SrcSpanAnnL") srcSpanAnnP :: SrcSpanAnn' (EpAnn AnnPragma) -> SDoc srcSpanAnnP = locatedAnn'' (text "SrcSpanAnnP") srcSpanAnnC :: SrcSpanAnn' (EpAnn AnnContext) -> SDoc srcSpanAnnC = locatedAnn'' (text "SrcSpanAnnC") srcSpanAnnN :: SrcSpanAnn' (EpAnn NameAnn) -> SDoc srcSpanAnnN = locatedAnn'' (text "SrcSpanAnnN") locatedAnn'' :: forall a. (Data a) => SDoc -> SrcSpanAnn' a -> SDoc locatedAnn'' tag ss = parens $ case cast ss of Just ((SrcSpanAnn ann s) :: SrcSpanAnn' a) -> case ba of BlankEpAnnotations -> parens (text "blanked:" <+> tag) NoBlankEpAnnotations -> text "SrcSpanAnn" <+> showAstData' ann <+> srcSpan s Nothing -> text "locatedAnn:unmatched" <+> tag <+> (parens $ text (showConstr (toConstr ss))) normalize_newlines :: String -> String normalize_newlines ('\\':'r':'\\':'n':xs) = '\\':'n':normalize_newlines xs normalize_newlines (x:xs) = x:normalize_newlines xs normalize_newlines [] = [] pprSrcSpanWithAnchor :: SrcSpan -> SDoc pprSrcSpanWithAnchor ss@(UnhelpfulSpan _) = ppr ss pprSrcSpanWithAnchor ss = ppr ss <+> parens (ppr (hackSrcSpanToAnchor ss))
cfa03693a892622d6d7db4627c11b3accd10b1fa189ee1a7cfa5b9b81358a400
libguestfs/virt-v2v
changeuid.ml
virt - v2v * Copyright ( C ) 2009 - 2020 Red Hat Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation ; either version 2 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License along * with this program ; if not , write to the Free Software Foundation , Inc. , * 51 Franklin Street , Fifth Floor , Boston , USA . * Copyright (C) 2009-2020 Red Hat Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *) (* Functions for making files and directories as another user. *) open Unix open Printf open Std_utils open Tools_utils open Unix_utils open Common_gettext.Gettext open Utils type t = { uid : int option; gid : int option; } let create ?uid ?gid () = { uid = uid; gid = gid } let with_fork { uid; gid } name f = let pid = fork () in if pid = 0 then ( (* Child. *) Option.iter setgid gid; Option.iter setuid uid; (try f () with exn -> eprintf "%s: changeuid: %s: %s\n%!" prog name (Printexc.to_string exn); Exit._exit 1 ); Exit._exit 0 ); (* Parent. *) let _, status = waitpid [] pid in match status with | WEXITED 0 -> () | WEXITED i -> error (f_"subprocess exited with non-zero error code %d") i | WSIGNALED i | WSTOPPED i -> error (f_"subprocess signalled or stopped by signal %d") i let mkdir t path perm = with_fork t (sprintf "mkdir: %s" path) (fun () -> mkdir path perm) let rmdir t path = with_fork t (sprintf "rmdir: %s" path) (fun () -> rmdir path) let output t path f = with_fork t path (fun () -> with_open_out path f) let make_file t path content = output t path (fun chan -> output_string chan content) let unlink t path = with_fork t (sprintf "unlink: %s" path) (fun () -> unlink path) let func t = with_fork t "func" let command t cmd = debug "changeuid: running: %s" cmd; with_fork t cmd ( fun () -> let r = Sys.command cmd in if r <> 0 then failwith "external command failed" )
null
https://raw.githubusercontent.com/libguestfs/virt-v2v/8ad152afc4dced17e26b40d3fe8f585da99c8816/output/changeuid.ml
ocaml
Functions for making files and directories as another user. Child. Parent.
virt - v2v * Copyright ( C ) 2009 - 2020 Red Hat Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation ; either version 2 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License along * with this program ; if not , write to the Free Software Foundation , Inc. , * 51 Franklin Street , Fifth Floor , Boston , USA . * Copyright (C) 2009-2020 Red Hat Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *) open Unix open Printf open Std_utils open Tools_utils open Unix_utils open Common_gettext.Gettext open Utils type t = { uid : int option; gid : int option; } let create ?uid ?gid () = { uid = uid; gid = gid } let with_fork { uid; gid } name f = let pid = fork () in if pid = 0 then ( Option.iter setgid gid; Option.iter setuid uid; (try f () with exn -> eprintf "%s: changeuid: %s: %s\n%!" prog name (Printexc.to_string exn); Exit._exit 1 ); Exit._exit 0 ); let _, status = waitpid [] pid in match status with | WEXITED 0 -> () | WEXITED i -> error (f_"subprocess exited with non-zero error code %d") i | WSIGNALED i | WSTOPPED i -> error (f_"subprocess signalled or stopped by signal %d") i let mkdir t path perm = with_fork t (sprintf "mkdir: %s" path) (fun () -> mkdir path perm) let rmdir t path = with_fork t (sprintf "rmdir: %s" path) (fun () -> rmdir path) let output t path f = with_fork t path (fun () -> with_open_out path f) let make_file t path content = output t path (fun chan -> output_string chan content) let unlink t path = with_fork t (sprintf "unlink: %s" path) (fun () -> unlink path) let func t = with_fork t "func" let command t cmd = debug "changeuid: running: %s" cmd; with_fork t cmd ( fun () -> let r = Sys.command cmd in if r <> 0 then failwith "external command failed" )
0a1f91b3517e07006ef1ceda6df17d62f4549e5c61ddb42087024c3ce2572894
yetanalytics/dave
lrs.cljc
(ns com.yetanalytics.dave.workbook.data.lrs (:require [clojure.spec.alpha :as s] [com.yetanalytics.dave.util.spec :as su] [xapi-schema.spec.resources :as xsr] [com.yetanalytics.dave.workbook.data.lrs.auth :as auth])) (s/def ::query :xapi.statements.GET.request/params) (s/def ::more :xapi.statements.GET.response.statement-result/more) (s/def ::auth auth/auth-spec) (s/def ::endpoint (s/and string? not-empty)) (s/def ::title (s/and string? not-empty)) (def partial-spec (s/keys :req-un [::endpoint] :opt-un [::query ::auth ::more ::title]))
null
https://raw.githubusercontent.com/yetanalytics/dave/7a71c2017889862b2fb567edc8196b4382d01beb/src/com/yetanalytics/dave/workbook/data/lrs.cljc
clojure
(ns com.yetanalytics.dave.workbook.data.lrs (:require [clojure.spec.alpha :as s] [com.yetanalytics.dave.util.spec :as su] [xapi-schema.spec.resources :as xsr] [com.yetanalytics.dave.workbook.data.lrs.auth :as auth])) (s/def ::query :xapi.statements.GET.request/params) (s/def ::more :xapi.statements.GET.response.statement-result/more) (s/def ::auth auth/auth-spec) (s/def ::endpoint (s/and string? not-empty)) (s/def ::title (s/and string? not-empty)) (def partial-spec (s/keys :req-un [::endpoint] :opt-un [::query ::auth ::more ::title]))
b440ae783d7d610610b9ae4a4d6ec55227b141bdbab2b1623dab7c5bdefc3521
cl-rabbit/cl-bunny
channel-id-allocator.lisp
(in-package :cl-bunny) (defstruct channel-id-allocator (int-allocator) (mutex)) (defun new-channel-id-allocator (max-channels) (make-channel-id-allocator :int-allocator (make-int-allocator :min 1 :max max-channels) :mutex (bt:make-lock "Channel Id Allocator Lock"))) (defun next-channel-id (channel-id-allocator) (bt:with-lock-held ((channel-id-allocator-mutex channel-id-allocator)) (int-allocator-allocate (channel-id-allocator-int-allocator channel-id-allocator)))) (defun release-channel-id (channel-id-allocator channel-id) (bt:with-lock-held ((channel-id-allocator-mutex channel-id-allocator)) (int-allocator-release (channel-id-allocator-int-allocator channel-id-allocator) channel-id))) (defun channel-id-allocated-p (channel-id-allocator channel-id) (bt:with-lock-held ((channel-id-allocator-mutex channel-id-allocator)) (int-allocator-allocated-p (channel-id-allocator-int-allocator channel-id-allocator) channel-id)))
null
https://raw.githubusercontent.com/cl-rabbit/cl-bunny/6da7fe161efc8d6bb0b8b09ac8efad03553d765c/src/support/channel-id-allocator.lisp
lisp
(in-package :cl-bunny) (defstruct channel-id-allocator (int-allocator) (mutex)) (defun new-channel-id-allocator (max-channels) (make-channel-id-allocator :int-allocator (make-int-allocator :min 1 :max max-channels) :mutex (bt:make-lock "Channel Id Allocator Lock"))) (defun next-channel-id (channel-id-allocator) (bt:with-lock-held ((channel-id-allocator-mutex channel-id-allocator)) (int-allocator-allocate (channel-id-allocator-int-allocator channel-id-allocator)))) (defun release-channel-id (channel-id-allocator channel-id) (bt:with-lock-held ((channel-id-allocator-mutex channel-id-allocator)) (int-allocator-release (channel-id-allocator-int-allocator channel-id-allocator) channel-id))) (defun channel-id-allocated-p (channel-id-allocator channel-id) (bt:with-lock-held ((channel-id-allocator-mutex channel-id-allocator)) (int-allocator-allocated-p (channel-id-allocator-int-allocator channel-id-allocator) channel-id)))
f63c5680a02448ae94118f4b406dc7bc48ce1a2b8fd42defd5c746cd7ff98964
ml4tp/tcoq
inductiveops.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) open Names open Term open Declarations open Environ open Evd * The following three functions are similar to the ones defined in Inductive , but they expect an env Inductive, but they expect an env *) val type_of_inductive : env -> pinductive -> types (** Return type as quoted by the user *) val type_of_constructor : env -> pconstructor -> types val type_of_constructors : env -> pinductive -> types array (** Return constructor types in normal form *) val arities_of_constructors : env -> pinductive -> types array (** An inductive type with its parameters (transparently supports reasoning either with only recursively uniform parameters or with all parameters including the recursively non-uniform ones *) type inductive_family val make_ind_family : inductive puniverses * constr list -> inductive_family val dest_ind_family : inductive_family -> inductive puniverses * constr list val map_ind_family : (constr -> constr) -> inductive_family -> inductive_family val liftn_inductive_family : int -> int -> inductive_family -> inductive_family val lift_inductive_family : int -> inductive_family -> inductive_family val substnl_ind_family : constr list -> int -> inductive_family -> inductive_family (** An inductive type with its parameters and real arguments *) type inductive_type = IndType of inductive_family * constr list val make_ind_type : inductive_family * constr list -> inductive_type val dest_ind_type : inductive_type -> inductive_family * constr list val map_inductive_type : (constr -> constr) -> inductive_type -> inductive_type val liftn_inductive_type : int -> int -> inductive_type -> inductive_type val lift_inductive_type : int -> inductive_type -> inductive_type val substnl_ind_type : constr list -> int -> inductive_type -> inductive_type val mkAppliedInd : inductive_type -> constr val mis_is_recursive_subset : int list -> wf_paths -> bool val mis_is_recursive : inductive * mutual_inductive_body * one_inductive_body -> bool val mis_nf_constructor_type : pinductive * mutual_inductive_body * one_inductive_body -> int -> constr * { 6 Extract information from an inductive name } (** @return number of constructors *) val nconstructors : inductive -> int val nconstructors_env : env -> inductive -> int * @return arity of constructors excluding parameters , excluding local defs val constructors_nrealargs : inductive -> int array val constructors_nrealargs_env : env -> inductive -> int array * @return arity of constructors excluding parameters , including local defs val constructors_nrealdecls : inductive -> int array val constructors_nrealdecls_env : env -> inductive -> int array * @return the arity , excluding params , excluding local defs val inductive_nrealargs : inductive -> int val inductive_nrealargs_env : env -> inductive -> int * @return the arity , excluding params , including local defs val inductive_nrealdecls : inductive -> int val inductive_nrealdecls_env : env -> inductive -> int * @return the arity , including params , excluding local defs val inductive_nallargs : inductive -> int val inductive_nallargs_env : env -> inductive -> int * @return the arity , including params , including local defs val inductive_nalldecls : inductive -> int val inductive_nalldecls_env : env -> inductive -> int * @return nb of params without local defs val inductive_nparams : inductive -> int val inductive_nparams_env : env -> inductive -> int * @return nb of params with local defs val inductive_nparamdecls : inductive -> int val inductive_nparamdecls_env : env -> inductive -> int (** @return params context *) val inductive_paramdecls : pinductive -> Context.Rel.t val inductive_paramdecls_env : env -> pinductive -> Context.Rel.t (** @return full arity context, hence with letin *) val inductive_alldecls : pinductive -> Context.Rel.t val inductive_alldecls_env : env -> pinductive -> Context.Rel.t * { 7 Extract information from a constructor name } (** @return param + args without letin *) val constructor_nallargs : constructor -> int val constructor_nallargs_env : env -> constructor -> int (** @return param + args with letin *) val constructor_nalldecls : constructor -> int val constructor_nalldecls_env : env -> constructor -> int (** @return args without letin *) val constructor_nrealargs : constructor -> int val constructor_nrealargs_env : env -> constructor -> int (** @return args with letin *) val constructor_nrealdecls : constructor -> int val constructor_nrealdecls_env : env -> constructor -> int * Is there local defs in params or args ? val constructor_has_local_defs : constructor -> bool val inductive_has_local_defs : inductive -> bool val allowed_sorts : env -> inductive -> sorts_family list (** (Co)Inductive records with primitive projections do not have eta-conversion, hence no dependent elimination. *) val has_dependent_elim : mutual_inductive_body -> bool (** Primitive projections *) val projection_nparams : projection -> int val projection_nparams_env : env -> projection -> int val type_of_projection_knowing_arg : env -> evar_map -> Projection.t -> constr -> types -> types (** Extract information from an inductive family *) type constructor_summary = { cs_cstr : pconstructor; (* internal name of the constructor plus universes *) cs_params : constr list; (* parameters of the constructor in current ctx *) cs_nargs : int; (* length of arguments signature (letin included) *) cs_args : Context.Rel.t; (* signature of the arguments (letin included) *) actual realargs in the concl of cstr } val lift_constructor : int -> constructor_summary -> constructor_summary val get_constructor : pinductive * mutual_inductive_body * one_inductive_body * constr list -> int -> constructor_summary val get_constructors : env -> inductive_family -> constructor_summary array val get_projections : env -> inductive_family -> constant array option (** [get_arity] returns the arity of the inductive family instantiated with the parameters; if recursively non-uniform parameters are not part of the inductive family, they appears in the arity *) val get_arity : env -> inductive_family -> Context.Rel.t * sorts_family val build_dependent_constructor : constructor_summary -> constr val build_dependent_inductive : env -> inductive_family -> constr val make_arity_signature : env -> bool -> inductive_family -> Context.Rel.t val make_arity : env -> bool -> inductive_family -> sorts -> types val build_branch_type : env -> bool -> constr -> constructor_summary -> types (** Raise [Not_found] if not given a valid inductive type *) val extract_mrectype : constr -> pinductive * constr list val find_mrectype : env -> evar_map -> types -> pinductive * constr list val find_mrectype_vect : env -> evar_map -> types -> pinductive * constr array val find_rectype : env -> evar_map -> types -> inductive_type val find_inductive : env -> evar_map -> types -> pinductive * constr list val find_coinductive : env -> evar_map -> types -> pinductive * constr list (********************) (** Builds the case predicate arity (dependent or not) *) val arity_of_case_predicate : env -> inductive_family -> bool -> sorts -> types val type_case_branches_with_names : env -> pinductive * constr list -> constr -> constr -> types array * types (** Annotation for cases *) val make_case_info : env -> inductive -> case_style -> case_info (** Make a case or substitute projections if the inductive type is a record with primitive projections. Fail with an error if the elimination is dependent while the inductive type does not allow dependent elimination. *) val make_case_or_project : env -> inductive_family -> case_info -> (* pred *) constr -> (* term *) constr -> (* branches *) constr array -> constr i Compatibility val make_default_case_info : env - > case_style - > inductive - > case_info i val make_default_case_info : env -> case_style -> inductive -> case_info i*) (********************) val type_of_inductive_knowing_conclusion : env -> evar_map -> Inductive.mind_specif puniverses -> types -> evar_map * types (********************) val control_only_guard : env -> types -> unit
null
https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/pretyping/inductiveops.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** * Return type as quoted by the user * Return constructor types in normal form * An inductive type with its parameters (transparently supports reasoning either with only recursively uniform parameters or with all parameters including the recursively non-uniform ones * An inductive type with its parameters and real arguments * @return number of constructors * @return params context * @return full arity context, hence with letin * @return param + args without letin * @return param + args with letin * @return args without letin * @return args with letin * (Co)Inductive records with primitive projections do not have eta-conversion, hence no dependent elimination. * Primitive projections * Extract information from an inductive family internal name of the constructor plus universes parameters of the constructor in current ctx length of arguments signature (letin included) signature of the arguments (letin included) * [get_arity] returns the arity of the inductive family instantiated with the parameters; if recursively non-uniform parameters are not part of the inductive family, they appears in the arity * Raise [Not_found] if not given a valid inductive type ****************** * Builds the case predicate arity (dependent or not) * Annotation for cases * Make a case or substitute projections if the inductive type is a record with primitive projections. Fail with an error if the elimination is dependent while the inductive type does not allow dependent elimination. pred term branches ****************** ******************
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Names open Term open Declarations open Environ open Evd * The following three functions are similar to the ones defined in Inductive , but they expect an env Inductive, but they expect an env *) val type_of_inductive : env -> pinductive -> types val type_of_constructor : env -> pconstructor -> types val type_of_constructors : env -> pinductive -> types array val arities_of_constructors : env -> pinductive -> types array type inductive_family val make_ind_family : inductive puniverses * constr list -> inductive_family val dest_ind_family : inductive_family -> inductive puniverses * constr list val map_ind_family : (constr -> constr) -> inductive_family -> inductive_family val liftn_inductive_family : int -> int -> inductive_family -> inductive_family val lift_inductive_family : int -> inductive_family -> inductive_family val substnl_ind_family : constr list -> int -> inductive_family -> inductive_family type inductive_type = IndType of inductive_family * constr list val make_ind_type : inductive_family * constr list -> inductive_type val dest_ind_type : inductive_type -> inductive_family * constr list val map_inductive_type : (constr -> constr) -> inductive_type -> inductive_type val liftn_inductive_type : int -> int -> inductive_type -> inductive_type val lift_inductive_type : int -> inductive_type -> inductive_type val substnl_ind_type : constr list -> int -> inductive_type -> inductive_type val mkAppliedInd : inductive_type -> constr val mis_is_recursive_subset : int list -> wf_paths -> bool val mis_is_recursive : inductive * mutual_inductive_body * one_inductive_body -> bool val mis_nf_constructor_type : pinductive * mutual_inductive_body * one_inductive_body -> int -> constr * { 6 Extract information from an inductive name } val nconstructors : inductive -> int val nconstructors_env : env -> inductive -> int * @return arity of constructors excluding parameters , excluding local defs val constructors_nrealargs : inductive -> int array val constructors_nrealargs_env : env -> inductive -> int array * @return arity of constructors excluding parameters , including local defs val constructors_nrealdecls : inductive -> int array val constructors_nrealdecls_env : env -> inductive -> int array * @return the arity , excluding params , excluding local defs val inductive_nrealargs : inductive -> int val inductive_nrealargs_env : env -> inductive -> int * @return the arity , excluding params , including local defs val inductive_nrealdecls : inductive -> int val inductive_nrealdecls_env : env -> inductive -> int * @return the arity , including params , excluding local defs val inductive_nallargs : inductive -> int val inductive_nallargs_env : env -> inductive -> int * @return the arity , including params , including local defs val inductive_nalldecls : inductive -> int val inductive_nalldecls_env : env -> inductive -> int * @return nb of params without local defs val inductive_nparams : inductive -> int val inductive_nparams_env : env -> inductive -> int * @return nb of params with local defs val inductive_nparamdecls : inductive -> int val inductive_nparamdecls_env : env -> inductive -> int val inductive_paramdecls : pinductive -> Context.Rel.t val inductive_paramdecls_env : env -> pinductive -> Context.Rel.t val inductive_alldecls : pinductive -> Context.Rel.t val inductive_alldecls_env : env -> pinductive -> Context.Rel.t * { 7 Extract information from a constructor name } val constructor_nallargs : constructor -> int val constructor_nallargs_env : env -> constructor -> int val constructor_nalldecls : constructor -> int val constructor_nalldecls_env : env -> constructor -> int val constructor_nrealargs : constructor -> int val constructor_nrealargs_env : env -> constructor -> int val constructor_nrealdecls : constructor -> int val constructor_nrealdecls_env : env -> constructor -> int * Is there local defs in params or args ? val constructor_has_local_defs : constructor -> bool val inductive_has_local_defs : inductive -> bool val allowed_sorts : env -> inductive -> sorts_family list val has_dependent_elim : mutual_inductive_body -> bool val projection_nparams : projection -> int val projection_nparams_env : env -> projection -> int val type_of_projection_knowing_arg : env -> evar_map -> Projection.t -> constr -> types -> types type constructor_summary = { actual realargs in the concl of cstr } val lift_constructor : int -> constructor_summary -> constructor_summary val get_constructor : pinductive * mutual_inductive_body * one_inductive_body * constr list -> int -> constructor_summary val get_constructors : env -> inductive_family -> constructor_summary array val get_projections : env -> inductive_family -> constant array option val get_arity : env -> inductive_family -> Context.Rel.t * sorts_family val build_dependent_constructor : constructor_summary -> constr val build_dependent_inductive : env -> inductive_family -> constr val make_arity_signature : env -> bool -> inductive_family -> Context.Rel.t val make_arity : env -> bool -> inductive_family -> sorts -> types val build_branch_type : env -> bool -> constr -> constructor_summary -> types val extract_mrectype : constr -> pinductive * constr list val find_mrectype : env -> evar_map -> types -> pinductive * constr list val find_mrectype_vect : env -> evar_map -> types -> pinductive * constr array val find_rectype : env -> evar_map -> types -> inductive_type val find_inductive : env -> evar_map -> types -> pinductive * constr list val find_coinductive : env -> evar_map -> types -> pinductive * constr list val arity_of_case_predicate : env -> inductive_family -> bool -> sorts -> types val type_case_branches_with_names : env -> pinductive * constr list -> constr -> constr -> types array * types val make_case_info : env -> inductive -> case_style -> case_info val make_case_or_project : env -> inductive_family -> case_info -> i Compatibility val make_default_case_info : env - > case_style - > inductive - > case_info i val make_default_case_info : env -> case_style -> inductive -> case_info i*) val type_of_inductive_knowing_conclusion : env -> evar_map -> Inductive.mind_specif puniverses -> types -> evar_map * types val control_only_guard : env -> types -> unit
aaf2a75caae4461cbfc228160fdd37ae9bec3a75f993fe5c0a3082badb0e6bc5
mlin/ocaml-sqlite3EZ
sqlite3EZ.ml
open List open Sqlite3 module Rc = Sqlite3.Rc module Data = Sqlite3.Data exception Rc of Rc.t exception Finally of exn*exn let check_rc = function | Rc.OK | Rc.DONE -> () | rc -> raise (Rc rc) let bindall stmt a = Array.iteri (fun i x -> check_rc (bind stmt (i+1) x)) a type statement_instance = { stmt : stmt; parameter_count : int; mutable in_progress : bool; } type statement_status = New | Instantiated | Finalized type statement = { lazy_inst : statement_instance Lazy.t; mutable status : statement_status; } let instance st = if st.status = Finalized then failwith "Sqlite3EZ: attempt to use finalized statement" st.status <- Instantiated Lazy.force st.lazy_inst let statement_finaliser = function | { status = Instantiated; lazy_inst } as st -> ignore (finalize (Lazy.force lazy_inst).stmt) st.status <- Finalized | _ -> () let make_statement' db sql = let inst = lazy let stmt = prepare db sql {stmt = stmt; parameter_count = bind_parameter_count stmt; in_progress = false } let x = { lazy_inst = inst; status = New } Gc.finalise statement_finaliser x x let finally_reset statement f = TODO handle expired / recompile let instance = instance statement if instance.in_progress then failwith "Sqlite3EZ: attempt to execute statement already in progress" instance.in_progress <- true try let y = f instance instance.in_progress <- false check_rc (reset instance.stmt) trick GC into keeping statement until now y with | exn -> instance.in_progress <- false try check_rc (reset instance.stmt) with exn2 -> raise (Finally (exn,exn2)) trick GC into keeping statement until now raise exn let statement_exec statement parameters = finally_reset statement fun instance -> if Array.length parameters <> instance.parameter_count then invalid_arg "Sqlite3EZ.statement_exec: wrong number of parameters" bindall instance.stmt parameters let rc = ref Rc.OK while !rc <> Rc.DONE do rc := step instance.stmt if !rc = Rc.ROW then failwith "Sqlite3EZ.statement_exec: not a (_ -> unit) statement" check_rc !rc let statement_query statement parameters cons fold init = finally_reset statement fun instance -> if Array.length parameters <> instance.parameter_count then invalid_arg "Sqlite3EZ.statement_query : wrong number of parameters" bindall instance.stmt parameters let arbox = ref None let x = ref init let rc = ref (step instance.stmt) while !rc = Rc.ROW do let k = data_count instance.stmt let ar = match !arbox with | Some ar when Array.length ar = k -> ar | Some _ -> failwith "Sqlite3EZ.statement_query: varying number of result columns" | None -> let ar = Array.make k Data.NULL arbox := Some ar ar for i = 0 to k - 1 do ar.(i) <- column instance.stmt i x := fold (cons ar) !x rc := step instance.stmt check_rc !rc !x let statement_finalize x = if x.status = Instantiated then let inst = instance x check_rc (finalize inst.stmt) x.status <- Finalized type db = { h : Sqlite3.db; mutable still_open : bool; statement_begin : statement; statement_commit : statement; statement_rollback : statement; statement_savepoint : statement; statement_release : statement; statement_rollback_to : statement; } let db_finaliser = function | { still_open = true; h} -> ignore (db_close h) | _ -> () let wrap_db h = { h = h; still_open = true; statement_begin = make_statement' h "BEGIN"; statement_commit = make_statement' h "COMMIT"; statement_rollback = make_statement' h "ROLLBACK"; statement_savepoint = make_statement' h "SAVEPOINT a"; statement_release = make_statement' h "RELEASE a"; statement_rollback_to = make_statement' h "ROLLBACK TO a"; } let db_open ?mode ?mutex ?cache ?vfs fn = let h = db_open ?mode ?mutex ?cache ?vfs fn let x = wrap_db h Gc.finalise db_finaliser x x let db_close = function | x when x.still_open = true -> x.still_open <- false ignore (db_close x.h) | _ -> () let with_db ?mode ?mutex ?cache ?vfs fn f = let db = db_open ?mode ?mutex ?cache ?vfs fn try let y = f db db_close db y with | exn -> try db_close db with exn' -> raise (Finally (exn,exn')) raise exn let db_handle { h } = h let exec { h } sql = check_rc (exec h sql) let empty = [||] let transact db f = statement_exec db.statement_begin empty try let y = f db statement_exec db.statement_commit empty y with | exn -> try statement_exec db.statement_rollback empty with exn' -> raise (Finally (exn,exn')) raise exn let atomically db f = statement_exec db.statement_savepoint [||] try let y = f db statement_exec db.statement_release [||] y with | exn -> try statement_exec db.statement_rollback_to [||] statement_exec db.statement_release [||] with exn' -> raise (Finally (exn,exn')) raise exn let last_insert_rowid db = last_insert_rowid db.h let changes db = changes db.h let make_statement { h } sql = make_statement' h sql
null
https://raw.githubusercontent.com/mlin/ocaml-sqlite3EZ/7071b0589dc6444cf988240229f03f4e0fb54f70/sqlite3EZ.ml
ocaml
open List open Sqlite3 module Rc = Sqlite3.Rc module Data = Sqlite3.Data exception Rc of Rc.t exception Finally of exn*exn let check_rc = function | Rc.OK | Rc.DONE -> () | rc -> raise (Rc rc) let bindall stmt a = Array.iteri (fun i x -> check_rc (bind stmt (i+1) x)) a type statement_instance = { stmt : stmt; parameter_count : int; mutable in_progress : bool; } type statement_status = New | Instantiated | Finalized type statement = { lazy_inst : statement_instance Lazy.t; mutable status : statement_status; } let instance st = if st.status = Finalized then failwith "Sqlite3EZ: attempt to use finalized statement" st.status <- Instantiated Lazy.force st.lazy_inst let statement_finaliser = function | { status = Instantiated; lazy_inst } as st -> ignore (finalize (Lazy.force lazy_inst).stmt) st.status <- Finalized | _ -> () let make_statement' db sql = let inst = lazy let stmt = prepare db sql {stmt = stmt; parameter_count = bind_parameter_count stmt; in_progress = false } let x = { lazy_inst = inst; status = New } Gc.finalise statement_finaliser x x let finally_reset statement f = TODO handle expired / recompile let instance = instance statement if instance.in_progress then failwith "Sqlite3EZ: attempt to execute statement already in progress" instance.in_progress <- true try let y = f instance instance.in_progress <- false check_rc (reset instance.stmt) trick GC into keeping statement until now y with | exn -> instance.in_progress <- false try check_rc (reset instance.stmt) with exn2 -> raise (Finally (exn,exn2)) trick GC into keeping statement until now raise exn let statement_exec statement parameters = finally_reset statement fun instance -> if Array.length parameters <> instance.parameter_count then invalid_arg "Sqlite3EZ.statement_exec: wrong number of parameters" bindall instance.stmt parameters let rc = ref Rc.OK while !rc <> Rc.DONE do rc := step instance.stmt if !rc = Rc.ROW then failwith "Sqlite3EZ.statement_exec: not a (_ -> unit) statement" check_rc !rc let statement_query statement parameters cons fold init = finally_reset statement fun instance -> if Array.length parameters <> instance.parameter_count then invalid_arg "Sqlite3EZ.statement_query : wrong number of parameters" bindall instance.stmt parameters let arbox = ref None let x = ref init let rc = ref (step instance.stmt) while !rc = Rc.ROW do let k = data_count instance.stmt let ar = match !arbox with | Some ar when Array.length ar = k -> ar | Some _ -> failwith "Sqlite3EZ.statement_query: varying number of result columns" | None -> let ar = Array.make k Data.NULL arbox := Some ar ar for i = 0 to k - 1 do ar.(i) <- column instance.stmt i x := fold (cons ar) !x rc := step instance.stmt check_rc !rc !x let statement_finalize x = if x.status = Instantiated then let inst = instance x check_rc (finalize inst.stmt) x.status <- Finalized type db = { h : Sqlite3.db; mutable still_open : bool; statement_begin : statement; statement_commit : statement; statement_rollback : statement; statement_savepoint : statement; statement_release : statement; statement_rollback_to : statement; } let db_finaliser = function | { still_open = true; h} -> ignore (db_close h) | _ -> () let wrap_db h = { h = h; still_open = true; statement_begin = make_statement' h "BEGIN"; statement_commit = make_statement' h "COMMIT"; statement_rollback = make_statement' h "ROLLBACK"; statement_savepoint = make_statement' h "SAVEPOINT a"; statement_release = make_statement' h "RELEASE a"; statement_rollback_to = make_statement' h "ROLLBACK TO a"; } let db_open ?mode ?mutex ?cache ?vfs fn = let h = db_open ?mode ?mutex ?cache ?vfs fn let x = wrap_db h Gc.finalise db_finaliser x x let db_close = function | x when x.still_open = true -> x.still_open <- false ignore (db_close x.h) | _ -> () let with_db ?mode ?mutex ?cache ?vfs fn f = let db = db_open ?mode ?mutex ?cache ?vfs fn try let y = f db db_close db y with | exn -> try db_close db with exn' -> raise (Finally (exn,exn')) raise exn let db_handle { h } = h let exec { h } sql = check_rc (exec h sql) let empty = [||] let transact db f = statement_exec db.statement_begin empty try let y = f db statement_exec db.statement_commit empty y with | exn -> try statement_exec db.statement_rollback empty with exn' -> raise (Finally (exn,exn')) raise exn let atomically db f = statement_exec db.statement_savepoint [||] try let y = f db statement_exec db.statement_release [||] y with | exn -> try statement_exec db.statement_rollback_to [||] statement_exec db.statement_release [||] with exn' -> raise (Finally (exn,exn')) raise exn let last_insert_rowid db = last_insert_rowid db.h let changes db = changes db.h let make_statement { h } sql = make_statement' h sql
ac06a6e99b555a3f852f2bffb744e0b201f5a69099004a480ead4cc1015e0199
finnishtransportagency/harja
paallystekerros.cljs
(ns harja.views.urakka.pot2.paallystekerros "POT2-lomakkeen päällystekerros" (:require [reagent.core :refer [atom] :as r] [harja.domain.paallystysilmoitus :as pot] [harja.domain.pot2 :as pot2-domain] [harja.domain.tierekisteri :as tr] [harja.domain.yllapitokohde :as yllapitokohteet-domain] [harja.loki :refer [log]] [harja.ui.debug :refer [debug]] [harja.ui.grid :as grid] [harja.ui.ikonit :as ikonit] [harja.ui.yleiset :refer [ajax-loader]] [harja.tiedot.urakka.paallystys :as paallystys] [harja.views.urakka.pot2.paallyste-ja-alusta-yhteiset :as pot2-yhteiset] [harja.tiedot.urakka.pot2.pot2-tiedot :as pot2-tiedot] [harja.tiedot.urakka.pot2.materiaalikirjasto :as mk-tiedot] [harja.ui.yleiset :as yleiset] [harja.validointi :as v] [harja.fmt :as fmt]) (:require-macros [reagent.ratom :refer [reaction]] [cljs.core.async.macros :refer [go]] [harja.atom :refer [reaction<!]])) (defn validoi-paallystekerros [rivi taulukko] (let [{:keys [perustiedot tr-osien-tiedot]} (:paallystysilmoitus-lomakedata @paallystys/tila) paakohde (select-keys perustiedot tr/paaluvali-avaimet) riittää pot2 : Kohteiden päällekkyys keskenään validoidaan , myös validoinnit . validoitu (if (= (:tr-numero paakohde) (:tr-numero rivi)) (yllapitokohteet-domain/validoi-alikohde paakohde rivi [] (get tr-osien-tiedot (:tr-numero rivi)) vuosi) (yllapitokohteet-domain/validoi-muukohde paakohde rivi [] (get tr-osien-tiedot (:tr-numero rivi)) vuosi))] (yllapitokohteet-domain/validoitu-kohde-tekstit (dissoc validoitu :alikohde-paallekkyys :muukohde-paallekkyys) false))) (defn kohde-toisten-kanssa-paallekkain-validointi [alikohde? _ rivi taulukko] (let [toiset-alikohteet (keep (fn [[indeksi kohdeosa]] (when (and (:tr-alkuosa kohdeosa) (:tr-alkuetaisyys kohdeosa) (:tr-loppuosa kohdeosa) (:tr-loppuetaisyys kohdeosa) (not= kohdeosa rivi)) kohdeosa)) taulukko) paallekkyydet (filter #(yllapitokohteet-domain/tr-valit-paallekkain? rivi %) toiset-alikohteet)] (yllapitokohteet-domain/validoitu-kohde-tekstit {:alikohde-paallekkyys paallekkyydet} (not alikohde?)))) (defn paallystekerros "Alikohteiden päällystekerroksen rivien muokkaus" [e! {:keys [kirjoitusoikeus? perustiedot tr-osien-pituudet ohjauskahvat] :as app} {:keys [massat materiaalikoodistot validointi virheet-atom]} kohdeosat-atom] (let [voi-muokata? (not= :lukittu (:tila perustiedot)) ohjauskahva (:paallystekerros ohjauskahvat)] [grid/muokkaus-grid {:otsikko "Kulutuskerros" :tunniste :kohdeosa-id :rivinumerot? true :voi-muokata? voi-muokata? :voi-lisata? false :voi-kumota? false :muutos #(e! (pot2-tiedot/->Pot2Muokattu)) :custom-toiminto {:teksti "Lisää toimenpide" :toiminto #(e! (pot2-tiedot/->LisaaPaallysterivi kohdeosat-atom)) :opts {:ikoni (ikonit/livicon-plus) :luokka "nappi-toissijainen"}} :ohjaus ohjauskahva :validoi-alussa? true :virheet virheet-atom :piilota-toiminnot? true :rivi-validointi (:rivi validointi) :taulukko-validointi (:taulukko validointi) :tyhja (if (nil? @kohdeosat-atom) [ajax-loader "Haetaan kohdeosia..."] [yleiset/vihje "Aloita painamalla Lisää toimenpide -painiketta."])} [{:otsikko "Toimen\u00ADpide" :nimi :toimenpide :tayta-alas? pot2-tiedot/tayta-alas?-fn :tyyppi :valinta :valinnat (or (:paallystekerros-toimenpiteet materiaalikoodistot) []) :valinta-arvo ::pot2-domain/koodi :valinta-nayta ::pot2-domain/lyhenne :validoi [[:ei-tyhja "Anna arvo"]] :leveys (:toimenpide pot2-yhteiset/gridin-leveydet)} {:otsikko "Tie" :tyyppi :positiivinen-numero :tasaa :oikea :kokonaisluku? true :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :nimi :tr-numero :validoi (:tr-numero validointi)} {:otsikko "Ajor." :nimi :tr-ajorata :tyyppi :valinta :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :alasveto-luokka "kavenna-jos-kapea" :valinnat pot/+ajoradat-numerona+ :valinta-arvo :koodi :valinta-nayta (fn [rivi] (if rivi (:nimi rivi) "- Valitse Ajorata -")) :kokonaisluku? true :validoi [[:ei-tyhja "Anna arvo"]]} {:otsikko "Kaista" :nimi :tr-kaista :tyyppi :valinta :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :alasveto-luokka "kavenna-jos-kapea" :valinnat pot/+kaistat+ :valinta-arvo :koodi :valinta-nayta (fn [rivi] (if rivi (:nimi rivi) "- Valitse kaista -")) :kokonaisluku? true :validoi [[:ei-tyhja "Anna arvo"]]} {:otsikko "Aosa" :tyyppi :positiivinen-numero :tasaa :oikea :kokonaisluku? true :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :nimi :tr-alkuosa :validoi (:tr-alkuosa validointi)} {:otsikko "Aet" :tyyppi :positiivinen-numero :tasaa :oikea :kokonaisluku? true :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :nimi :tr-alkuetaisyys :validoi (:tr-alkuetaisyys validointi)} {:otsikko "Losa" :tyyppi :positiivinen-numero :tasaa :oikea :kokonaisluku? true :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :nimi :tr-loppuosa :validoi (:tr-loppuosa validointi)} {:otsikko "Let" :tyyppi :positiivinen-numero :tasaa :oikea :kokonaisluku? true :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :nimi :tr-loppuetaisyys :validoi (:tr-loppuetaisyys validointi)} {:otsikko "Pituus" :nimi :pituus :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :tyyppi :positiivinen-numero :tasaa :oikea :muokattava? (constantly false) :hae (fn [rivi] (tr/laske-tien-pituus (into {} (map (juxt key (comp :pituus val))) (get tr-osien-pituudet (:tr-numero rivi))) rivi))} {:otsikko "Pääl\u00ADlyste" :nimi :materiaali :leveys (:materiaali pot2-yhteiset/gridin-leveydet) :tayta-alas? pot2-tiedot/tayta-alas?-fn :tyyppi :valinta :valinnat-fn (fn [rivi] (let [karhinta-toimenpide? (= pot2-domain/+kulutuskerros-toimenpide-karhinta+ (:toimenpide rivi)) massa-valinnainen? karhinta-toimenpide? massat (or massat [])] (if massa-valinnainen? (cons {::pot2-domain/massa-id nil :tyhja "ei päällystettä"} massat) massat))) :valinta-arvo ::pot2-domain/massa-id :linkki-fn (fn [arvo] (e! (pot2-tiedot/->NaytaMateriaalilomake {::pot2-domain/massa-id arvo} true))) :linkki-icon (ikonit/livicon-external) :valinta-nayta (fn [rivi] (if (empty? massat) [:div.neutraali-tausta "Lisää massa"] (if-let [tyhja (:tyhja rivi)] [:span tyhja] [:div.pot2-paallyste [mk-tiedot/materiaalin-rikastettu-nimi {:tyypit (:massatyypit materiaalikoodistot) :materiaali (pot2-tiedot/rivi->massa-tai-murske rivi {:massat massat}) :fmt :komponentti}]]))) :validoi [[:ei-tyhja-jos-toinen-avain-ei-joukossa :toimenpide [pot2-domain/+kulutuskerros-toimenpide-karhinta+] "Anna arvo"]]} {:otsikko "Leveys (m)" :nimi :leveys :tyyppi :positiivinen-numero :tasaa :oikea :tayta-alas? pot2-tiedot/tayta-alas?-fn :desimaalien-maara 2 :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :validoi [[:ei-tyhja "Anna arvo"]] :validoi-kentta-fn (fn [numero] (v/validoi-numero numero 0 20 2))} {:otsikko "Kok.m. (t)" :nimi :kokonaismassamaara :tyyppi :positiivinen-numero :tasaa :oikea :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :validoi [[:ei-tyhja "Anna arvo"]] :validoi-kentta-fn (fn [numero] (v/validoi-numero numero 0 1000000 1))} {:otsikko "Pinta-ala (m²)" :nimi :pinta_ala :tyyppi :positiivinen-numero :tasaa :oikea :muokattava? (constantly false) :fmt #(fmt/desimaaliluku-opt % 1) :hae (fn [rivi] (when-let [pituus (tr/laske-tien-pituus (into {} (map (juxt key (comp :pituus val))) (get tr-osien-pituudet (:tr-numero rivi))) rivi)] (when (:leveys rivi) (* (:leveys rivi) pituus)))) :leveys (:perusleveys pot2-yhteiset/gridin-leveydet)} {:otsikko "Massa\u00ADmenekki (kg/m\u00B2)" :nimi :massamenekki :tyyppi :positiivinen-numero :tasaa :oikea :fmt #(fmt/desimaaliluku-opt % 1) :muokattava? (constantly false) :hae (fn [rivi] (let [massamaara (:kokonaismassamaara rivi) pinta-ala (:pinta_ala rivi)] (when (and massamaara (> pinta-ala 0)) * 1000 , koska kok.massamäärä on tonneja , halutaan kg / m2 pinta-ala)))) :tayta-alas? pot2-tiedot/tayta-alas?-fn :leveys (:perusleveys pot2-yhteiset/gridin-leveydet)} {:otsikko "" :nimi :kulutuspaallyste-toiminnot :tyyppi :reagent-komponentti :leveys (:toiminnot pot2-yhteiset/gridin-leveydet) :tasaa :keskita :komponentti-args [e! app kirjoitusoikeus? kohdeosat-atom :paallystekerros voi-muokata? ohjauskahva] :komponentti pot2-yhteiset/rivin-toiminnot-sarake}] kohdeosat-atom]))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/93b03a7a977db212913284f1b14ee75aafc4c28d/src/cljs/harja/views/urakka/pot2/paallystekerros.cljs
clojure
(ns harja.views.urakka.pot2.paallystekerros "POT2-lomakkeen päällystekerros" (:require [reagent.core :refer [atom] :as r] [harja.domain.paallystysilmoitus :as pot] [harja.domain.pot2 :as pot2-domain] [harja.domain.tierekisteri :as tr] [harja.domain.yllapitokohde :as yllapitokohteet-domain] [harja.loki :refer [log]] [harja.ui.debug :refer [debug]] [harja.ui.grid :as grid] [harja.ui.ikonit :as ikonit] [harja.ui.yleiset :refer [ajax-loader]] [harja.tiedot.urakka.paallystys :as paallystys] [harja.views.urakka.pot2.paallyste-ja-alusta-yhteiset :as pot2-yhteiset] [harja.tiedot.urakka.pot2.pot2-tiedot :as pot2-tiedot] [harja.tiedot.urakka.pot2.materiaalikirjasto :as mk-tiedot] [harja.ui.yleiset :as yleiset] [harja.validointi :as v] [harja.fmt :as fmt]) (:require-macros [reagent.ratom :refer [reaction]] [cljs.core.async.macros :refer [go]] [harja.atom :refer [reaction<!]])) (defn validoi-paallystekerros [rivi taulukko] (let [{:keys [perustiedot tr-osien-tiedot]} (:paallystysilmoitus-lomakedata @paallystys/tila) paakohde (select-keys perustiedot tr/paaluvali-avaimet) riittää pot2 : Kohteiden päällekkyys keskenään validoidaan , myös validoinnit . validoitu (if (= (:tr-numero paakohde) (:tr-numero rivi)) (yllapitokohteet-domain/validoi-alikohde paakohde rivi [] (get tr-osien-tiedot (:tr-numero rivi)) vuosi) (yllapitokohteet-domain/validoi-muukohde paakohde rivi [] (get tr-osien-tiedot (:tr-numero rivi)) vuosi))] (yllapitokohteet-domain/validoitu-kohde-tekstit (dissoc validoitu :alikohde-paallekkyys :muukohde-paallekkyys) false))) (defn kohde-toisten-kanssa-paallekkain-validointi [alikohde? _ rivi taulukko] (let [toiset-alikohteet (keep (fn [[indeksi kohdeosa]] (when (and (:tr-alkuosa kohdeosa) (:tr-alkuetaisyys kohdeosa) (:tr-loppuosa kohdeosa) (:tr-loppuetaisyys kohdeosa) (not= kohdeosa rivi)) kohdeosa)) taulukko) paallekkyydet (filter #(yllapitokohteet-domain/tr-valit-paallekkain? rivi %) toiset-alikohteet)] (yllapitokohteet-domain/validoitu-kohde-tekstit {:alikohde-paallekkyys paallekkyydet} (not alikohde?)))) (defn paallystekerros "Alikohteiden päällystekerroksen rivien muokkaus" [e! {:keys [kirjoitusoikeus? perustiedot tr-osien-pituudet ohjauskahvat] :as app} {:keys [massat materiaalikoodistot validointi virheet-atom]} kohdeosat-atom] (let [voi-muokata? (not= :lukittu (:tila perustiedot)) ohjauskahva (:paallystekerros ohjauskahvat)] [grid/muokkaus-grid {:otsikko "Kulutuskerros" :tunniste :kohdeosa-id :rivinumerot? true :voi-muokata? voi-muokata? :voi-lisata? false :voi-kumota? false :muutos #(e! (pot2-tiedot/->Pot2Muokattu)) :custom-toiminto {:teksti "Lisää toimenpide" :toiminto #(e! (pot2-tiedot/->LisaaPaallysterivi kohdeosat-atom)) :opts {:ikoni (ikonit/livicon-plus) :luokka "nappi-toissijainen"}} :ohjaus ohjauskahva :validoi-alussa? true :virheet virheet-atom :piilota-toiminnot? true :rivi-validointi (:rivi validointi) :taulukko-validointi (:taulukko validointi) :tyhja (if (nil? @kohdeosat-atom) [ajax-loader "Haetaan kohdeosia..."] [yleiset/vihje "Aloita painamalla Lisää toimenpide -painiketta."])} [{:otsikko "Toimen\u00ADpide" :nimi :toimenpide :tayta-alas? pot2-tiedot/tayta-alas?-fn :tyyppi :valinta :valinnat (or (:paallystekerros-toimenpiteet materiaalikoodistot) []) :valinta-arvo ::pot2-domain/koodi :valinta-nayta ::pot2-domain/lyhenne :validoi [[:ei-tyhja "Anna arvo"]] :leveys (:toimenpide pot2-yhteiset/gridin-leveydet)} {:otsikko "Tie" :tyyppi :positiivinen-numero :tasaa :oikea :kokonaisluku? true :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :nimi :tr-numero :validoi (:tr-numero validointi)} {:otsikko "Ajor." :nimi :tr-ajorata :tyyppi :valinta :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :alasveto-luokka "kavenna-jos-kapea" :valinnat pot/+ajoradat-numerona+ :valinta-arvo :koodi :valinta-nayta (fn [rivi] (if rivi (:nimi rivi) "- Valitse Ajorata -")) :kokonaisluku? true :validoi [[:ei-tyhja "Anna arvo"]]} {:otsikko "Kaista" :nimi :tr-kaista :tyyppi :valinta :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :alasveto-luokka "kavenna-jos-kapea" :valinnat pot/+kaistat+ :valinta-arvo :koodi :valinta-nayta (fn [rivi] (if rivi (:nimi rivi) "- Valitse kaista -")) :kokonaisluku? true :validoi [[:ei-tyhja "Anna arvo"]]} {:otsikko "Aosa" :tyyppi :positiivinen-numero :tasaa :oikea :kokonaisluku? true :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :nimi :tr-alkuosa :validoi (:tr-alkuosa validointi)} {:otsikko "Aet" :tyyppi :positiivinen-numero :tasaa :oikea :kokonaisluku? true :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :nimi :tr-alkuetaisyys :validoi (:tr-alkuetaisyys validointi)} {:otsikko "Losa" :tyyppi :positiivinen-numero :tasaa :oikea :kokonaisluku? true :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :nimi :tr-loppuosa :validoi (:tr-loppuosa validointi)} {:otsikko "Let" :tyyppi :positiivinen-numero :tasaa :oikea :kokonaisluku? true :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :nimi :tr-loppuetaisyys :validoi (:tr-loppuetaisyys validointi)} {:otsikko "Pituus" :nimi :pituus :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :tyyppi :positiivinen-numero :tasaa :oikea :muokattava? (constantly false) :hae (fn [rivi] (tr/laske-tien-pituus (into {} (map (juxt key (comp :pituus val))) (get tr-osien-pituudet (:tr-numero rivi))) rivi))} {:otsikko "Pääl\u00ADlyste" :nimi :materiaali :leveys (:materiaali pot2-yhteiset/gridin-leveydet) :tayta-alas? pot2-tiedot/tayta-alas?-fn :tyyppi :valinta :valinnat-fn (fn [rivi] (let [karhinta-toimenpide? (= pot2-domain/+kulutuskerros-toimenpide-karhinta+ (:toimenpide rivi)) massa-valinnainen? karhinta-toimenpide? massat (or massat [])] (if massa-valinnainen? (cons {::pot2-domain/massa-id nil :tyhja "ei päällystettä"} massat) massat))) :valinta-arvo ::pot2-domain/massa-id :linkki-fn (fn [arvo] (e! (pot2-tiedot/->NaytaMateriaalilomake {::pot2-domain/massa-id arvo} true))) :linkki-icon (ikonit/livicon-external) :valinta-nayta (fn [rivi] (if (empty? massat) [:div.neutraali-tausta "Lisää massa"] (if-let [tyhja (:tyhja rivi)] [:span tyhja] [:div.pot2-paallyste [mk-tiedot/materiaalin-rikastettu-nimi {:tyypit (:massatyypit materiaalikoodistot) :materiaali (pot2-tiedot/rivi->massa-tai-murske rivi {:massat massat}) :fmt :komponentti}]]))) :validoi [[:ei-tyhja-jos-toinen-avain-ei-joukossa :toimenpide [pot2-domain/+kulutuskerros-toimenpide-karhinta+] "Anna arvo"]]} {:otsikko "Leveys (m)" :nimi :leveys :tyyppi :positiivinen-numero :tasaa :oikea :tayta-alas? pot2-tiedot/tayta-alas?-fn :desimaalien-maara 2 :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :validoi [[:ei-tyhja "Anna arvo"]] :validoi-kentta-fn (fn [numero] (v/validoi-numero numero 0 20 2))} {:otsikko "Kok.m. (t)" :nimi :kokonaismassamaara :tyyppi :positiivinen-numero :tasaa :oikea :leveys (:perusleveys pot2-yhteiset/gridin-leveydet) :validoi [[:ei-tyhja "Anna arvo"]] :validoi-kentta-fn (fn [numero] (v/validoi-numero numero 0 1000000 1))} {:otsikko "Pinta-ala (m²)" :nimi :pinta_ala :tyyppi :positiivinen-numero :tasaa :oikea :muokattava? (constantly false) :fmt #(fmt/desimaaliluku-opt % 1) :hae (fn [rivi] (when-let [pituus (tr/laske-tien-pituus (into {} (map (juxt key (comp :pituus val))) (get tr-osien-pituudet (:tr-numero rivi))) rivi)] (when (:leveys rivi) (* (:leveys rivi) pituus)))) :leveys (:perusleveys pot2-yhteiset/gridin-leveydet)} {:otsikko "Massa\u00ADmenekki (kg/m\u00B2)" :nimi :massamenekki :tyyppi :positiivinen-numero :tasaa :oikea :fmt #(fmt/desimaaliluku-opt % 1) :muokattava? (constantly false) :hae (fn [rivi] (let [massamaara (:kokonaismassamaara rivi) pinta-ala (:pinta_ala rivi)] (when (and massamaara (> pinta-ala 0)) * 1000 , koska kok.massamäärä on tonneja , halutaan kg / m2 pinta-ala)))) :tayta-alas? pot2-tiedot/tayta-alas?-fn :leveys (:perusleveys pot2-yhteiset/gridin-leveydet)} {:otsikko "" :nimi :kulutuspaallyste-toiminnot :tyyppi :reagent-komponentti :leveys (:toiminnot pot2-yhteiset/gridin-leveydet) :tasaa :keskita :komponentti-args [e! app kirjoitusoikeus? kohdeosat-atom :paallystekerros voi-muokata? ohjauskahva] :komponentti pot2-yhteiset/rivin-toiminnot-sarake}] kohdeosat-atom]))
5423358533c158e31d02310b454282e227e845ae37342d4c107954474900b41f
wireapp/wire-server
Activation.hs
-- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any -- later version. -- -- This program is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more -- details. -- You should have received a copy of the GNU Affero General Public License along -- with this program. If not, see </>. -- | Activation of 'Email' addresses and 'Phone' numbers. module Brig.Data.Activation ( Activation (..), ActivationKey (..), ActivationCode (..), ActivationEvent (..), ActivationError (..), activationErrorToRegisterError, newActivation, mkActivationKey, lookupActivationCode, activateKey, verifyCode, ) where import Brig.App (Env) import Brig.Data.User import Brig.Data.UserKey import qualified Brig.Effects.CodeStore as E import Brig.Effects.CodeStore.Cassandra import Brig.Options import Brig.Types.Intra import Cassandra import Control.Error import Data.Id import Data.Text (pack) import qualified Data.Text.Ascii as Ascii import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as LT import Imports import OpenSSL.BN (randIntegerZeroToNMinusOne) import OpenSSL.EVP.Digest (digestBS, getDigestByName) import Polysemy import Text.Printf (printf) import Wire.API.User import Wire.API.User.Activation | The information associated with the pending activation of a ' UserKey ' . data Activation = Activation | An opaque key for the original ' UserKey ' pending activation . activationKey :: !ActivationKey, -- | The confidential activation code. activationCode :: !ActivationCode } deriving (Eq, Show) data ActivationError = UserKeyExists !LT.Text | InvalidActivationCodeWrongUser | InvalidActivationCodeWrongCode | InvalidActivationEmail !Email !String | InvalidActivationPhone !Phone activationErrorToRegisterError :: ActivationError -> RegisterError activationErrorToRegisterError = \case UserKeyExists _ -> RegisterErrorUserKeyExists InvalidActivationCodeWrongUser -> RegisterErrorInvalidActivationCodeWrongUser InvalidActivationCodeWrongCode -> RegisterErrorInvalidActivationCodeWrongCode InvalidActivationEmail _ _ -> RegisterErrorInvalidEmail InvalidActivationPhone _ -> RegisterErrorInvalidPhone data ActivationEvent = AccountActivated !UserAccount | EmailActivated !UserId !Email | PhoneActivated !UserId !Phone | Max . number of activation attempts per ' ActivationKey ' . maxAttempts :: Int32 maxAttempts = 3 -- docs/reference/user/activation.md {#RefActivationSubmit} activateKey :: forall m. (MonadClient m, MonadReader Env m) => ActivationKey -> ActivationCode -> Maybe UserId -> ExceptT ActivationError m (Maybe ActivationEvent) activateKey k c u = verifyCode k c >>= pickUser >>= activate where pickUser (uk, u') = maybe (throwE invalidUser) (pure . (uk,)) (u <|> u') activate (key, uid) = do a <- lift (lookupAccount uid) >>= maybe (throwE invalidUser) pure unless (accountStatus a == Active) $ -- this is never 'PendingActivation' in the flow this function is used in. throwE invalidCode case userIdentity (accountUser a) of Nothing -> do claim key uid let ident = foldKey EmailIdentity PhoneIdentity key lift $ activateUser uid ident let a' = a {accountUser = (accountUser a) {userIdentity = Just ident}} pure . Just $ AccountActivated a' Just _ -> do let usr = accountUser a (profileNeedsUpdate, oldKey) = foldKey (\(e :: Email) -> (Just e /= userEmail usr,) . fmap userEmailKey . userEmail) (\(p :: Phone) -> (Just p /= userPhone usr,) . fmap userPhoneKey . userPhone) key usr in handleExistingIdentity uid profileNeedsUpdate oldKey key handleExistingIdentity uid profileNeedsUpdate oldKey key | oldKey == Just key && not profileNeedsUpdate = pure Nothing -- activating existing key and exactly same profile -- (can happen when a user clicks on activation links more than once) | oldKey == Just key && profileNeedsUpdate = do lift $ foldKey (updateEmailAndDeleteEmailUnvalidated uid) (updatePhone uid) key pure . Just $ foldKey (EmailActivated uid) (PhoneActivated uid) key -- if the key is the same, we only want to update our profile | otherwise = do lift (runM (codeStoreToCassandra @m @'[Embed m] (E.mkPasswordResetKey uid >>= E.codeDelete))) claim key uid lift $ foldKey (updateEmailAndDeleteEmailUnvalidated uid) (updatePhone uid) key for_ oldKey $ lift . deleteKey pure . Just $ foldKey (EmailActivated uid) (PhoneActivated uid) key where updateEmailAndDeleteEmailUnvalidated :: UserId -> Email -> m () updateEmailAndDeleteEmailUnvalidated u' email = updateEmail u' email <* deleteEmailUnvalidated u' claim key uid = do ok <- lift $ claimKey key uid unless ok $ throwE . UserKeyExists . LT.fromStrict $ foldKey fromEmail fromPhone key | Create a new pending activation for a given ' UserKey ' . newActivation :: MonadClient m => UserKey -> -- | The timeout for the activation code. Timeout -> -- | The user with whom to associate the activation code. Maybe UserId -> m Activation newActivation uk timeout u = do (typ, key, code) <- liftIO $ foldKey (\e -> ("email",fromEmail e,) <$> genCode) (\p -> ("phone",fromPhone p,) <$> genCode) uk insert typ key code where insert t k c = do key <- liftIO $ mkActivationKey uk retry x5 . write keyInsert $ params LocalQuorum (key, t, k, c, u, maxAttempts, round timeout) pure $ Activation key c genCode = ActivationCode . Ascii.unsafeFromText . pack . printf "%06d" <$> randIntegerZeroToNMinusOne 1000000 | Lookup an activation code and it 's associated owner ( if any ) for a ' UserKey ' . lookupActivationCode :: MonadClient m => UserKey -> m (Maybe (Maybe UserId, ActivationCode)) lookupActivationCode k = liftIO (mkActivationKey k) >>= retry x1 . query1 codeSelect . params LocalQuorum . Identity -- | Verify an activation code. verifyCode :: MonadClient m => ActivationKey -> ActivationCode -> ExceptT ActivationError m (UserKey, Maybe UserId) verifyCode key code = do s <- lift . retry x1 . query1 keySelect $ params LocalQuorum (Identity key) case s of Just (ttl, Ascii t, k, c, u, r) -> if | c == code -> mkScope t k u | r >= 1 -> countdown (key, t, k, c, u, r - 1, ttl) >> throwE invalidCode | otherwise -> revoke >> throwE invalidCode Nothing -> throwE invalidCode where mkScope "email" k u = case parseEmail k of Just e -> pure (userEmailKey e, u) Nothing -> throwE invalidCode mkScope "phone" k u = case parsePhone k of Just p -> pure (userPhoneKey p, u) Nothing -> throwE invalidCode mkScope _ _ _ = throwE invalidCode countdown = lift . retry x5 . write keyInsert . params LocalQuorum revoke = lift $ deleteActivationPair key mkActivationKey :: UserKey -> IO ActivationKey mkActivationKey k = do d <- liftIO $ getDigestByName "SHA256" d' <- maybe (fail "SHA256 not found") pure d let bs = digestBS d' (T.encodeUtf8 $ keyText k) pure . ActivationKey $ Ascii.encodeBase64Url bs deleteActivationPair :: MonadClient m => ActivationKey -> m () deleteActivationPair = write keyDelete . params LocalQuorum . Identity invalidUser :: ActivationError invalidUser = InvalidActivationCodeWrongUser -- "User does not exist." invalidCode :: ActivationError " Invalid activation code " keyInsert :: PrepQuery W (ActivationKey, Text, Text, ActivationCode, Maybe UserId, Int32, Int32) () keyInsert = "INSERT INTO activation_keys \ \(key, key_type, key_text, code, user, retries) VALUES \ \(? , ? , ? , ? , ? , ? ) USING TTL ?" keySelect :: PrepQuery R (Identity ActivationKey) (Int32, Ascii, Text, ActivationCode, Maybe UserId, Int32) keySelect = "SELECT ttl(code) as ttl, key_type, key_text, code, user, retries FROM activation_keys WHERE key = ?" codeSelect :: PrepQuery R (Identity ActivationKey) (Maybe UserId, ActivationCode) codeSelect = "SELECT user, code FROM activation_keys WHERE key = ?" keyDelete :: PrepQuery W (Identity ActivationKey) () keyDelete = "DELETE FROM activation_keys WHERE key = ?"
null
https://raw.githubusercontent.com/wireapp/wire-server/72a03a776d4a8607b0a9c3e622003467be914894/services/brig/src/Brig/Data/Activation.hs
haskell
This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. with this program. If not, see </>. | Activation of 'Email' addresses and 'Phone' numbers. | The confidential activation code. docs/reference/user/activation.md {#RefActivationSubmit} this is never 'PendingActivation' in the flow this function is used in. activating existing key and exactly same profile (can happen when a user clicks on activation links more than once) if the key is the same, we only want to update our profile | The timeout for the activation code. | The user with whom to associate the activation code. | Verify an activation code. "User does not exist."
Copyright ( C ) 2022 Wire Swiss GmbH < > the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any You should have received a copy of the GNU Affero General Public License along module Brig.Data.Activation ( Activation (..), ActivationKey (..), ActivationCode (..), ActivationEvent (..), ActivationError (..), activationErrorToRegisterError, newActivation, mkActivationKey, lookupActivationCode, activateKey, verifyCode, ) where import Brig.App (Env) import Brig.Data.User import Brig.Data.UserKey import qualified Brig.Effects.CodeStore as E import Brig.Effects.CodeStore.Cassandra import Brig.Options import Brig.Types.Intra import Cassandra import Control.Error import Data.Id import Data.Text (pack) import qualified Data.Text.Ascii as Ascii import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as LT import Imports import OpenSSL.BN (randIntegerZeroToNMinusOne) import OpenSSL.EVP.Digest (digestBS, getDigestByName) import Polysemy import Text.Printf (printf) import Wire.API.User import Wire.API.User.Activation | The information associated with the pending activation of a ' UserKey ' . data Activation = Activation | An opaque key for the original ' UserKey ' pending activation . activationKey :: !ActivationKey, activationCode :: !ActivationCode } deriving (Eq, Show) data ActivationError = UserKeyExists !LT.Text | InvalidActivationCodeWrongUser | InvalidActivationCodeWrongCode | InvalidActivationEmail !Email !String | InvalidActivationPhone !Phone activationErrorToRegisterError :: ActivationError -> RegisterError activationErrorToRegisterError = \case UserKeyExists _ -> RegisterErrorUserKeyExists InvalidActivationCodeWrongUser -> RegisterErrorInvalidActivationCodeWrongUser InvalidActivationCodeWrongCode -> RegisterErrorInvalidActivationCodeWrongCode InvalidActivationEmail _ _ -> RegisterErrorInvalidEmail InvalidActivationPhone _ -> RegisterErrorInvalidPhone data ActivationEvent = AccountActivated !UserAccount | EmailActivated !UserId !Email | PhoneActivated !UserId !Phone | Max . number of activation attempts per ' ActivationKey ' . maxAttempts :: Int32 maxAttempts = 3 activateKey :: forall m. (MonadClient m, MonadReader Env m) => ActivationKey -> ActivationCode -> Maybe UserId -> ExceptT ActivationError m (Maybe ActivationEvent) activateKey k c u = verifyCode k c >>= pickUser >>= activate where pickUser (uk, u') = maybe (throwE invalidUser) (pure . (uk,)) (u <|> u') activate (key, uid) = do a <- lift (lookupAccount uid) >>= maybe (throwE invalidUser) pure throwE invalidCode case userIdentity (accountUser a) of Nothing -> do claim key uid let ident = foldKey EmailIdentity PhoneIdentity key lift $ activateUser uid ident let a' = a {accountUser = (accountUser a) {userIdentity = Just ident}} pure . Just $ AccountActivated a' Just _ -> do let usr = accountUser a (profileNeedsUpdate, oldKey) = foldKey (\(e :: Email) -> (Just e /= userEmail usr,) . fmap userEmailKey . userEmail) (\(p :: Phone) -> (Just p /= userPhone usr,) . fmap userPhoneKey . userPhone) key usr in handleExistingIdentity uid profileNeedsUpdate oldKey key handleExistingIdentity uid profileNeedsUpdate oldKey key | oldKey == Just key && not profileNeedsUpdate = pure Nothing | oldKey == Just key && profileNeedsUpdate = do lift $ foldKey (updateEmailAndDeleteEmailUnvalidated uid) (updatePhone uid) key pure . Just $ foldKey (EmailActivated uid) (PhoneActivated uid) key | otherwise = do lift (runM (codeStoreToCassandra @m @'[Embed m] (E.mkPasswordResetKey uid >>= E.codeDelete))) claim key uid lift $ foldKey (updateEmailAndDeleteEmailUnvalidated uid) (updatePhone uid) key for_ oldKey $ lift . deleteKey pure . Just $ foldKey (EmailActivated uid) (PhoneActivated uid) key where updateEmailAndDeleteEmailUnvalidated :: UserId -> Email -> m () updateEmailAndDeleteEmailUnvalidated u' email = updateEmail u' email <* deleteEmailUnvalidated u' claim key uid = do ok <- lift $ claimKey key uid unless ok $ throwE . UserKeyExists . LT.fromStrict $ foldKey fromEmail fromPhone key | Create a new pending activation for a given ' UserKey ' . newActivation :: MonadClient m => UserKey -> Timeout -> Maybe UserId -> m Activation newActivation uk timeout u = do (typ, key, code) <- liftIO $ foldKey (\e -> ("email",fromEmail e,) <$> genCode) (\p -> ("phone",fromPhone p,) <$> genCode) uk insert typ key code where insert t k c = do key <- liftIO $ mkActivationKey uk retry x5 . write keyInsert $ params LocalQuorum (key, t, k, c, u, maxAttempts, round timeout) pure $ Activation key c genCode = ActivationCode . Ascii.unsafeFromText . pack . printf "%06d" <$> randIntegerZeroToNMinusOne 1000000 | Lookup an activation code and it 's associated owner ( if any ) for a ' UserKey ' . lookupActivationCode :: MonadClient m => UserKey -> m (Maybe (Maybe UserId, ActivationCode)) lookupActivationCode k = liftIO (mkActivationKey k) >>= retry x1 . query1 codeSelect . params LocalQuorum . Identity verifyCode :: MonadClient m => ActivationKey -> ActivationCode -> ExceptT ActivationError m (UserKey, Maybe UserId) verifyCode key code = do s <- lift . retry x1 . query1 keySelect $ params LocalQuorum (Identity key) case s of Just (ttl, Ascii t, k, c, u, r) -> if | c == code -> mkScope t k u | r >= 1 -> countdown (key, t, k, c, u, r - 1, ttl) >> throwE invalidCode | otherwise -> revoke >> throwE invalidCode Nothing -> throwE invalidCode where mkScope "email" k u = case parseEmail k of Just e -> pure (userEmailKey e, u) Nothing -> throwE invalidCode mkScope "phone" k u = case parsePhone k of Just p -> pure (userPhoneKey p, u) Nothing -> throwE invalidCode mkScope _ _ _ = throwE invalidCode countdown = lift . retry x5 . write keyInsert . params LocalQuorum revoke = lift $ deleteActivationPair key mkActivationKey :: UserKey -> IO ActivationKey mkActivationKey k = do d <- liftIO $ getDigestByName "SHA256" d' <- maybe (fail "SHA256 not found") pure d let bs = digestBS d' (T.encodeUtf8 $ keyText k) pure . ActivationKey $ Ascii.encodeBase64Url bs deleteActivationPair :: MonadClient m => ActivationKey -> m () deleteActivationPair = write keyDelete . params LocalQuorum . Identity invalidUser :: ActivationError invalidCode :: ActivationError " Invalid activation code " keyInsert :: PrepQuery W (ActivationKey, Text, Text, ActivationCode, Maybe UserId, Int32, Int32) () keyInsert = "INSERT INTO activation_keys \ \(key, key_type, key_text, code, user, retries) VALUES \ \(? , ? , ? , ? , ? , ? ) USING TTL ?" keySelect :: PrepQuery R (Identity ActivationKey) (Int32, Ascii, Text, ActivationCode, Maybe UserId, Int32) keySelect = "SELECT ttl(code) as ttl, key_type, key_text, code, user, retries FROM activation_keys WHERE key = ?" codeSelect :: PrepQuery R (Identity ActivationKey) (Maybe UserId, ActivationCode) codeSelect = "SELECT user, code FROM activation_keys WHERE key = ?" keyDelete :: PrepQuery W (Identity ActivationKey) () keyDelete = "DELETE FROM activation_keys WHERE key = ?"
a5efe2187b8abea238fc00e82613feca52b718af2ae5a8989cb0b8186557bfd9
froydnj/ironclad
prng.lisp
;;;; -*- mode: lisp; indent-tabs-mode: nil -*- ;;;; prng.lisp -- common functions for pseudo-random number generators (in-package :crypto) (defvar *prng* nil "Default pseudo-random-number generator for use by all crypto the user must initialize it , e.g. with ( setf crypto:*prng* (crypto:make-prng :fortuna)).") (defclass pseudo-random-number-generator () () (:documentation "A pseudo random number generator. Base class for other PRNGs; not intended to be instantiated.")) (defun list-all-prngs () '(fortuna)) (defgeneric make-prng (name &key seed) (:documentation "Create a new NAME-type random number generator, seeding it from SEED. If SEED is a pathname or namestring, read data from the indicated file; if it is sequence of bytes, use those bytes if it is : then read from /dev / random ; if it is :URANDOM then read from /dev/urandom; if it is NIL then the generator is not seeded.")) (defmethod make-prng :around (name &key (seed :random)) (let ((prng (call-next-method))) (cond ((eq seed nil)) ((find seed '(:random :urandom)) (read-os-random-seed seed prng)) ((or (pathnamep seed) (stringp seed)) (read-seed seed prng)) ((typep seed 'simple-octet-vector) (reseed (slot-value prng 'generator) seed) (incf (slot-value prng 'reseed-count))) (t (error "SEED must be an octet vector, pathname indicator, :random or :urandom"))) prng)) (defun random-data (num-bytes &optional (pseudo-random-number-generator *prng*)) (internal-random-data num-bytes pseudo-random-number-generator)) (defgeneric internal-random-data (num-bytes pseudo-random-number-generator) (:documentation "Generate NUM-BYTES bytes using PSEUDO-RANDOM-NUMBER-GENERATOR")) (defun random-bits (num-bits &optional (pseudo-random-number-generator *prng*)) (logand (1- (expt 2 num-bits)) (octets-to-integer (internal-random-data (ceiling num-bits 8) pseudo-random-number-generator)))) (defun strong-random (limit &optional (prng *prng*)) "Return a strong random number from 0 to limit-1 inclusive. A drop-in replacement for COMMON-LISP:RANDOM." (assert (plusp limit)) (assert prng) (etypecase limit (integer (let* ((log-limit (log limit 2)) (num-bytes (ceiling log-limit 8)) (mask (1- (expt 2 (ceiling log-limit))))) (loop for random = (logand (ironclad:octets-to-integer (internal-random-data num-bytes prng)) mask) until (< random limit) finally (return random)))) (float (float (let ((floor (floor 1 long-float-epsilon))) (* limit (/ (strong-random floor) floor))))))) (defun os-random-seed (source num-bytes) #+unix(let ((path (cond ((eq source :random) #P"/dev/random") ((eq source :urandom) #P"/dev/urandom") (t (error "Source must be either :random or :urandom")))) (seq (make-array num-bytes :element-type '(unsigned-byte 8)))) (with-open-file (seed-file path :element-type '(unsigned-byte 8)) (assert (>= (read-sequence seq seed-file) num-bytes)) seq)) ;; FIXME: this is _untested_! #+(and win32 sb-dynamic-core)(sb-win32:crypt-gen-random num-bytes) #-(or unix (and win32 sb-dynamic-core))(error "OS-RANDOM-SEED is not supported on your platform.")) (defun read-os-random-seed (source &optional (prng *prng*)) (internal-read-os-random-seed source prng) t) (defgeneric internal-read-os-random-seed (source prng) (:documentation "(Re)seed PRNG from SOURCE. SOURCE may be :random or :urandom")) (defun read-seed (path &optional (pseudo-random-number-generator *prng*)) "Reseed PSEUDO-RANDOM-NUMBER-GENERATOR from PATH. If PATH doesn't exist, reseed from /dev/random and then write that seed to PATH." (if (probe-file path) (internal-read-seed path pseudo-random-number-generator) (progn (read-os-random-seed pseudo-random-number-generator) (write-seed path pseudo-random-number-generator) FIXME : this only works under SBCL . It 's important , though , ;; as it sets the proper permissions for reading a seedfile. #+sbcl(sb-posix:chmod path (logior sb-posix:S-IRUSR sb-posix:S-IWUSR)))) t) (defgeneric internal-read-seed (path prng) (:documentation "Reseed PRNG from PATH.")) (defun write-seed (path &optional (prng *prng*)) (internal-write-seed path prng)) (defgeneric internal-write-seed (path prng) (:documentation "Write enough random data from PRNG to PATH to properly reseed it."))
null
https://raw.githubusercontent.com/froydnj/ironclad/fe88483bba68eac4db3b48bb4a5a40035965fc84/src/prng/prng.lisp
lisp
-*- mode: lisp; indent-tabs-mode: nil -*- prng.lisp -- common functions for pseudo-random number generators not intended to be instantiated.")) if it is sequence of bytes, use those bytes if it if it is NIL then the FIXME: this is _untested_! as it sets the proper permissions for reading a seedfile.
(in-package :crypto) (defvar *prng* nil "Default pseudo-random-number generator for use by all crypto the user must initialize it , e.g. with ( setf crypto:*prng* (crypto:make-prng :fortuna)).") (defclass pseudo-random-number-generator () () (:documentation "A pseudo random number generator. Base class for (defun list-all-prngs () '(fortuna)) (defgeneric make-prng (name &key seed) (:documentation "Create a new NAME-type random number generator, seeding it from SEED. If SEED is a pathname or namestring, read data generator is not seeded.")) (defmethod make-prng :around (name &key (seed :random)) (let ((prng (call-next-method))) (cond ((eq seed nil)) ((find seed '(:random :urandom)) (read-os-random-seed seed prng)) ((or (pathnamep seed) (stringp seed)) (read-seed seed prng)) ((typep seed 'simple-octet-vector) (reseed (slot-value prng 'generator) seed) (incf (slot-value prng 'reseed-count))) (t (error "SEED must be an octet vector, pathname indicator, :random or :urandom"))) prng)) (defun random-data (num-bytes &optional (pseudo-random-number-generator *prng*)) (internal-random-data num-bytes pseudo-random-number-generator)) (defgeneric internal-random-data (num-bytes pseudo-random-number-generator) (:documentation "Generate NUM-BYTES bytes using PSEUDO-RANDOM-NUMBER-GENERATOR")) (defun random-bits (num-bits &optional (pseudo-random-number-generator *prng*)) (logand (1- (expt 2 num-bits)) (octets-to-integer (internal-random-data (ceiling num-bits 8) pseudo-random-number-generator)))) (defun strong-random (limit &optional (prng *prng*)) "Return a strong random number from 0 to limit-1 inclusive. A drop-in replacement for COMMON-LISP:RANDOM." (assert (plusp limit)) (assert prng) (etypecase limit (integer (let* ((log-limit (log limit 2)) (num-bytes (ceiling log-limit 8)) (mask (1- (expt 2 (ceiling log-limit))))) (loop for random = (logand (ironclad:octets-to-integer (internal-random-data num-bytes prng)) mask) until (< random limit) finally (return random)))) (float (float (let ((floor (floor 1 long-float-epsilon))) (* limit (/ (strong-random floor) floor))))))) (defun os-random-seed (source num-bytes) #+unix(let ((path (cond ((eq source :random) #P"/dev/random") ((eq source :urandom) #P"/dev/urandom") (t (error "Source must be either :random or :urandom")))) (seq (make-array num-bytes :element-type '(unsigned-byte 8)))) (with-open-file (seed-file path :element-type '(unsigned-byte 8)) (assert (>= (read-sequence seq seed-file) num-bytes)) seq)) #+(and win32 sb-dynamic-core)(sb-win32:crypt-gen-random num-bytes) #-(or unix (and win32 sb-dynamic-core))(error "OS-RANDOM-SEED is not supported on your platform.")) (defun read-os-random-seed (source &optional (prng *prng*)) (internal-read-os-random-seed source prng) t) (defgeneric internal-read-os-random-seed (source prng) (:documentation "(Re)seed PRNG from SOURCE. SOURCE may be :random or :urandom")) (defun read-seed (path &optional (pseudo-random-number-generator *prng*)) "Reseed PSEUDO-RANDOM-NUMBER-GENERATOR from PATH. If PATH doesn't exist, reseed from /dev/random and then write that seed to PATH." (if (probe-file path) (internal-read-seed path pseudo-random-number-generator) (progn (read-os-random-seed pseudo-random-number-generator) (write-seed path pseudo-random-number-generator) FIXME : this only works under SBCL . It 's important , though , #+sbcl(sb-posix:chmod path (logior sb-posix:S-IRUSR sb-posix:S-IWUSR)))) t) (defgeneric internal-read-seed (path prng) (:documentation "Reseed PRNG from PATH.")) (defun write-seed (path &optional (prng *prng*)) (internal-write-seed path prng)) (defgeneric internal-write-seed (path prng) (:documentation "Write enough random data from PRNG to PATH to properly reseed it."))
0c44ca082719548ecc514591662909c1291386fb0c1b43cbdfd7698624d741a9
mzp/coq-ruby
type_errors.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) $ I d : type_errors.ml 10533 2008 - 02 - 08 16:54:47Z msozeau $ open Names open Term open Sign open Environ open Reduction (* Type errors. *) type guard_error = (* Fixpoints *) | NotEnoughAbstractionInFixBody | RecursionNotOnInductiveType of constr | RecursionOnIllegalTerm of int * constr * int list * int list | NotEnoughArgumentsForFixCall of int (* CoFixpoints *) | CodomainNotInductiveType of constr | NestedRecursiveOccurrences | UnguardedRecursiveCall of constr | RecCallInTypeOfAbstraction of constr | RecCallInNonRecArgOfConstructor of constr | RecCallInTypeOfDef of constr | RecCallInCaseFun of constr | RecCallInCaseArg of constr | RecCallInCasePred of constr | NotGuardedForm of constr type arity_error = | NonInformativeToInformative | StrongEliminationOnNonSmallType | WrongArity type type_error = | UnboundRel of int | UnboundVar of variable | NotAType of unsafe_judgment | BadAssumption of unsafe_judgment | ReferenceVariables of constr | ElimArity of inductive * sorts_family list * constr * unsafe_judgment * (sorts_family * sorts_family * arity_error) option | CaseNotInductive of unsafe_judgment | WrongCaseInfo of inductive * case_info | NumberBranches of unsafe_judgment * int | IllFormedBranch of constr * int * constr * constr | Generalization of (name * types) * unsafe_judgment | ActualType of unsafe_judgment * types | CantApplyBadType of (int * constr * constr) * unsafe_judgment * unsafe_judgment array | CantApplyNonFunctional of unsafe_judgment * unsafe_judgment array | IllFormedRecBody of guard_error * name array * int * env * unsafe_judgment array | IllTypedRecBody of int * name array * unsafe_judgment array * types array exception TypeError of env * type_error let nfj {uj_val=c;uj_type=ct} = {uj_val=c;uj_type=nf_betaiota ct} let error_unbound_rel env n = raise (TypeError (env, UnboundRel n)) let error_unbound_var env v = raise (TypeError (env, UnboundVar v)) let error_not_type env j = raise (TypeError (env, NotAType j)) let error_assumption env j = raise (TypeError (env, BadAssumption j)) let error_reference_variables env id = raise (TypeError (env, ReferenceVariables id)) let error_elim_arity env ind aritylst c pj okinds = raise (TypeError (env, ElimArity (ind,aritylst,c,pj,okinds))) let error_case_not_inductive env j = raise (TypeError (env, CaseNotInductive j)) let error_number_branches env cj expn = raise (TypeError (env, NumberBranches (nfj cj,expn))) let error_ill_formed_branch env c i actty expty = raise (TypeError (env, IllFormedBranch (c,i,nf_betaiota actty, nf_betaiota expty))) let error_generalization env nvar c = raise (TypeError (env, Generalization (nvar,c))) let error_actual_type env j expty = raise (TypeError (env, ActualType (j,expty))) let error_cant_apply_not_functional env rator randl = raise (TypeError (env, CantApplyNonFunctional (rator,randl))) let error_cant_apply_bad_type env t rator randl = raise (TypeError (env, CantApplyBadType (t,rator,randl))) let error_ill_formed_rec_body env why lna i fixenv vdefj = raise (TypeError (env, IllFormedRecBody (why,lna,i,fixenv,vdefj))) let error_ill_typed_rec_body env i lna vdefj vargs = raise (TypeError (env, IllTypedRecBody (i,lna,vdefj,vargs)))
null
https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/kernel/type_errors.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** Type errors. Fixpoints CoFixpoints
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * $ I d : type_errors.ml 10533 2008 - 02 - 08 16:54:47Z msozeau $ open Names open Term open Sign open Environ open Reduction type guard_error = | NotEnoughAbstractionInFixBody | RecursionNotOnInductiveType of constr | RecursionOnIllegalTerm of int * constr * int list * int list | NotEnoughArgumentsForFixCall of int | CodomainNotInductiveType of constr | NestedRecursiveOccurrences | UnguardedRecursiveCall of constr | RecCallInTypeOfAbstraction of constr | RecCallInNonRecArgOfConstructor of constr | RecCallInTypeOfDef of constr | RecCallInCaseFun of constr | RecCallInCaseArg of constr | RecCallInCasePred of constr | NotGuardedForm of constr type arity_error = | NonInformativeToInformative | StrongEliminationOnNonSmallType | WrongArity type type_error = | UnboundRel of int | UnboundVar of variable | NotAType of unsafe_judgment | BadAssumption of unsafe_judgment | ReferenceVariables of constr | ElimArity of inductive * sorts_family list * constr * unsafe_judgment * (sorts_family * sorts_family * arity_error) option | CaseNotInductive of unsafe_judgment | WrongCaseInfo of inductive * case_info | NumberBranches of unsafe_judgment * int | IllFormedBranch of constr * int * constr * constr | Generalization of (name * types) * unsafe_judgment | ActualType of unsafe_judgment * types | CantApplyBadType of (int * constr * constr) * unsafe_judgment * unsafe_judgment array | CantApplyNonFunctional of unsafe_judgment * unsafe_judgment array | IllFormedRecBody of guard_error * name array * int * env * unsafe_judgment array | IllTypedRecBody of int * name array * unsafe_judgment array * types array exception TypeError of env * type_error let nfj {uj_val=c;uj_type=ct} = {uj_val=c;uj_type=nf_betaiota ct} let error_unbound_rel env n = raise (TypeError (env, UnboundRel n)) let error_unbound_var env v = raise (TypeError (env, UnboundVar v)) let error_not_type env j = raise (TypeError (env, NotAType j)) let error_assumption env j = raise (TypeError (env, BadAssumption j)) let error_reference_variables env id = raise (TypeError (env, ReferenceVariables id)) let error_elim_arity env ind aritylst c pj okinds = raise (TypeError (env, ElimArity (ind,aritylst,c,pj,okinds))) let error_case_not_inductive env j = raise (TypeError (env, CaseNotInductive j)) let error_number_branches env cj expn = raise (TypeError (env, NumberBranches (nfj cj,expn))) let error_ill_formed_branch env c i actty expty = raise (TypeError (env, IllFormedBranch (c,i,nf_betaiota actty, nf_betaiota expty))) let error_generalization env nvar c = raise (TypeError (env, Generalization (nvar,c))) let error_actual_type env j expty = raise (TypeError (env, ActualType (j,expty))) let error_cant_apply_not_functional env rator randl = raise (TypeError (env, CantApplyNonFunctional (rator,randl))) let error_cant_apply_bad_type env t rator randl = raise (TypeError (env, CantApplyBadType (t,rator,randl))) let error_ill_formed_rec_body env why lna i fixenv vdefj = raise (TypeError (env, IllFormedRecBody (why,lna,i,fixenv,vdefj))) let error_ill_typed_rec_body env i lna vdefj vargs = raise (TypeError (env, IllTypedRecBody (i,lna,vdefj,vargs)))
eedc6b186f0c3243eac5e52576f3ed2b7b59a6d07dec12ea4fb25ad641a78c1a
metabase/metabase
image_bundle.clj
(ns metabase.pulse.render.image-bundle "Logic related to creating image bundles, and some predefined ones. An image bundle contains the data needed to either encode the image inline in a URL (when `render-type` is `:inline`), or create the hashes/references needed for an attached image (`render-type` of `:attachment`)" (:require [clojure.java.io :as io]) (:import (java.util Arrays) (org.apache.commons.io IOUtils) (org.fit.cssbox.misc Base64Coder))) (set! *warn-on-reflection* true) (defn- hash-bytes "Generate a hash to be used in a Content-ID" [^bytes img-bytes] (Math/abs ^Integer (Arrays/hashCode img-bytes))) (defn- hash-image-url "Generate a hash to be used in a Content-ID" [^java.net.URL url] (-> url io/input-stream IOUtils/toByteArray hash-bytes)) (defn- content-id-reference [content-id] (str "cid:" content-id)) (defn- mb-hash-str [image-hash] (str image-hash "@metabase")) (defn- write-byte-array-to-temp-file [^bytes img-bytes] (let [f (doto (java.io.File/createTempFile "metabase_pulse_image_" ".png") .deleteOnExit)] (with-open [fos (java.io.FileOutputStream. f)] (.write fos img-bytes)) f)) (defn- byte-array->url [^bytes img-bytes] (-> img-bytes write-byte-array-to-temp-file io/as-url)) (defn render-img-data-uri "Takes a PNG byte array and returns a Base64 encoded URI" [img-bytes] (str "data:image/png;base64," (String. (Base64Coder/encode img-bytes)))) (defmulti make-image-bundle "Create an image bundle. An image bundle contains the data needed to either encode the image inline (when `render-type` is `:inline`), or create the hashes/references needed for an attached image (`render-type` of `:attachment`)" (fn [render-type url-or-bytes] [render-type (class url-or-bytes)])) (defmethod make-image-bundle [:attachment java.net.URL] [render-type, ^java.net.URL url] (let [content-id (mb-hash-str (hash-image-url url))] {:content-id content-id :image-url url :image-src (content-id-reference content-id) :render-type render-type})) (defmethod make-image-bundle [:attachment (class (byte-array 0))] [render-type image-bytes] (let [image-url (byte-array->url image-bytes) content-id (mb-hash-str (hash-bytes image-bytes))] {:content-id content-id :image-url image-url :image-src (content-id-reference content-id) :render-type render-type})) (defmethod make-image-bundle [:inline java.net.URL] [render-type, ^java.net.URL url] {:image-src (-> url io/input-stream IOUtils/toByteArray render-img-data-uri) :image-url url :render-type render-type}) (defmethod make-image-bundle [:inline (Class/forName "[B")] [render-type image-bytes] {:image-src (render-img-data-uri image-bytes) :render-type render-type}) (def ^:private external-link-url (io/resource "frontend_client/app/assets/img/external_link.png")) (def ^:private no-results-url (io/resource "frontend_client/app/assets/img/")) (def ^:private attached-url (io/resource "frontend_client/app/assets/img/")) (def ^:private external-link-image (delay (make-image-bundle :attachment external-link-url))) (def ^:private no-results-image (delay (make-image-bundle :attachment no-results-url))) (def ^:private attached-image (delay (make-image-bundle :attachment attached-url))) (defn external-link-image-bundle "Image bundle for an external link icon." [render-type] (case render-type :attachment @external-link-image :inline (make-image-bundle render-type external-link-url))) (defn no-results-image-bundle "Image bundle for the 'No results' image." [render-type] (case render-type :attachment @no-results-image :inline (make-image-bundle render-type no-results-url))) (defn attached-image-bundle "Image bundle for paperclip 'attachment' image." [render-type] (case render-type :attachment @attached-image :inline (make-image-bundle render-type attached-url))) (defn image-bundle->attachment "Convert an image bundle into an email attachment." [{:keys [render-type content-id image-url]}] (case render-type :attachment {content-id image-url} :inline nil))
null
https://raw.githubusercontent.com/metabase/metabase/7e3048bf73f6cb7527579446166d054292166163/src/metabase/pulse/render/image_bundle.clj
clojure
(ns metabase.pulse.render.image-bundle "Logic related to creating image bundles, and some predefined ones. An image bundle contains the data needed to either encode the image inline in a URL (when `render-type` is `:inline`), or create the hashes/references needed for an attached image (`render-type` of `:attachment`)" (:require [clojure.java.io :as io]) (:import (java.util Arrays) (org.apache.commons.io IOUtils) (org.fit.cssbox.misc Base64Coder))) (set! *warn-on-reflection* true) (defn- hash-bytes "Generate a hash to be used in a Content-ID" [^bytes img-bytes] (Math/abs ^Integer (Arrays/hashCode img-bytes))) (defn- hash-image-url "Generate a hash to be used in a Content-ID" [^java.net.URL url] (-> url io/input-stream IOUtils/toByteArray hash-bytes)) (defn- content-id-reference [content-id] (str "cid:" content-id)) (defn- mb-hash-str [image-hash] (str image-hash "@metabase")) (defn- write-byte-array-to-temp-file [^bytes img-bytes] (let [f (doto (java.io.File/createTempFile "metabase_pulse_image_" ".png") .deleteOnExit)] (with-open [fos (java.io.FileOutputStream. f)] (.write fos img-bytes)) f)) (defn- byte-array->url [^bytes img-bytes] (-> img-bytes write-byte-array-to-temp-file io/as-url)) (defn render-img-data-uri "Takes a PNG byte array and returns a Base64 encoded URI" [img-bytes] (str "data:image/png;base64," (String. (Base64Coder/encode img-bytes)))) (defmulti make-image-bundle "Create an image bundle. An image bundle contains the data needed to either encode the image inline (when `render-type` is `:inline`), or create the hashes/references needed for an attached image (`render-type` of `:attachment`)" (fn [render-type url-or-bytes] [render-type (class url-or-bytes)])) (defmethod make-image-bundle [:attachment java.net.URL] [render-type, ^java.net.URL url] (let [content-id (mb-hash-str (hash-image-url url))] {:content-id content-id :image-url url :image-src (content-id-reference content-id) :render-type render-type})) (defmethod make-image-bundle [:attachment (class (byte-array 0))] [render-type image-bytes] (let [image-url (byte-array->url image-bytes) content-id (mb-hash-str (hash-bytes image-bytes))] {:content-id content-id :image-url image-url :image-src (content-id-reference content-id) :render-type render-type})) (defmethod make-image-bundle [:inline java.net.URL] [render-type, ^java.net.URL url] {:image-src (-> url io/input-stream IOUtils/toByteArray render-img-data-uri) :image-url url :render-type render-type}) (defmethod make-image-bundle [:inline (Class/forName "[B")] [render-type image-bytes] {:image-src (render-img-data-uri image-bytes) :render-type render-type}) (def ^:private external-link-url (io/resource "frontend_client/app/assets/img/external_link.png")) (def ^:private no-results-url (io/resource "frontend_client/app/assets/img/")) (def ^:private attached-url (io/resource "frontend_client/app/assets/img/")) (def ^:private external-link-image (delay (make-image-bundle :attachment external-link-url))) (def ^:private no-results-image (delay (make-image-bundle :attachment no-results-url))) (def ^:private attached-image (delay (make-image-bundle :attachment attached-url))) (defn external-link-image-bundle "Image bundle for an external link icon." [render-type] (case render-type :attachment @external-link-image :inline (make-image-bundle render-type external-link-url))) (defn no-results-image-bundle "Image bundle for the 'No results' image." [render-type] (case render-type :attachment @no-results-image :inline (make-image-bundle render-type no-results-url))) (defn attached-image-bundle "Image bundle for paperclip 'attachment' image." [render-type] (case render-type :attachment @attached-image :inline (make-image-bundle render-type attached-url))) (defn image-bundle->attachment "Convert an image bundle into an email attachment." [{:keys [render-type content-id image-url]}] (case render-type :attachment {content-id image-url} :inline nil))
3cab6af1a86549d023eaaefc305e11c24dd1a18aea7b7be8c5414332b50d650e
cmpitg/ulquikit
generate-html.lisp
;; This file is part of Ulquikit project . ;; Copyright ( C ) 2014 - 2017 Ha - Duong Nguyen < cmpitg AT gmailDOTcom > ;; Ulquikit 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. ;; Ulquikit 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 Ulquikit . If not , see < / > . ;; (in-package #:ulquikit-cmd) (defcmd generate-html (&key (from "src") (to "docs") (recursive t)) (declare ((or string pathname list) from) ((or string pathname) to)) (display-cmd "Generating HTML") (ulquikit:generate-html :from from :to to :recursive recursive))
null
https://raw.githubusercontent.com/cmpitg/ulquikit/4bea3ba0321de4e384347f829b68bcfb7c661b70/generated-src/commands/generate-html.lisp
lisp
any later version. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
This file is part of Ulquikit project . Copyright ( C ) 2014 - 2017 Ha - Duong Nguyen < cmpitg AT gmailDOTcom > Ulquikit 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 ) Ulquikit is distributed in the hope that it will be useful , but WITHOUT ANY You should have received a copy of the GNU General Public License along with Ulquikit . If not , see < / > . (in-package #:ulquikit-cmd) (defcmd generate-html (&key (from "src") (to "docs") (recursive t)) (declare ((or string pathname list) from) ((or string pathname) to)) (display-cmd "Generating HTML") (ulquikit:generate-html :from from :to to :recursive recursive))
0f3a07c0250e28be5198156d71786239764780c0e3d47ab165935d8402d1a1fa
techascent/tvm-clj
project.clj
(defproject tvm-example "0.1.0-SNAPSHOT" :description "Example project using tvm" :url "-ascent/tvm-clj" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.10.0"] [tvm-clj "5.0"] [techascent/tech.opencv "4.25"]] ;;This is useful if you want to see where the loaded tvm library ;;is coming from. We really recommend that you install a tvm ;;built specifically for your system into /usr/lib, however, as there ;;are quite a few options possible for tvm. :jvm-opts ["-Djna.debug_load=true"] )
null
https://raw.githubusercontent.com/techascent/tvm-clj/1088845bd613b4ba14b00381ffe3cdbd3d8b639e/examples/project.clj
clojure
This is useful if you want to see where the loaded tvm library is coming from. We really recommend that you install a tvm built specifically for your system into /usr/lib, however, as there are quite a few options possible for tvm.
(defproject tvm-example "0.1.0-SNAPSHOT" :description "Example project using tvm" :url "-ascent/tvm-clj" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.10.0"] [tvm-clj "5.0"] [techascent/tech.opencv "4.25"]] :jvm-opts ["-Djna.debug_load=true"] )
06faa7645b114422baa5be0fcaa819de7dea537dcd0964addf34ba9d8575da23
dktr0/estuary
Term.hs
{-# LANGUAGE OverloadedStrings #-} module Estuary.Types.Term where import Data.Text import Estuary.Types.Language data Term = EstuaryDescription | Tutorials | Solo | Collaborate | Send | CreateNewEnsemble | Language | Confirm | Cancel | CreateNewEnsembleNote | ModeratorPassword | CommunityPassword | HostPassword | ParticipantPassword | Ensemble | EnsembleName | EnsembleExpiry | AnonymousParticipants | TerminalChat | Theme | Load | Peak | About| NewTempo| EvalTerm | JoiningEnsemble | EnsembleUserName | EnsembleLocation | EnsembleLogin | Syntax | Connections | Latency | Resolution | Brightness | Reference | Settings | Activity | ActivityDescription | Status | StatusDescription | LatencyDescription | LoadDescription | FPS | FPSDescription | IPaddress | IPaddressDescription | TerminalViewCommands | Voices | AddATitle deriving (Show,Eq) translate :: Term -> Language -> Text translate AddATitle English = "Add a title" translate AddATitle Español = "Add a title" translate TerminalViewCommands Français = "Estuary (un symbiote de codage en ligne)" translate TerminalViewCommands English = "Estuary (a live coding symbiont)" translate TerminalViewCommands Español = "Estuary (una simbionte live coding)" translate EstuaryDescription Français = "Estuary (un symbiote de codage en ligne)" translate EstuaryDescription English = "Estuary (a live coding symbiont)" translate EstuaryDescription Español = "Estuary (una simbionte live coding)" translate Tutorials Français = "Tutoriels" translate Tutorials Español = "Tutoriales" translate Tutorials English = "Tutorials" translate About Français = "À propos de Estuary" translate About Español = "Acerca de Estuary" translate About English = "About Estuary" translate Solo Français = "Mode Seul" translate Solo Español = "Modo Solo" translate Solo English = "Solo Mode" translate Collaborate Français = "Collaborer" translate Collaborate Español = "Colaborar" translate Collaborate English = "Collaborate" translate Send Français = "Envoyer" translate Send Español = "Enviar" translate Send English = "Send" translate Ensemble English = "Ensemble" translate Ensemble Français = "Ensemble" translate Ensemble Español = "Ensamble" translate CreateNewEnsemble Français = "Créer un nouvel ensemble" translate CreateNewEnsemble English = "Create new ensemble" translate CreateNewEnsemble Español = "Crear nuevo ensamble" translate Language Français = "Langage" translate Language English = "Language" translate Language Español = "Idioma" translate Confirm Français = "Confirmer" translate Confirm English = "Confirm" translate Confirm Español = "Confirmar" translate Cancel Français = "Annuler" translate Cancel English = "Cancel" translate Cancel Español = "Cancelar" translate ModeratorPassword English = "Moderator password:" translate ModeratorPassword Español = "Contraseña del/de la moderador(a):" translate CommunityPassword English = "Community password:" translate CommunityPassword Español = "Contraseña comunitaria:" translate HostPassword English = "Host password:" translate HostPassword Español = "Contraseña del/de la anfintrión(a):" translate ParticipantPassword English = "Participant password:" translate ParticipantPassword Español = "Contraseña del/de la participante:" translate EnsembleName Français = "Nom de l'ensemble:" translate EnsembleName English = "Ensemble name:" translate EnsembleName Español = "Nombre del ensamble:" translate EnsembleExpiry English = "Ensemble Expiry:" translate EnsembleExpiry Español = "Expiración del ensemble:" translate AnonymousParticipants English = "Anonymous Participants" translate AnonymousParticipants Español = "Participantes Anónimos" translate TerminalChat Français = "Terminal/Chat:" translate TerminalChat English = "Terminal/Chat:" translate TerminalChat Español = "Terminal/Chat:" translate Theme Français = "Thème" translate Theme English = "Theme" translate Theme Español = "Tema" translate Load Français = "charge" translate Load English = "load" translate Load Español = "carga" translate NewTempo Français = "Établir un nouveau tempo" translate NewTempo English = "Set new tempo" translate NewTempo Español = "Establecer Nuevo tempo" translate EvalTerm Français = "Eval" translate EvalTerm English = "Eval" translate EvalTerm Español = "Eval" translate JoiningEnsemble Français = "Joindre l'ensemble" translate JoiningEnsemble English = "Joining ensemble" translate JoiningEnsemble Español = "Unirse al ensamble" translate EnsembleUserName Français = "Entrer le nom d'utilisateur (optionel) comme membre de l'ensemble:" translate EnsembleUserName English = "Enter username (optional) within ensemble:" translate EnsembleUserName Español = "Ingresar nombre de usuario dentro del ensamble (opcional):" translate EnsembleLocation Français = "Décrivez votre situation géographique (optionel):" translate EnsembleLocation English = "Describe your location (optional):" translate EnsembleLocation Español = "Coloca tu localización (opcional):" translate EnsembleLogin Français = "S'identifier" translate EnsembleLogin English = "Login" translate EnsembleLogin Español = "Ingresar" translate Peak Français = "pic" translate Peak English = "peak" translate Peak Español = "tope" translate Syntax English = "Syntax" translate Syntax Español = "Sintaxis" translate Connections English = "connections" translate Connections Español = "conexiones" translate Latency English = "latency" translate Latency Español = "latencia" translate Resolution English = "Resolution" translate Resolution Español = "Resolución" translate Brightness English = "Brightness" translate Brightness Español = "Brillo" translate Reference English = "Reference" translate Reference Español = "Referencia" translate Settings English = "Settings" translate Settings Español = "Configuración" translate Activity English = "activity" translate Activity Español = "actividad" translate ActivityDescription English = "The last time participants edited some code" translate ActivityDescription Español = "La última vez que las participantes editaron el código." translate Status English = "status" translate Status Español = "estatus" translate StatusDescription English = "Displays how are the participants doing today" translate StatusDescription Español = "Muestra cómo se sientes l@s participantes el día de hoy" translate LatencyDescription English = "The delay before a transfer of data begins" translate LatencyDescription Español = "El retraso de tiempo entre la transferencia de datos" translate LoadDescription English = "The amount of work each participant computer is doing" translate LoadDescription Español = "La cantidad de trabajo que cada computadora participante está haciendo" translate FPS English = "FPS" translate FPS Español = "CPS" translate FPSDescription English = "The frames per second of the participants" translate FPSDescription Español = "Los cuadros por segundo de cada participante" translate IPaddress English = "IP Address" translate IPaddress Español = "dirección IP" translate IPaddressDescription English = "The IP addresses of the participants" translate IPaddressDescription Español = "Las direcciones IP de l@s participantes" translate Voices English = "voices" translate x _ = translate x English
null
https://raw.githubusercontent.com/dktr0/estuary/d35fdb37bee3a55701131ccdbda3eb5255b86929/client/src/Estuary/Types/Term.hs
haskell
# LANGUAGE OverloadedStrings #
module Estuary.Types.Term where import Data.Text import Estuary.Types.Language data Term = EstuaryDescription | Tutorials | Solo | Collaborate | Send | CreateNewEnsemble | Language | Confirm | Cancel | CreateNewEnsembleNote | ModeratorPassword | CommunityPassword | HostPassword | ParticipantPassword | Ensemble | EnsembleName | EnsembleExpiry | AnonymousParticipants | TerminalChat | Theme | Load | Peak | About| NewTempo| EvalTerm | JoiningEnsemble | EnsembleUserName | EnsembleLocation | EnsembleLogin | Syntax | Connections | Latency | Resolution | Brightness | Reference | Settings | Activity | ActivityDescription | Status | StatusDescription | LatencyDescription | LoadDescription | FPS | FPSDescription | IPaddress | IPaddressDescription | TerminalViewCommands | Voices | AddATitle deriving (Show,Eq) translate :: Term -> Language -> Text translate AddATitle English = "Add a title" translate AddATitle Español = "Add a title" translate TerminalViewCommands Français = "Estuary (un symbiote de codage en ligne)" translate TerminalViewCommands English = "Estuary (a live coding symbiont)" translate TerminalViewCommands Español = "Estuary (una simbionte live coding)" translate EstuaryDescription Français = "Estuary (un symbiote de codage en ligne)" translate EstuaryDescription English = "Estuary (a live coding symbiont)" translate EstuaryDescription Español = "Estuary (una simbionte live coding)" translate Tutorials Français = "Tutoriels" translate Tutorials Español = "Tutoriales" translate Tutorials English = "Tutorials" translate About Français = "À propos de Estuary" translate About Español = "Acerca de Estuary" translate About English = "About Estuary" translate Solo Français = "Mode Seul" translate Solo Español = "Modo Solo" translate Solo English = "Solo Mode" translate Collaborate Français = "Collaborer" translate Collaborate Español = "Colaborar" translate Collaborate English = "Collaborate" translate Send Français = "Envoyer" translate Send Español = "Enviar" translate Send English = "Send" translate Ensemble English = "Ensemble" translate Ensemble Français = "Ensemble" translate Ensemble Español = "Ensamble" translate CreateNewEnsemble Français = "Créer un nouvel ensemble" translate CreateNewEnsemble English = "Create new ensemble" translate CreateNewEnsemble Español = "Crear nuevo ensamble" translate Language Français = "Langage" translate Language English = "Language" translate Language Español = "Idioma" translate Confirm Français = "Confirmer" translate Confirm English = "Confirm" translate Confirm Español = "Confirmar" translate Cancel Français = "Annuler" translate Cancel English = "Cancel" translate Cancel Español = "Cancelar" translate ModeratorPassword English = "Moderator password:" translate ModeratorPassword Español = "Contraseña del/de la moderador(a):" translate CommunityPassword English = "Community password:" translate CommunityPassword Español = "Contraseña comunitaria:" translate HostPassword English = "Host password:" translate HostPassword Español = "Contraseña del/de la anfintrión(a):" translate ParticipantPassword English = "Participant password:" translate ParticipantPassword Español = "Contraseña del/de la participante:" translate EnsembleName Français = "Nom de l'ensemble:" translate EnsembleName English = "Ensemble name:" translate EnsembleName Español = "Nombre del ensamble:" translate EnsembleExpiry English = "Ensemble Expiry:" translate EnsembleExpiry Español = "Expiración del ensemble:" translate AnonymousParticipants English = "Anonymous Participants" translate AnonymousParticipants Español = "Participantes Anónimos" translate TerminalChat Français = "Terminal/Chat:" translate TerminalChat English = "Terminal/Chat:" translate TerminalChat Español = "Terminal/Chat:" translate Theme Français = "Thème" translate Theme English = "Theme" translate Theme Español = "Tema" translate Load Français = "charge" translate Load English = "load" translate Load Español = "carga" translate NewTempo Français = "Établir un nouveau tempo" translate NewTempo English = "Set new tempo" translate NewTempo Español = "Establecer Nuevo tempo" translate EvalTerm Français = "Eval" translate EvalTerm English = "Eval" translate EvalTerm Español = "Eval" translate JoiningEnsemble Français = "Joindre l'ensemble" translate JoiningEnsemble English = "Joining ensemble" translate JoiningEnsemble Español = "Unirse al ensamble" translate EnsembleUserName Français = "Entrer le nom d'utilisateur (optionel) comme membre de l'ensemble:" translate EnsembleUserName English = "Enter username (optional) within ensemble:" translate EnsembleUserName Español = "Ingresar nombre de usuario dentro del ensamble (opcional):" translate EnsembleLocation Français = "Décrivez votre situation géographique (optionel):" translate EnsembleLocation English = "Describe your location (optional):" translate EnsembleLocation Español = "Coloca tu localización (opcional):" translate EnsembleLogin Français = "S'identifier" translate EnsembleLogin English = "Login" translate EnsembleLogin Español = "Ingresar" translate Peak Français = "pic" translate Peak English = "peak" translate Peak Español = "tope" translate Syntax English = "Syntax" translate Syntax Español = "Sintaxis" translate Connections English = "connections" translate Connections Español = "conexiones" translate Latency English = "latency" translate Latency Español = "latencia" translate Resolution English = "Resolution" translate Resolution Español = "Resolución" translate Brightness English = "Brightness" translate Brightness Español = "Brillo" translate Reference English = "Reference" translate Reference Español = "Referencia" translate Settings English = "Settings" translate Settings Español = "Configuración" translate Activity English = "activity" translate Activity Español = "actividad" translate ActivityDescription English = "The last time participants edited some code" translate ActivityDescription Español = "La última vez que las participantes editaron el código." translate Status English = "status" translate Status Español = "estatus" translate StatusDescription English = "Displays how are the participants doing today" translate StatusDescription Español = "Muestra cómo se sientes l@s participantes el día de hoy" translate LatencyDescription English = "The delay before a transfer of data begins" translate LatencyDescription Español = "El retraso de tiempo entre la transferencia de datos" translate LoadDescription English = "The amount of work each participant computer is doing" translate LoadDescription Español = "La cantidad de trabajo que cada computadora participante está haciendo" translate FPS English = "FPS" translate FPS Español = "CPS" translate FPSDescription English = "The frames per second of the participants" translate FPSDescription Español = "Los cuadros por segundo de cada participante" translate IPaddress English = "IP Address" translate IPaddress Español = "dirección IP" translate IPaddressDescription English = "The IP addresses of the participants" translate IPaddressDescription Español = "Las direcciones IP de l@s participantes" translate Voices English = "voices" translate x _ = translate x English
eb7d2e66c8c21674a44e8832d92db9de6c9b2abd2dfbd6dabe8cd8227c73b592
JHU-PL-Lab/jaylang
test_heavy.ml
open Core let ctx = Z3.mk_context [] module SuduZ3 = Sudu.Z3_api.Make (struct let ctx = ctx end) module To_test = struct open let solver = Z3.Solver.mk_solver SuduZ3.ctx None let heavy () = let es = List.range 0 50000 |> List.map ~f:(fun i -> SuduZ3.( eq (mk_string_s (string_of_int i)) (mk_string_s (string_of_int (i + 1))))) in let _ = Z3.Solver.check solver es in let _ = Z3.Solver.check solver es in true end let () = let open Alcotest in run "Sudu" [ ( "heavy", [ test_case "heavy" `Quick (fun () -> Alcotest.(check bool) "same bool" true @@ To_test.heavy ()); ] ); ]
null
https://raw.githubusercontent.com/JHU-PL-Lab/jaylang/81abf9ff185758a2aaefd90478da4c7bb53f4384/src-test/sudu/test_heavy.ml
ocaml
open Core let ctx = Z3.mk_context [] module SuduZ3 = Sudu.Z3_api.Make (struct let ctx = ctx end) module To_test = struct open let solver = Z3.Solver.mk_solver SuduZ3.ctx None let heavy () = let es = List.range 0 50000 |> List.map ~f:(fun i -> SuduZ3.( eq (mk_string_s (string_of_int i)) (mk_string_s (string_of_int (i + 1))))) in let _ = Z3.Solver.check solver es in let _ = Z3.Solver.check solver es in true end let () = let open Alcotest in run "Sudu" [ ( "heavy", [ test_case "heavy" `Quick (fun () -> Alcotest.(check bool) "same bool" true @@ To_test.heavy ()); ] ); ]
99affbd1a205e31c8991b6354bfd82a167ec69db9c29c9b6b0f348837b161a47
gga/janus
dsl.clj
(ns janus.dsl) (defmulti should-have (fn [& args] (nth args 0))) (defmethod should-have :path [& args] [:clause [:path (nth args 1) (nth args 2) (nth args 3)]]) (defmethod should-have :status [& args] [:clause [:status (nth args 1)]]) (defmethod should-have :header [& args] [:clause [:header (nth args 1) (nth args 2) (nth args 3)]]) (defn url [path] [:property {:name "url" :value path}]) (defn method [kw-method] [:property {:name "method" :value kw-method}]) (defn serialization [s11n] [:property {:name "serialization" :value s11n}]) (defn body [& args] [:body (if (keyword? (nth args 0)) {:type (nth args 0) :data (nth args 1)} {:type :string :data (nth args 0)})]) (defn before [setup-func] [:property {:name "before" :value setup-func}]) (defn after [teardown-func] [:property {:name "after" :value teardown-func}]) (defn header [name value] [:header {:name name :value value}]) (defn contract [name & definition] [:contract {:name name :properties (map #(nth % 1) (filter #(= :property (first %)) definition)) :clauses (map #(nth % 1) (filter #(= :clause (first %)) definition)) :headers (map #(nth % 1) (filter #(= :header (first %)) definition)) :body (first (map #(nth % 1) (filter #(= :body (first %)) definition)))}]) (defn service [name & definition] {:name name :properties (map #(nth % 1) (filter #(= :property (first %)) definition)) :headers (map #(nth % 1) (filter #(= :header (first %)) definition)) :contracts (map #(nth % 1) (filter #(= :contract (first %)) definition))}) (defn construct-domain [dsl-form] (let [dsl-ns (create-ns 'dsl-defn) compiled (binding [*ns* dsl-ns] (eval '(clojure.core/refer 'clojure.core)) (eval '(refer 'janus.dsl)) (eval dsl-form))] (remove-ns 'dsl-defn) compiled))
null
https://raw.githubusercontent.com/gga/janus/7141dae59a77e081f549f36f1548fd3efce682e1/src/janus/dsl.clj
clojure
(ns janus.dsl) (defmulti should-have (fn [& args] (nth args 0))) (defmethod should-have :path [& args] [:clause [:path (nth args 1) (nth args 2) (nth args 3)]]) (defmethod should-have :status [& args] [:clause [:status (nth args 1)]]) (defmethod should-have :header [& args] [:clause [:header (nth args 1) (nth args 2) (nth args 3)]]) (defn url [path] [:property {:name "url" :value path}]) (defn method [kw-method] [:property {:name "method" :value kw-method}]) (defn serialization [s11n] [:property {:name "serialization" :value s11n}]) (defn body [& args] [:body (if (keyword? (nth args 0)) {:type (nth args 0) :data (nth args 1)} {:type :string :data (nth args 0)})]) (defn before [setup-func] [:property {:name "before" :value setup-func}]) (defn after [teardown-func] [:property {:name "after" :value teardown-func}]) (defn header [name value] [:header {:name name :value value}]) (defn contract [name & definition] [:contract {:name name :properties (map #(nth % 1) (filter #(= :property (first %)) definition)) :clauses (map #(nth % 1) (filter #(= :clause (first %)) definition)) :headers (map #(nth % 1) (filter #(= :header (first %)) definition)) :body (first (map #(nth % 1) (filter #(= :body (first %)) definition)))}]) (defn service [name & definition] {:name name :properties (map #(nth % 1) (filter #(= :property (first %)) definition)) :headers (map #(nth % 1) (filter #(= :header (first %)) definition)) :contracts (map #(nth % 1) (filter #(= :contract (first %)) definition))}) (defn construct-domain [dsl-form] (let [dsl-ns (create-ns 'dsl-defn) compiled (binding [*ns* dsl-ns] (eval '(clojure.core/refer 'clojure.core)) (eval '(refer 'janus.dsl)) (eval dsl-form))] (remove-ns 'dsl-defn) compiled))
fd84a98d0dbb295349d3013756f7b96f2594aac342e9a34bc05c105f4b958728
tweag/inline-js
NodeVersion.hs
# LANGUAGE ViewPatterns # module Language.JavaScript.Inline.Core.NodeVersion where import Control.Exception import Control.Monad import Data.List import Data.Version import Language.JavaScript.Inline.Core.Exception import Language.JavaScript.Inline.Core.Utils import System.Process parseNodeVersion :: String -> Version parseNodeVersion s0 = Version vs $ case tag of "" -> [] _ -> [tag] where vs_ts = split (== '-') s0 vs = map read $ split (== '.') $ head vs_ts tag = intercalate "-" $ tail vs_ts isSupportedVersion :: Version -> Bool isSupportedVersion (versionBranch -> v) = (v >= [12, 0, 0]) || (v >= [10, 20, 0] && v < [11]) checkNodeVersion :: FilePath -> IO () checkNodeVersion p = do v <- parseNodeVersion <$> readProcess p ["--eval", "process.stdout.write(process.versions.node)"] "" unless (isSupportedVersion v) $ throwIO NodeVersionUnsupported
null
https://raw.githubusercontent.com/tweag/inline-js/ef675745e84d23d51c50660d40acf9e684fbb2d6/inline-js-core/src/Language/JavaScript/Inline/Core/NodeVersion.hs
haskell
# LANGUAGE ViewPatterns # module Language.JavaScript.Inline.Core.NodeVersion where import Control.Exception import Control.Monad import Data.List import Data.Version import Language.JavaScript.Inline.Core.Exception import Language.JavaScript.Inline.Core.Utils import System.Process parseNodeVersion :: String -> Version parseNodeVersion s0 = Version vs $ case tag of "" -> [] _ -> [tag] where vs_ts = split (== '-') s0 vs = map read $ split (== '.') $ head vs_ts tag = intercalate "-" $ tail vs_ts isSupportedVersion :: Version -> Bool isSupportedVersion (versionBranch -> v) = (v >= [12, 0, 0]) || (v >= [10, 20, 0] && v < [11]) checkNodeVersion :: FilePath -> IO () checkNodeVersion p = do v <- parseNodeVersion <$> readProcess p ["--eval", "process.stdout.write(process.versions.node)"] "" unless (isSupportedVersion v) $ throwIO NodeVersionUnsupported
b5a3a3ef66feba3459768c1ffae4340828a74b99d609c972e29e91517d908229
acl2/acl2
type-of-value.lisp
C Library ; Copyright ( C ) 2023 Kestrel Institute ( ) Copyright ( C ) 2023 Kestrel Technology LLC ( ) ; License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 . ; Author : ( ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "C") (include-book "integers") (include-book "arrays") (local (xdoc::set-default-parents atc-symbolic-execution-rules)) (local (include-book "kestrel/built-ins/disable" :dir :system)) (local (acl2::disable-most-builtin-logic-defuns)) (local (acl2::disable-builtin-rewrite-rules-for-defaults)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defsection atc-type-of-value-rules :short "Rules about @(tsee type-of-value)." :long (xdoc::topstring (xdoc::p "These rules rewrite @(tsee type-of-value) to specific types under hypotheses on different types of values that occur during symbolic execution.")) (defruled type-of-value-when-value-pointer (implies (and (valuep x) (value-case x :pointer)) (equal (type-of-value x) (type-pointer (value-pointer->reftype x)))) :enable type-of-value) (defval *atc-type-of-value-rules* '(type-of-value-when-ucharp type-of-value-when-scharp type-of-value-when-ushortp type-of-value-when-sshortp type-of-value-when-uintp type-of-value-when-sintp type-of-value-when-ulongp type-of-value-when-slongp type-of-value-when-ullongp type-of-value-when-sllongp type-of-value-when-value-pointer type-of-value-when-uchar-arrayp type-of-value-when-schar-arrayp type-of-value-when-ushort-arrayp type-of-value-when-sshort-arrayp type-of-value-when-uint-arrayp type-of-value-when-sint-arrayp type-of-value-when-ulong-arrayp type-of-value-when-slong-arrayp type-of-value-when-ullong-arrayp type-of-value-when-sllong-arrayp))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defsection atc-type-of-value-option-rules :short "Rules about @(tsee type-of-value-option)." :long (xdoc::topstring (xdoc::p "These rules reduce @(tsee type-of-value-option) to @(tsee type-of-value) when the argument is a value, and to @('void') when the argument is @('nil'). During execution, the argument is always either @('nil') or a term that is easily proved to be a value; so these rules suffice to eliminate @(tsee type-of-value-option).")) (defruled type-of-value-option-when-valuep (implies (valuep x) (equal (type-of-value-option x) (type-of-value x))) :enable (type-of-value-option value-option-some->val)) (defruled type-of-value-option-of-nil (equal (type-of-value-option nil) (type-void))) (defval *atc-type-of-value-option-rules* '(type-of-value-option-when-valuep type-of-value-option-of-nil)))
null
https://raw.githubusercontent.com/acl2/acl2/44f76f208004466a9e6cdf3a07dac98b3799817d/books/kestrel/c/atc/symbolic-execution-rules/type-of-value.lisp
lisp
C Library Copyright ( C ) 2023 Kestrel Institute ( ) Copyright ( C ) 2023 Kestrel Technology LLC ( ) License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 . Author : ( ) (in-package "C") (include-book "integers") (include-book "arrays") (local (xdoc::set-default-parents atc-symbolic-execution-rules)) (local (include-book "kestrel/built-ins/disable" :dir :system)) (local (acl2::disable-most-builtin-logic-defuns)) (local (acl2::disable-builtin-rewrite-rules-for-defaults)) (defsection atc-type-of-value-rules :short "Rules about @(tsee type-of-value)." :long (xdoc::topstring (xdoc::p "These rules rewrite @(tsee type-of-value) to specific types under hypotheses on different types of values that occur during symbolic execution.")) (defruled type-of-value-when-value-pointer (implies (and (valuep x) (value-case x :pointer)) (equal (type-of-value x) (type-pointer (value-pointer->reftype x)))) :enable type-of-value) (defval *atc-type-of-value-rules* '(type-of-value-when-ucharp type-of-value-when-scharp type-of-value-when-ushortp type-of-value-when-sshortp type-of-value-when-uintp type-of-value-when-sintp type-of-value-when-ulongp type-of-value-when-slongp type-of-value-when-ullongp type-of-value-when-sllongp type-of-value-when-value-pointer type-of-value-when-uchar-arrayp type-of-value-when-schar-arrayp type-of-value-when-ushort-arrayp type-of-value-when-sshort-arrayp type-of-value-when-uint-arrayp type-of-value-when-sint-arrayp type-of-value-when-ulong-arrayp type-of-value-when-slong-arrayp type-of-value-when-ullong-arrayp type-of-value-when-sllong-arrayp))) (defsection atc-type-of-value-option-rules :short "Rules about @(tsee type-of-value-option)." :long (xdoc::topstring (xdoc::p "These rules reduce @(tsee type-of-value-option) to @(tsee type-of-value) when the argument is a value, and to @('void') when the argument is @('nil'). During execution, the argument is always either @('nil') so these rules suffice to eliminate @(tsee type-of-value-option).")) (defruled type-of-value-option-when-valuep (implies (valuep x) (equal (type-of-value-option x) (type-of-value x))) :enable (type-of-value-option value-option-some->val)) (defruled type-of-value-option-of-nil (equal (type-of-value-option nil) (type-void))) (defval *atc-type-of-value-option-rules* '(type-of-value-option-when-valuep type-of-value-option-of-nil)))
9558ecee74adb560d3d3c01600d97b66bce2bdbfa0ddf822426c58482187ed7e
anoma/juvix
Trace.hs
module Juvix.Prelude.Trace ( module Juvix.Prelude.Trace, module Debug.Trace, ) where import Data.Text qualified as Text import Debug.Trace hiding (trace, traceM, traceShow) import Debug.Trace qualified as T import GHC.IO (unsafePerformIO) import Juvix.Prelude.Base setDebugMsg :: Text -> Text setDebugMsg msg = "[debug] " <> fmsg <> "\n" where fmsg | Text.null msg = "" | otherwise = msg <> " :" traceLabel :: Text -> Text -> a -> a traceLabel msg a = T.trace (unpack $ setDebugMsg msg <> a) {-# WARNING traceLabel "Using traceLabel" #-} trace :: Text -> a -> a trace = traceLabel "" {-# WARNING trace "Using trace" #-} traceM :: (Applicative f) => Text -> f () traceM t = traceLabel "" t (pure ()) {-# WARNING traceM "Using traceM" #-} traceShow :: (Show b) => b -> b traceShow b = traceLabel "" (pack . show $ b) b {-# WARNING traceShow "Using traceShow" #-} traceToFile :: FilePath -> Text -> a -> a traceToFile fpath t a = traceLabel (pack ("[" <> fpath <> "]")) t $ unsafePerformIO $ do writeFile fpath t return a {-# WARNING traceToFile "Using traceToFile" #-} traceToFile' :: Text -> a -> a traceToFile' = traceToFile "./juvix.log" {-# WARNING traceToFile' "Using traceToFile'" #-} traceToFileM :: (Applicative m) => FilePath -> Text -> a -> m () traceToFileM fpath t a = pure (traceToFile fpath t a) $> () {-# WARNING traceToFileM "Using traceFileM" #-}
null
https://raw.githubusercontent.com/anoma/juvix/807b3b1770289b8921304e92e7305c55c2e11f8f/src/Juvix/Prelude/Trace.hs
haskell
# WARNING traceLabel "Using traceLabel" # # WARNING trace "Using trace" # # WARNING traceM "Using traceM" # # WARNING traceShow "Using traceShow" # # WARNING traceToFile "Using traceToFile" # # WARNING traceToFile' "Using traceToFile'" # # WARNING traceToFileM "Using traceFileM" #
module Juvix.Prelude.Trace ( module Juvix.Prelude.Trace, module Debug.Trace, ) where import Data.Text qualified as Text import Debug.Trace hiding (trace, traceM, traceShow) import Debug.Trace qualified as T import GHC.IO (unsafePerformIO) import Juvix.Prelude.Base setDebugMsg :: Text -> Text setDebugMsg msg = "[debug] " <> fmsg <> "\n" where fmsg | Text.null msg = "" | otherwise = msg <> " :" traceLabel :: Text -> Text -> a -> a traceLabel msg a = T.trace (unpack $ setDebugMsg msg <> a) trace :: Text -> a -> a trace = traceLabel "" traceM :: (Applicative f) => Text -> f () traceM t = traceLabel "" t (pure ()) traceShow :: (Show b) => b -> b traceShow b = traceLabel "" (pack . show $ b) b traceToFile :: FilePath -> Text -> a -> a traceToFile fpath t a = traceLabel (pack ("[" <> fpath <> "]")) t $ unsafePerformIO $ do writeFile fpath t return a traceToFile' :: Text -> a -> a traceToFile' = traceToFile "./juvix.log" traceToFileM :: (Applicative m) => FilePath -> Text -> a -> m () traceToFileM fpath t a = pure (traceToFile fpath t a) $> ()
26a22863c2865c2387a4fc9b66f16353ddc69e2416012bb4553a8df235948495
sseefried/open-epidemic-game
FontTest.hs
module FontTest where import Foreign.Marshal.Alloc (allocaBytes) import Graphics.Rendering.Cairo import Text.Printf -- friends import FreeType ---------------------------------------------------------------------------------------------------- test :: String -> IO () test s = do ff <- loadFontFace pp <- runWithoutRender $ do setFontSize 1000 setFontFace ff (TextExtents bx by tw th ax ay) <- textExtents s return $ printf "%.2f %.2f %.2f %.2f %.2f %.2f\n" bx by tw th ax ay putStrLn pp ---------------------------------------------------------------------------------------------------- runWithoutRender :: Render a -> IO a runWithoutRender r = allocaBytes bytesPerWord32 $ \buffer -> do withImageSurfaceForData buffer FormatARGB32 1 1 bytesPerWord32 $ \surface -> do renderWith surface r where bytesPerWord32 = 4
null
https://raw.githubusercontent.com/sseefried/open-epidemic-game/ed623269022edc056dab3fd6d424295c984febec/extra-src/font-test/FontTest.hs
haskell
friends -------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------
module FontTest where import Foreign.Marshal.Alloc (allocaBytes) import Graphics.Rendering.Cairo import Text.Printf import FreeType test :: String -> IO () test s = do ff <- loadFontFace pp <- runWithoutRender $ do setFontSize 1000 setFontFace ff (TextExtents bx by tw th ax ay) <- textExtents s return $ printf "%.2f %.2f %.2f %.2f %.2f %.2f\n" bx by tw th ax ay putStrLn pp runWithoutRender :: Render a -> IO a runWithoutRender r = allocaBytes bytesPerWord32 $ \buffer -> do withImageSurfaceForData buffer FormatARGB32 1 1 bytesPerWord32 $ \surface -> do renderWith surface r where bytesPerWord32 = 4
30068dc7997acb15d11fb3edcb46348004a7498027586350d431952d636784ff
input-output-hk/plutus
Usages.hs
-- editorconfig-checker-disable-file # LANGUAGE FlexibleContexts # -- | Functions for computing variable usage inside terms. module UntypedPlutusCore.Analysis.Usages (termUsages, Usages, getUsageCount, allUsed) where import UntypedPlutusCore.Core.Type import UntypedPlutusCore.Subst import PlutusCore qualified as PLC import PlutusCore.Name qualified as PLC import Control.Lens import Data.MultiSet qualified as MSet import Data.MultiSet.Lens import Data.Set qualified as Set type Usages = MSet.MultiSet PLC.Unique -- | Get the usage count of @n@. getUsageCount :: (PLC.HasUnique n unique) => n -> Usages -> Int getUsageCount n = MSet.occur (n ^. PLC.unique . coerced) | Get a set of @n@s which are used at least once . allUsed :: Usages -> Set.Set PLC.Unique allUsed = MSet.toSet termUsages :: (PLC.HasUnique name PLC.TermUnique) => Term name uni fun a -> Usages termUsages = multiSetOf (vTerm . PLC.theUnique)
null
https://raw.githubusercontent.com/input-output-hk/plutus/cbd5f37288eb06738be28fc49af6a6b612e6c5fc/plutus-core/untyped-plutus-core/src/UntypedPlutusCore/Analysis/Usages.hs
haskell
editorconfig-checker-disable-file | Functions for computing variable usage inside terms. | Get the usage count of @n@.
# LANGUAGE FlexibleContexts # module UntypedPlutusCore.Analysis.Usages (termUsages, Usages, getUsageCount, allUsed) where import UntypedPlutusCore.Core.Type import UntypedPlutusCore.Subst import PlutusCore qualified as PLC import PlutusCore.Name qualified as PLC import Control.Lens import Data.MultiSet qualified as MSet import Data.MultiSet.Lens import Data.Set qualified as Set type Usages = MSet.MultiSet PLC.Unique getUsageCount :: (PLC.HasUnique n unique) => n -> Usages -> Int getUsageCount n = MSet.occur (n ^. PLC.unique . coerced) | Get a set of @n@s which are used at least once . allUsed :: Usages -> Set.Set PLC.Unique allUsed = MSet.toSet termUsages :: (PLC.HasUnique name PLC.TermUnique) => Term name uni fun a -> Usages termUsages = multiSetOf (vTerm . PLC.theUnique)
ed16c104baf0fda2fb6a72cb9b288ca66216240cf8e72fc75fa37f4b9fcaadc8
uxbox/uxbox-old
material_design_navigation.cljs
(ns uxbox.ui.icon-sets.material-design-navigation (:require [uxbox.ui.tools :as t])) (def material-design-navigation (sorted-map :apps { :name "Apps" :svg [:path {:style {:stroke nil} :d "M8 16h8V8H8v8zm12 24h8v-8h-8v8zM8 40h8v-8H8v8zm0-12h8v-8H8v8zm12 0h8v-8h-8v8zM32 8v8h8V8h-8zm-12 8h8V8h-8v8zm12 12h8v-8h-8v8zm0 12h8v-8h-8v8z"}]} :arrow-back { :name "Arrow Back" :svg [:path {:style {:stroke nil} :d "M40 22H15.66l11.17-11.17L24 8 8 24l16 16 2.83-2.83L15.66 26H40v-4z"}]} :arrow-drop-down { :name "Arrow Drop Down" :svg [:path {:style {:stroke nil} :d "M14 20l10 10 10-10z"}]} :arrow-drop-down-circle { :name "Arrow Drop Down Circle" :svg [:path {:style {:stroke nil} :d "M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm0 24l-8-8h16l-8 8z"}]} :arrow-drop-up { :name "Arrow Drop Up" :svg [:path {:style {:stroke nil} :d "M14 28l10-10 10 10z"}]} :arrow-forward { :name "Arrow Forward" :svg [:path {:style {:stroke nil} :d "M24 8l-2.83 2.83L32.34 22H8v4h24.34L21.17 37.17 24 40l16-16z"}]} :cancel { :name "Cancel" :svg [:path {:style {:stroke nil} :d "M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm10 27.17L31.17 34 24 26.83 16.83 34 14 31.17 21.17 24 14 16.83 16.83 14 24 21.17 31.17 14 34 16.83 26.83 24 34 31.17z"}]} :check { :name "Check" :svg [:path {:style {:stroke nil} :d "M18 32.34L9.66 24l-2.83 2.83L18 38l24-24-2.83-2.83z"}]} :chevron-left { :name "Chevron Left" :svg [:path {:style {:stroke nil} :d "M30.83 14.83L28 12 16 24l12 12 2.83-2.83L21.66 24z"}]} :chevron-right { :name "Chevron Right" :svg [:path {:style {:stroke nil} :d "M20 12l-2.83 2.83L26.34 24l-9.17 9.17L20 36l12-12z"}]} :close { :name "Close" :svg [:path {:style {:stroke nil} :d "M38 12.83L35.17 10 24 21.17 12.83 10 10 12.83 21.17 24 10 35.17 12.83 38 24 26.83 35.17 38 38 35.17 26.83 24z"}]} :expand-less { :name "Expand Less" :svg [:path {:style {:stroke nil} :d "M24 16L12 28l2.83 2.83L24 21.66l9.17 9.17L36 28z"}]} :expand-more { :name "Expand More" :svg [:path {:style {:stroke nil} :d "M33.17 17.17L24 26.34l-9.17-9.17L12 20l12 12 12-12z"}]} :fullscreen { :name "Fullscreen" :svg [:path {:style {:stroke nil} :d "M14 28h-4v10h10v-4h-6v-6zm-4-8h4v-6h6v-4H10v10zm24 14h-6v4h10V28h-4v6zm-6-24v4h6v6h4V10H28z"}]} :fullscreen-exit { :name "Fullscreen Exit" :svg [:path {:style {:stroke nil} :d "M10 32h6v6h4V28H10v4zm6-16h-6v4h10V10h-4v6zm12 22h4v-6h6v-4H28v10zm4-22v-6h-4v10h10v-4h-6z"}]} :menu { :name "Menu" :svg [:path {:style {:stroke nil} :d "M6 36h36v-4H6v4zm0-10h36v-4H6v4zm0-14v4h36v-4H6z"}]} :more-horiz { :name "More Horiz" :svg [:path {:style {:stroke nil} :d "M12 20c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm24 0c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm-12 0c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z"}]} :more-vert { :name "More Vert" :svg [:path {:style {:stroke nil} :d "M24 16c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 4c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 12c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z"}]} :refresh { :name "Refresh" :svg [:path {:style {:stroke nil} :d "M35.3 12.7C32.41 9.8 28.42 8 24 8 15.16 8 8.02 15.16 8.02 24S15.16 40 24 40c7.45 0 13.69-5.1 15.46-12H35.3c-1.65 4.66-6.07 8-11.3 8-6.63 0-12-5.37-12-12s5.37-12 12-12c3.31 0 6.28 1.38 8.45 3.55L26 22h14V8l-4.7 4.7z"}]} :unfold-less { :name "Unfold Less" :svg [:path {:style {:stroke nil} :d "M14.83 37.17L17.66 40 24 33.66 30.34 40l2.83-2.83L24 28l-9.17 9.17zm18.34-26.34L30.34 8 24 14.34 17.66 8l-2.83 2.83L24 20l9.17-9.17z"}]} :unfold-more { :name "Unfold More" :svg [:path {:style {:stroke nil} :d "M24 11.66L30.34 18l2.83-2.83L24 6l-9.17 9.17L17.66 18 24 11.66zm0 24.68L17.66 30l-2.83 2.83L24 42l9.17-9.17L30.34 30 24 36.34z"}]})) (t/register-icon-set! {:key :material-design-navigation :name "Material Design (Navigation)" :icons material-design-navigation})
null
https://raw.githubusercontent.com/uxbox/uxbox-old/9c3c3c406a6c629717cfc40e3da2f96df3bdebf7/src/frontend/uxbox/ui/icon_sets/material_design_navigation.cljs
clojure
(ns uxbox.ui.icon-sets.material-design-navigation (:require [uxbox.ui.tools :as t])) (def material-design-navigation (sorted-map :apps { :name "Apps" :svg [:path {:style {:stroke nil} :d "M8 16h8V8H8v8zm12 24h8v-8h-8v8zM8 40h8v-8H8v8zm0-12h8v-8H8v8zm12 0h8v-8h-8v8zM32 8v8h8V8h-8zm-12 8h8V8h-8v8zm12 12h8v-8h-8v8zm0 12h8v-8h-8v8z"}]} :arrow-back { :name "Arrow Back" :svg [:path {:style {:stroke nil} :d "M40 22H15.66l11.17-11.17L24 8 8 24l16 16 2.83-2.83L15.66 26H40v-4z"}]} :arrow-drop-down { :name "Arrow Drop Down" :svg [:path {:style {:stroke nil} :d "M14 20l10 10 10-10z"}]} :arrow-drop-down-circle { :name "Arrow Drop Down Circle" :svg [:path {:style {:stroke nil} :d "M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm0 24l-8-8h16l-8 8z"}]} :arrow-drop-up { :name "Arrow Drop Up" :svg [:path {:style {:stroke nil} :d "M14 28l10-10 10 10z"}]} :arrow-forward { :name "Arrow Forward" :svg [:path {:style {:stroke nil} :d "M24 8l-2.83 2.83L32.34 22H8v4h24.34L21.17 37.17 24 40l16-16z"}]} :cancel { :name "Cancel" :svg [:path {:style {:stroke nil} :d "M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 4zm10 27.17L31.17 34 24 26.83 16.83 34 14 31.17 21.17 24 14 16.83 16.83 14 24 21.17 31.17 14 34 16.83 26.83 24 34 31.17z"}]} :check { :name "Check" :svg [:path {:style {:stroke nil} :d "M18 32.34L9.66 24l-2.83 2.83L18 38l24-24-2.83-2.83z"}]} :chevron-left { :name "Chevron Left" :svg [:path {:style {:stroke nil} :d "M30.83 14.83L28 12 16 24l12 12 2.83-2.83L21.66 24z"}]} :chevron-right { :name "Chevron Right" :svg [:path {:style {:stroke nil} :d "M20 12l-2.83 2.83L26.34 24l-9.17 9.17L20 36l12-12z"}]} :close { :name "Close" :svg [:path {:style {:stroke nil} :d "M38 12.83L35.17 10 24 21.17 12.83 10 10 12.83 21.17 24 10 35.17 12.83 38 24 26.83 35.17 38 38 35.17 26.83 24z"}]} :expand-less { :name "Expand Less" :svg [:path {:style {:stroke nil} :d "M24 16L12 28l2.83 2.83L24 21.66l9.17 9.17L36 28z"}]} :expand-more { :name "Expand More" :svg [:path {:style {:stroke nil} :d "M33.17 17.17L24 26.34l-9.17-9.17L12 20l12 12 12-12z"}]} :fullscreen { :name "Fullscreen" :svg [:path {:style {:stroke nil} :d "M14 28h-4v10h10v-4h-6v-6zm-4-8h4v-6h6v-4H10v10zm24 14h-6v4h10V28h-4v6zm-6-24v4h6v6h4V10H28z"}]} :fullscreen-exit { :name "Fullscreen Exit" :svg [:path {:style {:stroke nil} :d "M10 32h6v6h4V28H10v4zm6-16h-6v4h10V10h-4v6zm12 22h4v-6h6v-4H28v10zm4-22v-6h-4v10h10v-4h-6z"}]} :menu { :name "Menu" :svg [:path {:style {:stroke nil} :d "M6 36h36v-4H6v4zm0-10h36v-4H6v4zm0-14v4h36v-4H6z"}]} :more-horiz { :name "More Horiz" :svg [:path {:style {:stroke nil} :d "M12 20c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm24 0c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm-12 0c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z"}]} :more-vert { :name "More Vert" :svg [:path {:style {:stroke nil} :d "M24 16c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 4c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 12c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z"}]} :refresh { :name "Refresh" :svg [:path {:style {:stroke nil} :d "M35.3 12.7C32.41 9.8 28.42 8 24 8 15.16 8 8.02 15.16 8.02 24S15.16 40 24 40c7.45 0 13.69-5.1 15.46-12H35.3c-1.65 4.66-6.07 8-11.3 8-6.63 0-12-5.37-12-12s5.37-12 12-12c3.31 0 6.28 1.38 8.45 3.55L26 22h14V8l-4.7 4.7z"}]} :unfold-less { :name "Unfold Less" :svg [:path {:style {:stroke nil} :d "M14.83 37.17L17.66 40 24 33.66 30.34 40l2.83-2.83L24 28l-9.17 9.17zm18.34-26.34L30.34 8 24 14.34 17.66 8l-2.83 2.83L24 20l9.17-9.17z"}]} :unfold-more { :name "Unfold More" :svg [:path {:style {:stroke nil} :d "M24 11.66L30.34 18l2.83-2.83L24 6l-9.17 9.17L17.66 18 24 11.66zm0 24.68L17.66 30l-2.83 2.83L24 42l9.17-9.17L30.34 30 24 36.34z"}]})) (t/register-icon-set! {:key :material-design-navigation :name "Material Design (Navigation)" :icons material-design-navigation})
0fffcf5298f93383169bcadca201e4041367fb07aaa702112f0082c212729fb2
meiersi/blaze-builder
Utf8.hs
{-# LANGUAGE OverloadedStrings #-} -- | Module : Blaze . ByteString . Builder . Html . Utf8 Copyright : ( c ) 2010 -- License : BSD3-style (see LICENSE) -- Maintainer : < > -- Stability : experimental Portability : tested on GHC only -- ' Write 's and ' Builder 's for serializing HTML escaped and UTF-8 encoded -- characters. -- -- This module is used by both the 'blaze-html' and the \'hamlet\' HTML -- templating libraries. If the 'Builder' from 'blaze-builder' replaces the -- 'Data.Binary.Builder' implementation, this module will most likely keep its -- place, as it provides a set of very specialized functions. module Blaze.ByteString.Builder.Html.Utf8 ( module Blaze.ByteString.Builder.Char.Utf8 * Writing HTML escaped and UTF-8 encoded characters to a buffer , writeHtmlEscapedChar * Creating Builders from HTML escaped and UTF-8 encoded characters , fromHtmlEscapedChar , fromHtmlEscapedString , fromHtmlEscapedShow , fromHtmlEscapedText , fromHtmlEscapedLazyText ) where for the ' IsString ' instance of bytesrings import qualified Data.Text as TS import qualified Data.Text.Lazy as TL import Blaze.ByteString.Builder import Blaze.ByteString.Builder.Internal import Blaze.ByteString.Builder.Char.Utf8 | Write a HTML escaped and UTF-8 encoded character to a bufffer . -- writeHtmlEscapedChar :: Char -> Write writeHtmlEscapedChar c0 = boundedWrite 6 (io c0) -- WARNING: Don't forget to change the bound if you change the bytestrings. where io '<' = getPoke $ writeByteString "&lt;" io '>' = getPoke $ writeByteString "&gt;" io '&' = getPoke $ writeByteString "&amp;" io '"' = getPoke $ writeByteString "&quot;" io '\'' = getPoke $ writeByteString "&#39;" io c = getPoke $ writeChar c # INLINE writeHtmlEscapedChar # | /O(1)./ Serialize a HTML escaped Unicode character using the UTF-8 -- encoding. -- fromHtmlEscapedChar :: Char -> Builder fromHtmlEscapedChar = fromWriteSingleton writeHtmlEscapedChar | /O(n)/. Serialize a HTML escaped Unicode ' String ' using the UTF-8 -- encoding. -- fromHtmlEscapedString :: String -> Builder fromHtmlEscapedString = fromWriteList writeHtmlEscapedChar | /O(n)/. Serialize a value by ' Show'ing it and then , HTML escaping and UTF-8 encoding the resulting ' String ' . -- fromHtmlEscapedShow :: Show a => a -> Builder fromHtmlEscapedShow = fromHtmlEscapedString . show | /O(n)/. Serialize a HTML escaped strict ' TS.Text ' value using the UTF-8 encoding . -- fromHtmlEscapedText :: TS.Text -> Builder fromHtmlEscapedText = fromHtmlEscapedString . TS.unpack | /O(n)/. Serialize a HTML escaped Unicode ' TL.Text ' using the UTF-8 encoding . -- fromHtmlEscapedLazyText :: TL.Text -> Builder fromHtmlEscapedLazyText = fromHtmlEscapedString . TL.unpack
null
https://raw.githubusercontent.com/meiersi/blaze-builder/2d8ce308951656ebf0318097989dc1c017dcff83/Blaze/ByteString/Builder/Html/Utf8.hs
haskell
# LANGUAGE OverloadedStrings # | License : BSD3-style (see LICENSE) Stability : experimental characters. This module is used by both the 'blaze-html' and the \'hamlet\' HTML templating libraries. If the 'Builder' from 'blaze-builder' replaces the 'Data.Binary.Builder' implementation, this module will most likely keep its place, as it provides a set of very specialized functions. WARNING: Don't forget to change the bound if you change the bytestrings. encoding. encoding.
Module : Blaze . ByteString . Builder . Html . Utf8 Copyright : ( c ) 2010 Maintainer : < > Portability : tested on GHC only ' Write 's and ' Builder 's for serializing HTML escaped and UTF-8 encoded module Blaze.ByteString.Builder.Html.Utf8 ( module Blaze.ByteString.Builder.Char.Utf8 * Writing HTML escaped and UTF-8 encoded characters to a buffer , writeHtmlEscapedChar * Creating Builders from HTML escaped and UTF-8 encoded characters , fromHtmlEscapedChar , fromHtmlEscapedString , fromHtmlEscapedShow , fromHtmlEscapedText , fromHtmlEscapedLazyText ) where for the ' IsString ' instance of bytesrings import qualified Data.Text as TS import qualified Data.Text.Lazy as TL import Blaze.ByteString.Builder import Blaze.ByteString.Builder.Internal import Blaze.ByteString.Builder.Char.Utf8 | Write a HTML escaped and UTF-8 encoded character to a bufffer . writeHtmlEscapedChar :: Char -> Write writeHtmlEscapedChar c0 = boundedWrite 6 (io c0) where io '<' = getPoke $ writeByteString "&lt;" io '>' = getPoke $ writeByteString "&gt;" io '&' = getPoke $ writeByteString "&amp;" io '"' = getPoke $ writeByteString "&quot;" io '\'' = getPoke $ writeByteString "&#39;" io c = getPoke $ writeChar c # INLINE writeHtmlEscapedChar # | /O(1)./ Serialize a HTML escaped Unicode character using the UTF-8 fromHtmlEscapedChar :: Char -> Builder fromHtmlEscapedChar = fromWriteSingleton writeHtmlEscapedChar | /O(n)/. Serialize a HTML escaped Unicode ' String ' using the UTF-8 fromHtmlEscapedString :: String -> Builder fromHtmlEscapedString = fromWriteList writeHtmlEscapedChar | /O(n)/. Serialize a value by ' Show'ing it and then , HTML escaping and UTF-8 encoding the resulting ' String ' . fromHtmlEscapedShow :: Show a => a -> Builder fromHtmlEscapedShow = fromHtmlEscapedString . show | /O(n)/. Serialize a HTML escaped strict ' TS.Text ' value using the UTF-8 encoding . fromHtmlEscapedText :: TS.Text -> Builder fromHtmlEscapedText = fromHtmlEscapedString . TS.unpack | /O(n)/. Serialize a HTML escaped Unicode ' TL.Text ' using the UTF-8 encoding . fromHtmlEscapedLazyText :: TL.Text -> Builder fromHtmlEscapedLazyText = fromHtmlEscapedString . TL.unpack
245a8ade238c2590bd7f2749e16fb92ae5db9ee72292ef51d19467cd7abb7d74
janestreet/core
pid.mli
(** Process ID. *) open! Import type t [@@deriving bin_io, hash, sexp, quickcheck] include Identifiable.S with type t := t val of_int : int -> t val to_int : t -> int * The pid of the " init " process , which is [ 1 ] by convention . val init : t module Stable : sig module V1 : Stable_comparable.With_stable_witness.V1 with type t = t and type comparator_witness = comparator_witness end
null
https://raw.githubusercontent.com/janestreet/core/e362df38c28fed401e7bcbad09db3fb283281010/core/src/pid.mli
ocaml
* Process ID.
open! Import type t [@@deriving bin_io, hash, sexp, quickcheck] include Identifiable.S with type t := t val of_int : int -> t val to_int : t -> int * The pid of the " init " process , which is [ 1 ] by convention . val init : t module Stable : sig module V1 : Stable_comparable.With_stable_witness.V1 with type t = t and type comparator_witness = comparator_witness end
b79fe6efa0a24264e22d1aaad0e9b0e1131bad2bb8ad7225308017d240004d25
ChildsplayOSU/bogl
Monad.hs
# LANGUAGE DeriveGeneric # | Module : Typechecker . Monad Description : Typechecker monad Copyright : ( c ) License : BSD-3 Module : Typechecker.Monad Description : Typechecker monad Copyright : (c) License : BSD-3 -} module Typechecker.Monad where import Control.Monad.State import Control.Monad.Identity import Control.Monad.Except import Control.Monad.Reader import Control.Monad.Extra import Text.Parsec.Pos import Language.Types hiding (content, size) import qualified Data.Set as S import Language.Syntax hiding (input) import Runtime.Builtins import Error.Error import Error.TypeError import Data.List -- | Types in the environment type TypeEnv = [(Name, Type)] | Typechecker environment data Env = Env { types :: TypeEnv, defs :: [TypeDef], input :: Xtype, content :: Xtype, size :: (Int, Int) } -- | Initial empty environment initEnv :: Xtype -> Xtype -> (Int, Int) -> [TypeDef] -> Env initEnv i _p s td = Env [] td i _p s -- | An example environment for interal use (e.g. testing, ghci) exampleEnv :: Env exampleEnv = Env (builtinT intxt intxt) [] intxt intxt (5, 5) | Typechecker state data Stat = Stat { source :: Maybe (Expr SourcePos), pos :: SourcePos } -- | Typechecking monad type Typechecked a = (StateT Stat (ReaderT Env (ExceptT Error Identity))) a -- | Run a computation inside of the typechecking monad typecheck :: Env -> Typechecked a -> Either Error (a, Stat) typecheck e a = runIdentity . runExceptT . (flip runReaderT e) $ (runStateT a (Stat Nothing (newPos "" 0 0))) -- | Add some types to the environment extendEnv :: Env -> (Name, Type) -> Env extendEnv (Env _t d i _p s) v = Env (v:_t) d i _p s -- | Get the type environment getEnv :: Typechecked TypeEnv getEnv = types <$> ask -- | Get the type definitions getDefs :: Typechecked [TypeDef] getDefs = defs <$> ask -- | Get the input type getInput :: Typechecked Xtype getInput = input <$> ask -- | Get the content type getContent :: Typechecked (Xtype) getContent = content <$> ask -- | Get the board size getSize :: Typechecked (Int, Int) getSize = size <$> ask -- | Check whether (x,y) is in the bounds of the board inBounds :: (Int, Int) -> Typechecked Bool inBounds (x, y) = do (x', y') <- getSize return $ x <= x' && y <= y' && x > 0 && y > 0 -- | Extend the environment localEnv :: ([(Name, Type)] -> [(Name, Type)]) -> Typechecked a -> Typechecked a localEnv f e = local (\(Env a td b c d) -> Env (f a) td b c d) e -- | Set the source line setSrc :: (Expr SourcePos) -> Typechecked () setSrc e = modify (\(Stat _ x) -> Stat (Just e) x) -- | Set the position setPos :: (SourcePos) -> Typechecked () setPos e = modify (\stat -> stat{pos = e}) -- | Get the position getPos :: Typechecked SourcePos getPos = pos <$> get -- | Get the source expression getSrc :: Typechecked (Expr ()) getSrc = do e <- source <$> get case e of Nothing -> unknown "Unable to get source expression!" Just _e -> return $ clearAnn _e -- | Get a type from the environment getType :: Name -> Typechecked Type getType n = do env <- getEnv inputT <- getInput contentT <- getContent case (lookup n env, lookup n (builtinT inputT contentT)) of (Just e, _) -> return e (_, Just e) -> return e _ -> notbound n -- | Types for which the subtype relation is defined -- In the Typechecked monad because subtyping depends on type definitions class Subtypeable t where (<:) :: t -> t -> Typechecked Bool instance Subtypeable Xtype where xa <: xb = do (xa', xb') <- derefs (xa, xb) return $ xa' <= xb' instance Subtypeable Type where (Plain xa) <: (Plain xb) = xa <: xb (Function (Ft xa xb)) <: (Function (Ft xa' xb')) = do inputs <- xa <: xa' outputs <- xb <: xb' return $ inputs && outputs _ <: _ = return False | Attempt to unify two types -- i.e. for types T1 and T2: has a type T been declared such that T1 <: T and T2 <: T unify :: Xtype -> Xtype -> Typechecked Xtype unify xa xb = do (xa', xb') <- derefs (xa, xb) pass xa , xb so errors report type names -- | Assign a type name to a type definition assignTypeName :: Xtype -> Typechecked (Maybe Xtype) assignTypeName x = do ds <- getDefs look <- findM (\a -> x <: snd a) ds case look of (Just (tn, _)) -> return $ Just $ namedt tn _ -> return Nothing | Attempt to unify two dereferenced types -- requires un - dereferenced versions of the types as well this is to report type names like T rather than type defs like Int & { X } unify' :: (Xtype, Xtype) -> (Xtype, Xtype) -> Typechecked Xtype unify' ((Tup xns), (Tup xs)) ((Tup yns), (Tup ys)) -- element-wise unification of tuples -- only unify tuples of equivalent lengths... | all (\x -> length x == length xs) [xns, xs, yns, ys] = Tup <$> zipWithM unify' (zip xns xs) (zip yns ys) -- ...otherwise, these tuples cannot be unified | otherwise = mismatch (Plain (Tup xns)) (Plain (Tup yns)) unify' (xn, (Tup xs)) (yn, (Tup ys)) = -- expand named type and assign names to tuple elements do xns <- findTuple xn yns <- findTuple yn unify' (xns, Tup xs) (yns, Tup ys) -- if one is a subtype of the other, then the result is the larger type -- else, create a type from tl and tr (if possible) and see if it has been defined in user program unify' (tnl, tl@(X y z)) (tnr, tr@(X w k)) | tr <= tl = return tl | tl <= tr = return tr | w <= y = do r <- assignTypeName $ X y (z `S.union` k) report r | y <= w = do r <- assignTypeName $ X w (z `S.union` k) report r where report (Just ty) = return ty report Nothing = mismatch (Plain tnl) (Plain tnr) unify' (tnl, _) (tnr, _) = mismatch (Plain tnl) (Plain tnr) -- | Dereference a named type (to enable a subtype check) e.g. type T1 = Int & { A , B } -- -- T1 ---deref--> Int & {A,B} deref :: Xtype -> Typechecked Xtype deref (X (Named n) s) = do ds <- getDefs case find (\a -> fst a == n) ds of Just (_, x) -> do d <- deref x return $ addSymbols s d _ -> unknown "Internal type dereference error" where | initial type was n & s. After dereferencing , use this create x & s addSymbols :: S.Set String -> Xtype -> Xtype addSymbols ss (X b ss') = X b (S.union ss ss') addSymbols _ tup = tup -- extended tuples not currently allowed by impl syntax deref (Tup xs) = do xs' <- mapM deref xs return $ Tup xs' deref h = return h -- | Dereferences a type until it finds a tuple. If there is not tuple, returns the original type -- This is used in 'eqntype' to ensure that params of multi-argument functions are assigned the -- type of their respective tuple element in the signature. -- -- e.g. type T1 = (Int, Int) -- type T2 = T1 -- -- dereference T2 to (Int, Int) -- TODO ! write a test for this findTuple :: Xtype -> Typechecked Xtype findTuple x = do x' <- findTuple' x case x' of Tup xs -> return $ Tup xs _ -> return x -- | Dereferences a type until it finds a tuple or no more dereferencing is possible -- See 'findTuple' for more info findTuple' :: Xtype -> Typechecked Xtype findTuple' (X (Named n) _) = do ds <- getDefs case find (\a -> fst a == n) ds of Just (_, Tup xs) -> return (Tup xs) Just (_, x) -> findTuple' x _ -> unknown "Internal type dereference error" findTuple' (Tup xs) = do xs' <- mapM findTuple' xs return $ Tup xs' findTuple' h = return h -- | Dereference a pair of named types (a convenience function that wraps deref) derefs :: (Xtype, Xtype) -> Typechecked (Xtype, Xtype) derefs (xl, xr) = do xl' <- deref xl xr' <- deref xr return (xl', xr') -- | Check if t1 has type t2 with subsumption (i.e. by subtyping) This is a wrapper around the instance to produce the type error if there is a mismatch hasType :: Xtype -> Xtype -> Typechecked Xtype hasType (Tup xs) (Tup ys) | length xs == length ys = Tup <$> zipWithM hasType xs ys hasType ta tb = ifM (ta <: tb) (return tb) (mismatch (Plain ta) (Plain tb)) -- | Returns a typechecked base type t :: Btype -> Typechecked Xtype t b = return (X b S.empty) -- smart constructors for type errors -- | Gets the source expression and its position from the 'Typechecked' monad getInfo :: Typechecked (Expr (), SourcePos) getInfo = ((,) <$> getSrc <*> getPos) -- | Type mismatch error mismatch :: Type -> Type -> Typechecked a mismatch _t1 _t2 = getInfo >>= (\(e, x) -> throwError $ cterr (Mismatch _t1 _t2 e) x) -- | Input type mismatch error inputmismatch :: Type -> Typechecked a inputmismatch act = do (e, x) <- getInfo it <- getInput throwError $ cterr (InputMismatch act (Plain it) e) x -- | Type mismatch error for function application appmismatch :: Name -> Type -> Type -> Typechecked a appmismatch n _t1 _t2 = getInfo >>= (\(e, x) -> throwError $ cterr (AppMismatch n _t1 _t2 e) x) -- | Not bound type error notbound :: Name -> Typechecked a notbound n = getPos >>= \x -> throwError $ cterr (NotBound n) x -- | Signature mismatch type error sigmismatch :: Name -> Type -> Type -> Typechecked a sigmismatch n _t1 _t2= getPos >>= \x -> throwError $ cterr (SigMismatch n _t1 _t2) x -- | Signature mismatch type error sigbadfeq :: Name -> Type -> Equation () -> Typechecked a sigbadfeq n _t1 f = getPos >>= \x -> throwError $ cterr (SigBadFeq n _t1 f) x -- | Unknown type error unknown :: String -> Typechecked a unknown s = getPos >>= \x -> throwError $ cterr (Unknown s) x -- | Bad Op type error badop :: Op -> Type -> Type -> Typechecked a badop o _t1 _t2 = getInfo >>= (\(e, x) -> throwError $ cterr (BadOp o _t1 _t2 e) x) -- | Out of Bounds type error outofbounds :: Pos -> Pos -> Typechecked a outofbounds _p sz = getPos >>= \x -> throwError $ cterr (OutOfBounds _p sz) x -- | Uninitialized board type error uninitialized :: Name -> Typechecked a uninitialized n = getPos >>= \x -> throwError $ cterr (Uninitialized n) x -- | Bad function application type error badapp :: Name -> Expr SourcePos -> Typechecked a badapp n e = getPos >>= \x -> throwError $ cterr (BadApp n (clearAnn e)) x -- | Cannot dereference function type error dereff :: Name -> Type -> Typechecked a dereff n _t = getPos >>= \x -> throwError $ cterr (Dereff n _t) x | Retrieve the extensions from an Xtype extensions :: Xtype -> Typechecked (S.Set Name) extensions (X _ xs) = return xs extensions _ = unknown "No extension for type!" -- no extension for this
null
https://raw.githubusercontent.com/ChildsplayOSU/bogl/8c649689bf26543be1a7ec72787b9c013ecb754f/src/Typechecker/Monad.hs
haskell
| Types in the environment | Initial empty environment | An example environment for interal use (e.g. testing, ghci) | Typechecking monad | Run a computation inside of the typechecking monad | Add some types to the environment | Get the type environment | Get the type definitions | Get the input type | Get the content type | Get the board size | Check whether (x,y) is in the bounds of the board | Extend the environment | Set the source line | Set the position | Get the position | Get the source expression | Get a type from the environment | Types for which the subtype relation is defined In the Typechecked monad because subtyping depends on type definitions i.e. for types T1 and T2: has a type T been declared such that T1 <: T and T2 <: T | Assign a type name to a type definition element-wise unification of tuples only unify tuples of equivalent lengths... ...otherwise, these tuples cannot be unified expand named type and assign names to tuple elements if one is a subtype of the other, then the result is the larger type else, create a type from tl and tr (if possible) and see if it has been defined in user program | Dereference a named type (to enable a subtype check) T1 ---deref--> Int & {A,B} extended tuples not currently allowed by impl syntax | Dereferences a type until it finds a tuple. If there is not tuple, returns the original type This is used in 'eqntype' to ensure that params of multi-argument functions are assigned the type of their respective tuple element in the signature. e.g. type T1 = (Int, Int) type T2 = T1 dereference T2 to (Int, Int) | Dereferences a type until it finds a tuple or no more dereferencing is possible See 'findTuple' for more info | Dereference a pair of named types (a convenience function that wraps deref) | Check if t1 has type t2 with subsumption (i.e. by subtyping) | Returns a typechecked base type smart constructors for type errors | Gets the source expression and its position from the 'Typechecked' monad | Type mismatch error | Input type mismatch error | Type mismatch error for function application | Not bound type error | Signature mismatch type error | Signature mismatch type error | Unknown type error | Bad Op type error | Out of Bounds type error | Uninitialized board type error | Bad function application type error | Cannot dereference function type error no extension for this
# LANGUAGE DeriveGeneric # | Module : Typechecker . Monad Description : Typechecker monad Copyright : ( c ) License : BSD-3 Module : Typechecker.Monad Description : Typechecker monad Copyright : (c) License : BSD-3 -} module Typechecker.Monad where import Control.Monad.State import Control.Monad.Identity import Control.Monad.Except import Control.Monad.Reader import Control.Monad.Extra import Text.Parsec.Pos import Language.Types hiding (content, size) import qualified Data.Set as S import Language.Syntax hiding (input) import Runtime.Builtins import Error.Error import Error.TypeError import Data.List type TypeEnv = [(Name, Type)] | Typechecker environment data Env = Env { types :: TypeEnv, defs :: [TypeDef], input :: Xtype, content :: Xtype, size :: (Int, Int) } initEnv :: Xtype -> Xtype -> (Int, Int) -> [TypeDef] -> Env initEnv i _p s td = Env [] td i _p s exampleEnv :: Env exampleEnv = Env (builtinT intxt intxt) [] intxt intxt (5, 5) | Typechecker state data Stat = Stat { source :: Maybe (Expr SourcePos), pos :: SourcePos } type Typechecked a = (StateT Stat (ReaderT Env (ExceptT Error Identity))) a typecheck :: Env -> Typechecked a -> Either Error (a, Stat) typecheck e a = runIdentity . runExceptT . (flip runReaderT e) $ (runStateT a (Stat Nothing (newPos "" 0 0))) extendEnv :: Env -> (Name, Type) -> Env extendEnv (Env _t d i _p s) v = Env (v:_t) d i _p s getEnv :: Typechecked TypeEnv getEnv = types <$> ask getDefs :: Typechecked [TypeDef] getDefs = defs <$> ask getInput :: Typechecked Xtype getInput = input <$> ask getContent :: Typechecked (Xtype) getContent = content <$> ask getSize :: Typechecked (Int, Int) getSize = size <$> ask inBounds :: (Int, Int) -> Typechecked Bool inBounds (x, y) = do (x', y') <- getSize return $ x <= x' && y <= y' && x > 0 && y > 0 localEnv :: ([(Name, Type)] -> [(Name, Type)]) -> Typechecked a -> Typechecked a localEnv f e = local (\(Env a td b c d) -> Env (f a) td b c d) e setSrc :: (Expr SourcePos) -> Typechecked () setSrc e = modify (\(Stat _ x) -> Stat (Just e) x) setPos :: (SourcePos) -> Typechecked () setPos e = modify (\stat -> stat{pos = e}) getPos :: Typechecked SourcePos getPos = pos <$> get getSrc :: Typechecked (Expr ()) getSrc = do e <- source <$> get case e of Nothing -> unknown "Unable to get source expression!" Just _e -> return $ clearAnn _e getType :: Name -> Typechecked Type getType n = do env <- getEnv inputT <- getInput contentT <- getContent case (lookup n env, lookup n (builtinT inputT contentT)) of (Just e, _) -> return e (_, Just e) -> return e _ -> notbound n class Subtypeable t where (<:) :: t -> t -> Typechecked Bool instance Subtypeable Xtype where xa <: xb = do (xa', xb') <- derefs (xa, xb) return $ xa' <= xb' instance Subtypeable Type where (Plain xa) <: (Plain xb) = xa <: xb (Function (Ft xa xb)) <: (Function (Ft xa' xb')) = do inputs <- xa <: xa' outputs <- xb <: xb' return $ inputs && outputs _ <: _ = return False | Attempt to unify two types unify :: Xtype -> Xtype -> Typechecked Xtype unify xa xb = do (xa', xb') <- derefs (xa, xb) pass xa , xb so errors report type names assignTypeName :: Xtype -> Typechecked (Maybe Xtype) assignTypeName x = do ds <- getDefs look <- findM (\a -> x <: snd a) ds case look of (Just (tn, _)) -> return $ Just $ namedt tn _ -> return Nothing | Attempt to unify two dereferenced types requires un - dereferenced versions of the types as well this is to report type names like T rather than type defs like Int & { X } unify' :: (Xtype, Xtype) -> (Xtype, Xtype) -> Typechecked Xtype | all (\x -> length x == length xs) [xns, xs, yns, ys] = Tup <$> zipWithM unify' (zip xns xs) (zip yns ys) | otherwise = mismatch (Plain (Tup xns)) (Plain (Tup yns)) do xns <- findTuple xn yns <- findTuple yn unify' (xns, Tup xs) (yns, Tup ys) unify' (tnl, tl@(X y z)) (tnr, tr@(X w k)) | tr <= tl = return tl | tl <= tr = return tr | w <= y = do r <- assignTypeName $ X y (z `S.union` k) report r | y <= w = do r <- assignTypeName $ X w (z `S.union` k) report r where report (Just ty) = return ty report Nothing = mismatch (Plain tnl) (Plain tnr) unify' (tnl, _) (tnr, _) = mismatch (Plain tnl) (Plain tnr) e.g. type T1 = Int & { A , B } deref :: Xtype -> Typechecked Xtype deref (X (Named n) s) = do ds <- getDefs case find (\a -> fst a == n) ds of Just (_, x) -> do d <- deref x return $ addSymbols s d _ -> unknown "Internal type dereference error" where | initial type was n & s. After dereferencing , use this create x & s addSymbols :: S.Set String -> Xtype -> Xtype addSymbols ss (X b ss') = X b (S.union ss ss') deref (Tup xs) = do xs' <- mapM deref xs return $ Tup xs' deref h = return h TODO ! write a test for this findTuple :: Xtype -> Typechecked Xtype findTuple x = do x' <- findTuple' x case x' of Tup xs -> return $ Tup xs _ -> return x findTuple' :: Xtype -> Typechecked Xtype findTuple' (X (Named n) _) = do ds <- getDefs case find (\a -> fst a == n) ds of Just (_, Tup xs) -> return (Tup xs) Just (_, x) -> findTuple' x _ -> unknown "Internal type dereference error" findTuple' (Tup xs) = do xs' <- mapM findTuple' xs return $ Tup xs' findTuple' h = return h derefs :: (Xtype, Xtype) -> Typechecked (Xtype, Xtype) derefs (xl, xr) = do xl' <- deref xl xr' <- deref xr return (xl', xr') This is a wrapper around the instance to produce the type error if there is a mismatch hasType :: Xtype -> Xtype -> Typechecked Xtype hasType (Tup xs) (Tup ys) | length xs == length ys = Tup <$> zipWithM hasType xs ys hasType ta tb = ifM (ta <: tb) (return tb) (mismatch (Plain ta) (Plain tb)) t :: Btype -> Typechecked Xtype t b = return (X b S.empty) getInfo :: Typechecked (Expr (), SourcePos) getInfo = ((,) <$> getSrc <*> getPos) mismatch :: Type -> Type -> Typechecked a mismatch _t1 _t2 = getInfo >>= (\(e, x) -> throwError $ cterr (Mismatch _t1 _t2 e) x) inputmismatch :: Type -> Typechecked a inputmismatch act = do (e, x) <- getInfo it <- getInput throwError $ cterr (InputMismatch act (Plain it) e) x appmismatch :: Name -> Type -> Type -> Typechecked a appmismatch n _t1 _t2 = getInfo >>= (\(e, x) -> throwError $ cterr (AppMismatch n _t1 _t2 e) x) notbound :: Name -> Typechecked a notbound n = getPos >>= \x -> throwError $ cterr (NotBound n) x sigmismatch :: Name -> Type -> Type -> Typechecked a sigmismatch n _t1 _t2= getPos >>= \x -> throwError $ cterr (SigMismatch n _t1 _t2) x sigbadfeq :: Name -> Type -> Equation () -> Typechecked a sigbadfeq n _t1 f = getPos >>= \x -> throwError $ cterr (SigBadFeq n _t1 f) x unknown :: String -> Typechecked a unknown s = getPos >>= \x -> throwError $ cterr (Unknown s) x badop :: Op -> Type -> Type -> Typechecked a badop o _t1 _t2 = getInfo >>= (\(e, x) -> throwError $ cterr (BadOp o _t1 _t2 e) x) outofbounds :: Pos -> Pos -> Typechecked a outofbounds _p sz = getPos >>= \x -> throwError $ cterr (OutOfBounds _p sz) x uninitialized :: Name -> Typechecked a uninitialized n = getPos >>= \x -> throwError $ cterr (Uninitialized n) x badapp :: Name -> Expr SourcePos -> Typechecked a badapp n e = getPos >>= \x -> throwError $ cterr (BadApp n (clearAnn e)) x dereff :: Name -> Type -> Typechecked a dereff n _t = getPos >>= \x -> throwError $ cterr (Dereff n _t) x | Retrieve the extensions from an Xtype extensions :: Xtype -> Typechecked (S.Set Name) extensions (X _ xs) = return xs
cd74e75859a08483bcc75bca6241f9cb7194789a7b8ad98c765e630925ef36a3
2600hz/community-scripts
string_with_invalid_newline.erl
{error,{66,"lexical error: invalid character inside string.\n"}}.
null
https://raw.githubusercontent.com/2600hz/community-scripts/b0b81342bf02300fcdbda99e4cecc1ee93823c70/CloneTools/lib/ejson-0.1.0/t/cases/string_with_invalid_newline.erl
erlang
{error,{66,"lexical error: invalid character inside string.\n"}}.
6969581a334061fd15471dbadd35288d057099b20d31337e6d4d86fc9e31de63
zellige/zellige
Geometry.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} # OPTIONS_GHC -fno - warn - orphans # module Data.Geometry.VectorTile.Geometry where import Data.Foldable (foldl') import qualified Data.Foldable as Foldable import qualified Data.Sequence as S import GHC.Generics (Generic) data Unknown = Unknown deriving (Eq, Show, Generic) data Point = Point {x :: !Int, y :: !Int} deriving (Eq, Show, Generic) newtype LineString = LineString {lsPoints :: S.Seq Point} deriving (Eq, Show, Generic) data Polygon = Polygon { polyPoints :: S.Seq Point , inner :: S.Seq Polygon } deriving (Eq, Show, Generic) area :: Polygon -> Maybe Double area p = fmap sum . sequence $ foldl' (\acc a -> area a : acc) [surveyor $ polyPoints p] (inner p) | The surveyor 's formula for calculating the area of a ` Polygon ` . If the value reported here is negative , then the ` Polygon ` should be -- considered an Interior Ring. -- Assumption : The ` V.Vector ` given has at least 4 ` Point`s . surveyor :: S.Seq Point -> Maybe Double surveyor (v'@((v'head S.:<| _) S.:|> v'last) S.:|> _) = case (v' S.|> v'head, v'last S.<| v') of (S.Empty, _) -> Nothing (_ S.:<| _, S.Empty) -> Nothing (_ S.:<| tailYns, initYps S.:|> _) -> Just $ (/ 2) . fromIntegral . Foldable.foldl' (+) 0 $ S.zipWith3 (\xn yn yp -> xn * (yn - yp)) xs yns yps where xs = fmap x v' yns = fmap y tailYns yps = fmap y initYps surveyor _ = Nothing
null
https://raw.githubusercontent.com/zellige/zellige/87e6dab11ac4c1843009043580f14422a1d83ebf/src/Data/Geometry/VectorTile/Geometry.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE TypeOperators # considered an Interior Ring.
# LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeFamilies # # OPTIONS_GHC -fno - warn - orphans # module Data.Geometry.VectorTile.Geometry where import Data.Foldable (foldl') import qualified Data.Foldable as Foldable import qualified Data.Sequence as S import GHC.Generics (Generic) data Unknown = Unknown deriving (Eq, Show, Generic) data Point = Point {x :: !Int, y :: !Int} deriving (Eq, Show, Generic) newtype LineString = LineString {lsPoints :: S.Seq Point} deriving (Eq, Show, Generic) data Polygon = Polygon { polyPoints :: S.Seq Point , inner :: S.Seq Polygon } deriving (Eq, Show, Generic) area :: Polygon -> Maybe Double area p = fmap sum . sequence $ foldl' (\acc a -> area a : acc) [surveyor $ polyPoints p] (inner p) | The surveyor 's formula for calculating the area of a ` Polygon ` . If the value reported here is negative , then the ` Polygon ` should be Assumption : The ` V.Vector ` given has at least 4 ` Point`s . surveyor :: S.Seq Point -> Maybe Double surveyor (v'@((v'head S.:<| _) S.:|> v'last) S.:|> _) = case (v' S.|> v'head, v'last S.<| v') of (S.Empty, _) -> Nothing (_ S.:<| _, S.Empty) -> Nothing (_ S.:<| tailYns, initYps S.:|> _) -> Just $ (/ 2) . fromIntegral . Foldable.foldl' (+) 0 $ S.zipWith3 (\xn yn yp -> xn * (yn - yp)) xs yns yps where xs = fmap x v' yns = fmap y tailYns yps = fmap y initYps surveyor _ = Nothing
bbbddf7b761d398869dadf02ee9c31c3916b08818892c6cc1d39aebacf44e623
Lambda-X/cljs-repl-web
io.cljs
(ns cljs-repl-web.io (:require [cljs.js :as cljs] [clojure.string :as string] [cognitect.transit :as transit] [replumb.repl :as replumb-repl] [adzerk.cljs-console :as log :include-macros true]) (:import [goog.events EventType] [goog.net XhrIo])) (defn fetch-file! "Very simple implementation of XMLHttpRequests that given a file path calls src-cb with the string fetched of nil in case of error. See doc at " [file-url src-cb] (try (.send XhrIo file-url (fn [e] (if (.isSuccess (.-target e)) (src-cb (.. e -target getResponseText)) (src-cb nil)))) (catch :default e (src-cb nil)))) (defn load-cljs-core-cache! "Load core.cljs.cache.aot.json given the url" [cache-url] (fetch-file! cache-url (fn [txt] (let [rdr (transit/reader :json) cache (transit/read rdr txt)] (cljs/load-analysis-cache! replumb-repl/st 'cljs.core cache))))) (defn print-version! "Return the current version from the version.properties file." [version-path] (fetch-file! version-path (fn [content] (let [version (second (string/split (->> (string/split-lines content) (remove #(= "#" (first %))) first) #"=" 2))] (log/info "[Version] ~{version}"))))) (comment (def s "#Tue Feb 16 13:27:59 PST 2016\nVERSION=0.2.2-ar\nOTHER=STUFF") )
null
https://raw.githubusercontent.com/Lambda-X/cljs-repl-web/0dabe8ff18d8c0f4ae6c9f052dc23eb1f5ad262c/src/cljs/cljs_repl_web/io.cljs
clojure
(ns cljs-repl-web.io (:require [cljs.js :as cljs] [clojure.string :as string] [cognitect.transit :as transit] [replumb.repl :as replumb-repl] [adzerk.cljs-console :as log :include-macros true]) (:import [goog.events EventType] [goog.net XhrIo])) (defn fetch-file! "Very simple implementation of XMLHttpRequests that given a file path calls src-cb with the string fetched of nil in case of error. See doc at " [file-url src-cb] (try (.send XhrIo file-url (fn [e] (if (.isSuccess (.-target e)) (src-cb (.. e -target getResponseText)) (src-cb nil)))) (catch :default e (src-cb nil)))) (defn load-cljs-core-cache! "Load core.cljs.cache.aot.json given the url" [cache-url] (fetch-file! cache-url (fn [txt] (let [rdr (transit/reader :json) cache (transit/read rdr txt)] (cljs/load-analysis-cache! replumb-repl/st 'cljs.core cache))))) (defn print-version! "Return the current version from the version.properties file." [version-path] (fetch-file! version-path (fn [content] (let [version (second (string/split (->> (string/split-lines content) (remove #(= "#" (first %))) first) #"=" 2))] (log/info "[Version] ~{version}"))))) (comment (def s "#Tue Feb 16 13:27:59 PST 2016\nVERSION=0.2.2-ar\nOTHER=STUFF") )
cc11eacf39785f3de04d92a9e5f0a886c51da667af5e03d76271236c5ba24f4a
typelead/etlas
Eta.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE RankNTypes #-} # LANGUAGE NamedFieldPuns # module Distribution.Simple.Eta ( configure, getInstalledPackages, getPackageDBContents, buildLib, buildExe, replLib, replExe, startInterpreter, installLib, installExe, libAbiHash, hcPkgInfo, registerPackage, componentGhcOptions, getLibDir, isDynamic, getGlobalPackageDB, mkMergedClassPath, mkMergedClassPathLbi, classPathSeparator, mkJarName, JavaExec(..), runJava, fetchMavenDependencies, findCoursierRef, findVerifyRef, findEtaServRef, getLibraryComponent, getDependencyClassPaths, InstallDirType(..), exeJarPath, libJarPath, getInstalledPackagesMonitorFiles ) where import Prelude () import Data.IORef import System.IO.Unsafe import Distribution.Compat.Prelude import Distribution.Simple.GHC.ImplInfo import qualified Distribution.Simple.GHC.Internal as Internal import Distribution.PackageDescription as PD import Distribution.InstalledPackageInfo hiding (frameworks, exposedModules) import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo import Distribution.Simple.PackageIndex ( InstalledPackageIndex ) import qualified Distribution.Simple.PackageIndex as PackageIndex import Distribution.Simple.LocalBuildInfo import Distribution.Simple.Utils import Distribution.Simple.Program import qualified Distribution.Simple.Program.HcPkg as HcPkg import Distribution.Simple.Program.GHC import Distribution.Simple.Setup hiding ( Flag ) import qualified Distribution.Simple.Setup as Cabal import Distribution.Simple.Compiler hiding ( Flag ) import Distribution.Version import Distribution.System import Distribution.Verbosity import Distribution.Utils.NubList import Distribution.Text import Distribution.Types.UnitId import Distribution.Types.UnqualComponentName import qualified Paths_etlas_cabal as Etlas (version) import qualified Data.Map as Map import Data.List import Data.Maybe import Control.Monad import System.Directory hiding (findFile) import System.FilePath configure :: Verbosity -> Maybe FilePath -> Maybe FilePath -> ProgramDb -> IO (Compiler, Maybe Platform, ProgramDb) configure verbosity hcPath hcPkgPath conf0 = do (etaProg, etaVersion, conf1) <- requireProgramVersion verbosity etaProgram anyVersion (userMaybeSpecifyPath "eta" hcPath conf0) let implInfo = etaVersionImplInfo etaVersion etaGhcVersion (etaPkgProg, etaPkgVersion, conf2) <- requireProgramVersion verbosity etaPkgProgram anyVersion (userMaybeSpecifyPath "eta-pkg" hcPkgPath conf1) when (etaVersion /= etaPkgVersion) $ die' verbosity $ "Version mismatch between eta and eta-pkg: " ++ programPath etaProg ++ " is version " ++ display etaVersion ++ " " ++ programPath etaPkgProg ++ " is version " ++ display etaPkgVersion let conf3 = conf2 languages <- Internal.getLanguages verbosity implInfo etaProg extensions <- Internal.getExtensions verbosity implInfo etaProg etaInfo <- Internal.getGhcInfo verbosity implInfo etaProg let comp = Compiler { compilerId = CompilerId Eta etaVersion, TODO : Make this unique for ETA ? compilerAbiTag = AbiTag $ "ghc" ++ intercalate "_" (map show . versionNumbers $ etaGhcVersion), compilerCompat = [CompilerId GHC etaGhcVersion], compilerLanguages = languages, compilerExtensions = extensions, compilerProperties = Map.fromList etaInfo } compPlatform = Nothing -- Internal.targetPlatform ghcInfo (_, conf4) <- requireProgram verbosity javaProgram conf3 (_, conf5) <- requireProgram verbosity javacProgram conf4 return (comp, compPlatform, conf5) | Given a single package DB , return all installed packages . getPackageDBContents :: Verbosity -> PackageDB -> ProgramDb -> IO InstalledPackageIndex getPackageDBContents verbosity packagedb progdb = do pkgss <- getInstalledPackages' verbosity [packagedb] progdb toPackageIndex verbosity pkgss progdb -- | Given a package DB stack, return all installed packages. getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramDb -> IO InstalledPackageIndex getInstalledPackages verbosity packagedbs progdb = do checkPackageDbEnvVar verbosity checkPackageDbStack verbosity packagedbs pkgss <- getInstalledPackages' verbosity packagedbs progdb index <- toPackageIndex verbosity pkgss progdb return $! index toPackageIndex :: Verbosity -> [(PackageDB, [InstalledPackageInfo])] -> ProgramDb -> IO InstalledPackageIndex toPackageIndex _ pkgss _ = do let indices = [ PackageIndex.fromList pkgs | (_, pkgs) <- pkgss ] return $! (mconcat indices) checkPackageDbEnvVar :: Verbosity -> IO () checkPackageDbEnvVar verbosity = Internal.checkPackageDbEnvVar verbosity "ETA" "ETA_PACKAGE_PATH" checkPackageDbStack :: Verbosity -> PackageDBStack -> IO () checkPackageDbStack _ (GlobalPackageDB:rest) | GlobalPackageDB `notElem` rest = return () checkPackageDbStack verbosity rest | GlobalPackageDB `notElem` rest = die' verbosity $ "With current ghc versions the global package db is always used " ++ "and must be listed first. This ghc limitation may be lifted in " ++ "future, see " checkPackageDbStack verbosity _ = die' verbosity $ "If the global package db is specified, it must be " ++ "specified first and cannot be specified multiple times" getInstalledPackages' :: Verbosity -> [PackageDB] -> ProgramDb -> IO [(PackageDB, [InstalledPackageInfo])] getInstalledPackages' verbosity packagedbs progdb = sequence [ do createDir packagedb pkgs <- HcPkg.dump (hcPkgInfo progdb) verbosity packagedb return (packagedb, pkgs) | packagedb <- packagedbs ] where createDir (SpecificPackageDB path) = createDirectoryIfMissing True path createDir _ = return () trimEnd :: String -> String trimEnd = reverse . dropWhile isSpace . reverse getLibDir :: Verbosity -> ProgramDb -> IO FilePath getLibDir verbosity progDb = trimEnd `fmap` getDbProgramOutput verbosity etaProgram progDb ["--print-libdir"] -- getLibDir' :: Verbosity -> ConfiguredProgram -> IO FilePath -- getLibDir' verbosity etaProg = ( reverse . . reverse ) ` fmap ` -- getProgramOutput verbosity etaProg ["--print-libdir"] | Return the ' FilePath ' to the global GHC package database . getGlobalPackageDB :: Verbosity -> ConfiguredProgram -> IO FilePath getGlobalPackageDB verbosity etaProg | Just version <- programVersion etaProg , version >= mkVersion [0,7,1] = trimEnd `fmap` getProgramOutput verbosity etaProg ["--print-global-package-db"] | otherwise = ((</> "package.conf.d") . trimEnd) `fmap` getProgramOutput verbosity etaProg ["--print-libdir"] buildLib, replLib :: Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO () buildLib = buildOrReplLib False replLib = buildOrReplLib True libJarPath :: LocalBuildInfo -> ComponentLocalBuildInfo -> FilePath libJarPath lbi clbi = buildDir lbi </> mkJarName (componentUnitId clbi) buildOrReplLib :: Bool -> Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO () buildOrReplLib forRepl verbosity numJobs pkgDescr lbi lib clbi = do let uid = componentUnitId clbi libTargetDir = buildDir lbi isVanillaLib = not forRepl && withVanillaLib lbi isSharedLib = not forRepl && withSharedLib lbi ifReplLib = when forRepl comp = compiler lbi (etaProg, _) <- requireProgram verbosity etaProgram (withPrograms lbi) mEtaServPath <- findEtaServ verbosity (programVersion etaProg) let runEtaProg = runGHC verbosity etaProg comp (hostPlatform lbi) libBi = libBuildInfo lib doWithResolvedDependencyClassPathsOrDie verbosity pkgDescr lbi clbi libBi RelativeInstallDir $ \ (depJars,mavenPaths) -> do let fullClassPath = depJars ++ mavenPaths createDirectoryIfMissingVerbose verbosity True libTargetDir -- TODO: do we need to put hs-boot files into place for mutually recursive -- modules? let javaSrcs = javaSources libBi baseOpts = componentGhcOptions verbosity lbi libBi clbi libTargetDir `mappend` mempty { ghcOptExtra = toNubListR $ maybe [] (\etaServPath -> ["-pgmi", etaServPath]) mEtaServPath } linkJavaLibOpts = mempty { ghcOptInputFiles = toNubListR javaSrcs, ghcOptExtra = toNubListR $ ["-cp", mkMergedClassPathLbi lbi fullClassPath] } vanillaOptsNoJavaLib = baseOpts `mappend` mempty { ghcOptMode = toFlag GhcModeMake, ghcOptNumJobs = numJobs, ghcOptInputModules = toNubListR $ allLibModules lib clbi, ghcOptOutputFile = toFlag target } vanillaOpts' = vanillaOptsNoJavaLib `mappend` linkJavaLibOpts sharedOpts = vanillaOpts' `mappend` mempty { Libs should never have the -shared flag -- ghcOptShared = toFlag True, ghcOptExtraDefault = toNubListR ["-staticlib"], ghcOptExtra = toNubListR $ etaSharedOptions libBi } vanillaOpts = vanillaOpts' { ghcOptExtraDefault = toNubListR ["-staticlib"] } replOpts = vanillaOpts' { ghcOptExtra = (overNubListR Internal.filterGhciFlags $ ghcOptExtra vanillaOpts') `mappend` toNubListR ["-inmemory"], ghcOptNumJobs = mempty, ghcOptMode = toFlag GhcModeInteractive, ghcOptOptimisation = toFlag GhcNoOptimisation } target = libTargetDir </> mkJarName uid unless (forRepl || (null (allLibModules lib clbi) && null javaSrcs)) $ do let withVerify act = do _ <- act when (fromFlagOrDefault False (configVerifyMode $ configFlags lbi)) $ runVerify verbosity fullClassPath target lbi if isVanillaLib then withVerify $ runEtaProg vanillaOpts else if isSharedLib then withVerify $ runEtaProg sharedOpts else return () ifReplLib (runEtaProg replOpts) -- | Start a REPL without loading any source files. startInterpreter :: Verbosity -> ProgramDb -> Compiler -> Platform -> PackageDBStack -> IO () startInterpreter verbosity progdb comp platform packageDBs = do let replOpts = mempty { ghcOptMode = toFlag GhcModeInteractive, ghcOptPackageDBs = packageDBs } checkPackageDbStack verbosity packageDBs (etaProg, _) <- requireProgram verbosity etaProgram progdb runGHC verbosity etaProg comp platform replOpts buildExe, replExe :: Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo -> IO () buildExe = buildOrReplExe False replExe = buildOrReplExe True exeJarPath :: LocalBuildInfo -> UnqualComponentName -> FilePath exeJarPath lbi ucn = buildDir lbi </> exeName' </> realExeName exeName' where exeName' = display ucn realExeName :: String -> FilePath realExeName exeName' | takeExtension exeName' /= ('.':jarExtension) = exeName' <.> jarExtension | otherwise = exeName' buildOrReplExe :: Bool -> Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo -> IO () buildOrReplExe forRepl verbosity numJobs pkgDescr lbi exe@Executable { exeName, modulePath = modPath } clbi = do let exeName' = display exeName exeNameReal = realExeName exeName' targetDir = buildDir lbi </> exeName' exeTmpDir = exeName' ++ "-tmp" exeDir = targetDir </> exeTmpDir exeJar = targetDir </> exeNameReal withDeps = doWithResolvedDependencyClassPathsOrDie verbosity pkgDescr lbi clbi exeBi (etaProg, _) <- requireProgram verbosity etaProgram (withPrograms lbi) mEtaServPath <- findEtaServ verbosity (programVersion etaProg) createDirectoryIfMissingVerbose verbosity True exeDir srcMainFile <- findFile (hsSourceDirs exeBi) modPath withDeps RelativeInstallDir $ \ (depJars,mavenPaths) -> do let fullClassPath = depJars ++ mavenPaths classPaths | isShared = fullClassPath | otherwise = [] -- Handle java sources javaSrcs | isShared = javaSrcs' | otherwise = mavenPaths ++ javaSrcs' runEtaProg = runGHC verbosity etaProg comp (hostPlatform lbi) baseOpts = (componentGhcOptions verbosity lbi exeBi clbi exeDir) `mappend` mempty { ghcOptInputFiles = toNubListR $ srcMainFile : javaSrcs, ghcOptInputModules = toNubListR $ exeModules exe, ghcOptNumJobs = numJobs, ghcOptExtra = toNubListR $ ["-cp", mkMergedClassPathLbi lbi fullClassPath] ++ maybe [] (\etaServPath -> ["-pgmi", etaServPath]) mEtaServPath } exeOpts = baseOpts `mappend` mempty { ghcOptMode = toFlag GhcModeMake, ghcOptOutputFile = toFlag exeJar, ghcOptShared = toFlag isShared } replOpts = baseOpts `mappend` mempty { ghcOptMode = toFlag GhcModeInteractive, ghcOptOptimisation = toFlag GhcNoOptimisation } withVerify act = do _ <- act when (fromFlagOrDefault False (configVerifyMode $ configFlags lbi)) $ runVerify verbosity (exeJar : classPaths) exeJar lbi if forRepl then runEtaProg replOpts else do withVerify $ runEtaProg exeOpts -- Generate command line file / jar exec launchers generateExeLaunchers verbosity lbi exeName' classPaths targetDir -- Generate launchers for the install phase unless forRepl $ withDeps AbsoluteGlobalInstallDir $ \ (depJars, mavenPaths) -> do let installLaunchersDir = targetDir </> "install-launchers" classPaths | isShared = depJars ++ mavenPaths | otherwise = [] createDirectoryIfMissingVerbose verbosity True installLaunchersDir generateExeLaunchers verbosity lbi exeName' classPaths installLaunchersDir where comp = compiler lbi exeBi = buildInfo exe isShared = withDynExe lbi javaSrcs' = javaSources exeBi dirEnvVarAndRef :: Bool -> (String,String) dirEnvVarAndRef isWindows' = (var,ref) where var = "DIR" ref | isWindows' = "%" ++ var ++ "%" | otherwise = "$" ++ var generateExeLaunchers :: Verbosity -> LocalBuildInfo -> String -> [String] -> FilePath -> IO () generateExeLaunchers verbosity lbi exeName classPaths targetDir = do generateExeLauncherScript verbosity lbi exeName classPaths targetDir Windows faces the dreaded line - length limit which forces us to create a launcher jar as a workaround . launcher jar as a workaround. -} when (isWindows lbi) $ generateExeLauncherJar verbosity lbi exeName classPaths targetDir generateExeLauncherScript :: Verbosity -> LocalBuildInfo -> String -> [String] -> FilePath -> IO () generateExeLauncherScript _verbosity lbi exeName classPaths targetDir = do let isWindows' = isWindows lbi classPathSep = head (classPathSeparator (hostPlatform lbi)) scriptClassPaths | null classPaths = "" | otherwise = mkMergedClassPathLbi lbi classPaths exeScript = exeLauncherScript classPathSep exeName scriptClassPaths isWindows' scriptFile | isWindows' = prefix ++ ".cmd" | otherwise = prefix where prefix = targetDir </> exeName writeUTF8File scriptFile exeScript p <- getPermissions scriptFile setPermissions scriptFile (p { executable = True }) exeLauncherScript :: Char -> String -> String -> Bool -> String exeLauncherScript classPathSep exeName classPaths isWindows' | isWindows' = unlines [ "@echo off" , "set " ++ dirEnvVar ++ "=%~dp0" , "if defined ETA_JAVA_CMD goto execute" , "if defined JAVA_HOME goto findJavaFromJavaHome" , "set ETA_JAVA_CMD=java.exe" , "goto execute" , ":findJavaFromJavaHome" , "set ETA_JAVA_HOME=%JAVA_HOME:\"=%" , "set ETA_JAVA_CMD=%ETA_JAVA_HOME%\\bin\\java.exe" , ":execute" , "\"%ETA_JAVA_CMD%\" -Deta.programName=" ++ exeName ++ " %JAVA_ARGS% %JAVA_OPTS% %ETA_JAVA_ARGS% " ++ "-classpath " ++ winClassPath ++ " eta.main %*" ] | otherwise = unlines [ "#!/usr/bin/env bash" , "SCRIPT=\"${BASH_SOURCE[0]}\"" , "getScriptDir() {" , " if [[ $(uname -s) == Darwin ]]" , " then" , " local OLD_DIR=`pwd`" , " SCRIPT_BASE=\"$SCRIPT\"" , " cd `dirname $SCRIPT_BASE`" , " SCRIPT_BASE=`basename $SCRIPT_BASE`" , " while [ -L \"$SCRIPT_BASE\" ]" , " do" , " SCRIPT_BASE=`readlink $SCRIPT_BASE`" , " cd `dirname $SCRIPT_BASE`" , " SCRIPT_BASE=`basename $SCRIPT_BASE`" , " done" , " local SCRIPT_DIR=`pwd -P`" , " SCRIPT=\"$SCRIPT_DIR/$SCRIPT_BASE\"" , " cd \"$OLD_DIR\"" , " else" , " SCRIPT=\"$(readlink -f \"$SCRIPT\")\"" , " fi" , " " ++ dirEnvVar ++ "=\"$(cd \"$(dirname \"$SCRIPT\")\" && pwd)\"" , "}" , "getScriptDir" , "if [ -z \"$ETA_JAVA_CMD\" ]; then" , " if [ -n \"$JAVA_HOME\" ] ; then" , " if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then" , " ETA_JAVA_CMD=\"$JAVA_HOME/jre/sh/java\"" , " else" , " ETA_JAVA_CMD=\"$JAVA_HOME/bin/java\"" , " fi" , " else" , " ETA_JAVA_CMD=\"java\"" , " fi" , "fi" , "$ETA_JAVA_CMD -Deta.programName=" ++ exeName ++ " $JAVA_ARGS $JAVA_OPTS $ETA_JAVA_ARGS " ++ "-classpath \"" ++ totalClassPath ++ "\" eta.main \"$@\"" ] where (dirEnvVar, dirEnvVarRef) = dirEnvVarAndRef isWindows' exeJarEnv = dirEnvVarRef </> realExeName exeName totalClassPath = exeJarEnv ++ [classPathSep] ++ classPaths ++ [classPathSep] ++ "$ETA_CLASSPATH" -- For Windows launcherJarEnv = dirEnvVarRef </> (exeName ++ ".launcher.jar") winClassPath = "\"" ++ launcherJarEnv ++ "\"" ++ [classPathSep] ++ "%ETA_CLASSPATH%" generateExeLauncherJar :: Verbosity -> LocalBuildInfo -> String -> [String] -> FilePath -> IO () generateExeLauncherJar verbosity lbi exeName classPaths targetDir = do jarProg <- fmap fst $ requireProgram verbosity jarProgram (withPrograms lbi) writeFile targetManifest $ unlines $ ["Manifest-Version: 1.0" ,"Created-By: etlas-" ++ display Etlas.version ,"Main-Class: eta.main" ,"Class-Path: " ++ realExeName exeName] ++ map ((++) " ") classPaths' -- Create the launcher jar runProgramInvocation verbosity $ programInvocation jarProg ["cfm", launcherJar, targetManifest] where addStartingPathSep path | hasDrive path = pathSeparator : path | otherwise = path (_, dirEnvVarRef) = dirEnvVarAndRef $ isWindows lbi replaceEnvVar = replacePrefix dirEnvVarRef "." uriEncodeSpaces = foldl' (\acc c -> acc ++ if c == ' ' then "%20" else [c]) "" classPaths' = map (uriEncodeSpaces . addStartingPathSep . replaceEnvVar) classPaths targetManifest = targetDir </> "MANIFEST.MF" launcherJar = targetDir </> (exeName ++ ".launcher.jar") isWindows :: LocalBuildInfo -> Bool isWindows lbi | Platform _ Windows <- hostPlatform lbi = True | otherwise = False replacePrefix :: Eq a => [a] -> [a] -> [a] -> [a] replacePrefix old new s | isPrefixOf old s = new ++ drop (length old) s | otherwise = s |Install for ghc , .hi , .a and , if --with - ghci given , .o installLib :: Verbosity -> LocalBuildInfo -> FilePath -- ^install location -> FilePath -- ^install location for dynamic libraries -> FilePath -- ^Build location -> PackageDescription -> Library -> ComponentLocalBuildInfo -> IO () installLib verbosity lbi targetDir _dynlibTargetDir builtDir _pkg lib clbi = do copyModuleFiles "hi" when hasLib $ do mapM_ (installOrdinaryIfExists builtDir targetDir) jarLibNames where installOrdinaryIfExists srcDir dstDir name = do exists <- doesFileExist $ srcDir </> name when exists $ installOrdinary srcDir dstDir name installOrdinary srcDir dstDir name = do createDirectoryIfMissingVerbose verbosity True dstDir installOrdinaryFile verbosity src dst where src = srcDir </> name dst = dstDir </> (fromMaybe name $ stripPrefix "HS" name) The stripPrefix " HS " bit is for backwards compat copyModuleFiles ext = findModuleFiles [builtDir] [ext] (allLibModules lib clbi) >>= installOrdinaryFiles verbosity targetDir _cid = compilerId (compiler lbi) libUids = [componentUnitId clbi] jarLibNames = map mkJarName libUids ++ map (("HS" ++) . mkJarName) libUids hasLib = not $ null (allLibModules lib clbi) && null (javaSources (libBuildInfo lib)) mkJarName :: UnitId -> String mkJarName uid = getHSLibraryName uid <.> "jar" installExe :: Verbosity -> LocalBuildInfo -> InstallDirs FilePath -- ^Where to copy the files to -> FilePath -- ^Build location ( prefix , suffix ) -> PackageDescription -> Executable -> IO () installExe verbosity lbi installDirs buildPref (_progprefix, _progsuffix) _pkg exe = do let _exeBi = buildInfo exe binDir = bindir installDirs toDir x = binDir </> x exeName' = display (exeName exe) buildDir = buildPref </> exeName' installLaunchersDir = buildDir </> "install-launchers" exeNameExt ext = if null ext then exeName' else exeName' <.> ext launchExt = if isWindows lbi then "cmd" else "" copy fromDir x = copyFile (fromDir </> x) (toDir x) createDirectoryIfMissingVerbose verbosity True binDir copy buildDir (exeNameExt "jar") copy installLaunchersDir (exeNameExt launchExt) when (isWindows lbi) $ copy installLaunchersDir (exeNameExt "launcher.jar") libAbiHash :: Verbosity -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO String libAbiHash verbosity _pkg_descr lbi lib clbi = do let libBi = libBuildInfo lib comp = compiler lbi platform = hostPlatform lbi vanillaArgs = (componentGhcOptions verbosity lbi libBi clbi (componentBuildDir lbi clbi)) `mappend` mempty { ghcOptMode = toFlag GhcModeAbiHash, ghcOptInputModules = toNubListR $ exposedModules lib } etaArgs = vanillaArgs (etaProg, _) <- requireProgram verbosity etaProgram (withPrograms lbi) getProgramInvocationOutput verbosity (ghcInvocation etaProg comp platform etaArgs) registerPackage :: Verbosity -> ProgramDb -> PackageDBStack -> InstalledPackageInfo -> HcPkg.RegisterOptions -> IO () registerPackage verbosity progdb packageDbs installedPkgInfo registerOptions = HcPkg.register (hcPkgInfo progdb) verbosity packageDbs installedPkgInfo registerOptions componentGhcOptions :: Verbosity -> LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo -> FilePath -> GhcOptions componentGhcOptions verbosity lbi bi clbi odir = let opts = Internal.componentGhcOptions verbosity implInfo lbi bi clbi odir comp = compiler lbi implInfo = getImplInfo comp in opts { ghcOptExtra = ghcOptExtra opts `mappend` toNubListR (["-pgmjavac", javacPath] ++ (hcOptions Eta bi)) } where Just javacProg = lookupProgram javacProgram (withPrograms lbi) javacPath = locationPath (programLocation javacProg) etaProfOptions : : - > [ String ] -- etaProfOptions bi = hcProfOptions GHC bi ` mappend ` hcProfOptions ETA bi etaSharedOptions :: BuildInfo -> [String] etaSharedOptions bi = hcSharedOptions GHC bi `mappend` hcSharedOptions Eta bi isDynamic :: Compiler -> Bool isDynamic = const True -- findEtaGhcVersion :: Verbosity -> FilePath -> IO (Maybe Version) findEtaGhcVersion verbosity pgm = findProgramVersion " --numeric - ghc - version " i d verbosity pgm -- findEtaPkgEtaVersion :: Verbosity -> FilePath -> IO (Maybe Version) findEtaPkgEtaVersion verbosity pgm = findProgramVersion " --numeric - eta - version " i d verbosity pgm -- ----------------------------------------------------------------------------- -- Registering hcPkgInfo :: ProgramDb -> HcPkg.HcPkgInfo hcPkgInfo progdb = HcPkg.HcPkgInfo { HcPkg.hcPkgProgram = etaPkgProg , HcPkg.noPkgDbStack = False , HcPkg.noVerboseFlag = False , HcPkg.flagPackageConf = False , HcPkg.supportsDirDbs = True , HcPkg.requiresDirDbs = True , HcPkg.nativeMultiInstance = True , HcPkg.recacheMultiInstance = True , HcPkg.suppressFilesCheck = True } where Just etaPkgProg = lookupProgram etaPkgProgram progdb NOTE : ETA is frozen after 7.10.3 etaGhcVersion :: Version etaGhcVersion = mkVersion [7,10,3] jarExtension :: String jarExtension = "jar" doWithResolvedDependencyClassPathsOrDie :: Verbosity -> PackageDescription -> LocalBuildInfo -> ComponentLocalBuildInfo -> BuildInfo -> InstallDirType -> (([FilePath], [FilePath]) -> IO ()) -> IO () doWithResolvedDependencyClassPathsOrDie verbosity pkgDescr lbi clbi bi libDirType action = do mDeps <- getDependencyClassPaths (installedPkgs lbi) pkgDescr lbi clbi bi libDirType case mDeps of Just (depJars, mavenDeps) -> do let mavenRepos = frameworks bi mavenPaths <- fetchMavenDependencies verbosity mavenRepos mavenDeps (withPrograms lbi) action (depJars,mavenPaths) Nothing -> die' verbosity "Missing dependencies. Try `etlas install --dependencies-only`?" data InstallDirType = RelativeInstallDir | AbsoluteLocalInstallDir | AbsoluteGlobalInstallDir getDependencyClassPaths :: InstalledPackageIndex -> PackageDescription -> LocalBuildInfo -> ComponentLocalBuildInfo -> BuildInfo -> InstallDirType -> IO (Maybe ([FilePath], [String])) getDependencyClassPaths packageIndex pkgDescr lbi clbi bi libDirType | Left closurePackageIndex <- closurePackageIndex' = do let packageInfos = PackageIndex.allPackages closurePackageIndex packageMavenDeps = concatMap InstalledPackageInfo.extraLibraries packageInfos packagesPaths <- fmap concat $ mapM hsLibraryPaths packageInfos return $ Just (libPath ++ packagesPaths, mavenDeps ++ libMavenDeps ++ packageMavenDeps) | otherwise = return Nothing where hsLibraryPaths pinfo = mapM (findFile (libraryDirs pinfo)) (map (<.> "jar") $ hsLibraries pinfo) closurePackageIndex' = PackageIndex.dependencyClosure packageIndex packages where packages = libDeps ++ packages'' mavenDeps = extraLibs bi libPath | null libs = [] | otherwise = case libDirType of RelativeInstallDir -> [dirEnvVarRef ++ "/../" ++ libJarName] AbsoluteLocalInstallDir -> [buildDir lbi </> libJarName] AbsoluteGlobalInstallDir -> [globalLibDir </> libJarName] where (_,dirEnvVarRef) = dirEnvVarAndRef $ isWindows lbi libUid = fromJust mbLibUid libJarName = mkJarName libUid globalLibDir = libdir $ absoluteComponentInstallDirs pkgDescr lbi libUid NoCopyDest libMavenDeps | null libs = [] | otherwise = extraLibs . libBuildInfo . fromJust $ library pkgDescr (mbLibUid, libDeps) | null libs = (Nothing, []) | otherwise = (Just $ componentUnitId clbi' , map fst $ componentPackageDeps clbi') where clbi' = fromJust libComponent (libs, packages'') = maybe ([], packages') (\lc -> partition (== lc) packages') $ fmap componentUnitId libComponent where packages' = map fst $ componentPackageDeps clbi libComponent = getLibraryComponent lbi getLibraryComponent :: LocalBuildInfo -> Maybe ComponentLocalBuildInfo getLibraryComponent lbi = fmap head clbis where clbis = Map.lookup CLibName $ componentNameMap lbi -- TODO: When there are multiple component dependencies ( Backpack - support ) this might break . -RM builtInMavenResolvers :: [(String, String)] builtInMavenResolvers = [ ("central", "/") , ("javaNet1", "/") , ("sonatype:public", "") , ("sonatype:snapshots", "") , ("sonatype:releases", "") , ("jcenter", "/") ] resolveOrId :: String -> String resolveOrId repo | Just resolved <- lookup repo builtInMavenResolvers = resolved | "bintray" `isPrefixOf` repo = let (_, rest) = break (== ':') repo (owner, repos') = break (== ':') $ drop 1 rest repos = drop 1 repos' in "/" ++ owner ++ "/" ++ repos ++ "/" | otherwise = repo classPathSeparator :: Platform -> String classPathSeparator (Platform _ Windows) = ";" classPathSeparator _ = ":" mkMergedClassPath :: Platform -> [FilePath] -> FilePath mkMergedClassPath platform = intercalate (classPathSeparator platform) mkMergedClassPathLbi :: LocalBuildInfo -> [FilePath] -> FilePath mkMergedClassPathLbi lbi = mkMergedClassPath (hostPlatform lbi) data JavaExec = Jar FilePath | JavaClass String runJava :: Verbosity -> [String] -> JavaExec -> [String] -> ProgramDb -> IO String runJava verb javaArgs javaExec javaExecArgs progDb = do (javaProg,_) <- requireProgram verb javaProgram progDb let (exJavaArgs,javaExec') = case javaExec of Jar path -> (["-jar"],path) JavaClass name -> ([],name) javaInv = programInvocation javaProg $ javaArgs ++ exJavaArgs javaInv' = withSystemProxySetting javaInv javaExecInv = simpleProgramInvocation javaExec' javaExecArgs getProgramInvocationOutput verb $ nestedProgramInvocation javaInv' javaExecInv withSystemProxySetting :: ProgramInvocation -> ProgramInvocation withSystemProxySetting javaInvoc@ProgramInvocation { progInvokeArgs = args } = javaInvoc {progInvokeArgs = args ++ proxySetting} where hasProxySetting = any (isSubsequenceOf "proxyHost") args proxySetting = if not hasProxySetting then ["-Djava.net.useSystemProxies=true"] else [] -- TODO: Extremely dirty (but safe) hack because etlas-cabal has no HTTP-aware modules. -- Basically, we want to be able to search the index for a given eta version -- when we can't find any. But we need HTTP ability for that. findCoursierRef :: IORef (Verbosity -> NoCallStackIO ()) findCoursierRef = unsafePerformIO $ newIORef $ \verbosity -> do info verbosity $ "The Coursier Ref has not been initialized!" return () runCoursier :: Verbosity -> [String] -> ProgramDb -> IO String runCoursier verbosity opts progDb = do etlasToolsDir <- defaultEtlasToolsDir let path = etlasToolsDir </> "coursier" exists <- doesFileExist path when (not exists) $ do findCoursier <- readIORef findCoursierRef findCoursier verbosity runJava verbosity ["-noverify"] (Jar path) opts progDb findEtaServRef :: IORef (Verbosity -> ProgramSearchPath -> NoCallStackIO (Maybe (FilePath, [FilePath]))) findEtaServRef = unsafePerformIO $ newIORef $ \verbosity _ -> do info verbosity $ "The Eta Serv Ref has not been initialized!" return Nothing findEtaServ :: Verbosity -> Maybe Version -> IO (Maybe FilePath) findEtaServ verbosity mVersion | Just version <- mVersion , version >= mkVersion [0,8] = do findEtaServ' <- readIORef findEtaServRef mResult <- findEtaServ' verbosity [] return $ fmap fst mResult | otherwise = return Nothing -- TODO: Extremely dirty (but safe) hack because etlas-cabal has no HTTP-aware modules. -- Basically, we want to be able to search the index for a given eta version -- when we can't find any. But we need HTTP ability for that. findVerifyRef :: IORef (Verbosity -> NoCallStackIO ()) findVerifyRef = unsafePerformIO $ newIORef $ \verbosity -> do info verbosity $ "The Verify Ref has not been initialized!" return () runVerify :: Verbosity -> [String] -> String -> LocalBuildInfo -> IO () runVerify verbosity classPath target lbi = do etlasToolsDir <- defaultEtlasToolsDir let path = etlasToolsDir </> "classes" verifyClass = path </> "Verify.class" exists <- doesFileExist verifyClass when (not exists) $ do findVerify <- readIORef findVerifyRef findVerify verbosity _ <- runJava verbosity ["-cp", mkMergedClassPathLbi lbi (path:classPath)] (JavaClass "Verify") [target] (withPrograms lbi) return () fetchMavenDependencies :: Verbosity -> [String] -> [String] -> ProgramDb -> IO [String] fetchMavenDependencies _ _ [] _ = return [] fetchMavenDependencies verb repos deps progDb = do let resolvedRepos = concatMap (\r -> ["-r", resolveOrId r]) repos fmap lines $ runCoursier verb (["fetch", "-a", "jar","--quiet"] ++ deps ++ resolvedRepos) progDb getInstalledPackagesMonitorFiles :: Verbosity -> Platform -> ProgramDb -> [PackageDB] -> IO [FilePath] getInstalledPackagesMonitorFiles verbosity _platform progdb = traverse getPackageDBPath where getPackageDBPath :: PackageDB -> IO FilePath getPackageDBPath GlobalPackageDB = selectMonitorFile =<< getGlobalPackageDB verbosity etaProg For Eta , both Global and User are one and the same . getPackageDBPath UserPackageDB = selectMonitorFile =<< getGlobalPackageDB verbosity etaProg getPackageDBPath (SpecificPackageDB path) = selectMonitorFile path GHC has old style file dbs , and new style directory dbs . -- Note that for dir style dbs, we only need to monitor the cache file, not the whole directory . The ghc program itself only reads the cache file so it 's safe to only monitor this one file . selectMonitorFile path = do isFileStyle <- doesFileExist path if isFileStyle then return path else return (path </> "package.cache") Just etaProg = lookupProgram etaProgram progdb
null
https://raw.githubusercontent.com/typelead/etlas/bbd7c558169e1fda086e759e1a6f8c8ca2807583/etlas-cabal/Distribution/Simple/Eta.hs
haskell
# LANGUAGE RankNTypes # Internal.targetPlatform ghcInfo | Given a package DB stack, return all installed packages. getLibDir' :: Verbosity -> ConfiguredProgram -> IO FilePath getLibDir' verbosity etaProg = getProgramOutput verbosity etaProg ["--print-libdir"] TODO: do we need to put hs-boot files into place for mutually recursive modules? ghcOptShared = toFlag True, | Start a REPL without loading any source files. Handle java sources Generate command line file / jar exec launchers Generate launchers for the install phase For Windows Create the launcher jar with - ghci given , .o ^install location ^install location for dynamic libraries ^Build location ^Where to copy the files to ^Build location etaProfOptions bi = findEtaGhcVersion :: Verbosity -> FilePath -> IO (Maybe Version) findEtaPkgEtaVersion :: Verbosity -> FilePath -> IO (Maybe Version) ----------------------------------------------------------------------------- Registering TODO: When there are multiple component dependencies TODO: Extremely dirty (but safe) hack because etlas-cabal has no HTTP-aware modules. Basically, we want to be able to search the index for a given eta version when we can't find any. But we need HTTP ability for that. TODO: Extremely dirty (but safe) hack because etlas-cabal has no HTTP-aware modules. Basically, we want to be able to search the index for a given eta version when we can't find any. But we need HTTP ability for that. Note that for dir style dbs, we only need to monitor the cache file, not
# LANGUAGE FlexibleContexts # # LANGUAGE NamedFieldPuns # module Distribution.Simple.Eta ( configure, getInstalledPackages, getPackageDBContents, buildLib, buildExe, replLib, replExe, startInterpreter, installLib, installExe, libAbiHash, hcPkgInfo, registerPackage, componentGhcOptions, getLibDir, isDynamic, getGlobalPackageDB, mkMergedClassPath, mkMergedClassPathLbi, classPathSeparator, mkJarName, JavaExec(..), runJava, fetchMavenDependencies, findCoursierRef, findVerifyRef, findEtaServRef, getLibraryComponent, getDependencyClassPaths, InstallDirType(..), exeJarPath, libJarPath, getInstalledPackagesMonitorFiles ) where import Prelude () import Data.IORef import System.IO.Unsafe import Distribution.Compat.Prelude import Distribution.Simple.GHC.ImplInfo import qualified Distribution.Simple.GHC.Internal as Internal import Distribution.PackageDescription as PD import Distribution.InstalledPackageInfo hiding (frameworks, exposedModules) import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo import Distribution.Simple.PackageIndex ( InstalledPackageIndex ) import qualified Distribution.Simple.PackageIndex as PackageIndex import Distribution.Simple.LocalBuildInfo import Distribution.Simple.Utils import Distribution.Simple.Program import qualified Distribution.Simple.Program.HcPkg as HcPkg import Distribution.Simple.Program.GHC import Distribution.Simple.Setup hiding ( Flag ) import qualified Distribution.Simple.Setup as Cabal import Distribution.Simple.Compiler hiding ( Flag ) import Distribution.Version import Distribution.System import Distribution.Verbosity import Distribution.Utils.NubList import Distribution.Text import Distribution.Types.UnitId import Distribution.Types.UnqualComponentName import qualified Paths_etlas_cabal as Etlas (version) import qualified Data.Map as Map import Data.List import Data.Maybe import Control.Monad import System.Directory hiding (findFile) import System.FilePath configure :: Verbosity -> Maybe FilePath -> Maybe FilePath -> ProgramDb -> IO (Compiler, Maybe Platform, ProgramDb) configure verbosity hcPath hcPkgPath conf0 = do (etaProg, etaVersion, conf1) <- requireProgramVersion verbosity etaProgram anyVersion (userMaybeSpecifyPath "eta" hcPath conf0) let implInfo = etaVersionImplInfo etaVersion etaGhcVersion (etaPkgProg, etaPkgVersion, conf2) <- requireProgramVersion verbosity etaPkgProgram anyVersion (userMaybeSpecifyPath "eta-pkg" hcPkgPath conf1) when (etaVersion /= etaPkgVersion) $ die' verbosity $ "Version mismatch between eta and eta-pkg: " ++ programPath etaProg ++ " is version " ++ display etaVersion ++ " " ++ programPath etaPkgProg ++ " is version " ++ display etaPkgVersion let conf3 = conf2 languages <- Internal.getLanguages verbosity implInfo etaProg extensions <- Internal.getExtensions verbosity implInfo etaProg etaInfo <- Internal.getGhcInfo verbosity implInfo etaProg let comp = Compiler { compilerId = CompilerId Eta etaVersion, TODO : Make this unique for ETA ? compilerAbiTag = AbiTag $ "ghc" ++ intercalate "_" (map show . versionNumbers $ etaGhcVersion), compilerCompat = [CompilerId GHC etaGhcVersion], compilerLanguages = languages, compilerExtensions = extensions, compilerProperties = Map.fromList etaInfo } (_, conf4) <- requireProgram verbosity javaProgram conf3 (_, conf5) <- requireProgram verbosity javacProgram conf4 return (comp, compPlatform, conf5) | Given a single package DB , return all installed packages . getPackageDBContents :: Verbosity -> PackageDB -> ProgramDb -> IO InstalledPackageIndex getPackageDBContents verbosity packagedb progdb = do pkgss <- getInstalledPackages' verbosity [packagedb] progdb toPackageIndex verbosity pkgss progdb getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramDb -> IO InstalledPackageIndex getInstalledPackages verbosity packagedbs progdb = do checkPackageDbEnvVar verbosity checkPackageDbStack verbosity packagedbs pkgss <- getInstalledPackages' verbosity packagedbs progdb index <- toPackageIndex verbosity pkgss progdb return $! index toPackageIndex :: Verbosity -> [(PackageDB, [InstalledPackageInfo])] -> ProgramDb -> IO InstalledPackageIndex toPackageIndex _ pkgss _ = do let indices = [ PackageIndex.fromList pkgs | (_, pkgs) <- pkgss ] return $! (mconcat indices) checkPackageDbEnvVar :: Verbosity -> IO () checkPackageDbEnvVar verbosity = Internal.checkPackageDbEnvVar verbosity "ETA" "ETA_PACKAGE_PATH" checkPackageDbStack :: Verbosity -> PackageDBStack -> IO () checkPackageDbStack _ (GlobalPackageDB:rest) | GlobalPackageDB `notElem` rest = return () checkPackageDbStack verbosity rest | GlobalPackageDB `notElem` rest = die' verbosity $ "With current ghc versions the global package db is always used " ++ "and must be listed first. This ghc limitation may be lifted in " ++ "future, see " checkPackageDbStack verbosity _ = die' verbosity $ "If the global package db is specified, it must be " ++ "specified first and cannot be specified multiple times" getInstalledPackages' :: Verbosity -> [PackageDB] -> ProgramDb -> IO [(PackageDB, [InstalledPackageInfo])] getInstalledPackages' verbosity packagedbs progdb = sequence [ do createDir packagedb pkgs <- HcPkg.dump (hcPkgInfo progdb) verbosity packagedb return (packagedb, pkgs) | packagedb <- packagedbs ] where createDir (SpecificPackageDB path) = createDirectoryIfMissing True path createDir _ = return () trimEnd :: String -> String trimEnd = reverse . dropWhile isSpace . reverse getLibDir :: Verbosity -> ProgramDb -> IO FilePath getLibDir verbosity progDb = trimEnd `fmap` getDbProgramOutput verbosity etaProgram progDb ["--print-libdir"] ( reverse . . reverse ) ` fmap ` | Return the ' FilePath ' to the global GHC package database . getGlobalPackageDB :: Verbosity -> ConfiguredProgram -> IO FilePath getGlobalPackageDB verbosity etaProg | Just version <- programVersion etaProg , version >= mkVersion [0,7,1] = trimEnd `fmap` getProgramOutput verbosity etaProg ["--print-global-package-db"] | otherwise = ((</> "package.conf.d") . trimEnd) `fmap` getProgramOutput verbosity etaProg ["--print-libdir"] buildLib, replLib :: Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO () buildLib = buildOrReplLib False replLib = buildOrReplLib True libJarPath :: LocalBuildInfo -> ComponentLocalBuildInfo -> FilePath libJarPath lbi clbi = buildDir lbi </> mkJarName (componentUnitId clbi) buildOrReplLib :: Bool -> Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO () buildOrReplLib forRepl verbosity numJobs pkgDescr lbi lib clbi = do let uid = componentUnitId clbi libTargetDir = buildDir lbi isVanillaLib = not forRepl && withVanillaLib lbi isSharedLib = not forRepl && withSharedLib lbi ifReplLib = when forRepl comp = compiler lbi (etaProg, _) <- requireProgram verbosity etaProgram (withPrograms lbi) mEtaServPath <- findEtaServ verbosity (programVersion etaProg) let runEtaProg = runGHC verbosity etaProg comp (hostPlatform lbi) libBi = libBuildInfo lib doWithResolvedDependencyClassPathsOrDie verbosity pkgDescr lbi clbi libBi RelativeInstallDir $ \ (depJars,mavenPaths) -> do let fullClassPath = depJars ++ mavenPaths createDirectoryIfMissingVerbose verbosity True libTargetDir let javaSrcs = javaSources libBi baseOpts = componentGhcOptions verbosity lbi libBi clbi libTargetDir `mappend` mempty { ghcOptExtra = toNubListR $ maybe [] (\etaServPath -> ["-pgmi", etaServPath]) mEtaServPath } linkJavaLibOpts = mempty { ghcOptInputFiles = toNubListR javaSrcs, ghcOptExtra = toNubListR $ ["-cp", mkMergedClassPathLbi lbi fullClassPath] } vanillaOptsNoJavaLib = baseOpts `mappend` mempty { ghcOptMode = toFlag GhcModeMake, ghcOptNumJobs = numJobs, ghcOptInputModules = toNubListR $ allLibModules lib clbi, ghcOptOutputFile = toFlag target } vanillaOpts' = vanillaOptsNoJavaLib `mappend` linkJavaLibOpts sharedOpts = vanillaOpts' `mappend` mempty { Libs should never have the -shared flag ghcOptExtraDefault = toNubListR ["-staticlib"], ghcOptExtra = toNubListR $ etaSharedOptions libBi } vanillaOpts = vanillaOpts' { ghcOptExtraDefault = toNubListR ["-staticlib"] } replOpts = vanillaOpts' { ghcOptExtra = (overNubListR Internal.filterGhciFlags $ ghcOptExtra vanillaOpts') `mappend` toNubListR ["-inmemory"], ghcOptNumJobs = mempty, ghcOptMode = toFlag GhcModeInteractive, ghcOptOptimisation = toFlag GhcNoOptimisation } target = libTargetDir </> mkJarName uid unless (forRepl || (null (allLibModules lib clbi) && null javaSrcs)) $ do let withVerify act = do _ <- act when (fromFlagOrDefault False (configVerifyMode $ configFlags lbi)) $ runVerify verbosity fullClassPath target lbi if isVanillaLib then withVerify $ runEtaProg vanillaOpts else if isSharedLib then withVerify $ runEtaProg sharedOpts else return () ifReplLib (runEtaProg replOpts) startInterpreter :: Verbosity -> ProgramDb -> Compiler -> Platform -> PackageDBStack -> IO () startInterpreter verbosity progdb comp platform packageDBs = do let replOpts = mempty { ghcOptMode = toFlag GhcModeInteractive, ghcOptPackageDBs = packageDBs } checkPackageDbStack verbosity packageDBs (etaProg, _) <- requireProgram verbosity etaProgram progdb runGHC verbosity etaProg comp platform replOpts buildExe, replExe :: Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo -> IO () buildExe = buildOrReplExe False replExe = buildOrReplExe True exeJarPath :: LocalBuildInfo -> UnqualComponentName -> FilePath exeJarPath lbi ucn = buildDir lbi </> exeName' </> realExeName exeName' where exeName' = display ucn realExeName :: String -> FilePath realExeName exeName' | takeExtension exeName' /= ('.':jarExtension) = exeName' <.> jarExtension | otherwise = exeName' buildOrReplExe :: Bool -> Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo -> IO () buildOrReplExe forRepl verbosity numJobs pkgDescr lbi exe@Executable { exeName, modulePath = modPath } clbi = do let exeName' = display exeName exeNameReal = realExeName exeName' targetDir = buildDir lbi </> exeName' exeTmpDir = exeName' ++ "-tmp" exeDir = targetDir </> exeTmpDir exeJar = targetDir </> exeNameReal withDeps = doWithResolvedDependencyClassPathsOrDie verbosity pkgDescr lbi clbi exeBi (etaProg, _) <- requireProgram verbosity etaProgram (withPrograms lbi) mEtaServPath <- findEtaServ verbosity (programVersion etaProg) createDirectoryIfMissingVerbose verbosity True exeDir srcMainFile <- findFile (hsSourceDirs exeBi) modPath withDeps RelativeInstallDir $ \ (depJars,mavenPaths) -> do let fullClassPath = depJars ++ mavenPaths classPaths | isShared = fullClassPath | otherwise = [] javaSrcs | isShared = javaSrcs' | otherwise = mavenPaths ++ javaSrcs' runEtaProg = runGHC verbosity etaProg comp (hostPlatform lbi) baseOpts = (componentGhcOptions verbosity lbi exeBi clbi exeDir) `mappend` mempty { ghcOptInputFiles = toNubListR $ srcMainFile : javaSrcs, ghcOptInputModules = toNubListR $ exeModules exe, ghcOptNumJobs = numJobs, ghcOptExtra = toNubListR $ ["-cp", mkMergedClassPathLbi lbi fullClassPath] ++ maybe [] (\etaServPath -> ["-pgmi", etaServPath]) mEtaServPath } exeOpts = baseOpts `mappend` mempty { ghcOptMode = toFlag GhcModeMake, ghcOptOutputFile = toFlag exeJar, ghcOptShared = toFlag isShared } replOpts = baseOpts `mappend` mempty { ghcOptMode = toFlag GhcModeInteractive, ghcOptOptimisation = toFlag GhcNoOptimisation } withVerify act = do _ <- act when (fromFlagOrDefault False (configVerifyMode $ configFlags lbi)) $ runVerify verbosity (exeJar : classPaths) exeJar lbi if forRepl then runEtaProg replOpts else do withVerify $ runEtaProg exeOpts generateExeLaunchers verbosity lbi exeName' classPaths targetDir unless forRepl $ withDeps AbsoluteGlobalInstallDir $ \ (depJars, mavenPaths) -> do let installLaunchersDir = targetDir </> "install-launchers" classPaths | isShared = depJars ++ mavenPaths | otherwise = [] createDirectoryIfMissingVerbose verbosity True installLaunchersDir generateExeLaunchers verbosity lbi exeName' classPaths installLaunchersDir where comp = compiler lbi exeBi = buildInfo exe isShared = withDynExe lbi javaSrcs' = javaSources exeBi dirEnvVarAndRef :: Bool -> (String,String) dirEnvVarAndRef isWindows' = (var,ref) where var = "DIR" ref | isWindows' = "%" ++ var ++ "%" | otherwise = "$" ++ var generateExeLaunchers :: Verbosity -> LocalBuildInfo -> String -> [String] -> FilePath -> IO () generateExeLaunchers verbosity lbi exeName classPaths targetDir = do generateExeLauncherScript verbosity lbi exeName classPaths targetDir Windows faces the dreaded line - length limit which forces us to create a launcher jar as a workaround . launcher jar as a workaround. -} when (isWindows lbi) $ generateExeLauncherJar verbosity lbi exeName classPaths targetDir generateExeLauncherScript :: Verbosity -> LocalBuildInfo -> String -> [String] -> FilePath -> IO () generateExeLauncherScript _verbosity lbi exeName classPaths targetDir = do let isWindows' = isWindows lbi classPathSep = head (classPathSeparator (hostPlatform lbi)) scriptClassPaths | null classPaths = "" | otherwise = mkMergedClassPathLbi lbi classPaths exeScript = exeLauncherScript classPathSep exeName scriptClassPaths isWindows' scriptFile | isWindows' = prefix ++ ".cmd" | otherwise = prefix where prefix = targetDir </> exeName writeUTF8File scriptFile exeScript p <- getPermissions scriptFile setPermissions scriptFile (p { executable = True }) exeLauncherScript :: Char -> String -> String -> Bool -> String exeLauncherScript classPathSep exeName classPaths isWindows' | isWindows' = unlines [ "@echo off" , "set " ++ dirEnvVar ++ "=%~dp0" , "if defined ETA_JAVA_CMD goto execute" , "if defined JAVA_HOME goto findJavaFromJavaHome" , "set ETA_JAVA_CMD=java.exe" , "goto execute" , ":findJavaFromJavaHome" , "set ETA_JAVA_HOME=%JAVA_HOME:\"=%" , "set ETA_JAVA_CMD=%ETA_JAVA_HOME%\\bin\\java.exe" , ":execute" , "\"%ETA_JAVA_CMD%\" -Deta.programName=" ++ exeName ++ " %JAVA_ARGS% %JAVA_OPTS% %ETA_JAVA_ARGS% " ++ "-classpath " ++ winClassPath ++ " eta.main %*" ] | otherwise = unlines [ "#!/usr/bin/env bash" , "SCRIPT=\"${BASH_SOURCE[0]}\"" , "getScriptDir() {" , " if [[ $(uname -s) == Darwin ]]" , " then" , " local OLD_DIR=`pwd`" , " SCRIPT_BASE=\"$SCRIPT\"" , " cd `dirname $SCRIPT_BASE`" , " SCRIPT_BASE=`basename $SCRIPT_BASE`" , " while [ -L \"$SCRIPT_BASE\" ]" , " do" , " SCRIPT_BASE=`readlink $SCRIPT_BASE`" , " cd `dirname $SCRIPT_BASE`" , " SCRIPT_BASE=`basename $SCRIPT_BASE`" , " done" , " local SCRIPT_DIR=`pwd -P`" , " SCRIPT=\"$SCRIPT_DIR/$SCRIPT_BASE\"" , " cd \"$OLD_DIR\"" , " else" , " SCRIPT=\"$(readlink -f \"$SCRIPT\")\"" , " fi" , " " ++ dirEnvVar ++ "=\"$(cd \"$(dirname \"$SCRIPT\")\" && pwd)\"" , "}" , "getScriptDir" , "if [ -z \"$ETA_JAVA_CMD\" ]; then" , " if [ -n \"$JAVA_HOME\" ] ; then" , " if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then" , " ETA_JAVA_CMD=\"$JAVA_HOME/jre/sh/java\"" , " else" , " ETA_JAVA_CMD=\"$JAVA_HOME/bin/java\"" , " fi" , " else" , " ETA_JAVA_CMD=\"java\"" , " fi" , "fi" , "$ETA_JAVA_CMD -Deta.programName=" ++ exeName ++ " $JAVA_ARGS $JAVA_OPTS $ETA_JAVA_ARGS " ++ "-classpath \"" ++ totalClassPath ++ "\" eta.main \"$@\"" ] where (dirEnvVar, dirEnvVarRef) = dirEnvVarAndRef isWindows' exeJarEnv = dirEnvVarRef </> realExeName exeName totalClassPath = exeJarEnv ++ [classPathSep] ++ classPaths ++ [classPathSep] ++ "$ETA_CLASSPATH" launcherJarEnv = dirEnvVarRef </> (exeName ++ ".launcher.jar") winClassPath = "\"" ++ launcherJarEnv ++ "\"" ++ [classPathSep] ++ "%ETA_CLASSPATH%" generateExeLauncherJar :: Verbosity -> LocalBuildInfo -> String -> [String] -> FilePath -> IO () generateExeLauncherJar verbosity lbi exeName classPaths targetDir = do jarProg <- fmap fst $ requireProgram verbosity jarProgram (withPrograms lbi) writeFile targetManifest $ unlines $ ["Manifest-Version: 1.0" ,"Created-By: etlas-" ++ display Etlas.version ,"Main-Class: eta.main" ,"Class-Path: " ++ realExeName exeName] ++ map ((++) " ") classPaths' runProgramInvocation verbosity $ programInvocation jarProg ["cfm", launcherJar, targetManifest] where addStartingPathSep path | hasDrive path = pathSeparator : path | otherwise = path (_, dirEnvVarRef) = dirEnvVarAndRef $ isWindows lbi replaceEnvVar = replacePrefix dirEnvVarRef "." uriEncodeSpaces = foldl' (\acc c -> acc ++ if c == ' ' then "%20" else [c]) "" classPaths' = map (uriEncodeSpaces . addStartingPathSep . replaceEnvVar) classPaths targetManifest = targetDir </> "MANIFEST.MF" launcherJar = targetDir </> (exeName ++ ".launcher.jar") isWindows :: LocalBuildInfo -> Bool isWindows lbi | Platform _ Windows <- hostPlatform lbi = True | otherwise = False replacePrefix :: Eq a => [a] -> [a] -> [a] -> [a] replacePrefix old new s | isPrefixOf old s = new ++ drop (length old) s | otherwise = s installLib :: Verbosity -> LocalBuildInfo -> PackageDescription -> Library -> ComponentLocalBuildInfo -> IO () installLib verbosity lbi targetDir _dynlibTargetDir builtDir _pkg lib clbi = do copyModuleFiles "hi" when hasLib $ do mapM_ (installOrdinaryIfExists builtDir targetDir) jarLibNames where installOrdinaryIfExists srcDir dstDir name = do exists <- doesFileExist $ srcDir </> name when exists $ installOrdinary srcDir dstDir name installOrdinary srcDir dstDir name = do createDirectoryIfMissingVerbose verbosity True dstDir installOrdinaryFile verbosity src dst where src = srcDir </> name dst = dstDir </> (fromMaybe name $ stripPrefix "HS" name) The stripPrefix " HS " bit is for backwards compat copyModuleFiles ext = findModuleFiles [builtDir] [ext] (allLibModules lib clbi) >>= installOrdinaryFiles verbosity targetDir _cid = compilerId (compiler lbi) libUids = [componentUnitId clbi] jarLibNames = map mkJarName libUids ++ map (("HS" ++) . mkJarName) libUids hasLib = not $ null (allLibModules lib clbi) && null (javaSources (libBuildInfo lib)) mkJarName :: UnitId -> String mkJarName uid = getHSLibraryName uid <.> "jar" installExe :: Verbosity -> LocalBuildInfo ( prefix , suffix ) -> PackageDescription -> Executable -> IO () installExe verbosity lbi installDirs buildPref (_progprefix, _progsuffix) _pkg exe = do let _exeBi = buildInfo exe binDir = bindir installDirs toDir x = binDir </> x exeName' = display (exeName exe) buildDir = buildPref </> exeName' installLaunchersDir = buildDir </> "install-launchers" exeNameExt ext = if null ext then exeName' else exeName' <.> ext launchExt = if isWindows lbi then "cmd" else "" copy fromDir x = copyFile (fromDir </> x) (toDir x) createDirectoryIfMissingVerbose verbosity True binDir copy buildDir (exeNameExt "jar") copy installLaunchersDir (exeNameExt launchExt) when (isWindows lbi) $ copy installLaunchersDir (exeNameExt "launcher.jar") libAbiHash :: Verbosity -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO String libAbiHash verbosity _pkg_descr lbi lib clbi = do let libBi = libBuildInfo lib comp = compiler lbi platform = hostPlatform lbi vanillaArgs = (componentGhcOptions verbosity lbi libBi clbi (componentBuildDir lbi clbi)) `mappend` mempty { ghcOptMode = toFlag GhcModeAbiHash, ghcOptInputModules = toNubListR $ exposedModules lib } etaArgs = vanillaArgs (etaProg, _) <- requireProgram verbosity etaProgram (withPrograms lbi) getProgramInvocationOutput verbosity (ghcInvocation etaProg comp platform etaArgs) registerPackage :: Verbosity -> ProgramDb -> PackageDBStack -> InstalledPackageInfo -> HcPkg.RegisterOptions -> IO () registerPackage verbosity progdb packageDbs installedPkgInfo registerOptions = HcPkg.register (hcPkgInfo progdb) verbosity packageDbs installedPkgInfo registerOptions componentGhcOptions :: Verbosity -> LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo -> FilePath -> GhcOptions componentGhcOptions verbosity lbi bi clbi odir = let opts = Internal.componentGhcOptions verbosity implInfo lbi bi clbi odir comp = compiler lbi implInfo = getImplInfo comp in opts { ghcOptExtra = ghcOptExtra opts `mappend` toNubListR (["-pgmjavac", javacPath] ++ (hcOptions Eta bi)) } where Just javacProg = lookupProgram javacProgram (withPrograms lbi) javacPath = locationPath (programLocation javacProg) etaProfOptions : : - > [ String ] hcProfOptions GHC bi ` mappend ` hcProfOptions ETA bi etaSharedOptions :: BuildInfo -> [String] etaSharedOptions bi = hcSharedOptions GHC bi `mappend` hcSharedOptions Eta bi isDynamic :: Compiler -> Bool isDynamic = const True findEtaGhcVersion verbosity pgm = findProgramVersion " --numeric - ghc - version " i d verbosity pgm findEtaPkgEtaVersion verbosity pgm = findProgramVersion " --numeric - eta - version " i d verbosity pgm hcPkgInfo :: ProgramDb -> HcPkg.HcPkgInfo hcPkgInfo progdb = HcPkg.HcPkgInfo { HcPkg.hcPkgProgram = etaPkgProg , HcPkg.noPkgDbStack = False , HcPkg.noVerboseFlag = False , HcPkg.flagPackageConf = False , HcPkg.supportsDirDbs = True , HcPkg.requiresDirDbs = True , HcPkg.nativeMultiInstance = True , HcPkg.recacheMultiInstance = True , HcPkg.suppressFilesCheck = True } where Just etaPkgProg = lookupProgram etaPkgProgram progdb NOTE : ETA is frozen after 7.10.3 etaGhcVersion :: Version etaGhcVersion = mkVersion [7,10,3] jarExtension :: String jarExtension = "jar" doWithResolvedDependencyClassPathsOrDie :: Verbosity -> PackageDescription -> LocalBuildInfo -> ComponentLocalBuildInfo -> BuildInfo -> InstallDirType -> (([FilePath], [FilePath]) -> IO ()) -> IO () doWithResolvedDependencyClassPathsOrDie verbosity pkgDescr lbi clbi bi libDirType action = do mDeps <- getDependencyClassPaths (installedPkgs lbi) pkgDescr lbi clbi bi libDirType case mDeps of Just (depJars, mavenDeps) -> do let mavenRepos = frameworks bi mavenPaths <- fetchMavenDependencies verbosity mavenRepos mavenDeps (withPrograms lbi) action (depJars,mavenPaths) Nothing -> die' verbosity "Missing dependencies. Try `etlas install --dependencies-only`?" data InstallDirType = RelativeInstallDir | AbsoluteLocalInstallDir | AbsoluteGlobalInstallDir getDependencyClassPaths :: InstalledPackageIndex -> PackageDescription -> LocalBuildInfo -> ComponentLocalBuildInfo -> BuildInfo -> InstallDirType -> IO (Maybe ([FilePath], [String])) getDependencyClassPaths packageIndex pkgDescr lbi clbi bi libDirType | Left closurePackageIndex <- closurePackageIndex' = do let packageInfos = PackageIndex.allPackages closurePackageIndex packageMavenDeps = concatMap InstalledPackageInfo.extraLibraries packageInfos packagesPaths <- fmap concat $ mapM hsLibraryPaths packageInfos return $ Just (libPath ++ packagesPaths, mavenDeps ++ libMavenDeps ++ packageMavenDeps) | otherwise = return Nothing where hsLibraryPaths pinfo = mapM (findFile (libraryDirs pinfo)) (map (<.> "jar") $ hsLibraries pinfo) closurePackageIndex' = PackageIndex.dependencyClosure packageIndex packages where packages = libDeps ++ packages'' mavenDeps = extraLibs bi libPath | null libs = [] | otherwise = case libDirType of RelativeInstallDir -> [dirEnvVarRef ++ "/../" ++ libJarName] AbsoluteLocalInstallDir -> [buildDir lbi </> libJarName] AbsoluteGlobalInstallDir -> [globalLibDir </> libJarName] where (_,dirEnvVarRef) = dirEnvVarAndRef $ isWindows lbi libUid = fromJust mbLibUid libJarName = mkJarName libUid globalLibDir = libdir $ absoluteComponentInstallDirs pkgDescr lbi libUid NoCopyDest libMavenDeps | null libs = [] | otherwise = extraLibs . libBuildInfo . fromJust $ library pkgDescr (mbLibUid, libDeps) | null libs = (Nothing, []) | otherwise = (Just $ componentUnitId clbi' , map fst $ componentPackageDeps clbi') where clbi' = fromJust libComponent (libs, packages'') = maybe ([], packages') (\lc -> partition (== lc) packages') $ fmap componentUnitId libComponent where packages' = map fst $ componentPackageDeps clbi libComponent = getLibraryComponent lbi getLibraryComponent :: LocalBuildInfo -> Maybe ComponentLocalBuildInfo getLibraryComponent lbi = fmap head clbis where clbis = Map.lookup CLibName $ componentNameMap lbi ( Backpack - support ) this might break . -RM builtInMavenResolvers :: [(String, String)] builtInMavenResolvers = [ ("central", "/") , ("javaNet1", "/") , ("sonatype:public", "") , ("sonatype:snapshots", "") , ("sonatype:releases", "") , ("jcenter", "/") ] resolveOrId :: String -> String resolveOrId repo | Just resolved <- lookup repo builtInMavenResolvers = resolved | "bintray" `isPrefixOf` repo = let (_, rest) = break (== ':') repo (owner, repos') = break (== ':') $ drop 1 rest repos = drop 1 repos' in "/" ++ owner ++ "/" ++ repos ++ "/" | otherwise = repo classPathSeparator :: Platform -> String classPathSeparator (Platform _ Windows) = ";" classPathSeparator _ = ":" mkMergedClassPath :: Platform -> [FilePath] -> FilePath mkMergedClassPath platform = intercalate (classPathSeparator platform) mkMergedClassPathLbi :: LocalBuildInfo -> [FilePath] -> FilePath mkMergedClassPathLbi lbi = mkMergedClassPath (hostPlatform lbi) data JavaExec = Jar FilePath | JavaClass String runJava :: Verbosity -> [String] -> JavaExec -> [String] -> ProgramDb -> IO String runJava verb javaArgs javaExec javaExecArgs progDb = do (javaProg,_) <- requireProgram verb javaProgram progDb let (exJavaArgs,javaExec') = case javaExec of Jar path -> (["-jar"],path) JavaClass name -> ([],name) javaInv = programInvocation javaProg $ javaArgs ++ exJavaArgs javaInv' = withSystemProxySetting javaInv javaExecInv = simpleProgramInvocation javaExec' javaExecArgs getProgramInvocationOutput verb $ nestedProgramInvocation javaInv' javaExecInv withSystemProxySetting :: ProgramInvocation -> ProgramInvocation withSystemProxySetting javaInvoc@ProgramInvocation { progInvokeArgs = args } = javaInvoc {progInvokeArgs = args ++ proxySetting} where hasProxySetting = any (isSubsequenceOf "proxyHost") args proxySetting = if not hasProxySetting then ["-Djava.net.useSystemProxies=true"] else [] findCoursierRef :: IORef (Verbosity -> NoCallStackIO ()) findCoursierRef = unsafePerformIO $ newIORef $ \verbosity -> do info verbosity $ "The Coursier Ref has not been initialized!" return () runCoursier :: Verbosity -> [String] -> ProgramDb -> IO String runCoursier verbosity opts progDb = do etlasToolsDir <- defaultEtlasToolsDir let path = etlasToolsDir </> "coursier" exists <- doesFileExist path when (not exists) $ do findCoursier <- readIORef findCoursierRef findCoursier verbosity runJava verbosity ["-noverify"] (Jar path) opts progDb findEtaServRef :: IORef (Verbosity -> ProgramSearchPath -> NoCallStackIO (Maybe (FilePath, [FilePath]))) findEtaServRef = unsafePerformIO $ newIORef $ \verbosity _ -> do info verbosity $ "The Eta Serv Ref has not been initialized!" return Nothing findEtaServ :: Verbosity -> Maybe Version -> IO (Maybe FilePath) findEtaServ verbosity mVersion | Just version <- mVersion , version >= mkVersion [0,8] = do findEtaServ' <- readIORef findEtaServRef mResult <- findEtaServ' verbosity [] return $ fmap fst mResult | otherwise = return Nothing findVerifyRef :: IORef (Verbosity -> NoCallStackIO ()) findVerifyRef = unsafePerformIO $ newIORef $ \verbosity -> do info verbosity $ "The Verify Ref has not been initialized!" return () runVerify :: Verbosity -> [String] -> String -> LocalBuildInfo -> IO () runVerify verbosity classPath target lbi = do etlasToolsDir <- defaultEtlasToolsDir let path = etlasToolsDir </> "classes" verifyClass = path </> "Verify.class" exists <- doesFileExist verifyClass when (not exists) $ do findVerify <- readIORef findVerifyRef findVerify verbosity _ <- runJava verbosity ["-cp", mkMergedClassPathLbi lbi (path:classPath)] (JavaClass "Verify") [target] (withPrograms lbi) return () fetchMavenDependencies :: Verbosity -> [String] -> [String] -> ProgramDb -> IO [String] fetchMavenDependencies _ _ [] _ = return [] fetchMavenDependencies verb repos deps progDb = do let resolvedRepos = concatMap (\r -> ["-r", resolveOrId r]) repos fmap lines $ runCoursier verb (["fetch", "-a", "jar","--quiet"] ++ deps ++ resolvedRepos) progDb getInstalledPackagesMonitorFiles :: Verbosity -> Platform -> ProgramDb -> [PackageDB] -> IO [FilePath] getInstalledPackagesMonitorFiles verbosity _platform progdb = traverse getPackageDBPath where getPackageDBPath :: PackageDB -> IO FilePath getPackageDBPath GlobalPackageDB = selectMonitorFile =<< getGlobalPackageDB verbosity etaProg For Eta , both Global and User are one and the same . getPackageDBPath UserPackageDB = selectMonitorFile =<< getGlobalPackageDB verbosity etaProg getPackageDBPath (SpecificPackageDB path) = selectMonitorFile path GHC has old style file dbs , and new style directory dbs . the whole directory . The ghc program itself only reads the cache file so it 's safe to only monitor this one file . selectMonitorFile path = do isFileStyle <- doesFileExist path if isFileStyle then return path else return (path </> "package.cache") Just etaProg = lookupProgram etaProgram progdb
5b425787d0eb1d0cfaf4b7b1bdd9023505da06692bc2867ef29b9625bcc02eae
bytekid/mkbtt
isFlat.ml
Copyright 2008 , Christian Sternagel , * GNU Lesser General Public License * * This file is part of TTT2 . * * TTT2 is free software : you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version . * * TTT2 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 Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with TTT2 . If not , see < / > . * GNU Lesser General Public License * * This file is part of TTT2. * * TTT2 is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * TTT2 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with TTT2. If not, see </>. *) (*** OPENS ********************************************************************) open Util;; (*** MODULES ******************************************************************) module F = Format;; (*** TYPES ********************************************************************) type flags = {help : bool ref; strict : bool ref; weak : bool ref};; (*** GLOBALS ******************************************************************) let code = "flat";; let name = "Flat Predicate";; let comment = "Checks if all systems of the given problem are flat.";; let keywords = ["is flat";"predicate"];; let flags = {help = ref false; strict = ref false; weak = ref false};; let spec = let spec = [ ("--help",Arg.Set flags.help,"Prints information about flags."); ("-help",Arg.Set flags.help,"Prints information about flags."); ("-h",Arg.Set flags.help,"Prints information about flags."); ("-s",Arg.Set flags.help, "Checks if the rules which should be oriented strictly form a flat TRS."); ("-w",Arg.Set flags.help, "Checks if the rules which should be oriented weakly form a flat TRS.")] in Arg.alignx 80 spec ;; let help = (comment,keywords,List.map Triple.drop_snd spec);; (*** FUNCTIONS ****************************************************************) let init _ = flags.help := false; flags.strict := false; flags.weak := false;; let solve fs = let configurate s = F.printf "%s@\n%!" s; flags.help := true in (try init (); Arg.parsex code spec fs with Arg.Bad s -> configurate s); if !(flags.help) then (Arg.usage spec ("Options for "^code^":"); exit 0); if !(flags.strict) then Trs.is_flat <.> fst <.> Problem.get_sw else if !(flags.weak) then Trs.is_flat <.> snd <.> Problem.get_sw else Problem.for_all Trs.is_flat ;;
null
https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/processors/src/predicate/isFlat.ml
ocaml
** OPENS ******************************************************************* ** MODULES ***************************************************************** ** TYPES ******************************************************************* ** GLOBALS ***************************************************************** ** FUNCTIONS ***************************************************************
Copyright 2008 , Christian Sternagel , * GNU Lesser General Public License * * This file is part of TTT2 . * * TTT2 is free software : you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version . * * TTT2 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 Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with TTT2 . If not , see < / > . * GNU Lesser General Public License * * This file is part of TTT2. * * TTT2 is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * TTT2 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with TTT2. If not, see </>. *) open Util;; module F = Format;; type flags = {help : bool ref; strict : bool ref; weak : bool ref};; let code = "flat";; let name = "Flat Predicate";; let comment = "Checks if all systems of the given problem are flat.";; let keywords = ["is flat";"predicate"];; let flags = {help = ref false; strict = ref false; weak = ref false};; let spec = let spec = [ ("--help",Arg.Set flags.help,"Prints information about flags."); ("-help",Arg.Set flags.help,"Prints information about flags."); ("-h",Arg.Set flags.help,"Prints information about flags."); ("-s",Arg.Set flags.help, "Checks if the rules which should be oriented strictly form a flat TRS."); ("-w",Arg.Set flags.help, "Checks if the rules which should be oriented weakly form a flat TRS.")] in Arg.alignx 80 spec ;; let help = (comment,keywords,List.map Triple.drop_snd spec);; let init _ = flags.help := false; flags.strict := false; flags.weak := false;; let solve fs = let configurate s = F.printf "%s@\n%!" s; flags.help := true in (try init (); Arg.parsex code spec fs with Arg.Bad s -> configurate s); if !(flags.help) then (Arg.usage spec ("Options for "^code^":"); exit 0); if !(flags.strict) then Trs.is_flat <.> fst <.> Problem.get_sw else if !(flags.weak) then Trs.is_flat <.> snd <.> Problem.get_sw else Problem.for_all Trs.is_flat ;;
7d3c96b3b18b4b09c7eb816d58c753ebc867a78d1e99bc6ebe6276846904f009
3b/3b-glim
state.lisp
(in-package #:3b-glim) (defconstant +position+ 0) only supporting 1 textures for now (defconstant +tangent-width+ 2) (defconstant +normal+ 3) (defconstant +color+ 4) (defconstant +flags+ 5) (defconstant +secondary-color+ 6) (defvar *format* (3b-glim/s:compile-vertex-format `(1 (,+position+ :vec4) (,+texture0+ :vec4) (,+tangent-width+ :vec4) (,+normal+ :vec3) (,+color+ :u8vec4) ;; stores extra data for generating line vertices ;; 0 = primitive type: see +trangle-flag+ etc above 1 = edge flag where applicable 2 = corner index for vertex - shader points / lines (,+flags+ (:u8vec4 nil)) (,+secondary-color+ :u8vec3) ))) ;; color ;; indices into prim-flags[] (defconstant +prim-mode-flag+ 0) (defconstant +edge-flag-flag+ 1) (defconstant +corner-index-flag+ 2) ;; values for flags[+prim-mode-flag+] (defconstant +triangle-flag+ 0) (defconstant +point-flag+ 1) (defconstant +line-flag+ 2) (defconstant +quad-flag+ 3) ( defconstant + line - cap - flag+ 3 ) ;; values for tex-mode* uniforms (defconstant +tex-mode-off+ 0) (defconstant +tex-mode-1d+ 1) (defconstant +tex-mode-2d+ 2) (defconstant +tex-mode-3d+ 3) ;; indices for draw-flags uniform (defconstant +draw-flag-mode+ 0) (defconstant +draw-flag-mode-back+ 1) (defconstant +draw-flag-lighting+ 2) ;; values for +draw-flag-mode+ (defconstant +draw-mode-normal+ 0) (defconstant +draw-mode-smooth+ 1) (defconstant +draw-mode-wireframe+ 2) ;; tris/quads only (defconstant +draw-mode-filled-wireframe+ 3) ;; tris/quads only ;; lighting stuff (defconstant +max-lights+ 4) (defun make-flags () (alexandria:plist-hash-table '(:line-smooth nil :point-smooth nil :wireframe nil :filled-wireframe nil :texture-1d nil :texture-2d nil :texture-3d nil :light0 nil :light1 nil :light2 nil :light3 nil :lighting nil))) (defstruct (light (:type vector)) (position (v4 0 0 1 0)) (ambient (v4 0 0 0 1)) (diffuse (v4 0 0 0 1)) (specular (v4 0 0 0 1)) (spot-dir (v3 0 0 -1)) (spot-params (v3 0 180 0)) (attenuation (v3 1 0 0))) (defconstant +state-changed-line-width+ 0) (defconstant +state-changed-point-size+ 1) (defconstant +state-changed-draw-flags+ 2) (defconstant +state-changed-tex+ 3) (defconstant +state-changed-lighting+ 4) (defclass renderer-config () ()) (defclass glim-state (3b-glim/s::writer-state) (;; parameters of current begin/end (primitive :reader primitive :initform nil :writer (setf %primitive)) (flags :reader flags :initform (make-flags)) (prim-flags :reader prim-flags :initform (make-array 4 :element-type 'octet :initial-element 0)) (use-tess :reader use-tess :initform nil :writer (setf %use-tess)) (renderer-config :reader renderer-config :initform nil :accessor %renderer-config) ;; extra space to remember previous vertices, used to convert ;; strip/loop/quad primitives into separate tris (primitive-temp :reader primitive-temp :initarg :primitive-temp) ;; for line/strip/fan primitives, we need to track which part of a ;; primitive we are drawing, 0 is start of batch, other values ;; depends on type (primitive-state :accessor primitive-state :initform 0) ;; store position of previous points in line so we can calculate tangent (line-temp :accessor line-temp :initform nil) fixme : match GL defaults (shade-model :accessor %shade-model :initform :smooth) (light-model :reader %light-model :initform (alexandria:plist-hash-table `(:light-model-local-viewer 1))) (color-material :reader %color-material :initform (alexandria:plist-hash-table `(:front :ambient-and-diffuse :back :ambient-and-diffuse))) (lights :reader lights :initform (vector (make-light :diffuse (v4 1 1 1 1) :specular (v4 1 1 1 1)) (make-light) (make-light) (make-light))) (draw-flags :accessor draw-flags :initform #(0 0 0 0)) (textures :reader textures :initform (make-array '(3) :initial-element nil)) (state-changed-flags :accessor state-changed-flags :initform -1) ;; if set, called when buffer fills up, or at end of frame. passed 1 argument containing draws since last call to draw callback or ;; to get-draws (draw-callback :reader draw-callback :initform nil :initarg :draw-callback))) (defmacro with-state ((&key draw-callback) &body body) `(3b-glim/s:with-state (*format*) (unless (typep *state* 'glim-state) (change-class *state* 'glim-state :draw-callback ,draw-callback :primitive-temp (coerce (loop repeat 4 collect (3b-glim/s::copy-current-vertex *state*)) 'vector))) (with-matrix-stacks () (ensure-matrix :modelview) (ensure-matrix :projection) ,@body))) (defmethod (setf point-size) :before (n (s glim-state)) (notice-state-changed *state* +state-changed-line-width+) ;; not valid inside BEGIN/END (assert (not (primitive s)))) (defmethod (setf line-width) :before (n (s glim-state)) (notice-state-changed *state* +state-changed-point-size+) ;; not valid inside BEGIN/END (assert (not (primitive s)))) (defun get-flag (flag) (gethash flag (flags *state*))) (defun get/clear-changed-flag (state change) (plusp (shiftf (ldb (byte 1 change) (state-changed-flags state)) 0))) (defun notice-state-changed (state change) (setf (ldb (byte 1 change) (state-changed-flags state)) 1)) (defmethod notice-flag-changed ((state glim-state) flag new) (case flag ((:lighting :light0 :light1 :light2 :light4) (setf (gethash flag (flags state)) new) (notice-state-changed state +state-changed-lighting+) ;; lighting enable is in draw flags, so update that too (notice-state-changed state +state-changed-draw-flags+)) ((:line-smooth :wireframe :point-smooth :filled-wireframe) (setf (gethash flag (flags state)) new) (notice-state-changed state +state-changed-draw-flags+)) ((:texture-1d :texture-2d :texture-3d) (setf (gethash flag (flags state)) new) (notice-state-changed state +state-changed-tex+)))) (defun maybe-call-draw-callback () (when (draw-callback *state*) (let ((draws (3b-glim/s:get-draws)) (buffers (3b-glim/s:get-buffers))) (when (and draws buffers) (funcall (draw-callback *state*) (renderer-config *state*) draws buffers))))) (defmethod begin-frame ((state glim-state)) (3b-glim/s:reset-buffers *state*) (setf (state-changed-flags *state*) -1) (begin-frame (renderer-config state))) (defmacro with-frame (() &body body) ` (prog1 (with-balanced-matrix-stacks () (begin-frame *state*) ,@body) (maybe-call-draw-callback))) ;; define with and without S to match cl-opengl (defmacro with-primitives (primitive &body body) `(with-primitive ,primitive ,@body)) (defmacro with-primitive (primitive &body body) `(progn (begin ,primitive) (unwind-protect (prog1 (progn ,@body) ;; on normal exit, we call END to finish chunk (end)) ;; and we clear primitive even on nlx so next begin doesn't fail (setf (%primitive *state*) nil)))) (defvar *primitives* (alexandria:plist-hash-table ;; min # of vertices to finish a primitive '(:points 1 :lines 2 :triangles 3 2 tris :line-strip 2 todo : : line - loop 2 :triangle-strip 3 :triangle-fan 3 2 tris ;; todo: ;; :polygon ? ))) (defun set-primitive (primitive size) (setf (%primitive *state*) (list primitive size t))) (defun restart-draw () (let* ((state *state*) (primitive (car (primitive state)))) (ecase primitive ((:triangles :points :lines :quads) always draw whole primitive to buffer , so just reset index to 0 (setf (primitive-index state) 0)) (:line-strip need to track 1 vertex from previous draw (setf (primitive-index state) 1)) ((:triangle-strip :triangle-fan :quad-strip) need to track 2 vertices from previous draw (setf (primitive-index state) 2))))) (defun index-overflow () (assert (primitive *state*)) (3b-glim/s:end) (maybe-call-draw-callback) ;; possibly could skip index for :triangles primitive, but using it ;; anyway for consistency for now (3b-glim/s:begin :triangles :indexed t) (restart-draw)) (defun check-index-overflow () if we have too many verts for 16bit indices ( + some extra space ;; for safety), start a new batch (when (> (+ (3b-glim/s::next-index *state*) 6) 65535) (index-overflow) t)) (defun %flag (offset value) (let ((pf (prim-flags *state*))) (declare (type octet-vector pf)) (setf (aref pf offset) value) (3b-glim/s:attrib-u8v +flags+ pf))) (defun begin (primitive) #++(declare (optimize speed)) (let ((prim-size (gethash primitive *primitives*)) (state *state*)) (macrolet ((df (flag mode &rest more) `(cond ,@ (loop for (f m) on (list* flag mode more) by #'cddr collect `((get-flag ,f) (unless (= (aref (draw-flags state) +draw-flag-mode+) (float ,m 0.0)) (notice-state-changed state +state-changed-draw-flags+)) (setf (aref (draw-flags state) +draw-flag-mode+) (float ,m 0.0)))) (t (unless (= (aref (draw-flags state) +draw-flag-mode+) (float +draw-mode-normal+ 0.0)) (notice-state-changed state +state-changed-draw-flags+)) (setf (aref (draw-flags state) +draw-flag-mode+) (float +draw-mode-normal+ 0.0))))) (dfb (flag mode &rest more) `(cond ,@ (loop for (f m) on (list* flag mode more) by #'cddr collect `((get-flag ,f) (setf (aref (draw-flags state) +draw-flag-mode-back+) (float ,m 0.0)))) (t (setf (aref (draw-flags state) +draw-flag-mode-back+) (float +draw-mode-normal+ 0.0)))))) (ecase primitive (:points (%flag +prim-mode-flag+ +point-flag+) (df :point-smooth +draw-mode-smooth+)) ((:lines :line-strip) (%flag +prim-mode-flag+ +line-flag+) (setf (line-temp state) (v4 0 0 0 1)) (df :line-smooth +draw-mode-smooth+)) ((:triangles :triangle-fan :triangle-strip) (%flag +prim-mode-flag+ +triangle-flag+) (df :filled-wireframe +draw-mode-filled-wireframe+ :wireframe +draw-mode-wireframe+) (dfb :backface-fill +draw-mode-normal+ :backface-filled-wireframe +draw-mode-filled-wireframe+ :backface-wireframe +draw-mode-wireframe+ :filled-wireframe +draw-mode-filled-wireframe+ :wireframe +draw-mode-wireframe+)) ((:quads :quad-strip) (%flag +prim-mode-flag+ +quad-flag+) (df :filled-wireframe +draw-mode-filled-wireframe+ :wireframe +draw-mode-wireframe+) (dfb :backface-fill +draw-mode-normal+ :backface-filled-wireframe +draw-mode-filled-wireframe+ :backface-wireframe +draw-mode-wireframe+ :filled-wireframe +draw-mode-filled-wireframe+ :wireframe +draw-mode-wireframe+)))) (setf (aref (draw-flags state) +draw-flag-lighting+) (if (get-flag :lighting) 1.0 0.0)) ;; todo: error messages (assert prim-size) (assert (not (primitive state))) (setf (primitive-state state) 0) ;; fixme: don't reset these if they haven't changed, or don't ;; apply (flet ((f (f) (get-flag f)) (fi (f) (if (get-flag f) 1 0))) (3b-glim/s:uniform 'mv (ensure-matrix :modelview)) (3b-glim/s:uniform 'proj (ensure-matrix :projection)) (when (get/clear-changed-flag state +state-changed-line-width+) (3b-glim/s:uniform 'line-width (s:current-line-width state))) (when (get/clear-changed-flag state +state-changed-point-size+) (3b-glim/s:uniform 'point-size (s:current-point-size state))) (when (get/clear-changed-flag state +state-changed-draw-flags+) (3b-glim/s:uniform 'draw-flags (draw-flags state))) (when (get/clear-changed-flag state +state-changed-tex+) (3b-glim/s:uniform :textures (copy-seq (textures state))) (3b-glim/s:uniform 'tex-mode0 (cond ((get-flag :texture-3d) +tex-mode-3d+) ((get-flag :texture-2d) +tex-mode-2d+) ((get-flag :texture-1d) +tex-mode-1d+) (t +tex-mode-off+)))) (when (get/clear-changed-flag state +state-changed-lighting+) (3b-glim/s:uniform 'lights-enabled (if (f :lighting) (vector (fi :light0) (fi :light1) (fi :light2) (fi :light3)) (vector 0 0 0 0))) (when (f :lighting) (3b-glim/s:uniform :lighting (concatenate 'vector (aref (lights state) 0) (aref (lights state) 1) (aref (lights state) 2) (aref (lights state) 3)))))) (3b-glim/s:begin :triangles :indexed t) (check-index-overflow) (set-primitive primitive prim-size))) (defun end () (assert (primitive *state*)) (setf (line-temp *state*) nil) (3b-glim/s:end) #++(maybe-call-draw-callback) #++(finish-chunk)) (defun write-vertex-line (v) (declare (optimize speed) (type (float-vector 4) v)) todo : tess and non - smooth width 1 lines #++ (or (use-tess *state*) (and (= (s:current-line-width *state*) 1) (not (gethash :line-smooth (flags *state*))))) ;; make sure we have space for a whole quad (check-index-overflow) ;; for line, we store start vertex in temp[0] (let* ((state *state*) (line-temp (line-temp state)) (primitive-temp (primitive-temp state))) (declare (type (float-vector 4) line-temp) (type (simple-array cons (4)) primitive-temp)) if this is first vertex of a line , just store it 0 or 2 (incf (the fixnum (primitive-state state))) (replace line-temp v) (3b-glim/s::copy-current-vertex-into state (aref primitive-temp 0)) (return-from write-vertex-line nil)) ;; otherwise, we are at enpoint of a segment, so add a quad to ;; buffers (let ((curr v) (prev line-temp) (line-width (s:current-line-width state)) (i 0)) (declare (type (float-vector 4) curr prev) (type single-float line-width) (type u16 i)) ;; copy current vertex state (3b-glim/s::copy-current-vertex-into state (aref primitive-temp 1)) ;; and restore state from start of line, so we can emit the ;; vertices (3b-glim/s::restore-vertex-copy state (aref primitive-temp 0)) ;; store current point (in temp[0]) as tangent (3b-glim/s::attrib-f +tangent-width+ (aref curr 0) (aref curr 1) (aref curr 2) line-width) ;; set corner and add points (%flag +corner-index-flag+ 0) (setf i (3b-glim/s::attrib-fv +position+ prev)) (%flag +corner-index-flag+ 1) (3b-glim/s::attrib-fv +position+ prev) ;; restore state for end, and repeat (3b-glim/s::restore-vertex-copy state (aref primitive-temp 1)) (3b-glim/s::attrib-f +tangent-width+ (aref prev 0) (aref prev 1) (aref prev 2) line-width ) ;; set corner and add points (%flag +corner-index-flag+ 2) (3b-glim/s::attrib-fv +position+ curr) (%flag +corner-index-flag+ 3) (3b-glim/s::attrib-fv +position+ curr) ;; emit indices (3b-glim/s:index (+ i 0) (+ i 1) (+ i 2)) (3b-glim/s:index (+ i 0) (+ i 2) (+ i 3)) ;; and update state (setf (primitive-state state) 2)))) (defun write-vertex-line-strip (v) todo : tess and non - smooth width 1 lines after first segment is done , we just update state to ' end of ;; segment' (when (>= (primitive-state *state*) 1) (rotatef (aref (primitive-temp *state*) 0) (aref (primitive-temp *state*) 1)) (setf (primitive-state *state*) 1)) ;; and let line code handle the rest (write-vertex-line v) (replace (line-temp *state*) v)) (defun write-vertex-point (v) (declare (optimize speed) (type (float-vector 4) v)) ;; todo: tess path, non-smooth size=1 ;; make sure we have space for a whole quad (check-index-overflow) (let* ((state *state*) (point-size (s:current-point-size state)) (i 0)) (declare (type single-float point-size) (type u16 i)) store width in 4th element of tangent (3b-glim/s::attrib-f +tangent-width+ 0.0 0.0 0.0 point-size) write out vertex 4 times with different corners (%flag +corner-index-flag+ 0) (setf i (3b-glim/s::attrib-fv +position+ v)) (%flag +corner-index-flag+ 1) (3b-glim/s::attrib-fv +position+ v) (%flag +corner-index-flag+ 2) (3b-glim/s::attrib-fv +position+ v) (%flag +corner-index-flag+ 3) (3b-glim/s::attrib-fv +position+ v) ;; and emit indices (3b-glim/s:index (+ i 0) (+ i 1) (+ i 2)) (3b-glim/s:index (+ i 0) (+ i 2) (+ i 3)))) (defun write-vertex-quad (v) (declare (optimize speed) (type (float-vector 4) v)) (let* ((c (primitive-state *state*)) (c4 (mod c 4)) (i 0)) (declare (type u32 c c4) (type u16 i)) (when (zerop c4) ;; make sure we have space for a whole quad (check-index-overflow)) (%flag +corner-index-flag+ c4) (setf (primitive-state *state*) (mod (1+ c) 4)) (setf i (3b-glim/s:attrib-fv +position+ v)) (when (= c 3) (3b-glim/s:index (- i 3) (- i 2) (- i 1)) (3b-glim/s:index (- i 3) (- i 1) (- i 0))))) (defun write-vertex-quad-strip (v) (declare (optimize speed) (type (float-vector 4) v)) ;; make sure we have space for a whole quad (check-index-overflow) (let* ((state *state*) (primitive-temp (primitive-temp state)) (c (primitive-state state)) (i 0)) (declare (type u32 c) (type u16 i) (type (simple-array t (4)) primitive-temp)) (when (= c 4) when starting a quad after first , duplicate previous 2 vertices (3b-glim/s::copy-current-vertex-into state (aref primitive-temp 2)) (3b-glim/s::restore-vertex-copy state (aref primitive-temp 1)) (%flag +corner-index-flag+ 0) (3b-glim/s::emit-vertex state) (3b-glim/s::restore-vertex-copy state (aref primitive-temp 0)) (%flag +corner-index-flag+ 1) (3b-glim/s::emit-vertex state) ;; restore current vertex (3b-glim/s::restore-vertex-copy state (aref primitive-temp 2)) and skip state to last 2 vertices (setf c 2)) (%flag +corner-index-flag+ c) (setf i (3b-glim/s:attrib-fv +position+ v)) (when (> c 1) ;; store vert for use in next quad (3b-glim/s::copy-current-vertex-into state (aref primitive-temp (- c 2)))) mod 8 so we can distinguish first quad from later quads (setf (primitive-state *state*) (mod (1+ c) 8)) (when (= c 3) (3b-glim/s:index (- i 3) (- i 2) (- i 1)) (3b-glim/s:index (- i 3) (- i 1) (- i 0))))) (defun write-vertex (v) (declare (optimize speed) (type (float-vector 4) v)) (let* ((state *state*) (primitive (car (primitive state))) (primitive-temp (primitive-temp state)) (ps (primitive-state state))) (declare (type u16 ps) (type (simple-array t (4)) primitive-temp)) (flet ((tri-corner (&optional (i ps)) (declare (type u16 i)) (%flag +corner-index-flag+ (mod i 3)) nil)) (ecase primitive ((:triangles) (tri-corner) (when (zerop ps) (check-index-overflow)) (setf ps (mod (+ ps 1) 3)) (setf (primitive-state state) ps) (3b-glim/s:index (3b-glim/s:attrib-fv +position+ v))) (:triangle-strip (tri-corner) (let ((p3 (mod ps 3))) (3b-glim/s::copy-current-vertex-into state (aref primitive-temp p3)) if we restarted a batch , we need to emit previous 2 ;; vertices again, otherwise we share indices with previous ;; tris (when (and (check-index-overflow) (> ps 2)) (3b-glim/s::restore-vertex-copy state (aref primitive-temp (mod (+ p3 1) 3))) (3b-glim/s::emit-vertex state) (3b-glim/s::restore-vertex-copy state (aref primitive-temp (mod (+ p3 2) 3))) (3b-glim/s::emit-vertex state) (3b-glim/s::restore-vertex-copy state (aref primitive-temp p3))) mod 6 so we can distinguish first tri (setf ps (mod (+ ps 1) 6)) (setf (primitive-state state) ps) #++(3b-glim/s:index (3b-glim/s:attrib-fv +position+ v)) (let ((i (3b-glim/s:attrib-fv +position+ v))) (declare (type u16 i)) index 0 and 1 do n't make a triangle , otherwise emit ;; indices for a triangle (when (> i 1) ( 3b - glim / s : index ( - i 2 ) ( - i 1 ) i ) (multiple-value-bind (f r) (floor i 2) (3b-glim/s:index (* 2 (+ f (- r 1))) (1- (* f 2)) i)))))) (:triangle-fan (tri-corner) if we restarted a batch , we need to emit previous 2 ;; vertices again, otherwise we share indices with previous ;; tris (when (and (check-index-overflow) (> ps 2)) (3b-glim/s::restore-vertex-copy state (aref primitive-temp 0)) (3b-glim/s::emit-vertex state) (3b-glim/s::restore-vertex-copy state (aref primitive-temp 1)) (3b-glim/s::emit-vertex state) (3b-glim/s::restore-vertex-copy state (aref primitive-temp 2))) (let ((i (3b-glim/s:attrib-fv +position+ v))) (declare (type u16 i)) (3b-glim/s::restore-vertex-copy state (aref primitive-temp ps)) index 0 and 1 do n't make a triangle , otherwise emit ;; indices (when (> i 1) (3b-glim/s:index 0 (1- i) i)) (setf (primitive-state state) (ecase ps (0 1) (1 2) (2 1))))) (:points (write-vertex-point v)) : lines and line - strips are converted to quads if size /= 1 or if ;; smooth is on (:lines (write-vertex-line v)) (:line-strip (write-vertex-line-strip v)) (:line-loop ;; todo: needs to store state extra state across chunks to close ;; loop ) ;; :quads and :quad-strip are converted to tris / tri-strips (:quads (write-vertex-quad v)) (:quad-strip (write-vertex-quad-strip v)))))) (defun %vertex (x y z w) (declare (optimize speed) (type single-float x y z w)) (let ((v (v4 x y z w))) (declare (type (float-vector 4) v) (dynamic-extent v)) (write-vertex v) nil)) (declaim (inline vertex vertex-v)) (defun vertex (x &optional (y 0.0) (z 0.0) (w 1.0)) (%vertex (f x) (f y) (f z) (f w))) (defun vertex-v (v) (etypecase v ((float-vector 4) (%vertex (aref v 0) (aref v 1) (aref v 2) (aref v 3))) ((float-vector 3) (%vertex (aref v 0) (aref v 1) (aref v 2) 1.0)) ((float-vector 2) (%vertex (aref v 0) (aref v 1) 0.0 1.0)) ((float-vector 1) (%vertex (aref v 0) 0.0 0.0 1.0)) (vector (flet ((a (x &optional (d 0.0) ) (if (array-in-bounds-p v x) (aref v x) d))) (vertex (a 0 0.0) (a 1 0.0) (a 2 0.0) (a 3 0.0)))) (list (apply 'vertex v)))) (defun %normal (x y z) (declare (optimize speed) (type single-float x y z)) (3b-glim/s:attrib-f +normal+ x y z)) (declaim (inline normal)) (defun normal (x y z) (%normal (f x) (f y) (f z))) #++ (defun edge-flag (flag) (let ((s (gethash :flags (vertex-format *state*)))) (when s (let ((v (current-vertex *state*))) (setf (aref v (+ (car s) 0)) (if flag 1 0)))))) (defun %multi-tex-coord (tex s tt r q) (declare (optimize speed) (type single-float s tt r q)) (assert (or (eql tex 0)(eql tex :texture0))) (3b-glim/s:attrib-f +texture0+ s tt r q)) (declaim (inline multi-tex-coord tex-coord)) (defun multi-tex-coord (tex s &optional (tt 0.0) (r 0.0) (q 1.0)) (%multi-tex-coord tex (f s) (f tt) (f r) (f q))) (defun tex-coord (s &optional (tt 0.0) (r 0.0) (q 1.0)) (%multi-tex-coord 0 (f s) (f tt) (f r) (f q))) #++ (defun fog-coord (x)) (defun %color (r g b a) (declare (optimize speed) (type single-float r g b a)) (3b-glim/s:attrib-u8sc +color+ r g b a)) (declaim (inline color)) (defun color (r g b &optional (a 1.0)) (%color (f r) (f g) (f b) (f a))) (defun %secondary-color (r g b) (declare (optimize speed) (type single-float r g b)) (3b-glim/s:attrib-u8sc +secondary-color+ r g b)) (declaim (inline secondary-color)) (defun secondary-color (r g b) (%secondary-color (f r) (f g) (f b))) (defun shade-model (model) (setf (%shade-model *state*) model)) (defun light-model (a b) ;; fixme: error checking (setf (gethash a (%light-model *state*)) b)) (defun color-material (a b) ;; fixme: error checking (setf (gethash a (%color-material *state*)) b)) #++ (defun map-draws (fun draws) (loop for draw in draws do (apply fun draw))) (defun polygon-mode (face mode) (notice-state-changed *state* +state-changed-draw-flags+) (ecase face (:front (ecase mode ((:line :wireframe) (setf (gethash :wireframe (flags *state*)) t) (setf (gethash :filled-wireframe (flags *state*)) nil)) (:fill (setf (gethash :wireframe (flags *state*)) nil) (setf (gethash :filled-wireframe (flags *state*)) nil)) (:filled-wireframe (setf (gethash :wireframe (flags *state*)) nil) (setf (gethash :filled-wireframe (flags *state*)) t)) #++ (:point ;; todo ? ))) (:back (ecase mode ((:line :wireframe) (setf (gethash :backface-wireframe (flags *state*)) t) (setf (gethash :backface-filled (flags *state*)) nil) (setf (gethash :backface-filled-wireframe (flags *state*)) nil)) (:fill (setf (gethash :backface-wireframe (flags *state*)) nil) (setf (gethash :backface-filled (flags *state*)) t) (setf (gethash :backface-filled-wireframe (flags *state*)) nil)) (:filled-wireframe (setf (gethash :backface-wireframe (flags *state*)) nil) (setf (gethash :backface-filled (flags *state*)) nil) (setf (gethash :backface-filled-wireframe (flags *state*)) t)))) (:front-and-back (polygon-mode :front mode) (polygon-mode :back mode)))) (defun bind-texture (target name) (notice-state-changed *state* +state-changed-tex+) (setf (aref (textures *state*) (ecase target (:texture-1d 0) (:texture-2d 1) (:texture-3d 2))) name)) (defun light (light pname param) (assert (< -1 light (length (lights *state*)))) (notice-state-changed *state* +state-changed-lighting+) (flet ((v3v () (map 'v3 'f param)) (v4v () (map 'v4 'f param))) (ecase pname (:position ;; pos/dir are transformed to eye space by current mv matrix when ;; set (let* ((p (v4v)) (v (sb-cga:vec (aref p 0) (aref p 1) (aref p 2))) (mv (ensure-matrix :modelview))) (if (zerop (aref p 3)) (replace p (sb-cga:transform-direction v mv)) (replace p (sb-cga:transform-point v mv))) (setf (light-position (aref (lights *state*) light)) p))) (:ambient (setf (light-ambient (aref (lights *state*) light)) (v4v))) (:diffuse (setf (light-diffuse (aref (lights *state*) light)) (v4v))) (:specular (setf (light-specular (aref (lights *state*) light)) (v4v))) (:spot-direction (let* ((p (v3v)) (mv (ensure-matrix :modelview))) (setf (light-spot-dir (aref (lights *state*) light)) (sb-cga:transform-direction p mv)))) (:spot-exponent (setf (aref (light-spot-params (aref (lights *state*) light)) 0) (f param))) (:spot-cutoff (setf (aref (light-spot-params (aref (lights *state*) light)) 1) (f param))) (:constant-attenuation (setf (aref (light-attenuation (aref (lights *state*) light)) 0) (f param))) (:linear-attenuation (setf (aref (light-attenuation (aref (lights *state*) light)) 1) (f param))) (:quadratic-attenuation (setf (aref (light-attenuation (aref (lights *state*) light)) 2) (f param))))))
null
https://raw.githubusercontent.com/3b/3b-glim/6299ddaf88bea180646a231fe9030e39bb499851/im/state.lisp
lisp
stores extra data for generating line vertices 0 = primitive type: see +trangle-flag+ etc above color indices into prim-flags[] values for flags[+prim-mode-flag+] values for tex-mode* uniforms indices for draw-flags uniform values for +draw-flag-mode+ tris/quads only tris/quads only lighting stuff parameters of current begin/end extra space to remember previous vertices, used to convert strip/loop/quad primitives into separate tris for line/strip/fan primitives, we need to track which part of a primitive we are drawing, 0 is start of batch, other values depends on type store position of previous points in line so we can calculate tangent if set, called when buffer fills up, or at end of frame. passed to get-draws not valid inside BEGIN/END not valid inside BEGIN/END lighting enable is in draw flags, so update that too define with and without S to match cl-opengl on normal exit, we call END to finish chunk and we clear primitive even on nlx so next begin doesn't fail min # of vertices to finish a primitive todo: :polygon ? possibly could skip index for :triangles primitive, but using it anyway for consistency for now for safety), start a new batch todo: error messages fixme: don't reset these if they haven't changed, or don't apply make sure we have space for a whole quad for line, we store start vertex in temp[0] otherwise, we are at enpoint of a segment, so add a quad to buffers copy current vertex state and restore state from start of line, so we can emit the vertices store current point (in temp[0]) as tangent set corner and add points restore state for end, and repeat set corner and add points emit indices and update state segment' and let line code handle the rest todo: tess path, non-smooth size=1 make sure we have space for a whole quad and emit indices make sure we have space for a whole quad make sure we have space for a whole quad restore current vertex store vert for use in next quad vertices again, otherwise we share indices with previous tris indices for a triangle vertices again, otherwise we share indices with previous tris indices smooth is on todo: needs to store state extra state across chunks to close loop :quads and :quad-strip are converted to tris / tri-strips fixme: error checking fixme: error checking todo ? pos/dir are transformed to eye space by current mv matrix when set
(in-package #:3b-glim) (defconstant +position+ 0) only supporting 1 textures for now (defconstant +tangent-width+ 2) (defconstant +normal+ 3) (defconstant +color+ 4) (defconstant +flags+ 5) (defconstant +secondary-color+ 6) (defvar *format* (3b-glim/s:compile-vertex-format `(1 (,+position+ :vec4) (,+texture0+ :vec4) (,+tangent-width+ :vec4) (,+normal+ :vec3) (,+color+ :u8vec4) 1 = edge flag where applicable 2 = corner index for vertex - shader points / lines (,+flags+ (:u8vec4 nil)) (,+secondary-color+ :u8vec3) (defconstant +prim-mode-flag+ 0) (defconstant +edge-flag-flag+ 1) (defconstant +corner-index-flag+ 2) (defconstant +triangle-flag+ 0) (defconstant +point-flag+ 1) (defconstant +line-flag+ 2) (defconstant +quad-flag+ 3) ( defconstant + line - cap - flag+ 3 ) (defconstant +tex-mode-off+ 0) (defconstant +tex-mode-1d+ 1) (defconstant +tex-mode-2d+ 2) (defconstant +tex-mode-3d+ 3) (defconstant +draw-flag-mode+ 0) (defconstant +draw-flag-mode-back+ 1) (defconstant +draw-flag-lighting+ 2) (defconstant +draw-mode-normal+ 0) (defconstant +draw-mode-smooth+ 1) (defconstant +max-lights+ 4) (defun make-flags () (alexandria:plist-hash-table '(:line-smooth nil :point-smooth nil :wireframe nil :filled-wireframe nil :texture-1d nil :texture-2d nil :texture-3d nil :light0 nil :light1 nil :light2 nil :light3 nil :lighting nil))) (defstruct (light (:type vector)) (position (v4 0 0 1 0)) (ambient (v4 0 0 0 1)) (diffuse (v4 0 0 0 1)) (specular (v4 0 0 0 1)) (spot-dir (v3 0 0 -1)) (spot-params (v3 0 180 0)) (attenuation (v3 1 0 0))) (defconstant +state-changed-line-width+ 0) (defconstant +state-changed-point-size+ 1) (defconstant +state-changed-draw-flags+ 2) (defconstant +state-changed-tex+ 3) (defconstant +state-changed-lighting+ 4) (defclass renderer-config () ()) (defclass glim-state (3b-glim/s::writer-state) (primitive :reader primitive :initform nil :writer (setf %primitive)) (flags :reader flags :initform (make-flags)) (prim-flags :reader prim-flags :initform (make-array 4 :element-type 'octet :initial-element 0)) (use-tess :reader use-tess :initform nil :writer (setf %use-tess)) (renderer-config :reader renderer-config :initform nil :accessor %renderer-config) (primitive-temp :reader primitive-temp :initarg :primitive-temp) (primitive-state :accessor primitive-state :initform 0) (line-temp :accessor line-temp :initform nil) fixme : match GL defaults (shade-model :accessor %shade-model :initform :smooth) (light-model :reader %light-model :initform (alexandria:plist-hash-table `(:light-model-local-viewer 1))) (color-material :reader %color-material :initform (alexandria:plist-hash-table `(:front :ambient-and-diffuse :back :ambient-and-diffuse))) (lights :reader lights :initform (vector (make-light :diffuse (v4 1 1 1 1) :specular (v4 1 1 1 1)) (make-light) (make-light) (make-light))) (draw-flags :accessor draw-flags :initform #(0 0 0 0)) (textures :reader textures :initform (make-array '(3) :initial-element nil)) (state-changed-flags :accessor state-changed-flags :initform -1) 1 argument containing draws since last call to draw callback or (draw-callback :reader draw-callback :initform nil :initarg :draw-callback))) (defmacro with-state ((&key draw-callback) &body body) `(3b-glim/s:with-state (*format*) (unless (typep *state* 'glim-state) (change-class *state* 'glim-state :draw-callback ,draw-callback :primitive-temp (coerce (loop repeat 4 collect (3b-glim/s::copy-current-vertex *state*)) 'vector))) (with-matrix-stacks () (ensure-matrix :modelview) (ensure-matrix :projection) ,@body))) (defmethod (setf point-size) :before (n (s glim-state)) (notice-state-changed *state* +state-changed-line-width+) (assert (not (primitive s)))) (defmethod (setf line-width) :before (n (s glim-state)) (notice-state-changed *state* +state-changed-point-size+) (assert (not (primitive s)))) (defun get-flag (flag) (gethash flag (flags *state*))) (defun get/clear-changed-flag (state change) (plusp (shiftf (ldb (byte 1 change) (state-changed-flags state)) 0))) (defun notice-state-changed (state change) (setf (ldb (byte 1 change) (state-changed-flags state)) 1)) (defmethod notice-flag-changed ((state glim-state) flag new) (case flag ((:lighting :light0 :light1 :light2 :light4) (setf (gethash flag (flags state)) new) (notice-state-changed state +state-changed-lighting+) (notice-state-changed state +state-changed-draw-flags+)) ((:line-smooth :wireframe :point-smooth :filled-wireframe) (setf (gethash flag (flags state)) new) (notice-state-changed state +state-changed-draw-flags+)) ((:texture-1d :texture-2d :texture-3d) (setf (gethash flag (flags state)) new) (notice-state-changed state +state-changed-tex+)))) (defun maybe-call-draw-callback () (when (draw-callback *state*) (let ((draws (3b-glim/s:get-draws)) (buffers (3b-glim/s:get-buffers))) (when (and draws buffers) (funcall (draw-callback *state*) (renderer-config *state*) draws buffers))))) (defmethod begin-frame ((state glim-state)) (3b-glim/s:reset-buffers *state*) (setf (state-changed-flags *state*) -1) (begin-frame (renderer-config state))) (defmacro with-frame (() &body body) ` (prog1 (with-balanced-matrix-stacks () (begin-frame *state*) ,@body) (maybe-call-draw-callback))) (defmacro with-primitives (primitive &body body) `(with-primitive ,primitive ,@body)) (defmacro with-primitive (primitive &body body) `(progn (begin ,primitive) (unwind-protect (prog1 (progn ,@body) (end)) (setf (%primitive *state*) nil)))) (defvar *primitives* (alexandria:plist-hash-table '(:points 1 :lines 2 :triangles 3 2 tris :line-strip 2 todo : : line - loop 2 :triangle-strip 3 :triangle-fan 3 2 tris ))) (defun set-primitive (primitive size) (setf (%primitive *state*) (list primitive size t))) (defun restart-draw () (let* ((state *state*) (primitive (car (primitive state)))) (ecase primitive ((:triangles :points :lines :quads) always draw whole primitive to buffer , so just reset index to 0 (setf (primitive-index state) 0)) (:line-strip need to track 1 vertex from previous draw (setf (primitive-index state) 1)) ((:triangle-strip :triangle-fan :quad-strip) need to track 2 vertices from previous draw (setf (primitive-index state) 2))))) (defun index-overflow () (assert (primitive *state*)) (3b-glim/s:end) (maybe-call-draw-callback) (3b-glim/s:begin :triangles :indexed t) (restart-draw)) (defun check-index-overflow () if we have too many verts for 16bit indices ( + some extra space (when (> (+ (3b-glim/s::next-index *state*) 6) 65535) (index-overflow) t)) (defun %flag (offset value) (let ((pf (prim-flags *state*))) (declare (type octet-vector pf)) (setf (aref pf offset) value) (3b-glim/s:attrib-u8v +flags+ pf))) (defun begin (primitive) #++(declare (optimize speed)) (let ((prim-size (gethash primitive *primitives*)) (state *state*)) (macrolet ((df (flag mode &rest more) `(cond ,@ (loop for (f m) on (list* flag mode more) by #'cddr collect `((get-flag ,f) (unless (= (aref (draw-flags state) +draw-flag-mode+) (float ,m 0.0)) (notice-state-changed state +state-changed-draw-flags+)) (setf (aref (draw-flags state) +draw-flag-mode+) (float ,m 0.0)))) (t (unless (= (aref (draw-flags state) +draw-flag-mode+) (float +draw-mode-normal+ 0.0)) (notice-state-changed state +state-changed-draw-flags+)) (setf (aref (draw-flags state) +draw-flag-mode+) (float +draw-mode-normal+ 0.0))))) (dfb (flag mode &rest more) `(cond ,@ (loop for (f m) on (list* flag mode more) by #'cddr collect `((get-flag ,f) (setf (aref (draw-flags state) +draw-flag-mode-back+) (float ,m 0.0)))) (t (setf (aref (draw-flags state) +draw-flag-mode-back+) (float +draw-mode-normal+ 0.0)))))) (ecase primitive (:points (%flag +prim-mode-flag+ +point-flag+) (df :point-smooth +draw-mode-smooth+)) ((:lines :line-strip) (%flag +prim-mode-flag+ +line-flag+) (setf (line-temp state) (v4 0 0 0 1)) (df :line-smooth +draw-mode-smooth+)) ((:triangles :triangle-fan :triangle-strip) (%flag +prim-mode-flag+ +triangle-flag+) (df :filled-wireframe +draw-mode-filled-wireframe+ :wireframe +draw-mode-wireframe+) (dfb :backface-fill +draw-mode-normal+ :backface-filled-wireframe +draw-mode-filled-wireframe+ :backface-wireframe +draw-mode-wireframe+ :filled-wireframe +draw-mode-filled-wireframe+ :wireframe +draw-mode-wireframe+)) ((:quads :quad-strip) (%flag +prim-mode-flag+ +quad-flag+) (df :filled-wireframe +draw-mode-filled-wireframe+ :wireframe +draw-mode-wireframe+) (dfb :backface-fill +draw-mode-normal+ :backface-filled-wireframe +draw-mode-filled-wireframe+ :backface-wireframe +draw-mode-wireframe+ :filled-wireframe +draw-mode-filled-wireframe+ :wireframe +draw-mode-wireframe+)))) (setf (aref (draw-flags state) +draw-flag-lighting+) (if (get-flag :lighting) 1.0 0.0)) (assert prim-size) (assert (not (primitive state))) (setf (primitive-state state) 0) (flet ((f (f) (get-flag f)) (fi (f) (if (get-flag f) 1 0))) (3b-glim/s:uniform 'mv (ensure-matrix :modelview)) (3b-glim/s:uniform 'proj (ensure-matrix :projection)) (when (get/clear-changed-flag state +state-changed-line-width+) (3b-glim/s:uniform 'line-width (s:current-line-width state))) (when (get/clear-changed-flag state +state-changed-point-size+) (3b-glim/s:uniform 'point-size (s:current-point-size state))) (when (get/clear-changed-flag state +state-changed-draw-flags+) (3b-glim/s:uniform 'draw-flags (draw-flags state))) (when (get/clear-changed-flag state +state-changed-tex+) (3b-glim/s:uniform :textures (copy-seq (textures state))) (3b-glim/s:uniform 'tex-mode0 (cond ((get-flag :texture-3d) +tex-mode-3d+) ((get-flag :texture-2d) +tex-mode-2d+) ((get-flag :texture-1d) +tex-mode-1d+) (t +tex-mode-off+)))) (when (get/clear-changed-flag state +state-changed-lighting+) (3b-glim/s:uniform 'lights-enabled (if (f :lighting) (vector (fi :light0) (fi :light1) (fi :light2) (fi :light3)) (vector 0 0 0 0))) (when (f :lighting) (3b-glim/s:uniform :lighting (concatenate 'vector (aref (lights state) 0) (aref (lights state) 1) (aref (lights state) 2) (aref (lights state) 3)))))) (3b-glim/s:begin :triangles :indexed t) (check-index-overflow) (set-primitive primitive prim-size))) (defun end () (assert (primitive *state*)) (setf (line-temp *state*) nil) (3b-glim/s:end) #++(maybe-call-draw-callback) #++(finish-chunk)) (defun write-vertex-line (v) (declare (optimize speed) (type (float-vector 4) v)) todo : tess and non - smooth width 1 lines #++ (or (use-tess *state*) (and (= (s:current-line-width *state*) 1) (not (gethash :line-smooth (flags *state*))))) (check-index-overflow) (let* ((state *state*) (line-temp (line-temp state)) (primitive-temp (primitive-temp state))) (declare (type (float-vector 4) line-temp) (type (simple-array cons (4)) primitive-temp)) if this is first vertex of a line , just store it 0 or 2 (incf (the fixnum (primitive-state state))) (replace line-temp v) (3b-glim/s::copy-current-vertex-into state (aref primitive-temp 0)) (return-from write-vertex-line nil)) (let ((curr v) (prev line-temp) (line-width (s:current-line-width state)) (i 0)) (declare (type (float-vector 4) curr prev) (type single-float line-width) (type u16 i)) (3b-glim/s::copy-current-vertex-into state (aref primitive-temp 1)) (3b-glim/s::restore-vertex-copy state (aref primitive-temp 0)) (3b-glim/s::attrib-f +tangent-width+ (aref curr 0) (aref curr 1) (aref curr 2) line-width) (%flag +corner-index-flag+ 0) (setf i (3b-glim/s::attrib-fv +position+ prev)) (%flag +corner-index-flag+ 1) (3b-glim/s::attrib-fv +position+ prev) (3b-glim/s::restore-vertex-copy state (aref primitive-temp 1)) (3b-glim/s::attrib-f +tangent-width+ (aref prev 0) (aref prev 1) (aref prev 2) line-width ) (%flag +corner-index-flag+ 2) (3b-glim/s::attrib-fv +position+ curr) (%flag +corner-index-flag+ 3) (3b-glim/s::attrib-fv +position+ curr) (3b-glim/s:index (+ i 0) (+ i 1) (+ i 2)) (3b-glim/s:index (+ i 0) (+ i 2) (+ i 3)) (setf (primitive-state state) 2)))) (defun write-vertex-line-strip (v) todo : tess and non - smooth width 1 lines after first segment is done , we just update state to ' end of (when (>= (primitive-state *state*) 1) (rotatef (aref (primitive-temp *state*) 0) (aref (primitive-temp *state*) 1)) (setf (primitive-state *state*) 1)) (write-vertex-line v) (replace (line-temp *state*) v)) (defun write-vertex-point (v) (declare (optimize speed) (type (float-vector 4) v)) (check-index-overflow) (let* ((state *state*) (point-size (s:current-point-size state)) (i 0)) (declare (type single-float point-size) (type u16 i)) store width in 4th element of tangent (3b-glim/s::attrib-f +tangent-width+ 0.0 0.0 0.0 point-size) write out vertex 4 times with different corners (%flag +corner-index-flag+ 0) (setf i (3b-glim/s::attrib-fv +position+ v)) (%flag +corner-index-flag+ 1) (3b-glim/s::attrib-fv +position+ v) (%flag +corner-index-flag+ 2) (3b-glim/s::attrib-fv +position+ v) (%flag +corner-index-flag+ 3) (3b-glim/s::attrib-fv +position+ v) (3b-glim/s:index (+ i 0) (+ i 1) (+ i 2)) (3b-glim/s:index (+ i 0) (+ i 2) (+ i 3)))) (defun write-vertex-quad (v) (declare (optimize speed) (type (float-vector 4) v)) (let* ((c (primitive-state *state*)) (c4 (mod c 4)) (i 0)) (declare (type u32 c c4) (type u16 i)) (when (zerop c4) (check-index-overflow)) (%flag +corner-index-flag+ c4) (setf (primitive-state *state*) (mod (1+ c) 4)) (setf i (3b-glim/s:attrib-fv +position+ v)) (when (= c 3) (3b-glim/s:index (- i 3) (- i 2) (- i 1)) (3b-glim/s:index (- i 3) (- i 1) (- i 0))))) (defun write-vertex-quad-strip (v) (declare (optimize speed) (type (float-vector 4) v)) (check-index-overflow) (let* ((state *state*) (primitive-temp (primitive-temp state)) (c (primitive-state state)) (i 0)) (declare (type u32 c) (type u16 i) (type (simple-array t (4)) primitive-temp)) (when (= c 4) when starting a quad after first , duplicate previous 2 vertices (3b-glim/s::copy-current-vertex-into state (aref primitive-temp 2)) (3b-glim/s::restore-vertex-copy state (aref primitive-temp 1)) (%flag +corner-index-flag+ 0) (3b-glim/s::emit-vertex state) (3b-glim/s::restore-vertex-copy state (aref primitive-temp 0)) (%flag +corner-index-flag+ 1) (3b-glim/s::emit-vertex state) (3b-glim/s::restore-vertex-copy state (aref primitive-temp 2)) and skip state to last 2 vertices (setf c 2)) (%flag +corner-index-flag+ c) (setf i (3b-glim/s:attrib-fv +position+ v)) (when (> c 1) (3b-glim/s::copy-current-vertex-into state (aref primitive-temp (- c 2)))) mod 8 so we can distinguish first quad from later quads (setf (primitive-state *state*) (mod (1+ c) 8)) (when (= c 3) (3b-glim/s:index (- i 3) (- i 2) (- i 1)) (3b-glim/s:index (- i 3) (- i 1) (- i 0))))) (defun write-vertex (v) (declare (optimize speed) (type (float-vector 4) v)) (let* ((state *state*) (primitive (car (primitive state))) (primitive-temp (primitive-temp state)) (ps (primitive-state state))) (declare (type u16 ps) (type (simple-array t (4)) primitive-temp)) (flet ((tri-corner (&optional (i ps)) (declare (type u16 i)) (%flag +corner-index-flag+ (mod i 3)) nil)) (ecase primitive ((:triangles) (tri-corner) (when (zerop ps) (check-index-overflow)) (setf ps (mod (+ ps 1) 3)) (setf (primitive-state state) ps) (3b-glim/s:index (3b-glim/s:attrib-fv +position+ v))) (:triangle-strip (tri-corner) (let ((p3 (mod ps 3))) (3b-glim/s::copy-current-vertex-into state (aref primitive-temp p3)) if we restarted a batch , we need to emit previous 2 (when (and (check-index-overflow) (> ps 2)) (3b-glim/s::restore-vertex-copy state (aref primitive-temp (mod (+ p3 1) 3))) (3b-glim/s::emit-vertex state) (3b-glim/s::restore-vertex-copy state (aref primitive-temp (mod (+ p3 2) 3))) (3b-glim/s::emit-vertex state) (3b-glim/s::restore-vertex-copy state (aref primitive-temp p3))) mod 6 so we can distinguish first tri (setf ps (mod (+ ps 1) 6)) (setf (primitive-state state) ps) #++(3b-glim/s:index (3b-glim/s:attrib-fv +position+ v)) (let ((i (3b-glim/s:attrib-fv +position+ v))) (declare (type u16 i)) index 0 and 1 do n't make a triangle , otherwise emit (when (> i 1) ( 3b - glim / s : index ( - i 2 ) ( - i 1 ) i ) (multiple-value-bind (f r) (floor i 2) (3b-glim/s:index (* 2 (+ f (- r 1))) (1- (* f 2)) i)))))) (:triangle-fan (tri-corner) if we restarted a batch , we need to emit previous 2 (when (and (check-index-overflow) (> ps 2)) (3b-glim/s::restore-vertex-copy state (aref primitive-temp 0)) (3b-glim/s::emit-vertex state) (3b-glim/s::restore-vertex-copy state (aref primitive-temp 1)) (3b-glim/s::emit-vertex state) (3b-glim/s::restore-vertex-copy state (aref primitive-temp 2))) (let ((i (3b-glim/s:attrib-fv +position+ v))) (declare (type u16 i)) (3b-glim/s::restore-vertex-copy state (aref primitive-temp ps)) index 0 and 1 do n't make a triangle , otherwise emit (when (> i 1) (3b-glim/s:index 0 (1- i) i)) (setf (primitive-state state) (ecase ps (0 1) (1 2) (2 1))))) (:points (write-vertex-point v)) : lines and line - strips are converted to quads if size /= 1 or if (:lines (write-vertex-line v)) (:line-strip (write-vertex-line-strip v)) (:line-loop ) (:quads (write-vertex-quad v)) (:quad-strip (write-vertex-quad-strip v)))))) (defun %vertex (x y z w) (declare (optimize speed) (type single-float x y z w)) (let ((v (v4 x y z w))) (declare (type (float-vector 4) v) (dynamic-extent v)) (write-vertex v) nil)) (declaim (inline vertex vertex-v)) (defun vertex (x &optional (y 0.0) (z 0.0) (w 1.0)) (%vertex (f x) (f y) (f z) (f w))) (defun vertex-v (v) (etypecase v ((float-vector 4) (%vertex (aref v 0) (aref v 1) (aref v 2) (aref v 3))) ((float-vector 3) (%vertex (aref v 0) (aref v 1) (aref v 2) 1.0)) ((float-vector 2) (%vertex (aref v 0) (aref v 1) 0.0 1.0)) ((float-vector 1) (%vertex (aref v 0) 0.0 0.0 1.0)) (vector (flet ((a (x &optional (d 0.0) ) (if (array-in-bounds-p v x) (aref v x) d))) (vertex (a 0 0.0) (a 1 0.0) (a 2 0.0) (a 3 0.0)))) (list (apply 'vertex v)))) (defun %normal (x y z) (declare (optimize speed) (type single-float x y z)) (3b-glim/s:attrib-f +normal+ x y z)) (declaim (inline normal)) (defun normal (x y z) (%normal (f x) (f y) (f z))) #++ (defun edge-flag (flag) (let ((s (gethash :flags (vertex-format *state*)))) (when s (let ((v (current-vertex *state*))) (setf (aref v (+ (car s) 0)) (if flag 1 0)))))) (defun %multi-tex-coord (tex s tt r q) (declare (optimize speed) (type single-float s tt r q)) (assert (or (eql tex 0)(eql tex :texture0))) (3b-glim/s:attrib-f +texture0+ s tt r q)) (declaim (inline multi-tex-coord tex-coord)) (defun multi-tex-coord (tex s &optional (tt 0.0) (r 0.0) (q 1.0)) (%multi-tex-coord tex (f s) (f tt) (f r) (f q))) (defun tex-coord (s &optional (tt 0.0) (r 0.0) (q 1.0)) (%multi-tex-coord 0 (f s) (f tt) (f r) (f q))) #++ (defun fog-coord (x)) (defun %color (r g b a) (declare (optimize speed) (type single-float r g b a)) (3b-glim/s:attrib-u8sc +color+ r g b a)) (declaim (inline color)) (defun color (r g b &optional (a 1.0)) (%color (f r) (f g) (f b) (f a))) (defun %secondary-color (r g b) (declare (optimize speed) (type single-float r g b)) (3b-glim/s:attrib-u8sc +secondary-color+ r g b)) (declaim (inline secondary-color)) (defun secondary-color (r g b) (%secondary-color (f r) (f g) (f b))) (defun shade-model (model) (setf (%shade-model *state*) model)) (defun light-model (a b) (setf (gethash a (%light-model *state*)) b)) (defun color-material (a b) (setf (gethash a (%color-material *state*)) b)) #++ (defun map-draws (fun draws) (loop for draw in draws do (apply fun draw))) (defun polygon-mode (face mode) (notice-state-changed *state* +state-changed-draw-flags+) (ecase face (:front (ecase mode ((:line :wireframe) (setf (gethash :wireframe (flags *state*)) t) (setf (gethash :filled-wireframe (flags *state*)) nil)) (:fill (setf (gethash :wireframe (flags *state*)) nil) (setf (gethash :filled-wireframe (flags *state*)) nil)) (:filled-wireframe (setf (gethash :wireframe (flags *state*)) nil) (setf (gethash :filled-wireframe (flags *state*)) t)) #++ (:point ))) (:back (ecase mode ((:line :wireframe) (setf (gethash :backface-wireframe (flags *state*)) t) (setf (gethash :backface-filled (flags *state*)) nil) (setf (gethash :backface-filled-wireframe (flags *state*)) nil)) (:fill (setf (gethash :backface-wireframe (flags *state*)) nil) (setf (gethash :backface-filled (flags *state*)) t) (setf (gethash :backface-filled-wireframe (flags *state*)) nil)) (:filled-wireframe (setf (gethash :backface-wireframe (flags *state*)) nil) (setf (gethash :backface-filled (flags *state*)) nil) (setf (gethash :backface-filled-wireframe (flags *state*)) t)))) (:front-and-back (polygon-mode :front mode) (polygon-mode :back mode)))) (defun bind-texture (target name) (notice-state-changed *state* +state-changed-tex+) (setf (aref (textures *state*) (ecase target (:texture-1d 0) (:texture-2d 1) (:texture-3d 2))) name)) (defun light (light pname param) (assert (< -1 light (length (lights *state*)))) (notice-state-changed *state* +state-changed-lighting+) (flet ((v3v () (map 'v3 'f param)) (v4v () (map 'v4 'f param))) (ecase pname (:position (let* ((p (v4v)) (v (sb-cga:vec (aref p 0) (aref p 1) (aref p 2))) (mv (ensure-matrix :modelview))) (if (zerop (aref p 3)) (replace p (sb-cga:transform-direction v mv)) (replace p (sb-cga:transform-point v mv))) (setf (light-position (aref (lights *state*) light)) p))) (:ambient (setf (light-ambient (aref (lights *state*) light)) (v4v))) (:diffuse (setf (light-diffuse (aref (lights *state*) light)) (v4v))) (:specular (setf (light-specular (aref (lights *state*) light)) (v4v))) (:spot-direction (let* ((p (v3v)) (mv (ensure-matrix :modelview))) (setf (light-spot-dir (aref (lights *state*) light)) (sb-cga:transform-direction p mv)))) (:spot-exponent (setf (aref (light-spot-params (aref (lights *state*) light)) 0) (f param))) (:spot-cutoff (setf (aref (light-spot-params (aref (lights *state*) light)) 1) (f param))) (:constant-attenuation (setf (aref (light-attenuation (aref (lights *state*) light)) 0) (f param))) (:linear-attenuation (setf (aref (light-attenuation (aref (lights *state*) light)) 1) (f param))) (:quadratic-attenuation (setf (aref (light-attenuation (aref (lights *state*) light)) 2) (f param))))))
c1a0794a9033ff11387f5780628edd5cb41d574433c58e68887c0ee55462fcd4
obsidiansystems/aeson-gadt-th
TH.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE CPP # # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PatternGuards # # LANGUAGE PatternSynonyms # # LANGUAGE QuasiQuotes # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # # LANGUAGE PolyKinds # module Data.Aeson.GADT.TH ( deriveJSONGADT , deriveToJSONGADT , deriveFromJSONGADT , deriveJSONGADTWithOptions , deriveToJSONGADTWithOptions , deriveFromJSONGADTWithOptions , JSONGADTOptions(JSONGADTOptions, gadtConstructorModifier) , defaultJSONGADTOptions ) where import Control.Monad (forM, replicateM) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Writer (WriterT, runWriterT, tell) import Data.Aeson (FromJSON(..), ToJSON(..)) import Data.List (group, intercalate, partition, sort) import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Data.Some (Some(..)) import Language.Haskell.TH hiding (cxt) import Language.Haskell.TH.Datatype (ConstructorInfo(..), applySubstitution, datatypeCons, reifyDatatype, unifyTypes) import Language.Haskell.TH.Datatype.TyVarBndr (TyVarBndr_, tvName) #if MIN_VERSION_dependent_sum(0,5,0) #else pattern Some :: tag a -> Some tag pattern Some x = This x #endif Do not export this type family , it must remain empty . It 's used as a way to trick GHC into not unifying certain type variables . type family Skolem :: k -> k skolemize :: Set Name -> Type -> Type skolemize rigids t = case t of ForallT bndrs cxt t' -> ForallT bndrs cxt (skolemize (Set.difference rigids (Set.fromList (map tvName bndrs))) t') AppT t1 t2 -> AppT (skolemize rigids t1) (skolemize rigids t2) SigT t1 k -> SigT (skolemize rigids t1) k VarT v -> if Set.member v rigids then AppT (ConT ''Skolem) (VarT v) else t InfixT t1 n t2 -> InfixT (skolemize rigids t1) n (skolemize rigids t2) UInfixT t1 n t2 -> UInfixT (skolemize rigids t1) n (skolemize rigids t2) ParensT t1 -> ParensT (skolemize rigids t1) _ -> t reifyInstancesWithRigids :: Set Name -> Name -> [Type] -> Q [InstanceDec] reifyInstancesWithRigids rigids cls tys = reifyInstances cls (map (skolemize rigids) tys) -- | Determine the type variables which occur freely in a type. freeTypeVariables :: Type -> Set Name freeTypeVariables t = case t of ForallT bndrs _ t' -> Set.difference (freeTypeVariables t') (Set.fromList (map tvName bndrs)) AppT t1 t2 -> Set.union (freeTypeVariables t1) (freeTypeVariables t2) SigT t1 _ -> freeTypeVariables t1 VarT n -> Set.singleton n _ -> Set.empty newtype JSONGADTOptions = JSONGADTOptions { gadtConstructorModifier :: String -> String } defaultJSONGADTOptions :: JSONGADTOptions defaultJSONGADTOptions = JSONGADTOptions { gadtConstructorModifier = id } | Derive ' ToJSON ' and ' FromJSON ' instances for the named GADT deriveJSONGADT :: Name -> DecsQ deriveJSONGADT = deriveJSONGADTWithOptions defaultJSONGADTOptions deriveJSONGADTWithOptions :: JSONGADTOptions -> Name -> DecsQ deriveJSONGADTWithOptions opts n = do tj <- deriveToJSONGADTWithOptions opts n fj <- deriveFromJSONGADTWithOptions opts n return (tj ++ fj) deriveToJSONGADT :: Name -> DecsQ deriveToJSONGADT = deriveToJSONGADTWithOptions defaultJSONGADTOptions deriveToJSONGADTWithOptions :: JSONGADTOptions -> Name -> DecsQ deriveToJSONGADTWithOptions opts n = do info <- reifyDatatype n let cons = datatypeCons info topVars <- makeTopVars n let n' = foldl (\c v -> AppT c (VarT v)) (ConT n) topVars (matches, constraints') <- runWriterT (mapM (fmap pure . conMatchesToJSON opts topVars) cons) let constraints = map head . group . sort $ constraints' -- This 'head' is safe because 'group' returns a list of non-empty lists impl <- funD 'toJSON [ clause [] (normalB $ lamCaseE matches) [] ] return [ InstanceD Nothing constraints (AppT (ConT ''ToJSON) n') [impl] ] makeTopVars :: Name -> Q [Name] makeTopVars tyConName = do (tyVarBndrs, kArity) <- tyConArity' tyConName extraVars <- replicateM kArity (newName "topvar") return (map tvName tyVarBndrs ++ extraVars) deriveFromJSONGADT :: Name -> DecsQ deriveFromJSONGADT = deriveFromJSONGADTWithOptions defaultJSONGADTOptions deriveFromJSONGADTWithOptions :: JSONGADTOptions -> Name -> DecsQ deriveFromJSONGADTWithOptions opts n = do info <- reifyDatatype n let cons = datatypeCons info allConNames = intercalate ", " $ map (gadtConstructorModifier opts . nameBase . constructorName) cons wildName <- newName "s" let wild = match (varP wildName) (normalB [e| fail $ "Expected tag to be one of [" ++ allConNames ++ "] but got: " ++ $(varE wildName) |]) [] topVars <- makeTopVars n let n' = foldl (\c v -> AppT c (VarT v)) (ConT n) $ init topVars (matches, constraints') <- runWriterT $ mapM (conMatchesParseJSON opts topVars [|_v'|]) cons let constraints = map head . group . sort $ constraints' -- This 'head' is safe because 'group' returns a list of non-empty lists v <- newName "v" parser <- funD 'parseJSON [ clause [varP v] (normalB [e| do (tag', _v') <- parseJSON $(varE v) $(caseE [|tag' :: String|] $ map pure matches ++ [wild]) |]) [] ] return [ InstanceD Nothing constraints (AppT (ConT ''FromJSON) (AppT (ConT ''Some) n')) [parser] ] splitTopVars :: [Name] -> (Set Name, Name) splitTopVars allTopVars = case reverse allTopVars of (x:xs) -> (Set.fromList xs, x) _ -> error "splitTopVars: Empty set of variables" | Implementation of ' toJSON ' conMatchesToJSON :: JSONGADTOptions -> [Name] -> ConstructorInfo -> WriterT [Type] Q Match conMatchesToJSON opts allTopVars c = do let (topVars, lastVar) = splitTopVars allTopVars name = constructorName c base = gadtConstructorModifier opts $ nameBase name toJSONExp e = [| toJSON $(e) |] vars <- lift . forM (constructorFields c) $ \_ -> newName "x" let body = toJSONExp $ tupE [ [| base :: String |] -- The singleton is special-cased because of -- -rc1/docs/html/users_guide/8.10.1-notes.html#template-haskell , case vars of [v] -> toJSONExp $ varE v vs -> tupE $ map (toJSONExp . varE) vs ] _ <- conMatches ''ToJSON topVars lastVar c lift $ match (conP name (map varP vars)) (normalB body) [] -- | Implementation of 'parseJSON' conMatchesParseJSON :: JSONGADTOptions -> [Name] -> ExpQ -> ConstructorInfo -> WriterT [Type] Q Match conMatchesParseJSON opts allTopVars e c = do let (topVars, lastVar) = splitTopVars allTopVars (pat, conApp) <- conMatches ''FromJSON topVars lastVar c let match' = match (litP (StringL (gadtConstructorModifier opts $ nameBase (constructorName c)))) body = doE [ bindS (return pat) [| parseJSON $e |] , noBindS [| return (Some $(return conApp)) |] ] lift $ match' (normalB body) [] conMatches ^ Name of class ( '' ToJSON or '' FromJSON ) -> Set Name -- Names of variables used in the instance head in argument order -> Name -- Final type variable (the index type) -> ConstructorInfo -> WriterT [Type] Q (Pat, Exp) conMatches clsName topVars ixVar c = do let name = constructorName c types = constructorFields c (constraints, equalities') = flip partition (constructorContext c) $ \case AppT (AppT EqualityT _) _ -> False _ -> True equalities = concat [ [(a, b), (b, a)] | AppT (AppT EqualityT a) b <- equalities' ] unifiedEqualities :: [Map Name Type] <- lift $ forM equalities $ \(a, b) -> unifyTypes [a, b] let rigidImplications :: Map Name (Set Name) rigidImplications = Map.unionsWith Set.union $ fmap freeTypeVariables <$> unifiedEqualities let expandRigids :: Set Name -> Set Name expandRigids rigids = Set.union rigids $ Set.unions $ Map.elems $ restrictKeys rigidImplications rigids expandRigidsFully rigids = let rigids' = expandRigids rigids in if rigids' == rigids then rigids else expandRigidsFully rigids' rigidVars = expandRigidsFully topVars ixSpecialization :: Map Name Type ixSpecialization = restrictKeys (Map.unions unifiedEqualities) $ Set.singleton ixVar -- We filter out constraints which don't mention variables from the instance head mostly to avoid warnings, but a good deal more of these occur than one might expect due to the normalisation done by reifyDatatype . tellCxt cs = do tell $ applySubstitution ixSpecialization cs tellCxt constraints vars <- forM types $ \typ -> do x <- lift $ newName "x" let demandInstanceIfNecessary = do insts <- lift $ reifyInstancesWithRigids rigidVars clsName [typ] case insts of [] -> tellCxt [AppT (ConT clsName) typ] [InstanceD _ cxt (AppT _className ityp) _] -> do sub <- lift $ unifyTypes [ityp, typ] tellCxt $ applySubstitution sub cxt _ -> error $ "The following instances of " ++ show clsName ++ " for " ++ show typ ++ " exist (rigids: " ++ unwords (map show $ Set.toList rigidVars) ++ "), and I don't know which to pick:\n" ++ unlines (map (show . ppr) insts) case typ of AppT tn (VarT _) -> do This may be a nested GADT , so check for special FromJSON instance insts <- lift $ reifyInstancesWithRigids rigidVars clsName [AppT (ConT ''Some) tn] case insts of [] -> do -- No special instance, try to check the type for a straightforward one, since if we don't have one, we need to demand it. demandInstanceIfNecessary return (VarP x, VarE x) [InstanceD _ cxt (AppT _className (AppT (ConT _some) ityp)) _] -> do sub <- lift $ unifyTypes [ityp, tn] tellCxt $ applySubstitution sub cxt return (ConP 'Some [VarP x], VarE x) _ -> error $ "The following instances of " ++ show clsName ++ " for " ++ show (ppr [AppT (ConT ''Some) tn]) ++ " exist (rigids: " ++ unwords (map show $ Set.toList rigidVars) ++ "), and I don't know which to pick:\n" ++ unlines (map (show . ppr) insts) _ -> do demandInstanceIfNecessary return (VarP x, VarE x) -- The singleton is special-cased because of -- -rc1/docs/html/users_guide/8.10.1-notes.html#template-haskell let pat = case vars of [v] -> fst v vs -> TupP (map fst vs) conApp = foldl AppE (ConE name) (map snd vars) return (pat, conApp) ----------------------------------------------------------------------------------------------------- -- | Determine the arity of a kind. kindArity :: Kind -> Int kindArity = \case ForallT _ _ t -> kindArity t AppT (AppT ArrowT _) t -> 1 + kindArity t SigT t _ -> kindArity t ParensT t -> kindArity t _ -> 0 -- | Given the name of a type constructor, determine a list of type variables bound as parameters by -- its declaration, and the arity of the kind of type being defined (i.e. how many more arguments would -- need to be supplied in addition to the bound parameters in order to obtain an ordinary type of kind *). -- If the supplied 'Name' is anything other than a data or newtype, produces an error. tyConArity' :: Name -> Q ([TyVarBndr_ ()], Int) tyConArity' n = reify n >>= return . \case TyConI (DataD _ _ ts mk _ _) -> (ts, maybe 0 kindArity mk) TyConI (NewtypeD _ _ ts mk _ _) -> (ts, maybe 0 kindArity mk) _ -> error $ "tyConArity': Supplied name reified to something other than a data declaration: " ++ show n ----------------------------------------------------------------------------------------------------- restrictKeys :: Ord k => Map k v -> Set k -> Map k v restrictKeys m s = #if MIN_VERSION_containers(0,5,8) Map.restrictKeys m s #else Map.intersection m $ Map.fromSet (const ()) s #endif
null
https://raw.githubusercontent.com/obsidiansystems/aeson-gadt-th/7d2cdd0c666dc0e4feddbfcc5bd2425c4af33f3e/src/Data/Aeson/GADT/TH.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE GADTs # # LANGUAGE RankNTypes # | Determine the type variables which occur freely in a type. This 'head' is safe because 'group' returns a list of non-empty lists This 'head' is safe because 'group' returns a list of non-empty lists The singleton is special-cased because of -rc1/docs/html/users_guide/8.10.1-notes.html#template-haskell | Implementation of 'parseJSON' Names of variables used in the instance head in argument order Final type variable (the index type) We filter out constraints which don't mention variables from the instance head mostly to avoid warnings, No special instance, try to check the type for a straightforward one, since if we don't have one, we need to demand it. The singleton is special-cased because of -rc1/docs/html/users_guide/8.10.1-notes.html#template-haskell --------------------------------------------------------------------------------------------------- | Determine the arity of a kind. | Given the name of a type constructor, determine a list of type variables bound as parameters by its declaration, and the arity of the kind of type being defined (i.e. how many more arguments would need to be supplied in addition to the bound parameters in order to obtain an ordinary type of kind *). If the supplied 'Name' is anything other than a data or newtype, produces an error. ---------------------------------------------------------------------------------------------------
# LANGUAGE CPP # # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PatternGuards # # LANGUAGE PatternSynonyms # # LANGUAGE QuasiQuotes # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # # LANGUAGE PolyKinds # module Data.Aeson.GADT.TH ( deriveJSONGADT , deriveToJSONGADT , deriveFromJSONGADT , deriveJSONGADTWithOptions , deriveToJSONGADTWithOptions , deriveFromJSONGADTWithOptions , JSONGADTOptions(JSONGADTOptions, gadtConstructorModifier) , defaultJSONGADTOptions ) where import Control.Monad (forM, replicateM) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Writer (WriterT, runWriterT, tell) import Data.Aeson (FromJSON(..), ToJSON(..)) import Data.List (group, intercalate, partition, sort) import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Data.Some (Some(..)) import Language.Haskell.TH hiding (cxt) import Language.Haskell.TH.Datatype (ConstructorInfo(..), applySubstitution, datatypeCons, reifyDatatype, unifyTypes) import Language.Haskell.TH.Datatype.TyVarBndr (TyVarBndr_, tvName) #if MIN_VERSION_dependent_sum(0,5,0) #else pattern Some :: tag a -> Some tag pattern Some x = This x #endif Do not export this type family , it must remain empty . It 's used as a way to trick GHC into not unifying certain type variables . type family Skolem :: k -> k skolemize :: Set Name -> Type -> Type skolemize rigids t = case t of ForallT bndrs cxt t' -> ForallT bndrs cxt (skolemize (Set.difference rigids (Set.fromList (map tvName bndrs))) t') AppT t1 t2 -> AppT (skolemize rigids t1) (skolemize rigids t2) SigT t1 k -> SigT (skolemize rigids t1) k VarT v -> if Set.member v rigids then AppT (ConT ''Skolem) (VarT v) else t InfixT t1 n t2 -> InfixT (skolemize rigids t1) n (skolemize rigids t2) UInfixT t1 n t2 -> UInfixT (skolemize rigids t1) n (skolemize rigids t2) ParensT t1 -> ParensT (skolemize rigids t1) _ -> t reifyInstancesWithRigids :: Set Name -> Name -> [Type] -> Q [InstanceDec] reifyInstancesWithRigids rigids cls tys = reifyInstances cls (map (skolemize rigids) tys) freeTypeVariables :: Type -> Set Name freeTypeVariables t = case t of ForallT bndrs _ t' -> Set.difference (freeTypeVariables t') (Set.fromList (map tvName bndrs)) AppT t1 t2 -> Set.union (freeTypeVariables t1) (freeTypeVariables t2) SigT t1 _ -> freeTypeVariables t1 VarT n -> Set.singleton n _ -> Set.empty newtype JSONGADTOptions = JSONGADTOptions { gadtConstructorModifier :: String -> String } defaultJSONGADTOptions :: JSONGADTOptions defaultJSONGADTOptions = JSONGADTOptions { gadtConstructorModifier = id } | Derive ' ToJSON ' and ' FromJSON ' instances for the named GADT deriveJSONGADT :: Name -> DecsQ deriveJSONGADT = deriveJSONGADTWithOptions defaultJSONGADTOptions deriveJSONGADTWithOptions :: JSONGADTOptions -> Name -> DecsQ deriveJSONGADTWithOptions opts n = do tj <- deriveToJSONGADTWithOptions opts n fj <- deriveFromJSONGADTWithOptions opts n return (tj ++ fj) deriveToJSONGADT :: Name -> DecsQ deriveToJSONGADT = deriveToJSONGADTWithOptions defaultJSONGADTOptions deriveToJSONGADTWithOptions :: JSONGADTOptions -> Name -> DecsQ deriveToJSONGADTWithOptions opts n = do info <- reifyDatatype n let cons = datatypeCons info topVars <- makeTopVars n let n' = foldl (\c v -> AppT c (VarT v)) (ConT n) topVars (matches, constraints') <- runWriterT (mapM (fmap pure . conMatchesToJSON opts topVars) cons) impl <- funD 'toJSON [ clause [] (normalB $ lamCaseE matches) [] ] return [ InstanceD Nothing constraints (AppT (ConT ''ToJSON) n') [impl] ] makeTopVars :: Name -> Q [Name] makeTopVars tyConName = do (tyVarBndrs, kArity) <- tyConArity' tyConName extraVars <- replicateM kArity (newName "topvar") return (map tvName tyVarBndrs ++ extraVars) deriveFromJSONGADT :: Name -> DecsQ deriveFromJSONGADT = deriveFromJSONGADTWithOptions defaultJSONGADTOptions deriveFromJSONGADTWithOptions :: JSONGADTOptions -> Name -> DecsQ deriveFromJSONGADTWithOptions opts n = do info <- reifyDatatype n let cons = datatypeCons info allConNames = intercalate ", " $ map (gadtConstructorModifier opts . nameBase . constructorName) cons wildName <- newName "s" let wild = match (varP wildName) (normalB [e| fail $ "Expected tag to be one of [" ++ allConNames ++ "] but got: " ++ $(varE wildName) |]) [] topVars <- makeTopVars n let n' = foldl (\c v -> AppT c (VarT v)) (ConT n) $ init topVars (matches, constraints') <- runWriterT $ mapM (conMatchesParseJSON opts topVars [|_v'|]) cons v <- newName "v" parser <- funD 'parseJSON [ clause [varP v] (normalB [e| do (tag', _v') <- parseJSON $(varE v) $(caseE [|tag' :: String|] $ map pure matches ++ [wild]) |]) [] ] return [ InstanceD Nothing constraints (AppT (ConT ''FromJSON) (AppT (ConT ''Some) n')) [parser] ] splitTopVars :: [Name] -> (Set Name, Name) splitTopVars allTopVars = case reverse allTopVars of (x:xs) -> (Set.fromList xs, x) _ -> error "splitTopVars: Empty set of variables" | Implementation of ' toJSON ' conMatchesToJSON :: JSONGADTOptions -> [Name] -> ConstructorInfo -> WriterT [Type] Q Match conMatchesToJSON opts allTopVars c = do let (topVars, lastVar) = splitTopVars allTopVars name = constructorName c base = gadtConstructorModifier opts $ nameBase name toJSONExp e = [| toJSON $(e) |] vars <- lift . forM (constructorFields c) $ \_ -> newName "x" let body = toJSONExp $ tupE [ [| base :: String |] , case vars of [v] -> toJSONExp $ varE v vs -> tupE $ map (toJSONExp . varE) vs ] _ <- conMatches ''ToJSON topVars lastVar c lift $ match (conP name (map varP vars)) (normalB body) [] conMatchesParseJSON :: JSONGADTOptions -> [Name] -> ExpQ -> ConstructorInfo -> WriterT [Type] Q Match conMatchesParseJSON opts allTopVars e c = do let (topVars, lastVar) = splitTopVars allTopVars (pat, conApp) <- conMatches ''FromJSON topVars lastVar c let match' = match (litP (StringL (gadtConstructorModifier opts $ nameBase (constructorName c)))) body = doE [ bindS (return pat) [| parseJSON $e |] , noBindS [| return (Some $(return conApp)) |] ] lift $ match' (normalB body) [] conMatches ^ Name of class ( '' ToJSON or '' FromJSON ) -> ConstructorInfo -> WriterT [Type] Q (Pat, Exp) conMatches clsName topVars ixVar c = do let name = constructorName c types = constructorFields c (constraints, equalities') = flip partition (constructorContext c) $ \case AppT (AppT EqualityT _) _ -> False _ -> True equalities = concat [ [(a, b), (b, a)] | AppT (AppT EqualityT a) b <- equalities' ] unifiedEqualities :: [Map Name Type] <- lift $ forM equalities $ \(a, b) -> unifyTypes [a, b] let rigidImplications :: Map Name (Set Name) rigidImplications = Map.unionsWith Set.union $ fmap freeTypeVariables <$> unifiedEqualities let expandRigids :: Set Name -> Set Name expandRigids rigids = Set.union rigids $ Set.unions $ Map.elems $ restrictKeys rigidImplications rigids expandRigidsFully rigids = let rigids' = expandRigids rigids in if rigids' == rigids then rigids else expandRigidsFully rigids' rigidVars = expandRigidsFully topVars ixSpecialization :: Map Name Type ixSpecialization = restrictKeys (Map.unions unifiedEqualities) $ Set.singleton ixVar but a good deal more of these occur than one might expect due to the normalisation done by reifyDatatype . tellCxt cs = do tell $ applySubstitution ixSpecialization cs tellCxt constraints vars <- forM types $ \typ -> do x <- lift $ newName "x" let demandInstanceIfNecessary = do insts <- lift $ reifyInstancesWithRigids rigidVars clsName [typ] case insts of [] -> tellCxt [AppT (ConT clsName) typ] [InstanceD _ cxt (AppT _className ityp) _] -> do sub <- lift $ unifyTypes [ityp, typ] tellCxt $ applySubstitution sub cxt _ -> error $ "The following instances of " ++ show clsName ++ " for " ++ show typ ++ " exist (rigids: " ++ unwords (map show $ Set.toList rigidVars) ++ "), and I don't know which to pick:\n" ++ unlines (map (show . ppr) insts) case typ of AppT tn (VarT _) -> do This may be a nested GADT , so check for special FromJSON instance insts <- lift $ reifyInstancesWithRigids rigidVars clsName [AppT (ConT ''Some) tn] case insts of [] -> do demandInstanceIfNecessary return (VarP x, VarE x) [InstanceD _ cxt (AppT _className (AppT (ConT _some) ityp)) _] -> do sub <- lift $ unifyTypes [ityp, tn] tellCxt $ applySubstitution sub cxt return (ConP 'Some [VarP x], VarE x) _ -> error $ "The following instances of " ++ show clsName ++ " for " ++ show (ppr [AppT (ConT ''Some) tn]) ++ " exist (rigids: " ++ unwords (map show $ Set.toList rigidVars) ++ "), and I don't know which to pick:\n" ++ unlines (map (show . ppr) insts) _ -> do demandInstanceIfNecessary return (VarP x, VarE x) let pat = case vars of [v] -> fst v vs -> TupP (map fst vs) conApp = foldl AppE (ConE name) (map snd vars) return (pat, conApp) kindArity :: Kind -> Int kindArity = \case ForallT _ _ t -> kindArity t AppT (AppT ArrowT _) t -> 1 + kindArity t SigT t _ -> kindArity t ParensT t -> kindArity t _ -> 0 tyConArity' :: Name -> Q ([TyVarBndr_ ()], Int) tyConArity' n = reify n >>= return . \case TyConI (DataD _ _ ts mk _ _) -> (ts, maybe 0 kindArity mk) TyConI (NewtypeD _ _ ts mk _ _) -> (ts, maybe 0 kindArity mk) _ -> error $ "tyConArity': Supplied name reified to something other than a data declaration: " ++ show n restrictKeys :: Ord k => Map k v -> Set k -> Map k v restrictKeys m s = #if MIN_VERSION_containers(0,5,8) Map.restrictKeys m s #else Map.intersection m $ Map.fromSet (const ()) s #endif
e517014327c431c54347129c84a66a84b9a0d2500335db00a1fd578aa4f3620a
ivan-m/graphviz
X11.hs
{-# LANGUAGE OverloadedStrings #-} | Module : Data . GraphViz . Attributes . Colors . X11 Description : Specification of X11 colors . Copyright : ( c ) License : 3 - Clause BSD - style Maintainer : Graphviz 's definition of X11 colors differs from the \"normal\ " list installed on many systems at @/usr / share / X11 / rgb.txt@. For example , @Crimson@ is not a usual X11 color . Furthermore , all @Gray*@ colors are duplicated with @Grey*@ names . To simplify this , these duplicates have been removed but ' X11Color 's with " ( whether they have the duplicate spelling or not ) in their name are also parseable as if they were spelt with \"@grey@\ " . The complete list of X11 colors can be found at < #x11 > . Module : Data.GraphViz.Attributes.Colors.X11 Description : Specification of X11 colors. Copyright : (c) Ivan Lazar Miljenovic License : 3-Clause BSD-style Maintainer : Graphviz's definition of X11 colors differs from the \"normal\" list installed on many systems at @/usr/share/X11/rgb.txt@. For example, @Crimson@ is not a usual X11 color. Furthermore, all @Gray*@ colors are duplicated with @Grey*@ names. To simplify this, these duplicates have been removed but /all/ 'X11Color's with \"@Gray@\" (whether they have the duplicate spelling or not) in their name are also parseable as if they were spelt with \"@grey@\". The complete list of X11 colors can be found at <#x11>. -} module Data.GraphViz.Attributes.Colors.X11 ( X11Color(..) , x11Colour ) where import Data.GraphViz.Parsing import Data.GraphViz.Printing import Data.Colour( AlphaColour, opaque, transparent) import Data.Colour.SRGB(sRGB24) -- ----------------------------------------------------------------------------- | The X11 colors that Graphviz uses . Note that these are slightly -- different from the \"normal\" X11 colors used (e.g. the inclusion of @Crimson@ ) . Graphviz 's list of colors also duplicated almost all @Gray@ colors with @Grey@ ones ; parsing of an ' X11Color ' which is specified using \"grey\ " will succeed , even for those that do n't have the duplicate spelling ( e.g. @DarkSlateGray1@ ) . data X11Color = AliceBlue | AntiqueWhite | AntiqueWhite1 | AntiqueWhite2 | AntiqueWhite3 | AntiqueWhite4 | Aquamarine | Aquamarine1 | Aquamarine2 | Aquamarine3 | Aquamarine4 | Azure | Azure1 | Azure2 | Azure3 | Azure4 | Beige | Bisque | Bisque1 | Bisque2 | Bisque3 | Bisque4 | Black | BlanchedAlmond | Blue | Blue1 | Blue2 | Blue3 | Blue4 | BlueViolet | Brown | Brown1 | Brown2 | Brown3 | Brown4 | Burlywood | Burlywood1 | Burlywood2 | Burlywood3 | Burlywood4 | CadetBlue | CadetBlue1 | CadetBlue2 | CadetBlue3 | CadetBlue4 | Chartreuse | Chartreuse1 | Chartreuse2 | Chartreuse3 | Chartreuse4 | Chocolate | Chocolate1 | Chocolate2 | Chocolate3 | Chocolate4 | Coral | Coral1 | Coral2 | Coral3 | Coral4 | CornFlowerBlue | CornSilk | CornSilk1 | CornSilk2 | CornSilk3 | CornSilk4 | Crimson | Cyan | Cyan1 | Cyan2 | Cyan3 | Cyan4 | DarkGoldenrod | DarkGoldenrod1 | DarkGoldenrod2 | DarkGoldenrod3 | DarkGoldenrod4 | DarkGreen | Darkkhaki | DarkOliveGreen | DarkOliveGreen1 | DarkOliveGreen2 | DarkOliveGreen3 | DarkOliveGreen4 | DarkOrange | DarkOrange1 | DarkOrange2 | DarkOrange3 | DarkOrange4 | DarkOrchid | DarkOrchid1 | DarkOrchid2 | DarkOrchid3 | DarkOrchid4 | DarkSalmon | DarkSeaGreen | DarkSeaGreen1 | DarkSeaGreen2 | DarkSeaGreen3 | DarkSeaGreen4 | DarkSlateBlue | DarkSlateGray | DarkSlateGray1 | DarkSlateGray2 | DarkSlateGray3 | DarkSlateGray4 | DarkTurquoise | DarkViolet | DeepPink | DeepPink1 | DeepPink2 | DeepPink3 | DeepPink4 | DeepSkyBlue | DeepSkyBlue1 | DeepSkyBlue2 | DeepSkyBlue3 | DeepSkyBlue4 | DimGray | DodgerBlue | DodgerBlue1 | DodgerBlue2 | DodgerBlue3 | DodgerBlue4 | Firebrick | Firebrick1 | Firebrick2 | Firebrick3 | Firebrick4 | FloralWhite | ForestGreen | Gainsboro | GhostWhite | Gold | Gold1 | Gold2 | Gold3 | Gold4 | Goldenrod | Goldenrod1 | Goldenrod2 | Goldenrod3 | Goldenrod4 | Gray | Gray0 | Gray1 | Gray2 | Gray3 | Gray4 | Gray5 | Gray6 | Gray7 | Gray8 | Gray9 | Gray10 | Gray11 | Gray12 | Gray13 | Gray14 | Gray15 | Gray16 | Gray17 | Gray18 | Gray19 | Gray20 | Gray21 | Gray22 | Gray23 | Gray24 | Gray25 | Gray26 | Gray27 | Gray28 | Gray29 | Gray30 | Gray31 | Gray32 | Gray33 | Gray34 | Gray35 | Gray36 | Gray37 | Gray38 | Gray39 | Gray40 | Gray41 | Gray42 | Gray43 | Gray44 | Gray45 | Gray46 | Gray47 | Gray48 | Gray49 | Gray50 | Gray51 | Gray52 | Gray53 | Gray54 | Gray55 | Gray56 | Gray57 | Gray58 | Gray59 | Gray60 | Gray61 | Gray62 | Gray63 | Gray64 | Gray65 | Gray66 | Gray67 | Gray68 | Gray69 | Gray70 | Gray71 | Gray72 | Gray73 | Gray74 | Gray75 | Gray76 | Gray77 | Gray78 | Gray79 | Gray80 | Gray81 | Gray82 | Gray83 | Gray84 | Gray85 | Gray86 | Gray87 | Gray88 | Gray89 | Gray90 | Gray91 | Gray92 | Gray93 | Gray94 | Gray95 | Gray96 | Gray97 | Gray98 | Gray99 | Gray100 | Green | Green1 | Green2 | Green3 | Green4 | GreenYellow | HoneyDew | HoneyDew1 | HoneyDew2 | HoneyDew3 | HoneyDew4 | HotPink | HotPink1 | HotPink2 | HotPink3 | HotPink4 | IndianRed | IndianRed1 | IndianRed2 | IndianRed3 | IndianRed4 | Indigo | Ivory | Ivory1 | Ivory2 | Ivory3 | Ivory4 | Khaki | Khaki1 | Khaki2 | Khaki3 | Khaki4 | Lavender | LavenderBlush | LavenderBlush1 | LavenderBlush2 | LavenderBlush3 | LavenderBlush4 | LawnGreen | LemonChiffon | LemonChiffon1 | LemonChiffon2 | LemonChiffon3 | LemonChiffon4 | LightBlue | LightBlue1 | LightBlue2 | LightBlue3 | LightBlue4 | LightCoral | LightCyan | LightCyan1 | LightCyan2 | LightCyan3 | LightCyan4 | LightGoldenrod | LightGoldenrod1 | LightGoldenrod2 | LightGoldenrod3 | LightGoldenrod4 | LightGoldenrodYellow | LightGray | LightPink | LightPink1 | LightPink2 | LightPink3 | LightPink4 | LightSalmon | LightSalmon1 | LightSalmon2 | LightSalmon3 | LightSalmon4 | LightSeaGreen | LightSkyBlue | LightSkyBlue1 | LightSkyBlue2 | LightSkyBlue3 | LightSkyBlue4 | LightSlateBlue | LightSlateGray | LightSteelBlue | LightSteelBlue1 | LightSteelBlue2 | LightSteelBlue3 | LightSteelBlue4 | LightYellow | LightYellow1 | LightYellow2 | LightYellow3 | LightYellow4 | LimeGreen | Linen | Magenta | Magenta1 | Magenta2 | Magenta3 | Magenta4 | Maroon | Maroon1 | Maroon2 | Maroon3 | Maroon4 | MediumAquamarine | MediumBlue | MediumOrchid | MediumOrchid1 | MediumOrchid2 | MediumOrchid3 | MediumOrchid4 | MediumPurple | MediumPurple1 | MediumPurple2 | MediumPurple3 | MediumPurple4 | MediumSeaGreen | MediumSlateBlue | MediumSpringGreen | MediumTurquoise | MediumVioletRed | MidnightBlue | MintCream | MistyRose | MistyRose1 | MistyRose2 | MistyRose3 | MistyRose4 | Moccasin | NavajoWhite | NavajoWhite1 | NavajoWhite2 | NavajoWhite3 | NavajoWhite4 | Navy | NavyBlue | OldLace | OliveDrab | OliveDrab1 | OliveDrab2 | OliveDrab3 | OliveDrab4 | Orange | Orange1 | Orange2 | Orange3 | Orange4 | OrangeRed | OrangeRed1 | OrangeRed2 | OrangeRed3 | OrangeRed4 | Orchid | Orchid1 | Orchid2 | Orchid3 | Orchid4 | PaleGoldenrod | PaleGreen | PaleGreen1 | PaleGreen2 | PaleGreen3 | PaleGreen4 | PaleTurquoise | PaleTurquoise1 | PaleTurquoise2 | PaleTurquoise3 | PaleTurquoise4 | PaleVioletRed | PaleVioletRed1 | PaleVioletRed2 | PaleVioletRed3 | PaleVioletRed4 | PapayaWhip | PeachPuff | PeachPuff1 | PeachPuff2 | PeachPuff3 | PeachPuff4 | Peru | Pink | Pink1 | Pink2 | Pink3 | Pink4 | Plum | Plum1 | Plum2 | Plum3 | Plum4 | PowderBlue | Purple | Purple1 | Purple2 | Purple3 | Purple4 | Red | Red1 | Red2 | Red3 | Red4 | RosyBrown | RosyBrown1 | RosyBrown2 | RosyBrown3 | RosyBrown4 | RoyalBlue | RoyalBlue1 | RoyalBlue2 | RoyalBlue3 | RoyalBlue4 | SaddleBrown | Salmon | Salmon1 | Salmon2 | Salmon3 | Salmon4 | SandyBrown | SeaGreen | SeaGreen1 | SeaGreen2 | SeaGreen3 | SeaGreen4 | SeaShell | SeaShell1 | SeaShell2 | SeaShell3 | SeaShell4 | Sienna | Sienna1 | Sienna2 | Sienna3 | Sienna4 | SkyBlue | SkyBlue1 | SkyBlue2 | SkyBlue3 | SkyBlue4 | SlateBlue | SlateBlue1 | SlateBlue2 | SlateBlue3 | SlateBlue4 | SlateGray | SlateGray1 | SlateGray2 | SlateGray3 | SlateGray4 | Snow | Snow1 | Snow2 | Snow3 | Snow4 | SpringGreen | SpringGreen1 | SpringGreen2 | SpringGreen3 | SpringGreen4 | SteelBlue | SteelBlue1 | SteelBlue2 | SteelBlue3 | SteelBlue4 | Tan | Tan1 | Tan2 | Tan3 | Tan4 | Thistle | Thistle1 | Thistle2 | Thistle3 | Thistle4 | Tomato | Tomato1 | Tomato2 | Tomato3 | Tomato4 ^ Equivalent to setting [ SItem Invisible [ ] ] @. | Turquoise | Turquoise1 | Turquoise2 | Turquoise3 | Turquoise4 | Violet | VioletRed | VioletRed1 | VioletRed2 | VioletRed3 | VioletRed4 | Wheat | Wheat1 | Wheat2 | Wheat3 | Wheat4 | White | WhiteSmoke | Yellow | Yellow1 | Yellow2 | Yellow3 | Yellow4 | YellowGreen deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot X11Color where unqtDot AliceBlue = unqtText "aliceblue" unqtDot AntiqueWhite = unqtText "antiquewhite" unqtDot AntiqueWhite1 = unqtText "antiquewhite1" unqtDot AntiqueWhite2 = unqtText "antiquewhite2" unqtDot AntiqueWhite3 = unqtText "antiquewhite3" unqtDot AntiqueWhite4 = unqtText "antiquewhite4" unqtDot Aquamarine = unqtText "aquamarine" unqtDot Aquamarine1 = unqtText "aquamarine1" unqtDot Aquamarine2 = unqtText "aquamarine2" unqtDot Aquamarine3 = unqtText "aquamarine3" unqtDot Aquamarine4 = unqtText "aquamarine4" unqtDot Azure = unqtText "azure" unqtDot Azure1 = unqtText "azure1" unqtDot Azure2 = unqtText "azure2" unqtDot Azure3 = unqtText "azure3" unqtDot Azure4 = unqtText "azure4" unqtDot Beige = unqtText "beige" unqtDot Bisque = unqtText "bisque" unqtDot Bisque1 = unqtText "bisque1" unqtDot Bisque2 = unqtText "bisque2" unqtDot Bisque3 = unqtText "bisque3" unqtDot Bisque4 = unqtText "bisque4" unqtDot Black = unqtText "black" unqtDot BlanchedAlmond = unqtText "blanchedalmond" unqtDot Blue = unqtText "blue" unqtDot Blue1 = unqtText "blue1" unqtDot Blue2 = unqtText "blue2" unqtDot Blue3 = unqtText "blue3" unqtDot Blue4 = unqtText "blue4" unqtDot BlueViolet = unqtText "blueviolet" unqtDot Brown = unqtText "brown" unqtDot Brown1 = unqtText "brown1" unqtDot Brown2 = unqtText "brown2" unqtDot Brown3 = unqtText "brown3" unqtDot Brown4 = unqtText "brown4" unqtDot Burlywood = unqtText "burlywood" unqtDot Burlywood1 = unqtText "burlywood1" unqtDot Burlywood2 = unqtText "burlywood2" unqtDot Burlywood3 = unqtText "burlywood3" unqtDot Burlywood4 = unqtText "burlywood4" unqtDot CadetBlue = unqtText "cadetblue" unqtDot CadetBlue1 = unqtText "cadetblue1" unqtDot CadetBlue2 = unqtText "cadetblue2" unqtDot CadetBlue3 = unqtText "cadetblue3" unqtDot CadetBlue4 = unqtText "cadetblue4" unqtDot Chartreuse = unqtText "chartreuse" unqtDot Chartreuse1 = unqtText "chartreuse1" unqtDot Chartreuse2 = unqtText "chartreuse2" unqtDot Chartreuse3 = unqtText "chartreuse3" unqtDot Chartreuse4 = unqtText "chartreuse4" unqtDot Chocolate = unqtText "chocolate" unqtDot Chocolate1 = unqtText "chocolate1" unqtDot Chocolate2 = unqtText "chocolate2" unqtDot Chocolate3 = unqtText "chocolate3" unqtDot Chocolate4 = unqtText "chocolate4" unqtDot Coral = unqtText "coral" unqtDot Coral1 = unqtText "coral1" unqtDot Coral2 = unqtText "coral2" unqtDot Coral3 = unqtText "coral3" unqtDot Coral4 = unqtText "coral4" unqtDot CornFlowerBlue = unqtText "cornflowerblue" unqtDot CornSilk = unqtText "cornsilk" unqtDot CornSilk1 = unqtText "cornsilk1" unqtDot CornSilk2 = unqtText "cornsilk2" unqtDot CornSilk3 = unqtText "cornsilk3" unqtDot CornSilk4 = unqtText "cornsilk4" unqtDot Crimson = unqtText "crimson" unqtDot Cyan = unqtText "cyan" unqtDot Cyan1 = unqtText "cyan1" unqtDot Cyan2 = unqtText "cyan2" unqtDot Cyan3 = unqtText "cyan3" unqtDot Cyan4 = unqtText "cyan4" unqtDot DarkGoldenrod = unqtText "darkgoldenrod" unqtDot DarkGoldenrod1 = unqtText "darkgoldenrod1" unqtDot DarkGoldenrod2 = unqtText "darkgoldenrod2" unqtDot DarkGoldenrod3 = unqtText "darkgoldenrod3" unqtDot DarkGoldenrod4 = unqtText "darkgoldenrod4" unqtDot DarkGreen = unqtText "darkgreen" unqtDot Darkkhaki = unqtText "darkkhaki" unqtDot DarkOliveGreen = unqtText "darkolivegreen" unqtDot DarkOliveGreen1 = unqtText "darkolivegreen1" unqtDot DarkOliveGreen2 = unqtText "darkolivegreen2" unqtDot DarkOliveGreen3 = unqtText "darkolivegreen3" unqtDot DarkOliveGreen4 = unqtText "darkolivegreen4" unqtDot DarkOrange = unqtText "darkorange" unqtDot DarkOrange1 = unqtText "darkorange1" unqtDot DarkOrange2 = unqtText "darkorange2" unqtDot DarkOrange3 = unqtText "darkorange3" unqtDot DarkOrange4 = unqtText "darkorange4" unqtDot DarkOrchid = unqtText "darkorchid" unqtDot DarkOrchid1 = unqtText "darkorchid1" unqtDot DarkOrchid2 = unqtText "darkorchid2" unqtDot DarkOrchid3 = unqtText "darkorchid3" unqtDot DarkOrchid4 = unqtText "darkorchid4" unqtDot DarkSalmon = unqtText "darksalmon" unqtDot DarkSeaGreen = unqtText "darkseagreen" unqtDot DarkSeaGreen1 = unqtText "darkseagreen1" unqtDot DarkSeaGreen2 = unqtText "darkseagreen2" unqtDot DarkSeaGreen3 = unqtText "darkseagreen3" unqtDot DarkSeaGreen4 = unqtText "darkseagreen4" unqtDot DarkSlateBlue = unqtText "darkslateblue" unqtDot DarkSlateGray = unqtText "darkslategray" unqtDot DarkSlateGray1 = unqtText "darkslategray1" unqtDot DarkSlateGray2 = unqtText "darkslategray2" unqtDot DarkSlateGray3 = unqtText "darkslategray3" unqtDot DarkSlateGray4 = unqtText "darkslategray4" unqtDot DarkTurquoise = unqtText "darkturquoise" unqtDot DarkViolet = unqtText "darkviolet" unqtDot DeepPink = unqtText "deeppink" unqtDot DeepPink1 = unqtText "deeppink1" unqtDot DeepPink2 = unqtText "deeppink2" unqtDot DeepPink3 = unqtText "deeppink3" unqtDot DeepPink4 = unqtText "deeppink4" unqtDot DeepSkyBlue = unqtText "deepskyblue" unqtDot DeepSkyBlue1 = unqtText "deepskyblue1" unqtDot DeepSkyBlue2 = unqtText "deepskyblue2" unqtDot DeepSkyBlue3 = unqtText "deepskyblue3" unqtDot DeepSkyBlue4 = unqtText "deepskyblue4" unqtDot DimGray = unqtText "dimgray" unqtDot DodgerBlue = unqtText "dodgerblue" unqtDot DodgerBlue1 = unqtText "dodgerblue1" unqtDot DodgerBlue2 = unqtText "dodgerblue2" unqtDot DodgerBlue3 = unqtText "dodgerblue3" unqtDot DodgerBlue4 = unqtText "dodgerblue4" unqtDot Firebrick = unqtText "firebrick" unqtDot Firebrick1 = unqtText "firebrick1" unqtDot Firebrick2 = unqtText "firebrick2" unqtDot Firebrick3 = unqtText "firebrick3" unqtDot Firebrick4 = unqtText "firebrick4" unqtDot FloralWhite = unqtText "floralwhite" unqtDot ForestGreen = unqtText "forestgreen" unqtDot Gainsboro = unqtText "gainsboro" unqtDot GhostWhite = unqtText "ghostwhite" unqtDot Gold = unqtText "gold" unqtDot Gold1 = unqtText "gold1" unqtDot Gold2 = unqtText "gold2" unqtDot Gold3 = unqtText "gold3" unqtDot Gold4 = unqtText "gold4" unqtDot Goldenrod = unqtText "goldenrod" unqtDot Goldenrod1 = unqtText "goldenrod1" unqtDot Goldenrod2 = unqtText "goldenrod2" unqtDot Goldenrod3 = unqtText "goldenrod3" unqtDot Goldenrod4 = unqtText "goldenrod4" unqtDot Gray = unqtText "gray" unqtDot Gray0 = unqtText "gray0" unqtDot Gray1 = unqtText "gray1" unqtDot Gray2 = unqtText "gray2" unqtDot Gray3 = unqtText "gray3" unqtDot Gray4 = unqtText "gray4" unqtDot Gray5 = unqtText "gray5" unqtDot Gray6 = unqtText "gray6" unqtDot Gray7 = unqtText "gray7" unqtDot Gray8 = unqtText "gray8" unqtDot Gray9 = unqtText "gray9" unqtDot Gray10 = unqtText "gray10" unqtDot Gray11 = unqtText "gray11" unqtDot Gray12 = unqtText "gray12" unqtDot Gray13 = unqtText "gray13" unqtDot Gray14 = unqtText "gray14" unqtDot Gray15 = unqtText "gray15" unqtDot Gray16 = unqtText "gray16" unqtDot Gray17 = unqtText "gray17" unqtDot Gray18 = unqtText "gray18" unqtDot Gray19 = unqtText "gray19" unqtDot Gray20 = unqtText "gray20" unqtDot Gray21 = unqtText "gray21" unqtDot Gray22 = unqtText "gray22" unqtDot Gray23 = unqtText "gray23" unqtDot Gray24 = unqtText "gray24" unqtDot Gray25 = unqtText "gray25" unqtDot Gray26 = unqtText "gray26" unqtDot Gray27 = unqtText "gray27" unqtDot Gray28 = unqtText "gray28" unqtDot Gray29 = unqtText "gray29" unqtDot Gray30 = unqtText "gray30" unqtDot Gray31 = unqtText "gray31" unqtDot Gray32 = unqtText "gray32" unqtDot Gray33 = unqtText "gray33" unqtDot Gray34 = unqtText "gray34" unqtDot Gray35 = unqtText "gray35" unqtDot Gray36 = unqtText "gray36" unqtDot Gray37 = unqtText "gray37" unqtDot Gray38 = unqtText "gray38" unqtDot Gray39 = unqtText "gray39" unqtDot Gray40 = unqtText "gray40" unqtDot Gray41 = unqtText "gray41" unqtDot Gray42 = unqtText "gray42" unqtDot Gray43 = unqtText "gray43" unqtDot Gray44 = unqtText "gray44" unqtDot Gray45 = unqtText "gray45" unqtDot Gray46 = unqtText "gray46" unqtDot Gray47 = unqtText "gray47" unqtDot Gray48 = unqtText "gray48" unqtDot Gray49 = unqtText "gray49" unqtDot Gray50 = unqtText "gray50" unqtDot Gray51 = unqtText "gray51" unqtDot Gray52 = unqtText "gray52" unqtDot Gray53 = unqtText "gray53" unqtDot Gray54 = unqtText "gray54" unqtDot Gray55 = unqtText "gray55" unqtDot Gray56 = unqtText "gray56" unqtDot Gray57 = unqtText "gray57" unqtDot Gray58 = unqtText "gray58" unqtDot Gray59 = unqtText "gray59" unqtDot Gray60 = unqtText "gray60" unqtDot Gray61 = unqtText "gray61" unqtDot Gray62 = unqtText "gray62" unqtDot Gray63 = unqtText "gray63" unqtDot Gray64 = unqtText "gray64" unqtDot Gray65 = unqtText "gray65" unqtDot Gray66 = unqtText "gray66" unqtDot Gray67 = unqtText "gray67" unqtDot Gray68 = unqtText "gray68" unqtDot Gray69 = unqtText "gray69" unqtDot Gray70 = unqtText "gray70" unqtDot Gray71 = unqtText "gray71" unqtDot Gray72 = unqtText "gray72" unqtDot Gray73 = unqtText "gray73" unqtDot Gray74 = unqtText "gray74" unqtDot Gray75 = unqtText "gray75" unqtDot Gray76 = unqtText "gray76" unqtDot Gray77 = unqtText "gray77" unqtDot Gray78 = unqtText "gray78" unqtDot Gray79 = unqtText "gray79" unqtDot Gray80 = unqtText "gray80" unqtDot Gray81 = unqtText "gray81" unqtDot Gray82 = unqtText "gray82" unqtDot Gray83 = unqtText "gray83" unqtDot Gray84 = unqtText "gray84" unqtDot Gray85 = unqtText "gray85" unqtDot Gray86 = unqtText "gray86" unqtDot Gray87 = unqtText "gray87" unqtDot Gray88 = unqtText "gray88" unqtDot Gray89 = unqtText "gray89" unqtDot Gray90 = unqtText "gray90" unqtDot Gray91 = unqtText "gray91" unqtDot Gray92 = unqtText "gray92" unqtDot Gray93 = unqtText "gray93" unqtDot Gray94 = unqtText "gray94" unqtDot Gray95 = unqtText "gray95" unqtDot Gray96 = unqtText "gray96" unqtDot Gray97 = unqtText "gray97" unqtDot Gray98 = unqtText "gray98" unqtDot Gray99 = unqtText "gray99" unqtDot Gray100 = unqtText "gray100" unqtDot Green = unqtText "green" unqtDot Green1 = unqtText "green1" unqtDot Green2 = unqtText "green2" unqtDot Green3 = unqtText "green3" unqtDot Green4 = unqtText "green4" unqtDot GreenYellow = unqtText "greenyellow" unqtDot HoneyDew = unqtText "honeydew" unqtDot HoneyDew1 = unqtText "honeydew1" unqtDot HoneyDew2 = unqtText "honeydew2" unqtDot HoneyDew3 = unqtText "honeydew3" unqtDot HoneyDew4 = unqtText "honeydew4" unqtDot HotPink = unqtText "hotpink" unqtDot HotPink1 = unqtText "hotpink1" unqtDot HotPink2 = unqtText "hotpink2" unqtDot HotPink3 = unqtText "hotpink3" unqtDot HotPink4 = unqtText "hotpink4" unqtDot IndianRed = unqtText "indianred" unqtDot IndianRed1 = unqtText "indianred1" unqtDot IndianRed2 = unqtText "indianred2" unqtDot IndianRed3 = unqtText "indianred3" unqtDot IndianRed4 = unqtText "indianred4" unqtDot Indigo = unqtText "indigo" unqtDot Ivory = unqtText "ivory" unqtDot Ivory1 = unqtText "ivory1" unqtDot Ivory2 = unqtText "ivory2" unqtDot Ivory3 = unqtText "ivory3" unqtDot Ivory4 = unqtText "ivory4" unqtDot Khaki = unqtText "khaki" unqtDot Khaki1 = unqtText "khaki1" unqtDot Khaki2 = unqtText "khaki2" unqtDot Khaki3 = unqtText "khaki3" unqtDot Khaki4 = unqtText "khaki4" unqtDot Lavender = unqtText "lavender" unqtDot LavenderBlush = unqtText "lavenderblush" unqtDot LavenderBlush1 = unqtText "lavenderblush1" unqtDot LavenderBlush2 = unqtText "lavenderblush2" unqtDot LavenderBlush3 = unqtText "lavenderblush3" unqtDot LavenderBlush4 = unqtText "lavenderblush4" unqtDot LawnGreen = unqtText "lawngreen" unqtDot LemonChiffon = unqtText "lemonchiffon" unqtDot LemonChiffon1 = unqtText "lemonchiffon1" unqtDot LemonChiffon2 = unqtText "lemonchiffon2" unqtDot LemonChiffon3 = unqtText "lemonchiffon3" unqtDot LemonChiffon4 = unqtText "lemonchiffon4" unqtDot LightBlue = unqtText "lightblue" unqtDot LightBlue1 = unqtText "lightblue1" unqtDot LightBlue2 = unqtText "lightblue2" unqtDot LightBlue3 = unqtText "lightblue3" unqtDot LightBlue4 = unqtText "lightblue4" unqtDot LightCoral = unqtText "lightcoral" unqtDot LightCyan = unqtText "lightcyan" unqtDot LightCyan1 = unqtText "lightcyan1" unqtDot LightCyan2 = unqtText "lightcyan2" unqtDot LightCyan3 = unqtText "lightcyan3" unqtDot LightCyan4 = unqtText "lightcyan4" unqtDot LightGoldenrod = unqtText "lightgoldenrod" unqtDot LightGoldenrod1 = unqtText "lightgoldenrod1" unqtDot LightGoldenrod2 = unqtText "lightgoldenrod2" unqtDot LightGoldenrod3 = unqtText "lightgoldenrod3" unqtDot LightGoldenrod4 = unqtText "lightgoldenrod4" unqtDot LightGoldenrodYellow = unqtText "lightgoldenrodyellow" unqtDot LightGray = unqtText "lightgray" unqtDot LightPink = unqtText "lightpink" unqtDot LightPink1 = unqtText "lightpink1" unqtDot LightPink2 = unqtText "lightpink2" unqtDot LightPink3 = unqtText "lightpink3" unqtDot LightPink4 = unqtText "lightpink4" unqtDot LightSalmon = unqtText "lightsalmon" unqtDot LightSalmon1 = unqtText "lightsalmon1" unqtDot LightSalmon2 = unqtText "lightsalmon2" unqtDot LightSalmon3 = unqtText "lightsalmon3" unqtDot LightSalmon4 = unqtText "lightsalmon4" unqtDot LightSeaGreen = unqtText "lightseagreen" unqtDot LightSkyBlue = unqtText "lightskyblue" unqtDot LightSkyBlue1 = unqtText "lightskyblue1" unqtDot LightSkyBlue2 = unqtText "lightskyblue2" unqtDot LightSkyBlue3 = unqtText "lightskyblue3" unqtDot LightSkyBlue4 = unqtText "lightskyblue4" unqtDot LightSlateBlue = unqtText "lightslateblue" unqtDot LightSlateGray = unqtText "lightslategray" unqtDot LightSteelBlue = unqtText "lightsteelblue" unqtDot LightSteelBlue1 = unqtText "lightsteelblue1" unqtDot LightSteelBlue2 = unqtText "lightsteelblue2" unqtDot LightSteelBlue3 = unqtText "lightsteelblue3" unqtDot LightSteelBlue4 = unqtText "lightsteelblue4" unqtDot LightYellow = unqtText "lightyellow" unqtDot LightYellow1 = unqtText "lightyellow1" unqtDot LightYellow2 = unqtText "lightyellow2" unqtDot LightYellow3 = unqtText "lightyellow3" unqtDot LightYellow4 = unqtText "lightyellow4" unqtDot LimeGreen = unqtText "limegreen" unqtDot Linen = unqtText "linen" unqtDot Magenta = unqtText "magenta" unqtDot Magenta1 = unqtText "magenta1" unqtDot Magenta2 = unqtText "magenta2" unqtDot Magenta3 = unqtText "magenta3" unqtDot Magenta4 = unqtText "magenta4" unqtDot Maroon = unqtText "maroon" unqtDot Maroon1 = unqtText "maroon1" unqtDot Maroon2 = unqtText "maroon2" unqtDot Maroon3 = unqtText "maroon3" unqtDot Maroon4 = unqtText "maroon4" unqtDot MediumAquamarine = unqtText "mediumaquamarine" unqtDot MediumBlue = unqtText "mediumblue" unqtDot MediumOrchid = unqtText "mediumorchid" unqtDot MediumOrchid1 = unqtText "mediumorchid1" unqtDot MediumOrchid2 = unqtText "mediumorchid2" unqtDot MediumOrchid3 = unqtText "mediumorchid3" unqtDot MediumOrchid4 = unqtText "mediumorchid4" unqtDot MediumPurple = unqtText "mediumpurple" unqtDot MediumPurple1 = unqtText "mediumpurple1" unqtDot MediumPurple2 = unqtText "mediumpurple2" unqtDot MediumPurple3 = unqtText "mediumpurple3" unqtDot MediumPurple4 = unqtText "mediumpurple4" unqtDot MediumSeaGreen = unqtText "mediumseagreen" unqtDot MediumSlateBlue = unqtText "mediumslateblue" unqtDot MediumSpringGreen = unqtText "mediumspringgreen" unqtDot MediumTurquoise = unqtText "mediumturquoise" unqtDot MediumVioletRed = unqtText "mediumvioletred" unqtDot MidnightBlue = unqtText "midnightblue" unqtDot MintCream = unqtText "mintcream" unqtDot MistyRose = unqtText "mistyrose" unqtDot MistyRose1 = unqtText "mistyrose1" unqtDot MistyRose2 = unqtText "mistyrose2" unqtDot MistyRose3 = unqtText "mistyrose3" unqtDot MistyRose4 = unqtText "mistyrose4" unqtDot Moccasin = unqtText "moccasin" unqtDot NavajoWhite = unqtText "navajowhite" unqtDot NavajoWhite1 = unqtText "navajowhite1" unqtDot NavajoWhite2 = unqtText "navajowhite2" unqtDot NavajoWhite3 = unqtText "navajowhite3" unqtDot NavajoWhite4 = unqtText "navajowhite4" unqtDot Navy = unqtText "navy" unqtDot NavyBlue = unqtText "navyblue" unqtDot OldLace = unqtText "oldlace" unqtDot OliveDrab = unqtText "olivedrab" unqtDot OliveDrab1 = unqtText "olivedrab1" unqtDot OliveDrab2 = unqtText "olivedrab2" unqtDot OliveDrab3 = unqtText "olivedrab3" unqtDot OliveDrab4 = unqtText "olivedrab4" unqtDot Orange = unqtText "orange" unqtDot Orange1 = unqtText "orange1" unqtDot Orange2 = unqtText "orange2" unqtDot Orange3 = unqtText "orange3" unqtDot Orange4 = unqtText "orange4" unqtDot OrangeRed = unqtText "orangered" unqtDot OrangeRed1 = unqtText "orangered1" unqtDot OrangeRed2 = unqtText "orangered2" unqtDot OrangeRed3 = unqtText "orangered3" unqtDot OrangeRed4 = unqtText "orangered4" unqtDot Orchid = unqtText "orchid" unqtDot Orchid1 = unqtText "orchid1" unqtDot Orchid2 = unqtText "orchid2" unqtDot Orchid3 = unqtText "orchid3" unqtDot Orchid4 = unqtText "orchid4" unqtDot PaleGoldenrod = unqtText "palegoldenrod" unqtDot PaleGreen = unqtText "palegreen" unqtDot PaleGreen1 = unqtText "palegreen1" unqtDot PaleGreen2 = unqtText "palegreen2" unqtDot PaleGreen3 = unqtText "palegreen3" unqtDot PaleGreen4 = unqtText "palegreen4" unqtDot PaleTurquoise = unqtText "paleturquoise" unqtDot PaleTurquoise1 = unqtText "paleturquoise1" unqtDot PaleTurquoise2 = unqtText "paleturquoise2" unqtDot PaleTurquoise3 = unqtText "paleturquoise3" unqtDot PaleTurquoise4 = unqtText "paleturquoise4" unqtDot PaleVioletRed = unqtText "palevioletred" unqtDot PaleVioletRed1 = unqtText "palevioletred1" unqtDot PaleVioletRed2 = unqtText "palevioletred2" unqtDot PaleVioletRed3 = unqtText "palevioletred3" unqtDot PaleVioletRed4 = unqtText "palevioletred4" unqtDot PapayaWhip = unqtText "papayawhip" unqtDot PeachPuff = unqtText "peachpuff" unqtDot PeachPuff1 = unqtText "peachpuff1" unqtDot PeachPuff2 = unqtText "peachpuff2" unqtDot PeachPuff3 = unqtText "peachpuff3" unqtDot PeachPuff4 = unqtText "peachpuff4" unqtDot Peru = unqtText "peru" unqtDot Pink = unqtText "pink" unqtDot Pink1 = unqtText "pink1" unqtDot Pink2 = unqtText "pink2" unqtDot Pink3 = unqtText "pink3" unqtDot Pink4 = unqtText "pink4" unqtDot Plum = unqtText "plum" unqtDot Plum1 = unqtText "plum1" unqtDot Plum2 = unqtText "plum2" unqtDot Plum3 = unqtText "plum3" unqtDot Plum4 = unqtText "plum4" unqtDot PowderBlue = unqtText "powderblue" unqtDot Purple = unqtText "purple" unqtDot Purple1 = unqtText "purple1" unqtDot Purple2 = unqtText "purple2" unqtDot Purple3 = unqtText "purple3" unqtDot Purple4 = unqtText "purple4" unqtDot Red = unqtText "red" unqtDot Red1 = unqtText "red1" unqtDot Red2 = unqtText "red2" unqtDot Red3 = unqtText "red3" unqtDot Red4 = unqtText "red4" unqtDot RosyBrown = unqtText "rosybrown" unqtDot RosyBrown1 = unqtText "rosybrown1" unqtDot RosyBrown2 = unqtText "rosybrown2" unqtDot RosyBrown3 = unqtText "rosybrown3" unqtDot RosyBrown4 = unqtText "rosybrown4" unqtDot RoyalBlue = unqtText "royalblue" unqtDot RoyalBlue1 = unqtText "royalblue1" unqtDot RoyalBlue2 = unqtText "royalblue2" unqtDot RoyalBlue3 = unqtText "royalblue3" unqtDot RoyalBlue4 = unqtText "royalblue4" unqtDot SaddleBrown = unqtText "saddlebrown" unqtDot Salmon = unqtText "salmon" unqtDot Salmon1 = unqtText "salmon1" unqtDot Salmon2 = unqtText "salmon2" unqtDot Salmon3 = unqtText "salmon3" unqtDot Salmon4 = unqtText "salmon4" unqtDot SandyBrown = unqtText "sandybrown" unqtDot SeaGreen = unqtText "seagreen" unqtDot SeaGreen1 = unqtText "seagreen1" unqtDot SeaGreen2 = unqtText "seagreen2" unqtDot SeaGreen3 = unqtText "seagreen3" unqtDot SeaGreen4 = unqtText "seagreen4" unqtDot SeaShell = unqtText "seashell" unqtDot SeaShell1 = unqtText "seashell1" unqtDot SeaShell2 = unqtText "seashell2" unqtDot SeaShell3 = unqtText "seashell3" unqtDot SeaShell4 = unqtText "seashell4" unqtDot Sienna = unqtText "sienna" unqtDot Sienna1 = unqtText "sienna1" unqtDot Sienna2 = unqtText "sienna2" unqtDot Sienna3 = unqtText "sienna3" unqtDot Sienna4 = unqtText "sienna4" unqtDot SkyBlue = unqtText "skyblue" unqtDot SkyBlue1 = unqtText "skyblue1" unqtDot SkyBlue2 = unqtText "skyblue2" unqtDot SkyBlue3 = unqtText "skyblue3" unqtDot SkyBlue4 = unqtText "skyblue4" unqtDot SlateBlue = unqtText "slateblue" unqtDot SlateBlue1 = unqtText "slateblue1" unqtDot SlateBlue2 = unqtText "slateblue2" unqtDot SlateBlue3 = unqtText "slateblue3" unqtDot SlateBlue4 = unqtText "slateblue4" unqtDot SlateGray = unqtText "slategray" unqtDot SlateGray1 = unqtText "slategray1" unqtDot SlateGray2 = unqtText "slategray2" unqtDot SlateGray3 = unqtText "slategray3" unqtDot SlateGray4 = unqtText "slategray4" unqtDot Snow = unqtText "snow" unqtDot Snow1 = unqtText "snow1" unqtDot Snow2 = unqtText "snow2" unqtDot Snow3 = unqtText "snow3" unqtDot Snow4 = unqtText "snow4" unqtDot SpringGreen = unqtText "springgreen" unqtDot SpringGreen1 = unqtText "springgreen1" unqtDot SpringGreen2 = unqtText "springgreen2" unqtDot SpringGreen3 = unqtText "springgreen3" unqtDot SpringGreen4 = unqtText "springgreen4" unqtDot SteelBlue = unqtText "steelblue" unqtDot SteelBlue1 = unqtText "steelblue1" unqtDot SteelBlue2 = unqtText "steelblue2" unqtDot SteelBlue3 = unqtText "steelblue3" unqtDot SteelBlue4 = unqtText "steelblue4" unqtDot Tan = unqtText "tan" unqtDot Tan1 = unqtText "tan1" unqtDot Tan2 = unqtText "tan2" unqtDot Tan3 = unqtText "tan3" unqtDot Tan4 = unqtText "tan4" unqtDot Thistle = unqtText "thistle" unqtDot Thistle1 = unqtText "thistle1" unqtDot Thistle2 = unqtText "thistle2" unqtDot Thistle3 = unqtText "thistle3" unqtDot Thistle4 = unqtText "thistle4" unqtDot Tomato = unqtText "tomato" unqtDot Tomato1 = unqtText "tomato1" unqtDot Tomato2 = unqtText "tomato2" unqtDot Tomato3 = unqtText "tomato3" unqtDot Tomato4 = unqtText "tomato4" unqtDot Transparent = unqtText "transparent" unqtDot Turquoise = unqtText "turquoise" unqtDot Turquoise1 = unqtText "turquoise1" unqtDot Turquoise2 = unqtText "turquoise2" unqtDot Turquoise3 = unqtText "turquoise3" unqtDot Turquoise4 = unqtText "turquoise4" unqtDot Violet = unqtText "violet" unqtDot VioletRed = unqtText "violetred" unqtDot VioletRed1 = unqtText "violetred1" unqtDot VioletRed2 = unqtText "violetred2" unqtDot VioletRed3 = unqtText "violetred3" unqtDot VioletRed4 = unqtText "violetred4" unqtDot Wheat = unqtText "wheat" unqtDot Wheat1 = unqtText "wheat1" unqtDot Wheat2 = unqtText "wheat2" unqtDot Wheat3 = unqtText "wheat3" unqtDot Wheat4 = unqtText "wheat4" unqtDot White = unqtText "white" unqtDot WhiteSmoke = unqtText "whitesmoke" unqtDot Yellow = unqtText "yellow" unqtDot Yellow1 = unqtText "yellow1" unqtDot Yellow2 = unqtText "yellow2" unqtDot Yellow3 = unqtText "yellow3" unqtDot Yellow4 = unqtText "yellow4" unqtDot YellowGreen = unqtText "yellowgreen" instance ParseDot X11Color where parseUnqt = stringValue [ ("aliceblue", AliceBlue) , ("antiquewhite", AntiqueWhite) , ("antiquewhite1", AntiqueWhite1) , ("antiquewhite2", AntiqueWhite2) , ("antiquewhite3", AntiqueWhite3) , ("antiquewhite4", AntiqueWhite4) , ("aquamarine", Aquamarine) , ("aquamarine1", Aquamarine1) , ("aquamarine2", Aquamarine2) , ("aquamarine3", Aquamarine3) , ("aquamarine4", Aquamarine4) , ("azure", Azure) , ("azure1", Azure1) , ("azure2", Azure2) , ("azure3", Azure3) , ("azure4", Azure4) , ("beige", Beige) , ("bisque", Bisque) , ("bisque1", Bisque1) , ("bisque2", Bisque2) , ("bisque3", Bisque3) , ("bisque4", Bisque4) , ("black", Black) , ("blanchedalmond", BlanchedAlmond) , ("blue", Blue) , ("blue1", Blue1) , ("blue2", Blue2) , ("blue3", Blue3) , ("blue4", Blue4) , ("blueviolet", BlueViolet) , ("brown", Brown) , ("brown1", Brown1) , ("brown2", Brown2) , ("brown3", Brown3) , ("brown4", Brown4) , ("burlywood", Burlywood) , ("burlywood1", Burlywood1) , ("burlywood2", Burlywood2) , ("burlywood3", Burlywood3) , ("burlywood4", Burlywood4) , ("cadetblue", CadetBlue) , ("cadetblue1", CadetBlue1) , ("cadetblue2", CadetBlue2) , ("cadetblue3", CadetBlue3) , ("cadetblue4", CadetBlue4) , ("chartreuse", Chartreuse) , ("chartreuse1", Chartreuse1) , ("chartreuse2", Chartreuse2) , ("chartreuse3", Chartreuse3) , ("chartreuse4", Chartreuse4) , ("chocolate", Chocolate) , ("chocolate1", Chocolate1) , ("chocolate2", Chocolate2) , ("chocolate3", Chocolate3) , ("chocolate4", Chocolate4) , ("coral", Coral) , ("coral1", Coral1) , ("coral2", Coral2) , ("coral3", Coral3) , ("coral4", Coral4) , ("cornflowerblue", CornFlowerBlue) , ("cornsilk", CornSilk) , ("cornsilk1", CornSilk1) , ("cornsilk2", CornSilk2) , ("cornsilk3", CornSilk3) , ("cornsilk4", CornSilk4) , ("crimson", Crimson) , ("cyan", Cyan) , ("cyan1", Cyan1) , ("cyan2", Cyan2) , ("cyan3", Cyan3) , ("cyan4", Cyan4) , ("darkgoldenrod", DarkGoldenrod) , ("darkgoldenrod1", DarkGoldenrod1) , ("darkgoldenrod2", DarkGoldenrod2) , ("darkgoldenrod3", DarkGoldenrod3) , ("darkgoldenrod4", DarkGoldenrod4) , ("darkgreen", DarkGreen) , ("darkkhaki", Darkkhaki) , ("darkolivegreen", DarkOliveGreen) , ("darkolivegreen1", DarkOliveGreen1) , ("darkolivegreen2", DarkOliveGreen2) , ("darkolivegreen3", DarkOliveGreen3) , ("darkolivegreen4", DarkOliveGreen4) , ("darkorange", DarkOrange) , ("darkorange1", DarkOrange1) , ("darkorange2", DarkOrange2) , ("darkorange3", DarkOrange3) , ("darkorange4", DarkOrange4) , ("darkorchid", DarkOrchid) , ("darkorchid1", DarkOrchid1) , ("darkorchid2", DarkOrchid2) , ("darkorchid3", DarkOrchid3) , ("darkorchid4", DarkOrchid4) , ("darksalmon", DarkSalmon) , ("darkseagreen", DarkSeaGreen) , ("darkseagreen1", DarkSeaGreen1) , ("darkseagreen2", DarkSeaGreen2) , ("darkseagreen3", DarkSeaGreen3) , ("darkseagreen4", DarkSeaGreen4) , ("darkslateblue", DarkSlateBlue) , ("darkslategray", DarkSlateGray) , ("darkslategrey", DarkSlateGray) , ("darkslategray1", DarkSlateGray1) , ("darkslategrey1", DarkSlateGray1) , ("darkslategray2", DarkSlateGray2) , ("darkslategrey2", DarkSlateGray2) , ("darkslategray3", DarkSlateGray3) , ("darkslategrey3", DarkSlateGray3) , ("darkslategray4", DarkSlateGray4) , ("darkslategrey4", DarkSlateGray4) , ("darkturquoise", DarkTurquoise) , ("darkviolet", DarkViolet) , ("deeppink", DeepPink) , ("deeppink1", DeepPink1) , ("deeppink2", DeepPink2) , ("deeppink3", DeepPink3) , ("deeppink4", DeepPink4) , ("deepskyblue", DeepSkyBlue) , ("deepskyblue1", DeepSkyBlue1) , ("deepskyblue2", DeepSkyBlue2) , ("deepskyblue3", DeepSkyBlue3) , ("deepskyblue4", DeepSkyBlue4) , ("dimgray", DimGray) , ("dimgrey", DimGray) , ("dodgerblue", DodgerBlue) , ("dodgerblue1", DodgerBlue1) , ("dodgerblue2", DodgerBlue2) , ("dodgerblue3", DodgerBlue3) , ("dodgerblue4", DodgerBlue4) , ("firebrick", Firebrick) , ("firebrick1", Firebrick1) , ("firebrick2", Firebrick2) , ("firebrick3", Firebrick3) , ("firebrick4", Firebrick4) , ("floralwhite", FloralWhite) , ("forestgreen", ForestGreen) , ("gainsboro", Gainsboro) , ("ghostwhite", GhostWhite) , ("gold", Gold) , ("gold1", Gold1) , ("gold2", Gold2) , ("gold3", Gold3) , ("gold4", Gold4) , ("goldenrod", Goldenrod) , ("goldenrod1", Goldenrod1) , ("goldenrod2", Goldenrod2) , ("goldenrod3", Goldenrod3) , ("goldenrod4", Goldenrod4) , ("gray", Gray) , ("grey", Gray) , ("gray0", Gray0) , ("grey0", Gray0) , ("gray1", Gray1) , ("grey1", Gray1) , ("gray2", Gray2) , ("grey2", Gray2) , ("gray3", Gray3) , ("grey3", Gray3) , ("gray4", Gray4) , ("grey4", Gray4) , ("gray5", Gray5) , ("grey5", Gray5) , ("gray6", Gray6) , ("grey6", Gray6) , ("gray7", Gray7) , ("grey7", Gray7) , ("gray8", Gray8) , ("grey8", Gray8) , ("gray9", Gray9) , ("grey9", Gray9) , ("gray10", Gray10) , ("grey10", Gray10) , ("gray11", Gray11) , ("grey11", Gray11) , ("gray12", Gray12) , ("grey12", Gray12) , ("gray13", Gray13) , ("grey13", Gray13) , ("gray14", Gray14) , ("grey14", Gray14) , ("gray15", Gray15) , ("grey15", Gray15) , ("gray16", Gray16) , ("grey16", Gray16) , ("gray17", Gray17) , ("grey17", Gray17) , ("gray18", Gray18) , ("grey18", Gray18) , ("gray19", Gray19) , ("grey19", Gray19) , ("gray20", Gray20) , ("grey20", Gray20) , ("gray21", Gray21) , ("grey21", Gray21) , ("gray22", Gray22) , ("grey22", Gray22) , ("gray23", Gray23) , ("grey23", Gray23) , ("gray24", Gray24) , ("grey24", Gray24) , ("gray25", Gray25) , ("grey25", Gray25) , ("gray26", Gray26) , ("grey26", Gray26) , ("gray27", Gray27) , ("grey27", Gray27) , ("gray28", Gray28) , ("grey28", Gray28) , ("gray29", Gray29) , ("grey29", Gray29) , ("gray30", Gray30) , ("grey30", Gray30) , ("gray31", Gray31) , ("grey31", Gray31) , ("gray32", Gray32) , ("grey32", Gray32) , ("gray33", Gray33) , ("grey33", Gray33) , ("gray34", Gray34) , ("grey34", Gray34) , ("gray35", Gray35) , ("grey35", Gray35) , ("gray36", Gray36) , ("grey36", Gray36) , ("gray37", Gray37) , ("grey37", Gray37) , ("gray38", Gray38) , ("grey38", Gray38) , ("gray39", Gray39) , ("grey39", Gray39) , ("gray40", Gray40) , ("grey40", Gray40) , ("gray41", Gray41) , ("grey41", Gray41) , ("gray42", Gray42) , ("grey42", Gray42) , ("gray43", Gray43) , ("grey43", Gray43) , ("gray44", Gray44) , ("grey44", Gray44) , ("gray45", Gray45) , ("grey45", Gray45) , ("gray46", Gray46) , ("grey46", Gray46) , ("gray47", Gray47) , ("grey47", Gray47) , ("gray48", Gray48) , ("grey48", Gray48) , ("gray49", Gray49) , ("grey49", Gray49) , ("gray50", Gray50) , ("grey50", Gray50) , ("gray51", Gray51) , ("grey51", Gray51) , ("gray52", Gray52) , ("grey52", Gray52) , ("gray53", Gray53) , ("grey53", Gray53) , ("gray54", Gray54) , ("grey54", Gray54) , ("gray55", Gray55) , ("grey55", Gray55) , ("gray56", Gray56) , ("grey56", Gray56) , ("gray57", Gray57) , ("grey57", Gray57) , ("gray58", Gray58) , ("grey58", Gray58) , ("gray59", Gray59) , ("grey59", Gray59) , ("gray60", Gray60) , ("grey60", Gray60) , ("gray61", Gray61) , ("grey61", Gray61) , ("gray62", Gray62) , ("grey62", Gray62) , ("gray63", Gray63) , ("grey63", Gray63) , ("gray64", Gray64) , ("grey64", Gray64) , ("gray65", Gray65) , ("grey65", Gray65) , ("gray66", Gray66) , ("grey66", Gray66) , ("gray67", Gray67) , ("grey67", Gray67) , ("gray68", Gray68) , ("grey68", Gray68) , ("gray69", Gray69) , ("grey69", Gray69) , ("gray70", Gray70) , ("grey70", Gray70) , ("gray71", Gray71) , ("grey71", Gray71) , ("gray72", Gray72) , ("grey72", Gray72) , ("gray73", Gray73) , ("grey73", Gray73) , ("gray74", Gray74) , ("grey74", Gray74) , ("gray75", Gray75) , ("grey75", Gray75) , ("gray76", Gray76) , ("grey76", Gray76) , ("gray77", Gray77) , ("grey77", Gray77) , ("gray78", Gray78) , ("grey78", Gray78) , ("gray79", Gray79) , ("grey79", Gray79) , ("gray80", Gray80) , ("grey80", Gray80) , ("gray81", Gray81) , ("grey81", Gray81) , ("gray82", Gray82) , ("grey82", Gray82) , ("gray83", Gray83) , ("grey83", Gray83) , ("gray84", Gray84) , ("grey84", Gray84) , ("gray85", Gray85) , ("grey85", Gray85) , ("gray86", Gray86) , ("grey86", Gray86) , ("gray87", Gray87) , ("grey87", Gray87) , ("gray88", Gray88) , ("grey88", Gray88) , ("gray89", Gray89) , ("grey89", Gray89) , ("gray90", Gray90) , ("grey90", Gray90) , ("gray91", Gray91) , ("grey91", Gray91) , ("gray92", Gray92) , ("grey92", Gray92) , ("gray93", Gray93) , ("grey93", Gray93) , ("gray94", Gray94) , ("grey94", Gray94) , ("gray95", Gray95) , ("grey95", Gray95) , ("gray96", Gray96) , ("grey96", Gray96) , ("gray97", Gray97) , ("grey97", Gray97) , ("gray98", Gray98) , ("grey98", Gray98) , ("gray99", Gray99) , ("grey99", Gray99) , ("gray100", Gray100) , ("grey100", Gray100) , ("green", Green) , ("green1", Green1) , ("green2", Green2) , ("green3", Green3) , ("green4", Green4) , ("greenyellow", GreenYellow) , ("honeydew", HoneyDew) , ("honeydew1", HoneyDew1) , ("honeydew2", HoneyDew2) , ("honeydew3", HoneyDew3) , ("honeydew4", HoneyDew4) , ("hotpink", HotPink) , ("hotpink1", HotPink1) , ("hotpink2", HotPink2) , ("hotpink3", HotPink3) , ("hotpink4", HotPink4) , ("indianred", IndianRed) , ("indianred1", IndianRed1) , ("indianred2", IndianRed2) , ("indianred3", IndianRed3) , ("indianred4", IndianRed4) , ("indigo", Indigo) , ("ivory", Ivory) , ("ivory1", Ivory1) , ("ivory2", Ivory2) , ("ivory3", Ivory3) , ("ivory4", Ivory4) , ("khaki", Khaki) , ("khaki1", Khaki1) , ("khaki2", Khaki2) , ("khaki3", Khaki3) , ("khaki4", Khaki4) , ("lavender", Lavender) , ("lavenderblush", LavenderBlush) , ("lavenderblush1", LavenderBlush1) , ("lavenderblush2", LavenderBlush2) , ("lavenderblush3", LavenderBlush3) , ("lavenderblush4", LavenderBlush4) , ("lawngreen", LawnGreen) , ("lemonchiffon", LemonChiffon) , ("lemonchiffon1", LemonChiffon1) , ("lemonchiffon2", LemonChiffon2) , ("lemonchiffon3", LemonChiffon3) , ("lemonchiffon4", LemonChiffon4) , ("lightblue", LightBlue) , ("lightblue1", LightBlue1) , ("lightblue2", LightBlue2) , ("lightblue3", LightBlue3) , ("lightblue4", LightBlue4) , ("lightcoral", LightCoral) , ("lightcyan", LightCyan) , ("lightcyan1", LightCyan1) , ("lightcyan2", LightCyan2) , ("lightcyan3", LightCyan3) , ("lightcyan4", LightCyan4) , ("lightgoldenrod", LightGoldenrod) , ("lightgoldenrod1", LightGoldenrod1) , ("lightgoldenrod2", LightGoldenrod2) , ("lightgoldenrod3", LightGoldenrod3) , ("lightgoldenrod4", LightGoldenrod4) , ("lightgoldenrodyellow", LightGoldenrodYellow) , ("lightgray", LightGray) , ("lightgrey", LightGray) , ("lightpink", LightPink) , ("lightpink1", LightPink1) , ("lightpink2", LightPink2) , ("lightpink3", LightPink3) , ("lightpink4", LightPink4) , ("lightsalmon", LightSalmon) , ("lightsalmon1", LightSalmon1) , ("lightsalmon2", LightSalmon2) , ("lightsalmon3", LightSalmon3) , ("lightsalmon4", LightSalmon4) , ("lightseagreen", LightSeaGreen) , ("lightskyblue", LightSkyBlue) , ("lightskyblue1", LightSkyBlue1) , ("lightskyblue2", LightSkyBlue2) , ("lightskyblue3", LightSkyBlue3) , ("lightskyblue4", LightSkyBlue4) , ("lightslateblue", LightSlateBlue) , ("lightslategray", LightSlateGray) , ("lightslategrey", LightSlateGray) , ("lightsteelblue", LightSteelBlue) , ("lightsteelblue1", LightSteelBlue1) , ("lightsteelblue2", LightSteelBlue2) , ("lightsteelblue3", LightSteelBlue3) , ("lightsteelblue4", LightSteelBlue4) , ("lightyellow", LightYellow) , ("lightyellow1", LightYellow1) , ("lightyellow2", LightYellow2) , ("lightyellow3", LightYellow3) , ("lightyellow4", LightYellow4) , ("limegreen", LimeGreen) , ("linen", Linen) , ("magenta", Magenta) , ("magenta1", Magenta1) , ("magenta2", Magenta2) , ("magenta3", Magenta3) , ("magenta4", Magenta4) , ("maroon", Maroon) , ("maroon1", Maroon1) , ("maroon2", Maroon2) , ("maroon3", Maroon3) , ("maroon4", Maroon4) , ("mediumaquamarine", MediumAquamarine) , ("mediumblue", MediumBlue) , ("mediumorchid", MediumOrchid) , ("mediumorchid1", MediumOrchid1) , ("mediumorchid2", MediumOrchid2) , ("mediumorchid3", MediumOrchid3) , ("mediumorchid4", MediumOrchid4) , ("mediumpurple", MediumPurple) , ("mediumpurple1", MediumPurple1) , ("mediumpurple2", MediumPurple2) , ("mediumpurple3", MediumPurple3) , ("mediumpurple4", MediumPurple4) , ("mediumseagreen", MediumSeaGreen) , ("mediumslateblue", MediumSlateBlue) , ("mediumspringgreen", MediumSpringGreen) , ("mediumturquoise", MediumTurquoise) , ("mediumvioletred", MediumVioletRed) , ("midnightblue", MidnightBlue) , ("mintcream", MintCream) , ("mistyrose", MistyRose) , ("mistyrose1", MistyRose1) , ("mistyrose2", MistyRose2) , ("mistyrose3", MistyRose3) , ("mistyrose4", MistyRose4) , ("moccasin", Moccasin) , ("navajowhite", NavajoWhite) , ("navajowhite1", NavajoWhite1) , ("navajowhite2", NavajoWhite2) , ("navajowhite3", NavajoWhite3) , ("navajowhite4", NavajoWhite4) , ("navy", Navy) , ("navyblue", NavyBlue) , ("oldlace", OldLace) , ("olivedrab", OliveDrab) , ("olivedrab1", OliveDrab1) , ("olivedrab2", OliveDrab2) , ("olivedrab3", OliveDrab3) , ("olivedrab4", OliveDrab4) , ("orange", Orange) , ("orange1", Orange1) , ("orange2", Orange2) , ("orange3", Orange3) , ("orange4", Orange4) , ("orangered", OrangeRed) , ("orangered1", OrangeRed1) , ("orangered2", OrangeRed2) , ("orangered3", OrangeRed3) , ("orangered4", OrangeRed4) , ("orchid", Orchid) , ("orchid1", Orchid1) , ("orchid2", Orchid2) , ("orchid3", Orchid3) , ("orchid4", Orchid4) , ("palegoldenrod", PaleGoldenrod) , ("palegreen", PaleGreen) , ("palegreen1", PaleGreen1) , ("palegreen2", PaleGreen2) , ("palegreen3", PaleGreen3) , ("palegreen4", PaleGreen4) , ("paleturquoise", PaleTurquoise) , ("paleturquoise1", PaleTurquoise1) , ("paleturquoise2", PaleTurquoise2) , ("paleturquoise3", PaleTurquoise3) , ("paleturquoise4", PaleTurquoise4) , ("palevioletred", PaleVioletRed) , ("palevioletred1", PaleVioletRed1) , ("palevioletred2", PaleVioletRed2) , ("palevioletred3", PaleVioletRed3) , ("palevioletred4", PaleVioletRed4) , ("papayawhip", PapayaWhip) , ("peachpuff", PeachPuff) , ("peachpuff1", PeachPuff1) , ("peachpuff2", PeachPuff2) , ("peachpuff3", PeachPuff3) , ("peachpuff4", PeachPuff4) , ("peru", Peru) , ("pink", Pink) , ("pink1", Pink1) , ("pink2", Pink2) , ("pink3", Pink3) , ("pink4", Pink4) , ("plum", Plum) , ("plum1", Plum1) , ("plum2", Plum2) , ("plum3", Plum3) , ("plum4", Plum4) , ("powderblue", PowderBlue) , ("purple", Purple) , ("purple1", Purple1) , ("purple2", Purple2) , ("purple3", Purple3) , ("purple4", Purple4) , ("red", Red) , ("red1", Red1) , ("red2", Red2) , ("red3", Red3) , ("red4", Red4) , ("rosybrown", RosyBrown) , ("rosybrown1", RosyBrown1) , ("rosybrown2", RosyBrown2) , ("rosybrown3", RosyBrown3) , ("rosybrown4", RosyBrown4) , ("royalblue", RoyalBlue) , ("royalblue1", RoyalBlue1) , ("royalblue2", RoyalBlue2) , ("royalblue3", RoyalBlue3) , ("royalblue4", RoyalBlue4) , ("saddlebrown", SaddleBrown) , ("salmon", Salmon) , ("salmon1", Salmon1) , ("salmon2", Salmon2) , ("salmon3", Salmon3) , ("salmon4", Salmon4) , ("sandybrown", SandyBrown) , ("seagreen", SeaGreen) , ("seagreen1", SeaGreen1) , ("seagreen2", SeaGreen2) , ("seagreen3", SeaGreen3) , ("seagreen4", SeaGreen4) , ("seashell", SeaShell) , ("seashell1", SeaShell1) , ("seashell2", SeaShell2) , ("seashell3", SeaShell3) , ("seashell4", SeaShell4) , ("sienna", Sienna) , ("sienna1", Sienna1) , ("sienna2", Sienna2) , ("sienna3", Sienna3) , ("sienna4", Sienna4) , ("skyblue", SkyBlue) , ("skyblue1", SkyBlue1) , ("skyblue2", SkyBlue2) , ("skyblue3", SkyBlue3) , ("skyblue4", SkyBlue4) , ("slateblue", SlateBlue) , ("slateblue1", SlateBlue1) , ("slateblue2", SlateBlue2) , ("slateblue3", SlateBlue3) , ("slateblue4", SlateBlue4) , ("slategray", SlateGray) , ("slategrey", SlateGray) , ("slategray1", SlateGray1) , ("slategrey1", SlateGray1) , ("slategray2", SlateGray2) , ("slategrey2", SlateGray2) , ("slategray3", SlateGray3) , ("slategrey3", SlateGray3) , ("slategray4", SlateGray4) , ("slategrey4", SlateGray4) , ("snow", Snow) , ("snow1", Snow1) , ("snow2", Snow2) , ("snow3", Snow3) , ("snow4", Snow4) , ("springgreen", SpringGreen) , ("springgreen1", SpringGreen1) , ("springgreen2", SpringGreen2) , ("springgreen3", SpringGreen3) , ("springgreen4", SpringGreen4) , ("steelblue", SteelBlue) , ("steelblue1", SteelBlue1) , ("steelblue2", SteelBlue2) , ("steelblue3", SteelBlue3) , ("steelblue4", SteelBlue4) , ("tan", Tan) , ("tan1", Tan1) , ("tan2", Tan2) , ("tan3", Tan3) , ("tan4", Tan4) , ("thistle", Thistle) , ("thistle1", Thistle1) , ("thistle2", Thistle2) , ("thistle3", Thistle3) , ("thistle4", Thistle4) , ("tomato", Tomato) , ("tomato1", Tomato1) , ("tomato2", Tomato2) , ("tomato3", Tomato3) , ("tomato4", Tomato4) , ("transparent", Transparent) , ("invis", Transparent) , ("none", Transparent) , ("turquoise", Turquoise) , ("turquoise1", Turquoise1) , ("turquoise2", Turquoise2) , ("turquoise3", Turquoise3) , ("turquoise4", Turquoise4) , ("violet", Violet) , ("violetred", VioletRed) , ("violetred1", VioletRed1) , ("violetred2", VioletRed2) , ("violetred3", VioletRed3) , ("violetred4", VioletRed4) , ("wheat", Wheat) , ("wheat1", Wheat1) , ("wheat2", Wheat2) , ("wheat3", Wheat3) , ("wheat4", Wheat4) , ("white", White) , ("whitesmoke", WhiteSmoke) , ("yellow", Yellow) , ("yellow1", Yellow1) , ("yellow2", Yellow2) , ("yellow3", Yellow3) , ("yellow4", Yellow4) , ("yellowgreen", YellowGreen) ] -- | Convert an 'X11Color' to its equivalent 'Colour' value. Note -- that it uses 'AlphaColour' because of 'Transparent'; all other -- 'X11Color' values are completely opaque. x11Colour :: X11Color -> AlphaColour Double x11Colour AliceBlue = opaque $ sRGB24 240 248 255 x11Colour AntiqueWhite = opaque $ sRGB24 250 235 215 x11Colour AntiqueWhite1 = opaque $ sRGB24 255 239 219 x11Colour AntiqueWhite2 = opaque $ sRGB24 238 223 204 x11Colour AntiqueWhite3 = opaque $ sRGB24 205 192 176 x11Colour AntiqueWhite4 = opaque $ sRGB24 139 131 120 x11Colour Aquamarine = opaque $ sRGB24 127 255 212 x11Colour Aquamarine1 = opaque $ sRGB24 127 255 212 x11Colour Aquamarine2 = opaque $ sRGB24 118 238 198 x11Colour Aquamarine3 = opaque $ sRGB24 102 205 170 x11Colour Aquamarine4 = opaque $ sRGB24 69 139 116 x11Colour Azure = opaque $ sRGB24 240 255 255 x11Colour Azure1 = opaque $ sRGB24 240 255 255 x11Colour Azure2 = opaque $ sRGB24 224 238 238 x11Colour Azure3 = opaque $ sRGB24 193 205 205 x11Colour Azure4 = opaque $ sRGB24 131 139 139 x11Colour Beige = opaque $ sRGB24 245 245 220 x11Colour Bisque = opaque $ sRGB24 255 228 196 x11Colour Bisque1 = opaque $ sRGB24 255 228 196 x11Colour Bisque2 = opaque $ sRGB24 238 213 183 x11Colour Bisque3 = opaque $ sRGB24 205 183 158 x11Colour Bisque4 = opaque $ sRGB24 139 125 107 x11Colour Black = opaque $ sRGB24 0 0 0 x11Colour BlanchedAlmond = opaque $ sRGB24 255 235 205 x11Colour Blue = opaque $ sRGB24 0 0 255 x11Colour Blue1 = opaque $ sRGB24 0 0 255 x11Colour Blue2 = opaque $ sRGB24 0 0 238 x11Colour Blue3 = opaque $ sRGB24 0 0 205 x11Colour Blue4 = opaque $ sRGB24 0 0 139 x11Colour BlueViolet = opaque $ sRGB24 138 43 226 x11Colour Brown = opaque $ sRGB24 165 42 42 x11Colour Brown1 = opaque $ sRGB24 255 64 64 x11Colour Brown2 = opaque $ sRGB24 238 59 59 x11Colour Brown3 = opaque $ sRGB24 205 51 51 x11Colour Brown4 = opaque $ sRGB24 139 35 35 x11Colour Burlywood = opaque $ sRGB24 222 184 135 x11Colour Burlywood1 = opaque $ sRGB24 255 211 155 x11Colour Burlywood2 = opaque $ sRGB24 238 197 145 x11Colour Burlywood3 = opaque $ sRGB24 205 170 125 x11Colour Burlywood4 = opaque $ sRGB24 139 115 85 x11Colour CadetBlue = opaque $ sRGB24 95 158 160 x11Colour CadetBlue1 = opaque $ sRGB24 152 245 255 x11Colour CadetBlue2 = opaque $ sRGB24 142 229 238 x11Colour CadetBlue3 = opaque $ sRGB24 122 197 205 x11Colour CadetBlue4 = opaque $ sRGB24 83 134 139 x11Colour Chartreuse = opaque $ sRGB24 127 255 0 x11Colour Chartreuse1 = opaque $ sRGB24 127 255 0 x11Colour Chartreuse2 = opaque $ sRGB24 118 238 0 x11Colour Chartreuse3 = opaque $ sRGB24 102 205 0 x11Colour Chartreuse4 = opaque $ sRGB24 69 139 0 x11Colour Chocolate = opaque $ sRGB24 210 105 30 x11Colour Chocolate1 = opaque $ sRGB24 255 127 36 x11Colour Chocolate2 = opaque $ sRGB24 238 118 33 x11Colour Chocolate3 = opaque $ sRGB24 205 102 29 x11Colour Chocolate4 = opaque $ sRGB24 139 69 19 x11Colour Coral = opaque $ sRGB24 255 127 80 x11Colour Coral1 = opaque $ sRGB24 255 114 86 x11Colour Coral2 = opaque $ sRGB24 238 106 80 x11Colour Coral3 = opaque $ sRGB24 205 91 69 x11Colour Coral4 = opaque $ sRGB24 139 62 47 x11Colour CornFlowerBlue = opaque $ sRGB24 100 149 237 x11Colour CornSilk = opaque $ sRGB24 255 248 220 x11Colour CornSilk1 = opaque $ sRGB24 255 248 220 x11Colour CornSilk2 = opaque $ sRGB24 238 232 205 x11Colour CornSilk3 = opaque $ sRGB24 205 200 177 x11Colour CornSilk4 = opaque $ sRGB24 139 136 120 x11Colour Crimson = opaque $ sRGB24 220 20 60 x11Colour Cyan = opaque $ sRGB24 0 255 255 x11Colour Cyan1 = opaque $ sRGB24 0 255 255 x11Colour Cyan2 = opaque $ sRGB24 0 238 238 x11Colour Cyan3 = opaque $ sRGB24 0 205 205 x11Colour Cyan4 = opaque $ sRGB24 0 139 139 x11Colour DarkGoldenrod = opaque $ sRGB24 184 134 11 x11Colour DarkGoldenrod1 = opaque $ sRGB24 255 185 15 x11Colour DarkGoldenrod2 = opaque $ sRGB24 238 173 14 x11Colour DarkGoldenrod3 = opaque $ sRGB24 205 149 12 x11Colour DarkGoldenrod4 = opaque $ sRGB24 139 101 8 x11Colour DarkGreen = opaque $ sRGB24 0 100 0 x11Colour Darkkhaki = opaque $ sRGB24 189 183 107 x11Colour DarkOliveGreen = opaque $ sRGB24 85 107 47 x11Colour DarkOliveGreen1 = opaque $ sRGB24 202 255 112 x11Colour DarkOliveGreen2 = opaque $ sRGB24 188 238 104 x11Colour DarkOliveGreen3 = opaque $ sRGB24 162 205 90 x11Colour DarkOliveGreen4 = opaque $ sRGB24 110 139 61 x11Colour DarkOrange = opaque $ sRGB24 255 140 0 x11Colour DarkOrange1 = opaque $ sRGB24 255 127 0 x11Colour DarkOrange2 = opaque $ sRGB24 238 118 0 x11Colour DarkOrange3 = opaque $ sRGB24 205 102 0 x11Colour DarkOrange4 = opaque $ sRGB24 139 69 0 x11Colour DarkOrchid = opaque $ sRGB24 153 50 204 x11Colour DarkOrchid1 = opaque $ sRGB24 191 62 255 x11Colour DarkOrchid2 = opaque $ sRGB24 178 58 238 x11Colour DarkOrchid3 = opaque $ sRGB24 154 50 205 x11Colour DarkOrchid4 = opaque $ sRGB24 104 34 139 x11Colour DarkSalmon = opaque $ sRGB24 233 150 122 x11Colour DarkSeaGreen = opaque $ sRGB24 143 188 143 x11Colour DarkSeaGreen1 = opaque $ sRGB24 193 255 193 x11Colour DarkSeaGreen2 = opaque $ sRGB24 180 238 180 x11Colour DarkSeaGreen3 = opaque $ sRGB24 155 205 155 x11Colour DarkSeaGreen4 = opaque $ sRGB24 105 139 105 x11Colour DarkSlateBlue = opaque $ sRGB24 72 61 139 x11Colour DarkSlateGray = opaque $ sRGB24 47 79 79 x11Colour DarkSlateGray1 = opaque $ sRGB24 151 255 255 x11Colour DarkSlateGray2 = opaque $ sRGB24 141 238 238 x11Colour DarkSlateGray3 = opaque $ sRGB24 121 205 205 x11Colour DarkSlateGray4 = opaque $ sRGB24 82 139 139 x11Colour DarkTurquoise = opaque $ sRGB24 0 206 209 x11Colour DarkViolet = opaque $ sRGB24 148 0 211 x11Colour DeepPink = opaque $ sRGB24 255 20 147 x11Colour DeepPink1 = opaque $ sRGB24 255 20 147 x11Colour DeepPink2 = opaque $ sRGB24 238 18 137 x11Colour DeepPink3 = opaque $ sRGB24 205 16 118 x11Colour DeepPink4 = opaque $ sRGB24 139 10 80 x11Colour DeepSkyBlue = opaque $ sRGB24 0 191 255 x11Colour DeepSkyBlue1 = opaque $ sRGB24 0 191 255 x11Colour DeepSkyBlue2 = opaque $ sRGB24 0 178 238 x11Colour DeepSkyBlue3 = opaque $ sRGB24 0 154 205 x11Colour DeepSkyBlue4 = opaque $ sRGB24 0 104 139 x11Colour DimGray = opaque $ sRGB24 105 105 105 x11Colour DodgerBlue = opaque $ sRGB24 30 144 255 x11Colour DodgerBlue1 = opaque $ sRGB24 30 144 255 x11Colour DodgerBlue2 = opaque $ sRGB24 28 134 238 x11Colour DodgerBlue3 = opaque $ sRGB24 24 116 205 x11Colour DodgerBlue4 = opaque $ sRGB24 16 78 139 x11Colour Firebrick = opaque $ sRGB24 178 34 34 x11Colour Firebrick1 = opaque $ sRGB24 255 48 48 x11Colour Firebrick2 = opaque $ sRGB24 238 44 44 x11Colour Firebrick3 = opaque $ sRGB24 205 38 38 x11Colour Firebrick4 = opaque $ sRGB24 139 26 26 x11Colour FloralWhite = opaque $ sRGB24 255 250 240 x11Colour ForestGreen = opaque $ sRGB24 34 139 34 x11Colour Gainsboro = opaque $ sRGB24 220 220 220 x11Colour GhostWhite = opaque $ sRGB24 248 248 255 x11Colour Gold = opaque $ sRGB24 255 215 0 x11Colour Gold1 = opaque $ sRGB24 255 215 0 x11Colour Gold2 = opaque $ sRGB24 238 201 0 x11Colour Gold3 = opaque $ sRGB24 205 173 0 x11Colour Gold4 = opaque $ sRGB24 139 117 0 x11Colour Goldenrod = opaque $ sRGB24 218 165 32 x11Colour Goldenrod1 = opaque $ sRGB24 255 193 37 x11Colour Goldenrod2 = opaque $ sRGB24 238 180 34 x11Colour Goldenrod3 = opaque $ sRGB24 205 155 29 x11Colour Goldenrod4 = opaque $ sRGB24 139 105 20 x11Colour Gray = opaque $ sRGB24 192 192 192 x11Colour Gray0 = opaque $ sRGB24 0 0 0 x11Colour Gray1 = opaque $ sRGB24 3 3 3 x11Colour Gray2 = opaque $ sRGB24 5 5 5 x11Colour Gray3 = opaque $ sRGB24 8 8 8 x11Colour Gray4 = opaque $ sRGB24 10 10 10 x11Colour Gray5 = opaque $ sRGB24 13 13 13 x11Colour Gray6 = opaque $ sRGB24 15 15 15 x11Colour Gray7 = opaque $ sRGB24 18 18 18 x11Colour Gray8 = opaque $ sRGB24 20 20 20 x11Colour Gray9 = opaque $ sRGB24 23 23 23 x11Colour Gray10 = opaque $ sRGB24 26 26 26 x11Colour Gray11 = opaque $ sRGB24 28 28 28 x11Colour Gray12 = opaque $ sRGB24 31 31 31 x11Colour Gray13 = opaque $ sRGB24 33 33 33 x11Colour Gray14 = opaque $ sRGB24 36 36 36 x11Colour Gray15 = opaque $ sRGB24 38 38 38 x11Colour Gray16 = opaque $ sRGB24 41 41 41 x11Colour Gray17 = opaque $ sRGB24 43 43 43 x11Colour Gray18 = opaque $ sRGB24 46 46 46 x11Colour Gray19 = opaque $ sRGB24 48 48 48 x11Colour Gray20 = opaque $ sRGB24 51 51 51 x11Colour Gray21 = opaque $ sRGB24 54 54 54 x11Colour Gray22 = opaque $ sRGB24 56 56 56 x11Colour Gray23 = opaque $ sRGB24 59 59 59 x11Colour Gray24 = opaque $ sRGB24 61 61 61 x11Colour Gray25 = opaque $ sRGB24 64 64 64 x11Colour Gray26 = opaque $ sRGB24 66 66 66 x11Colour Gray27 = opaque $ sRGB24 69 69 69 x11Colour Gray28 = opaque $ sRGB24 71 71 71 x11Colour Gray29 = opaque $ sRGB24 74 74 74 x11Colour Gray30 = opaque $ sRGB24 77 77 77 x11Colour Gray31 = opaque $ sRGB24 79 79 79 x11Colour Gray32 = opaque $ sRGB24 82 82 82 x11Colour Gray33 = opaque $ sRGB24 84 84 84 x11Colour Gray34 = opaque $ sRGB24 87 87 87 x11Colour Gray35 = opaque $ sRGB24 89 89 89 x11Colour Gray36 = opaque $ sRGB24 92 92 92 x11Colour Gray37 = opaque $ sRGB24 94 94 94 x11Colour Gray38 = opaque $ sRGB24 97 97 97 x11Colour Gray39 = opaque $ sRGB24 99 99 99 x11Colour Gray40 = opaque $ sRGB24 102 102 102 x11Colour Gray41 = opaque $ sRGB24 105 105 105 x11Colour Gray42 = opaque $ sRGB24 107 107 107 x11Colour Gray43 = opaque $ sRGB24 110 110 110 x11Colour Gray44 = opaque $ sRGB24 112 112 112 x11Colour Gray45 = opaque $ sRGB24 115 115 115 x11Colour Gray46 = opaque $ sRGB24 117 117 117 x11Colour Gray47 = opaque $ sRGB24 120 120 120 x11Colour Gray48 = opaque $ sRGB24 122 122 122 x11Colour Gray49 = opaque $ sRGB24 125 125 125 x11Colour Gray50 = opaque $ sRGB24 127 127 127 x11Colour Gray51 = opaque $ sRGB24 130 130 130 x11Colour Gray52 = opaque $ sRGB24 133 133 133 x11Colour Gray53 = opaque $ sRGB24 135 135 135 x11Colour Gray54 = opaque $ sRGB24 138 138 138 x11Colour Gray55 = opaque $ sRGB24 140 140 140 x11Colour Gray56 = opaque $ sRGB24 143 143 143 x11Colour Gray57 = opaque $ sRGB24 145 145 145 x11Colour Gray58 = opaque $ sRGB24 148 148 148 x11Colour Gray59 = opaque $ sRGB24 150 150 150 x11Colour Gray60 = opaque $ sRGB24 153 153 153 x11Colour Gray61 = opaque $ sRGB24 156 156 156 x11Colour Gray62 = opaque $ sRGB24 158 158 158 x11Colour Gray63 = opaque $ sRGB24 161 161 161 x11Colour Gray64 = opaque $ sRGB24 163 163 163 x11Colour Gray65 = opaque $ sRGB24 166 166 166 x11Colour Gray66 = opaque $ sRGB24 168 168 168 x11Colour Gray67 = opaque $ sRGB24 171 171 171 x11Colour Gray68 = opaque $ sRGB24 173 173 173 x11Colour Gray69 = opaque $ sRGB24 176 176 176 x11Colour Gray70 = opaque $ sRGB24 179 179 179 x11Colour Gray71 = opaque $ sRGB24 181 181 181 x11Colour Gray72 = opaque $ sRGB24 184 184 184 x11Colour Gray73 = opaque $ sRGB24 186 186 186 x11Colour Gray74 = opaque $ sRGB24 189 189 189 x11Colour Gray75 = opaque $ sRGB24 191 191 191 x11Colour Gray76 = opaque $ sRGB24 194 194 194 x11Colour Gray77 = opaque $ sRGB24 196 196 196 x11Colour Gray78 = opaque $ sRGB24 199 199 199 x11Colour Gray79 = opaque $ sRGB24 201 201 201 x11Colour Gray80 = opaque $ sRGB24 204 204 204 x11Colour Gray81 = opaque $ sRGB24 207 207 207 x11Colour Gray82 = opaque $ sRGB24 209 209 209 x11Colour Gray83 = opaque $ sRGB24 212 212 212 x11Colour Gray84 = opaque $ sRGB24 214 214 214 x11Colour Gray85 = opaque $ sRGB24 217 217 217 x11Colour Gray86 = opaque $ sRGB24 219 219 219 x11Colour Gray87 = opaque $ sRGB24 222 222 222 x11Colour Gray88 = opaque $ sRGB24 224 224 224 x11Colour Gray89 = opaque $ sRGB24 227 227 227 x11Colour Gray90 = opaque $ sRGB24 229 229 229 x11Colour Gray91 = opaque $ sRGB24 232 232 232 x11Colour Gray92 = opaque $ sRGB24 235 235 235 x11Colour Gray93 = opaque $ sRGB24 237 237 237 x11Colour Gray94 = opaque $ sRGB24 240 240 240 x11Colour Gray95 = opaque $ sRGB24 242 242 242 x11Colour Gray96 = opaque $ sRGB24 245 245 245 x11Colour Gray97 = opaque $ sRGB24 247 247 247 x11Colour Gray98 = opaque $ sRGB24 250 250 250 x11Colour Gray99 = opaque $ sRGB24 252 252 252 x11Colour Gray100 = opaque $ sRGB24 255 255 255 x11Colour Green = opaque $ sRGB24 0 255 0 x11Colour Green1 = opaque $ sRGB24 0 255 0 x11Colour Green2 = opaque $ sRGB24 0 238 0 x11Colour Green3 = opaque $ sRGB24 0 205 0 x11Colour Green4 = opaque $ sRGB24 0 139 0 x11Colour GreenYellow = opaque $ sRGB24 173 255 47 x11Colour HoneyDew = opaque $ sRGB24 240 255 240 x11Colour HoneyDew1 = opaque $ sRGB24 240 255 240 x11Colour HoneyDew2 = opaque $ sRGB24 224 238 224 x11Colour HoneyDew3 = opaque $ sRGB24 193 205 193 x11Colour HoneyDew4 = opaque $ sRGB24 131 139 131 x11Colour HotPink = opaque $ sRGB24 255 105 180 x11Colour HotPink1 = opaque $ sRGB24 255 110 180 x11Colour HotPink2 = opaque $ sRGB24 238 106 167 x11Colour HotPink3 = opaque $ sRGB24 205 96 144 x11Colour HotPink4 = opaque $ sRGB24 139 58 98 x11Colour IndianRed = opaque $ sRGB24 205 92 92 x11Colour IndianRed1 = opaque $ sRGB24 255 106 106 x11Colour IndianRed2 = opaque $ sRGB24 238 99 99 x11Colour IndianRed3 = opaque $ sRGB24 205 85 85 x11Colour IndianRed4 = opaque $ sRGB24 139 58 58 x11Colour Indigo = opaque $ sRGB24 75 0 130 x11Colour Ivory = opaque $ sRGB24 255 255 240 x11Colour Ivory1 = opaque $ sRGB24 255 255 240 x11Colour Ivory2 = opaque $ sRGB24 238 238 224 x11Colour Ivory3 = opaque $ sRGB24 205 205 193 x11Colour Ivory4 = opaque $ sRGB24 139 139 131 x11Colour Khaki = opaque $ sRGB24 240 230 140 x11Colour Khaki1 = opaque $ sRGB24 255 246 143 x11Colour Khaki2 = opaque $ sRGB24 238 230 133 x11Colour Khaki3 = opaque $ sRGB24 205 198 115 x11Colour Khaki4 = opaque $ sRGB24 139 134 78 x11Colour Lavender = opaque $ sRGB24 230 230 250 x11Colour LavenderBlush = opaque $ sRGB24 255 240 245 x11Colour LavenderBlush1 = opaque $ sRGB24 255 240 245 x11Colour LavenderBlush2 = opaque $ sRGB24 238 224 229 x11Colour LavenderBlush3 = opaque $ sRGB24 205 193 197 x11Colour LavenderBlush4 = opaque $ sRGB24 139 131 134 x11Colour LawnGreen = opaque $ sRGB24 124 252 0 x11Colour LemonChiffon = opaque $ sRGB24 255 250 205 x11Colour LemonChiffon1 = opaque $ sRGB24 255 250 205 x11Colour LemonChiffon2 = opaque $ sRGB24 238 233 191 x11Colour LemonChiffon3 = opaque $ sRGB24 205 201 165 x11Colour LemonChiffon4 = opaque $ sRGB24 139 137 112 x11Colour LightBlue = opaque $ sRGB24 173 216 230 x11Colour LightBlue1 = opaque $ sRGB24 191 239 255 x11Colour LightBlue2 = opaque $ sRGB24 178 223 238 x11Colour LightBlue3 = opaque $ sRGB24 154 192 205 x11Colour LightBlue4 = opaque $ sRGB24 104 131 139 x11Colour LightCoral = opaque $ sRGB24 240 128 128 x11Colour LightCyan = opaque $ sRGB24 224 255 255 x11Colour LightCyan1 = opaque $ sRGB24 224 255 255 x11Colour LightCyan2 = opaque $ sRGB24 209 238 238 x11Colour LightCyan3 = opaque $ sRGB24 180 205 205 x11Colour LightCyan4 = opaque $ sRGB24 122 139 139 x11Colour LightGoldenrod = opaque $ sRGB24 238 221 130 x11Colour LightGoldenrod1 = opaque $ sRGB24 255 236 139 x11Colour LightGoldenrod2 = opaque $ sRGB24 238 220 130 x11Colour LightGoldenrod3 = opaque $ sRGB24 205 190 112 x11Colour LightGoldenrod4 = opaque $ sRGB24 139 129 76 x11Colour LightGoldenrodYellow = opaque $ sRGB24 250 250 210 x11Colour LightGray = opaque $ sRGB24 211 211 211 x11Colour LightPink = opaque $ sRGB24 255 182 193 x11Colour LightPink1 = opaque $ sRGB24 255 174 185 x11Colour LightPink2 = opaque $ sRGB24 238 162 173 x11Colour LightPink3 = opaque $ sRGB24 205 140 149 x11Colour LightPink4 = opaque $ sRGB24 139 95 101 x11Colour LightSalmon = opaque $ sRGB24 255 160 122 x11Colour LightSalmon1 = opaque $ sRGB24 255 160 122 x11Colour LightSalmon2 = opaque $ sRGB24 238 149 114 x11Colour LightSalmon3 = opaque $ sRGB24 205 129 98 x11Colour LightSalmon4 = opaque $ sRGB24 139 87 66 x11Colour LightSeaGreen = opaque $ sRGB24 32 178 170 x11Colour LightSkyBlue = opaque $ sRGB24 135 206 250 x11Colour LightSkyBlue1 = opaque $ sRGB24 176 226 255 x11Colour LightSkyBlue2 = opaque $ sRGB24 164 211 238 x11Colour LightSkyBlue3 = opaque $ sRGB24 141 182 205 x11Colour LightSkyBlue4 = opaque $ sRGB24 96 123 139 x11Colour LightSlateBlue = opaque $ sRGB24 132 112 255 x11Colour LightSlateGray = opaque $ sRGB24 119 136 153 x11Colour LightSteelBlue = opaque $ sRGB24 176 196 222 x11Colour LightSteelBlue1 = opaque $ sRGB24 202 225 255 x11Colour LightSteelBlue2 = opaque $ sRGB24 188 210 238 x11Colour LightSteelBlue3 = opaque $ sRGB24 162 181 205 x11Colour LightSteelBlue4 = opaque $ sRGB24 110 123 139 x11Colour LightYellow = opaque $ sRGB24 255 255 224 x11Colour LightYellow1 = opaque $ sRGB24 255 255 224 x11Colour LightYellow2 = opaque $ sRGB24 238 238 209 x11Colour LightYellow3 = opaque $ sRGB24 205 205 180 x11Colour LightYellow4 = opaque $ sRGB24 139 139 122 x11Colour LimeGreen = opaque $ sRGB24 50 205 50 x11Colour Linen = opaque $ sRGB24 250 240 230 x11Colour Magenta = opaque $ sRGB24 255 0 255 x11Colour Magenta1 = opaque $ sRGB24 255 0 255 x11Colour Magenta2 = opaque $ sRGB24 238 0 238 x11Colour Magenta3 = opaque $ sRGB24 205 0 205 x11Colour Magenta4 = opaque $ sRGB24 139 0 139 x11Colour Maroon = opaque $ sRGB24 176 48 96 x11Colour Maroon1 = opaque $ sRGB24 255 52 179 x11Colour Maroon2 = opaque $ sRGB24 238 48 167 x11Colour Maroon3 = opaque $ sRGB24 205 41 144 x11Colour Maroon4 = opaque $ sRGB24 139 28 98 x11Colour MediumAquamarine = opaque $ sRGB24 102 205 170 x11Colour MediumBlue = opaque $ sRGB24 0 0 205 x11Colour MediumOrchid = opaque $ sRGB24 186 85 211 x11Colour MediumOrchid1 = opaque $ sRGB24 224 102 255 x11Colour MediumOrchid2 = opaque $ sRGB24 209 95 238 x11Colour MediumOrchid3 = opaque $ sRGB24 180 82 205 x11Colour MediumOrchid4 = opaque $ sRGB24 122 55 139 x11Colour MediumPurple = opaque $ sRGB24 147 112 219 x11Colour MediumPurple1 = opaque $ sRGB24 171 130 255 x11Colour MediumPurple2 = opaque $ sRGB24 159 121 238 x11Colour MediumPurple3 = opaque $ sRGB24 137 104 205 x11Colour MediumPurple4 = opaque $ sRGB24 93 71 139 x11Colour MediumSeaGreen = opaque $ sRGB24 60 179 113 x11Colour MediumSlateBlue = opaque $ sRGB24 123 104 238 x11Colour MediumSpringGreen = opaque $ sRGB24 0 250 154 x11Colour MediumTurquoise = opaque $ sRGB24 72 209 204 x11Colour MediumVioletRed = opaque $ sRGB24 199 21 133 x11Colour MidnightBlue = opaque $ sRGB24 25 25 112 x11Colour MintCream = opaque $ sRGB24 245 255 250 x11Colour MistyRose = opaque $ sRGB24 255 228 225 x11Colour MistyRose1 = opaque $ sRGB24 255 228 225 x11Colour MistyRose2 = opaque $ sRGB24 238 213 210 x11Colour MistyRose3 = opaque $ sRGB24 205 183 181 x11Colour MistyRose4 = opaque $ sRGB24 139 125 123 x11Colour Moccasin = opaque $ sRGB24 255 228 181 x11Colour NavajoWhite = opaque $ sRGB24 255 222 173 x11Colour NavajoWhite1 = opaque $ sRGB24 255 222 173 x11Colour NavajoWhite2 = opaque $ sRGB24 238 207 161 x11Colour NavajoWhite3 = opaque $ sRGB24 205 179 139 x11Colour NavajoWhite4 = opaque $ sRGB24 139 121 94 x11Colour Navy = opaque $ sRGB24 0 0 128 x11Colour NavyBlue = opaque $ sRGB24 0 0 128 x11Colour OldLace = opaque $ sRGB24 253 245 230 x11Colour OliveDrab = opaque $ sRGB24 107 142 35 x11Colour OliveDrab1 = opaque $ sRGB24 192 255 62 x11Colour OliveDrab2 = opaque $ sRGB24 179 238 58 x11Colour OliveDrab3 = opaque $ sRGB24 154 205 50 x11Colour OliveDrab4 = opaque $ sRGB24 105 139 34 x11Colour Orange = opaque $ sRGB24 255 165 0 x11Colour Orange1 = opaque $ sRGB24 255 165 0 x11Colour Orange2 = opaque $ sRGB24 238 154 0 x11Colour Orange3 = opaque $ sRGB24 205 133 0 x11Colour Orange4 = opaque $ sRGB24 139 90 0 x11Colour OrangeRed = opaque $ sRGB24 255 69 0 x11Colour OrangeRed1 = opaque $ sRGB24 255 69 0 x11Colour OrangeRed2 = opaque $ sRGB24 238 64 0 x11Colour OrangeRed3 = opaque $ sRGB24 205 55 0 x11Colour OrangeRed4 = opaque $ sRGB24 139 37 0 x11Colour Orchid = opaque $ sRGB24 218 112 214 x11Colour Orchid1 = opaque $ sRGB24 255 131 250 x11Colour Orchid2 = opaque $ sRGB24 238 122 233 x11Colour Orchid3 = opaque $ sRGB24 205 105 201 x11Colour Orchid4 = opaque $ sRGB24 139 71 137 x11Colour PaleGoldenrod = opaque $ sRGB24 238 232 170 x11Colour PaleGreen = opaque $ sRGB24 152 251 152 x11Colour PaleGreen1 = opaque $ sRGB24 154 255 154 x11Colour PaleGreen2 = opaque $ sRGB24 144 238 144 x11Colour PaleGreen3 = opaque $ sRGB24 124 205 124 x11Colour PaleGreen4 = opaque $ sRGB24 84 139 84 x11Colour PaleTurquoise = opaque $ sRGB24 175 238 238 x11Colour PaleTurquoise1 = opaque $ sRGB24 187 255 255 x11Colour PaleTurquoise2 = opaque $ sRGB24 174 238 238 x11Colour PaleTurquoise3 = opaque $ sRGB24 150 205 205 x11Colour PaleTurquoise4 = opaque $ sRGB24 102 139 139 x11Colour PaleVioletRed = opaque $ sRGB24 219 112 147 x11Colour PaleVioletRed1 = opaque $ sRGB24 255 130 171 x11Colour PaleVioletRed2 = opaque $ sRGB24 238 121 159 x11Colour PaleVioletRed3 = opaque $ sRGB24 205 104 137 x11Colour PaleVioletRed4 = opaque $ sRGB24 139 71 93 x11Colour PapayaWhip = opaque $ sRGB24 255 239 213 x11Colour PeachPuff = opaque $ sRGB24 255 218 185 x11Colour PeachPuff1 = opaque $ sRGB24 255 218 185 x11Colour PeachPuff2 = opaque $ sRGB24 238 203 173 x11Colour PeachPuff3 = opaque $ sRGB24 205 175 149 x11Colour PeachPuff4 = opaque $ sRGB24 139 119 101 x11Colour Peru = opaque $ sRGB24 205 133 63 x11Colour Pink = opaque $ sRGB24 255 192 203 x11Colour Pink1 = opaque $ sRGB24 255 181 197 x11Colour Pink2 = opaque $ sRGB24 238 169 184 x11Colour Pink3 = opaque $ sRGB24 205 145 158 x11Colour Pink4 = opaque $ sRGB24 139 99 108 x11Colour Plum = opaque $ sRGB24 221 160 221 x11Colour Plum1 = opaque $ sRGB24 255 187 255 x11Colour Plum2 = opaque $ sRGB24 238 174 238 x11Colour Plum3 = opaque $ sRGB24 205 150 205 x11Colour Plum4 = opaque $ sRGB24 139 102 139 x11Colour PowderBlue = opaque $ sRGB24 176 224 230 x11Colour Purple = opaque $ sRGB24 160 32 240 x11Colour Purple1 = opaque $ sRGB24 155 48 255 x11Colour Purple2 = opaque $ sRGB24 145 44 238 x11Colour Purple3 = opaque $ sRGB24 125 38 205 x11Colour Purple4 = opaque $ sRGB24 85 26 139 x11Colour Red = opaque $ sRGB24 255 0 0 x11Colour Red1 = opaque $ sRGB24 255 0 0 x11Colour Red2 = opaque $ sRGB24 238 0 0 x11Colour Red3 = opaque $ sRGB24 205 0 0 x11Colour Red4 = opaque $ sRGB24 139 0 0 x11Colour RosyBrown = opaque $ sRGB24 188 143 143 x11Colour RosyBrown1 = opaque $ sRGB24 255 193 193 x11Colour RosyBrown2 = opaque $ sRGB24 238 180 180 x11Colour RosyBrown3 = opaque $ sRGB24 205 155 155 x11Colour RosyBrown4 = opaque $ sRGB24 139 105 105 x11Colour RoyalBlue = opaque $ sRGB24 65 105 225 x11Colour RoyalBlue1 = opaque $ sRGB24 72 118 255 x11Colour RoyalBlue2 = opaque $ sRGB24 67 110 238 x11Colour RoyalBlue3 = opaque $ sRGB24 58 95 205 x11Colour RoyalBlue4 = opaque $ sRGB24 39 64 139 x11Colour SaddleBrown = opaque $ sRGB24 139 69 19 x11Colour Salmon = opaque $ sRGB24 250 128 114 x11Colour Salmon1 = opaque $ sRGB24 255 140 105 x11Colour Salmon2 = opaque $ sRGB24 238 130 98 x11Colour Salmon3 = opaque $ sRGB24 205 112 84 x11Colour Salmon4 = opaque $ sRGB24 139 76 57 x11Colour SandyBrown = opaque $ sRGB24 244 164 96 x11Colour SeaGreen = opaque $ sRGB24 46 139 87 x11Colour SeaGreen1 = opaque $ sRGB24 84 255 159 x11Colour SeaGreen2 = opaque $ sRGB24 78 238 148 x11Colour SeaGreen3 = opaque $ sRGB24 67 205 128 x11Colour SeaGreen4 = opaque $ sRGB24 46 139 87 x11Colour SeaShell = opaque $ sRGB24 255 245 238 x11Colour SeaShell1 = opaque $ sRGB24 255 245 238 x11Colour SeaShell2 = opaque $ sRGB24 238 229 222 x11Colour SeaShell3 = opaque $ sRGB24 205 197 191 x11Colour SeaShell4 = opaque $ sRGB24 139 134 130 x11Colour Sienna = opaque $ sRGB24 160 82 45 x11Colour Sienna1 = opaque $ sRGB24 255 130 71 x11Colour Sienna2 = opaque $ sRGB24 238 121 66 x11Colour Sienna3 = opaque $ sRGB24 205 104 57 x11Colour Sienna4 = opaque $ sRGB24 139 71 38 x11Colour SkyBlue = opaque $ sRGB24 135 206 235 x11Colour SkyBlue1 = opaque $ sRGB24 135 206 255 x11Colour SkyBlue2 = opaque $ sRGB24 126 192 238 x11Colour SkyBlue3 = opaque $ sRGB24 108 166 205 x11Colour SkyBlue4 = opaque $ sRGB24 74 112 139 x11Colour SlateBlue = opaque $ sRGB24 106 90 205 x11Colour SlateBlue1 = opaque $ sRGB24 131 111 255 x11Colour SlateBlue2 = opaque $ sRGB24 122 103 238 x11Colour SlateBlue3 = opaque $ sRGB24 105 89 205 x11Colour SlateBlue4 = opaque $ sRGB24 71 60 139 x11Colour SlateGray = opaque $ sRGB24 112 128 144 x11Colour SlateGray1 = opaque $ sRGB24 198 226 255 x11Colour SlateGray2 = opaque $ sRGB24 185 211 238 x11Colour SlateGray3 = opaque $ sRGB24 159 182 205 x11Colour SlateGray4 = opaque $ sRGB24 108 123 139 x11Colour Snow = opaque $ sRGB24 255 250 250 x11Colour Snow1 = opaque $ sRGB24 255 250 250 x11Colour Snow2 = opaque $ sRGB24 238 233 233 x11Colour Snow3 = opaque $ sRGB24 205 201 201 x11Colour Snow4 = opaque $ sRGB24 139 137 137 x11Colour SpringGreen = opaque $ sRGB24 0 255 127 x11Colour SpringGreen1 = opaque $ sRGB24 0 255 127 x11Colour SpringGreen2 = opaque $ sRGB24 0 238 118 x11Colour SpringGreen3 = opaque $ sRGB24 0 205 102 x11Colour SpringGreen4 = opaque $ sRGB24 0 139 69 x11Colour SteelBlue = opaque $ sRGB24 70 130 180 x11Colour SteelBlue1 = opaque $ sRGB24 99 184 255 x11Colour SteelBlue2 = opaque $ sRGB24 92 172 238 x11Colour SteelBlue3 = opaque $ sRGB24 79 148 205 x11Colour SteelBlue4 = opaque $ sRGB24 54 100 139 x11Colour Tan = opaque $ sRGB24 210 180 140 x11Colour Tan1 = opaque $ sRGB24 255 165 79 x11Colour Tan2 = opaque $ sRGB24 238 154 73 x11Colour Tan3 = opaque $ sRGB24 205 133 63 x11Colour Tan4 = opaque $ sRGB24 139 90 43 x11Colour Thistle = opaque $ sRGB24 216 191 216 x11Colour Thistle1 = opaque $ sRGB24 255 225 255 x11Colour Thistle2 = opaque $ sRGB24 238 210 238 x11Colour Thistle3 = opaque $ sRGB24 205 181 205 x11Colour Thistle4 = opaque $ sRGB24 139 123 139 x11Colour Tomato = opaque $ sRGB24 255 99 71 x11Colour Tomato1 = opaque $ sRGB24 255 99 71 x11Colour Tomato2 = opaque $ sRGB24 238 92 66 x11Colour Tomato3 = opaque $ sRGB24 205 79 57 x11Colour Tomato4 = opaque $ sRGB24 139 54 38 x11Colour Transparent = transparent x11Colour Turquoise = opaque $ sRGB24 64 224 208 x11Colour Turquoise1 = opaque $ sRGB24 0 245 255 x11Colour Turquoise2 = opaque $ sRGB24 0 229 238 x11Colour Turquoise3 = opaque $ sRGB24 0 197 205 x11Colour Turquoise4 = opaque $ sRGB24 0 134 139 x11Colour Violet = opaque $ sRGB24 238 130 238 x11Colour VioletRed = opaque $ sRGB24 208 32 144 x11Colour VioletRed1 = opaque $ sRGB24 255 62 150 x11Colour VioletRed2 = opaque $ sRGB24 238 58 140 x11Colour VioletRed3 = opaque $ sRGB24 205 50 120 x11Colour VioletRed4 = opaque $ sRGB24 139 34 82 x11Colour Wheat = opaque $ sRGB24 245 222 179 x11Colour Wheat1 = opaque $ sRGB24 255 231 186 x11Colour Wheat2 = opaque $ sRGB24 238 216 174 x11Colour Wheat3 = opaque $ sRGB24 205 186 150 x11Colour Wheat4 = opaque $ sRGB24 139 126 102 x11Colour White = opaque $ sRGB24 255 255 255 x11Colour WhiteSmoke = opaque $ sRGB24 245 245 245 x11Colour Yellow = opaque $ sRGB24 255 255 0 x11Colour Yellow1 = opaque $ sRGB24 255 255 0 x11Colour Yellow2 = opaque $ sRGB24 238 238 0 x11Colour Yellow3 = opaque $ sRGB24 205 205 0 x11Colour Yellow4 = opaque $ sRGB24 139 139 0 x11Colour YellowGreen = opaque $ sRGB24 154 205 50
null
https://raw.githubusercontent.com/ivan-m/graphviz/42dbb6312d7edf789d7055079de7b4fa099a4acc/Data/GraphViz/Attributes/Colors/X11.hs
haskell
# LANGUAGE OverloadedStrings # ----------------------------------------------------------------------------- different from the \"normal\" X11 colors used (e.g. the inclusion | Convert an 'X11Color' to its equivalent 'Colour' value. Note that it uses 'AlphaColour' because of 'Transparent'; all other 'X11Color' values are completely opaque.
| Module : Data . GraphViz . Attributes . Colors . X11 Description : Specification of X11 colors . Copyright : ( c ) License : 3 - Clause BSD - style Maintainer : Graphviz 's definition of X11 colors differs from the \"normal\ " list installed on many systems at @/usr / share / X11 / rgb.txt@. For example , @Crimson@ is not a usual X11 color . Furthermore , all @Gray*@ colors are duplicated with @Grey*@ names . To simplify this , these duplicates have been removed but ' X11Color 's with " ( whether they have the duplicate spelling or not ) in their name are also parseable as if they were spelt with \"@grey@\ " . The complete list of X11 colors can be found at < #x11 > . Module : Data.GraphViz.Attributes.Colors.X11 Description : Specification of X11 colors. Copyright : (c) Ivan Lazar Miljenovic License : 3-Clause BSD-style Maintainer : Graphviz's definition of X11 colors differs from the \"normal\" list installed on many systems at @/usr/share/X11/rgb.txt@. For example, @Crimson@ is not a usual X11 color. Furthermore, all @Gray*@ colors are duplicated with @Grey*@ names. To simplify this, these duplicates have been removed but /all/ 'X11Color's with \"@Gray@\" (whether they have the duplicate spelling or not) in their name are also parseable as if they were spelt with \"@grey@\". The complete list of X11 colors can be found at <#x11>. -} module Data.GraphViz.Attributes.Colors.X11 ( X11Color(..) , x11Colour ) where import Data.GraphViz.Parsing import Data.GraphViz.Printing import Data.Colour( AlphaColour, opaque, transparent) import Data.Colour.SRGB(sRGB24) | The X11 colors that Graphviz uses . Note that these are slightly of @Crimson@ ) . Graphviz 's list of colors also duplicated almost all @Gray@ colors with @Grey@ ones ; parsing of an ' X11Color ' which is specified using \"grey\ " will succeed , even for those that do n't have the duplicate spelling ( e.g. @DarkSlateGray1@ ) . data X11Color = AliceBlue | AntiqueWhite | AntiqueWhite1 | AntiqueWhite2 | AntiqueWhite3 | AntiqueWhite4 | Aquamarine | Aquamarine1 | Aquamarine2 | Aquamarine3 | Aquamarine4 | Azure | Azure1 | Azure2 | Azure3 | Azure4 | Beige | Bisque | Bisque1 | Bisque2 | Bisque3 | Bisque4 | Black | BlanchedAlmond | Blue | Blue1 | Blue2 | Blue3 | Blue4 | BlueViolet | Brown | Brown1 | Brown2 | Brown3 | Brown4 | Burlywood | Burlywood1 | Burlywood2 | Burlywood3 | Burlywood4 | CadetBlue | CadetBlue1 | CadetBlue2 | CadetBlue3 | CadetBlue4 | Chartreuse | Chartreuse1 | Chartreuse2 | Chartreuse3 | Chartreuse4 | Chocolate | Chocolate1 | Chocolate2 | Chocolate3 | Chocolate4 | Coral | Coral1 | Coral2 | Coral3 | Coral4 | CornFlowerBlue | CornSilk | CornSilk1 | CornSilk2 | CornSilk3 | CornSilk4 | Crimson | Cyan | Cyan1 | Cyan2 | Cyan3 | Cyan4 | DarkGoldenrod | DarkGoldenrod1 | DarkGoldenrod2 | DarkGoldenrod3 | DarkGoldenrod4 | DarkGreen | Darkkhaki | DarkOliveGreen | DarkOliveGreen1 | DarkOliveGreen2 | DarkOliveGreen3 | DarkOliveGreen4 | DarkOrange | DarkOrange1 | DarkOrange2 | DarkOrange3 | DarkOrange4 | DarkOrchid | DarkOrchid1 | DarkOrchid2 | DarkOrchid3 | DarkOrchid4 | DarkSalmon | DarkSeaGreen | DarkSeaGreen1 | DarkSeaGreen2 | DarkSeaGreen3 | DarkSeaGreen4 | DarkSlateBlue | DarkSlateGray | DarkSlateGray1 | DarkSlateGray2 | DarkSlateGray3 | DarkSlateGray4 | DarkTurquoise | DarkViolet | DeepPink | DeepPink1 | DeepPink2 | DeepPink3 | DeepPink4 | DeepSkyBlue | DeepSkyBlue1 | DeepSkyBlue2 | DeepSkyBlue3 | DeepSkyBlue4 | DimGray | DodgerBlue | DodgerBlue1 | DodgerBlue2 | DodgerBlue3 | DodgerBlue4 | Firebrick | Firebrick1 | Firebrick2 | Firebrick3 | Firebrick4 | FloralWhite | ForestGreen | Gainsboro | GhostWhite | Gold | Gold1 | Gold2 | Gold3 | Gold4 | Goldenrod | Goldenrod1 | Goldenrod2 | Goldenrod3 | Goldenrod4 | Gray | Gray0 | Gray1 | Gray2 | Gray3 | Gray4 | Gray5 | Gray6 | Gray7 | Gray8 | Gray9 | Gray10 | Gray11 | Gray12 | Gray13 | Gray14 | Gray15 | Gray16 | Gray17 | Gray18 | Gray19 | Gray20 | Gray21 | Gray22 | Gray23 | Gray24 | Gray25 | Gray26 | Gray27 | Gray28 | Gray29 | Gray30 | Gray31 | Gray32 | Gray33 | Gray34 | Gray35 | Gray36 | Gray37 | Gray38 | Gray39 | Gray40 | Gray41 | Gray42 | Gray43 | Gray44 | Gray45 | Gray46 | Gray47 | Gray48 | Gray49 | Gray50 | Gray51 | Gray52 | Gray53 | Gray54 | Gray55 | Gray56 | Gray57 | Gray58 | Gray59 | Gray60 | Gray61 | Gray62 | Gray63 | Gray64 | Gray65 | Gray66 | Gray67 | Gray68 | Gray69 | Gray70 | Gray71 | Gray72 | Gray73 | Gray74 | Gray75 | Gray76 | Gray77 | Gray78 | Gray79 | Gray80 | Gray81 | Gray82 | Gray83 | Gray84 | Gray85 | Gray86 | Gray87 | Gray88 | Gray89 | Gray90 | Gray91 | Gray92 | Gray93 | Gray94 | Gray95 | Gray96 | Gray97 | Gray98 | Gray99 | Gray100 | Green | Green1 | Green2 | Green3 | Green4 | GreenYellow | HoneyDew | HoneyDew1 | HoneyDew2 | HoneyDew3 | HoneyDew4 | HotPink | HotPink1 | HotPink2 | HotPink3 | HotPink4 | IndianRed | IndianRed1 | IndianRed2 | IndianRed3 | IndianRed4 | Indigo | Ivory | Ivory1 | Ivory2 | Ivory3 | Ivory4 | Khaki | Khaki1 | Khaki2 | Khaki3 | Khaki4 | Lavender | LavenderBlush | LavenderBlush1 | LavenderBlush2 | LavenderBlush3 | LavenderBlush4 | LawnGreen | LemonChiffon | LemonChiffon1 | LemonChiffon2 | LemonChiffon3 | LemonChiffon4 | LightBlue | LightBlue1 | LightBlue2 | LightBlue3 | LightBlue4 | LightCoral | LightCyan | LightCyan1 | LightCyan2 | LightCyan3 | LightCyan4 | LightGoldenrod | LightGoldenrod1 | LightGoldenrod2 | LightGoldenrod3 | LightGoldenrod4 | LightGoldenrodYellow | LightGray | LightPink | LightPink1 | LightPink2 | LightPink3 | LightPink4 | LightSalmon | LightSalmon1 | LightSalmon2 | LightSalmon3 | LightSalmon4 | LightSeaGreen | LightSkyBlue | LightSkyBlue1 | LightSkyBlue2 | LightSkyBlue3 | LightSkyBlue4 | LightSlateBlue | LightSlateGray | LightSteelBlue | LightSteelBlue1 | LightSteelBlue2 | LightSteelBlue3 | LightSteelBlue4 | LightYellow | LightYellow1 | LightYellow2 | LightYellow3 | LightYellow4 | LimeGreen | Linen | Magenta | Magenta1 | Magenta2 | Magenta3 | Magenta4 | Maroon | Maroon1 | Maroon2 | Maroon3 | Maroon4 | MediumAquamarine | MediumBlue | MediumOrchid | MediumOrchid1 | MediumOrchid2 | MediumOrchid3 | MediumOrchid4 | MediumPurple | MediumPurple1 | MediumPurple2 | MediumPurple3 | MediumPurple4 | MediumSeaGreen | MediumSlateBlue | MediumSpringGreen | MediumTurquoise | MediumVioletRed | MidnightBlue | MintCream | MistyRose | MistyRose1 | MistyRose2 | MistyRose3 | MistyRose4 | Moccasin | NavajoWhite | NavajoWhite1 | NavajoWhite2 | NavajoWhite3 | NavajoWhite4 | Navy | NavyBlue | OldLace | OliveDrab | OliveDrab1 | OliveDrab2 | OliveDrab3 | OliveDrab4 | Orange | Orange1 | Orange2 | Orange3 | Orange4 | OrangeRed | OrangeRed1 | OrangeRed2 | OrangeRed3 | OrangeRed4 | Orchid | Orchid1 | Orchid2 | Orchid3 | Orchid4 | PaleGoldenrod | PaleGreen | PaleGreen1 | PaleGreen2 | PaleGreen3 | PaleGreen4 | PaleTurquoise | PaleTurquoise1 | PaleTurquoise2 | PaleTurquoise3 | PaleTurquoise4 | PaleVioletRed | PaleVioletRed1 | PaleVioletRed2 | PaleVioletRed3 | PaleVioletRed4 | PapayaWhip | PeachPuff | PeachPuff1 | PeachPuff2 | PeachPuff3 | PeachPuff4 | Peru | Pink | Pink1 | Pink2 | Pink3 | Pink4 | Plum | Plum1 | Plum2 | Plum3 | Plum4 | PowderBlue | Purple | Purple1 | Purple2 | Purple3 | Purple4 | Red | Red1 | Red2 | Red3 | Red4 | RosyBrown | RosyBrown1 | RosyBrown2 | RosyBrown3 | RosyBrown4 | RoyalBlue | RoyalBlue1 | RoyalBlue2 | RoyalBlue3 | RoyalBlue4 | SaddleBrown | Salmon | Salmon1 | Salmon2 | Salmon3 | Salmon4 | SandyBrown | SeaGreen | SeaGreen1 | SeaGreen2 | SeaGreen3 | SeaGreen4 | SeaShell | SeaShell1 | SeaShell2 | SeaShell3 | SeaShell4 | Sienna | Sienna1 | Sienna2 | Sienna3 | Sienna4 | SkyBlue | SkyBlue1 | SkyBlue2 | SkyBlue3 | SkyBlue4 | SlateBlue | SlateBlue1 | SlateBlue2 | SlateBlue3 | SlateBlue4 | SlateGray | SlateGray1 | SlateGray2 | SlateGray3 | SlateGray4 | Snow | Snow1 | Snow2 | Snow3 | Snow4 | SpringGreen | SpringGreen1 | SpringGreen2 | SpringGreen3 | SpringGreen4 | SteelBlue | SteelBlue1 | SteelBlue2 | SteelBlue3 | SteelBlue4 | Tan | Tan1 | Tan2 | Tan3 | Tan4 | Thistle | Thistle1 | Thistle2 | Thistle3 | Thistle4 | Tomato | Tomato1 | Tomato2 | Tomato3 | Tomato4 ^ Equivalent to setting [ SItem Invisible [ ] ] @. | Turquoise | Turquoise1 | Turquoise2 | Turquoise3 | Turquoise4 | Violet | VioletRed | VioletRed1 | VioletRed2 | VioletRed3 | VioletRed4 | Wheat | Wheat1 | Wheat2 | Wheat3 | Wheat4 | White | WhiteSmoke | Yellow | Yellow1 | Yellow2 | Yellow3 | Yellow4 | YellowGreen deriving (Eq, Ord, Bounded, Enum, Show, Read) instance PrintDot X11Color where unqtDot AliceBlue = unqtText "aliceblue" unqtDot AntiqueWhite = unqtText "antiquewhite" unqtDot AntiqueWhite1 = unqtText "antiquewhite1" unqtDot AntiqueWhite2 = unqtText "antiquewhite2" unqtDot AntiqueWhite3 = unqtText "antiquewhite3" unqtDot AntiqueWhite4 = unqtText "antiquewhite4" unqtDot Aquamarine = unqtText "aquamarine" unqtDot Aquamarine1 = unqtText "aquamarine1" unqtDot Aquamarine2 = unqtText "aquamarine2" unqtDot Aquamarine3 = unqtText "aquamarine3" unqtDot Aquamarine4 = unqtText "aquamarine4" unqtDot Azure = unqtText "azure" unqtDot Azure1 = unqtText "azure1" unqtDot Azure2 = unqtText "azure2" unqtDot Azure3 = unqtText "azure3" unqtDot Azure4 = unqtText "azure4" unqtDot Beige = unqtText "beige" unqtDot Bisque = unqtText "bisque" unqtDot Bisque1 = unqtText "bisque1" unqtDot Bisque2 = unqtText "bisque2" unqtDot Bisque3 = unqtText "bisque3" unqtDot Bisque4 = unqtText "bisque4" unqtDot Black = unqtText "black" unqtDot BlanchedAlmond = unqtText "blanchedalmond" unqtDot Blue = unqtText "blue" unqtDot Blue1 = unqtText "blue1" unqtDot Blue2 = unqtText "blue2" unqtDot Blue3 = unqtText "blue3" unqtDot Blue4 = unqtText "blue4" unqtDot BlueViolet = unqtText "blueviolet" unqtDot Brown = unqtText "brown" unqtDot Brown1 = unqtText "brown1" unqtDot Brown2 = unqtText "brown2" unqtDot Brown3 = unqtText "brown3" unqtDot Brown4 = unqtText "brown4" unqtDot Burlywood = unqtText "burlywood" unqtDot Burlywood1 = unqtText "burlywood1" unqtDot Burlywood2 = unqtText "burlywood2" unqtDot Burlywood3 = unqtText "burlywood3" unqtDot Burlywood4 = unqtText "burlywood4" unqtDot CadetBlue = unqtText "cadetblue" unqtDot CadetBlue1 = unqtText "cadetblue1" unqtDot CadetBlue2 = unqtText "cadetblue2" unqtDot CadetBlue3 = unqtText "cadetblue3" unqtDot CadetBlue4 = unqtText "cadetblue4" unqtDot Chartreuse = unqtText "chartreuse" unqtDot Chartreuse1 = unqtText "chartreuse1" unqtDot Chartreuse2 = unqtText "chartreuse2" unqtDot Chartreuse3 = unqtText "chartreuse3" unqtDot Chartreuse4 = unqtText "chartreuse4" unqtDot Chocolate = unqtText "chocolate" unqtDot Chocolate1 = unqtText "chocolate1" unqtDot Chocolate2 = unqtText "chocolate2" unqtDot Chocolate3 = unqtText "chocolate3" unqtDot Chocolate4 = unqtText "chocolate4" unqtDot Coral = unqtText "coral" unqtDot Coral1 = unqtText "coral1" unqtDot Coral2 = unqtText "coral2" unqtDot Coral3 = unqtText "coral3" unqtDot Coral4 = unqtText "coral4" unqtDot CornFlowerBlue = unqtText "cornflowerblue" unqtDot CornSilk = unqtText "cornsilk" unqtDot CornSilk1 = unqtText "cornsilk1" unqtDot CornSilk2 = unqtText "cornsilk2" unqtDot CornSilk3 = unqtText "cornsilk3" unqtDot CornSilk4 = unqtText "cornsilk4" unqtDot Crimson = unqtText "crimson" unqtDot Cyan = unqtText "cyan" unqtDot Cyan1 = unqtText "cyan1" unqtDot Cyan2 = unqtText "cyan2" unqtDot Cyan3 = unqtText "cyan3" unqtDot Cyan4 = unqtText "cyan4" unqtDot DarkGoldenrod = unqtText "darkgoldenrod" unqtDot DarkGoldenrod1 = unqtText "darkgoldenrod1" unqtDot DarkGoldenrod2 = unqtText "darkgoldenrod2" unqtDot DarkGoldenrod3 = unqtText "darkgoldenrod3" unqtDot DarkGoldenrod4 = unqtText "darkgoldenrod4" unqtDot DarkGreen = unqtText "darkgreen" unqtDot Darkkhaki = unqtText "darkkhaki" unqtDot DarkOliveGreen = unqtText "darkolivegreen" unqtDot DarkOliveGreen1 = unqtText "darkolivegreen1" unqtDot DarkOliveGreen2 = unqtText "darkolivegreen2" unqtDot DarkOliveGreen3 = unqtText "darkolivegreen3" unqtDot DarkOliveGreen4 = unqtText "darkolivegreen4" unqtDot DarkOrange = unqtText "darkorange" unqtDot DarkOrange1 = unqtText "darkorange1" unqtDot DarkOrange2 = unqtText "darkorange2" unqtDot DarkOrange3 = unqtText "darkorange3" unqtDot DarkOrange4 = unqtText "darkorange4" unqtDot DarkOrchid = unqtText "darkorchid" unqtDot DarkOrchid1 = unqtText "darkorchid1" unqtDot DarkOrchid2 = unqtText "darkorchid2" unqtDot DarkOrchid3 = unqtText "darkorchid3" unqtDot DarkOrchid4 = unqtText "darkorchid4" unqtDot DarkSalmon = unqtText "darksalmon" unqtDot DarkSeaGreen = unqtText "darkseagreen" unqtDot DarkSeaGreen1 = unqtText "darkseagreen1" unqtDot DarkSeaGreen2 = unqtText "darkseagreen2" unqtDot DarkSeaGreen3 = unqtText "darkseagreen3" unqtDot DarkSeaGreen4 = unqtText "darkseagreen4" unqtDot DarkSlateBlue = unqtText "darkslateblue" unqtDot DarkSlateGray = unqtText "darkslategray" unqtDot DarkSlateGray1 = unqtText "darkslategray1" unqtDot DarkSlateGray2 = unqtText "darkslategray2" unqtDot DarkSlateGray3 = unqtText "darkslategray3" unqtDot DarkSlateGray4 = unqtText "darkslategray4" unqtDot DarkTurquoise = unqtText "darkturquoise" unqtDot DarkViolet = unqtText "darkviolet" unqtDot DeepPink = unqtText "deeppink" unqtDot DeepPink1 = unqtText "deeppink1" unqtDot DeepPink2 = unqtText "deeppink2" unqtDot DeepPink3 = unqtText "deeppink3" unqtDot DeepPink4 = unqtText "deeppink4" unqtDot DeepSkyBlue = unqtText "deepskyblue" unqtDot DeepSkyBlue1 = unqtText "deepskyblue1" unqtDot DeepSkyBlue2 = unqtText "deepskyblue2" unqtDot DeepSkyBlue3 = unqtText "deepskyblue3" unqtDot DeepSkyBlue4 = unqtText "deepskyblue4" unqtDot DimGray = unqtText "dimgray" unqtDot DodgerBlue = unqtText "dodgerblue" unqtDot DodgerBlue1 = unqtText "dodgerblue1" unqtDot DodgerBlue2 = unqtText "dodgerblue2" unqtDot DodgerBlue3 = unqtText "dodgerblue3" unqtDot DodgerBlue4 = unqtText "dodgerblue4" unqtDot Firebrick = unqtText "firebrick" unqtDot Firebrick1 = unqtText "firebrick1" unqtDot Firebrick2 = unqtText "firebrick2" unqtDot Firebrick3 = unqtText "firebrick3" unqtDot Firebrick4 = unqtText "firebrick4" unqtDot FloralWhite = unqtText "floralwhite" unqtDot ForestGreen = unqtText "forestgreen" unqtDot Gainsboro = unqtText "gainsboro" unqtDot GhostWhite = unqtText "ghostwhite" unqtDot Gold = unqtText "gold" unqtDot Gold1 = unqtText "gold1" unqtDot Gold2 = unqtText "gold2" unqtDot Gold3 = unqtText "gold3" unqtDot Gold4 = unqtText "gold4" unqtDot Goldenrod = unqtText "goldenrod" unqtDot Goldenrod1 = unqtText "goldenrod1" unqtDot Goldenrod2 = unqtText "goldenrod2" unqtDot Goldenrod3 = unqtText "goldenrod3" unqtDot Goldenrod4 = unqtText "goldenrod4" unqtDot Gray = unqtText "gray" unqtDot Gray0 = unqtText "gray0" unqtDot Gray1 = unqtText "gray1" unqtDot Gray2 = unqtText "gray2" unqtDot Gray3 = unqtText "gray3" unqtDot Gray4 = unqtText "gray4" unqtDot Gray5 = unqtText "gray5" unqtDot Gray6 = unqtText "gray6" unqtDot Gray7 = unqtText "gray7" unqtDot Gray8 = unqtText "gray8" unqtDot Gray9 = unqtText "gray9" unqtDot Gray10 = unqtText "gray10" unqtDot Gray11 = unqtText "gray11" unqtDot Gray12 = unqtText "gray12" unqtDot Gray13 = unqtText "gray13" unqtDot Gray14 = unqtText "gray14" unqtDot Gray15 = unqtText "gray15" unqtDot Gray16 = unqtText "gray16" unqtDot Gray17 = unqtText "gray17" unqtDot Gray18 = unqtText "gray18" unqtDot Gray19 = unqtText "gray19" unqtDot Gray20 = unqtText "gray20" unqtDot Gray21 = unqtText "gray21" unqtDot Gray22 = unqtText "gray22" unqtDot Gray23 = unqtText "gray23" unqtDot Gray24 = unqtText "gray24" unqtDot Gray25 = unqtText "gray25" unqtDot Gray26 = unqtText "gray26" unqtDot Gray27 = unqtText "gray27" unqtDot Gray28 = unqtText "gray28" unqtDot Gray29 = unqtText "gray29" unqtDot Gray30 = unqtText "gray30" unqtDot Gray31 = unqtText "gray31" unqtDot Gray32 = unqtText "gray32" unqtDot Gray33 = unqtText "gray33" unqtDot Gray34 = unqtText "gray34" unqtDot Gray35 = unqtText "gray35" unqtDot Gray36 = unqtText "gray36" unqtDot Gray37 = unqtText "gray37" unqtDot Gray38 = unqtText "gray38" unqtDot Gray39 = unqtText "gray39" unqtDot Gray40 = unqtText "gray40" unqtDot Gray41 = unqtText "gray41" unqtDot Gray42 = unqtText "gray42" unqtDot Gray43 = unqtText "gray43" unqtDot Gray44 = unqtText "gray44" unqtDot Gray45 = unqtText "gray45" unqtDot Gray46 = unqtText "gray46" unqtDot Gray47 = unqtText "gray47" unqtDot Gray48 = unqtText "gray48" unqtDot Gray49 = unqtText "gray49" unqtDot Gray50 = unqtText "gray50" unqtDot Gray51 = unqtText "gray51" unqtDot Gray52 = unqtText "gray52" unqtDot Gray53 = unqtText "gray53" unqtDot Gray54 = unqtText "gray54" unqtDot Gray55 = unqtText "gray55" unqtDot Gray56 = unqtText "gray56" unqtDot Gray57 = unqtText "gray57" unqtDot Gray58 = unqtText "gray58" unqtDot Gray59 = unqtText "gray59" unqtDot Gray60 = unqtText "gray60" unqtDot Gray61 = unqtText "gray61" unqtDot Gray62 = unqtText "gray62" unqtDot Gray63 = unqtText "gray63" unqtDot Gray64 = unqtText "gray64" unqtDot Gray65 = unqtText "gray65" unqtDot Gray66 = unqtText "gray66" unqtDot Gray67 = unqtText "gray67" unqtDot Gray68 = unqtText "gray68" unqtDot Gray69 = unqtText "gray69" unqtDot Gray70 = unqtText "gray70" unqtDot Gray71 = unqtText "gray71" unqtDot Gray72 = unqtText "gray72" unqtDot Gray73 = unqtText "gray73" unqtDot Gray74 = unqtText "gray74" unqtDot Gray75 = unqtText "gray75" unqtDot Gray76 = unqtText "gray76" unqtDot Gray77 = unqtText "gray77" unqtDot Gray78 = unqtText "gray78" unqtDot Gray79 = unqtText "gray79" unqtDot Gray80 = unqtText "gray80" unqtDot Gray81 = unqtText "gray81" unqtDot Gray82 = unqtText "gray82" unqtDot Gray83 = unqtText "gray83" unqtDot Gray84 = unqtText "gray84" unqtDot Gray85 = unqtText "gray85" unqtDot Gray86 = unqtText "gray86" unqtDot Gray87 = unqtText "gray87" unqtDot Gray88 = unqtText "gray88" unqtDot Gray89 = unqtText "gray89" unqtDot Gray90 = unqtText "gray90" unqtDot Gray91 = unqtText "gray91" unqtDot Gray92 = unqtText "gray92" unqtDot Gray93 = unqtText "gray93" unqtDot Gray94 = unqtText "gray94" unqtDot Gray95 = unqtText "gray95" unqtDot Gray96 = unqtText "gray96" unqtDot Gray97 = unqtText "gray97" unqtDot Gray98 = unqtText "gray98" unqtDot Gray99 = unqtText "gray99" unqtDot Gray100 = unqtText "gray100" unqtDot Green = unqtText "green" unqtDot Green1 = unqtText "green1" unqtDot Green2 = unqtText "green2" unqtDot Green3 = unqtText "green3" unqtDot Green4 = unqtText "green4" unqtDot GreenYellow = unqtText "greenyellow" unqtDot HoneyDew = unqtText "honeydew" unqtDot HoneyDew1 = unqtText "honeydew1" unqtDot HoneyDew2 = unqtText "honeydew2" unqtDot HoneyDew3 = unqtText "honeydew3" unqtDot HoneyDew4 = unqtText "honeydew4" unqtDot HotPink = unqtText "hotpink" unqtDot HotPink1 = unqtText "hotpink1" unqtDot HotPink2 = unqtText "hotpink2" unqtDot HotPink3 = unqtText "hotpink3" unqtDot HotPink4 = unqtText "hotpink4" unqtDot IndianRed = unqtText "indianred" unqtDot IndianRed1 = unqtText "indianred1" unqtDot IndianRed2 = unqtText "indianred2" unqtDot IndianRed3 = unqtText "indianred3" unqtDot IndianRed4 = unqtText "indianred4" unqtDot Indigo = unqtText "indigo" unqtDot Ivory = unqtText "ivory" unqtDot Ivory1 = unqtText "ivory1" unqtDot Ivory2 = unqtText "ivory2" unqtDot Ivory3 = unqtText "ivory3" unqtDot Ivory4 = unqtText "ivory4" unqtDot Khaki = unqtText "khaki" unqtDot Khaki1 = unqtText "khaki1" unqtDot Khaki2 = unqtText "khaki2" unqtDot Khaki3 = unqtText "khaki3" unqtDot Khaki4 = unqtText "khaki4" unqtDot Lavender = unqtText "lavender" unqtDot LavenderBlush = unqtText "lavenderblush" unqtDot LavenderBlush1 = unqtText "lavenderblush1" unqtDot LavenderBlush2 = unqtText "lavenderblush2" unqtDot LavenderBlush3 = unqtText "lavenderblush3" unqtDot LavenderBlush4 = unqtText "lavenderblush4" unqtDot LawnGreen = unqtText "lawngreen" unqtDot LemonChiffon = unqtText "lemonchiffon" unqtDot LemonChiffon1 = unqtText "lemonchiffon1" unqtDot LemonChiffon2 = unqtText "lemonchiffon2" unqtDot LemonChiffon3 = unqtText "lemonchiffon3" unqtDot LemonChiffon4 = unqtText "lemonchiffon4" unqtDot LightBlue = unqtText "lightblue" unqtDot LightBlue1 = unqtText "lightblue1" unqtDot LightBlue2 = unqtText "lightblue2" unqtDot LightBlue3 = unqtText "lightblue3" unqtDot LightBlue4 = unqtText "lightblue4" unqtDot LightCoral = unqtText "lightcoral" unqtDot LightCyan = unqtText "lightcyan" unqtDot LightCyan1 = unqtText "lightcyan1" unqtDot LightCyan2 = unqtText "lightcyan2" unqtDot LightCyan3 = unqtText "lightcyan3" unqtDot LightCyan4 = unqtText "lightcyan4" unqtDot LightGoldenrod = unqtText "lightgoldenrod" unqtDot LightGoldenrod1 = unqtText "lightgoldenrod1" unqtDot LightGoldenrod2 = unqtText "lightgoldenrod2" unqtDot LightGoldenrod3 = unqtText "lightgoldenrod3" unqtDot LightGoldenrod4 = unqtText "lightgoldenrod4" unqtDot LightGoldenrodYellow = unqtText "lightgoldenrodyellow" unqtDot LightGray = unqtText "lightgray" unqtDot LightPink = unqtText "lightpink" unqtDot LightPink1 = unqtText "lightpink1" unqtDot LightPink2 = unqtText "lightpink2" unqtDot LightPink3 = unqtText "lightpink3" unqtDot LightPink4 = unqtText "lightpink4" unqtDot LightSalmon = unqtText "lightsalmon" unqtDot LightSalmon1 = unqtText "lightsalmon1" unqtDot LightSalmon2 = unqtText "lightsalmon2" unqtDot LightSalmon3 = unqtText "lightsalmon3" unqtDot LightSalmon4 = unqtText "lightsalmon4" unqtDot LightSeaGreen = unqtText "lightseagreen" unqtDot LightSkyBlue = unqtText "lightskyblue" unqtDot LightSkyBlue1 = unqtText "lightskyblue1" unqtDot LightSkyBlue2 = unqtText "lightskyblue2" unqtDot LightSkyBlue3 = unqtText "lightskyblue3" unqtDot LightSkyBlue4 = unqtText "lightskyblue4" unqtDot LightSlateBlue = unqtText "lightslateblue" unqtDot LightSlateGray = unqtText "lightslategray" unqtDot LightSteelBlue = unqtText "lightsteelblue" unqtDot LightSteelBlue1 = unqtText "lightsteelblue1" unqtDot LightSteelBlue2 = unqtText "lightsteelblue2" unqtDot LightSteelBlue3 = unqtText "lightsteelblue3" unqtDot LightSteelBlue4 = unqtText "lightsteelblue4" unqtDot LightYellow = unqtText "lightyellow" unqtDot LightYellow1 = unqtText "lightyellow1" unqtDot LightYellow2 = unqtText "lightyellow2" unqtDot LightYellow3 = unqtText "lightyellow3" unqtDot LightYellow4 = unqtText "lightyellow4" unqtDot LimeGreen = unqtText "limegreen" unqtDot Linen = unqtText "linen" unqtDot Magenta = unqtText "magenta" unqtDot Magenta1 = unqtText "magenta1" unqtDot Magenta2 = unqtText "magenta2" unqtDot Magenta3 = unqtText "magenta3" unqtDot Magenta4 = unqtText "magenta4" unqtDot Maroon = unqtText "maroon" unqtDot Maroon1 = unqtText "maroon1" unqtDot Maroon2 = unqtText "maroon2" unqtDot Maroon3 = unqtText "maroon3" unqtDot Maroon4 = unqtText "maroon4" unqtDot MediumAquamarine = unqtText "mediumaquamarine" unqtDot MediumBlue = unqtText "mediumblue" unqtDot MediumOrchid = unqtText "mediumorchid" unqtDot MediumOrchid1 = unqtText "mediumorchid1" unqtDot MediumOrchid2 = unqtText "mediumorchid2" unqtDot MediumOrchid3 = unqtText "mediumorchid3" unqtDot MediumOrchid4 = unqtText "mediumorchid4" unqtDot MediumPurple = unqtText "mediumpurple" unqtDot MediumPurple1 = unqtText "mediumpurple1" unqtDot MediumPurple2 = unqtText "mediumpurple2" unqtDot MediumPurple3 = unqtText "mediumpurple3" unqtDot MediumPurple4 = unqtText "mediumpurple4" unqtDot MediumSeaGreen = unqtText "mediumseagreen" unqtDot MediumSlateBlue = unqtText "mediumslateblue" unqtDot MediumSpringGreen = unqtText "mediumspringgreen" unqtDot MediumTurquoise = unqtText "mediumturquoise" unqtDot MediumVioletRed = unqtText "mediumvioletred" unqtDot MidnightBlue = unqtText "midnightblue" unqtDot MintCream = unqtText "mintcream" unqtDot MistyRose = unqtText "mistyrose" unqtDot MistyRose1 = unqtText "mistyrose1" unqtDot MistyRose2 = unqtText "mistyrose2" unqtDot MistyRose3 = unqtText "mistyrose3" unqtDot MistyRose4 = unqtText "mistyrose4" unqtDot Moccasin = unqtText "moccasin" unqtDot NavajoWhite = unqtText "navajowhite" unqtDot NavajoWhite1 = unqtText "navajowhite1" unqtDot NavajoWhite2 = unqtText "navajowhite2" unqtDot NavajoWhite3 = unqtText "navajowhite3" unqtDot NavajoWhite4 = unqtText "navajowhite4" unqtDot Navy = unqtText "navy" unqtDot NavyBlue = unqtText "navyblue" unqtDot OldLace = unqtText "oldlace" unqtDot OliveDrab = unqtText "olivedrab" unqtDot OliveDrab1 = unqtText "olivedrab1" unqtDot OliveDrab2 = unqtText "olivedrab2" unqtDot OliveDrab3 = unqtText "olivedrab3" unqtDot OliveDrab4 = unqtText "olivedrab4" unqtDot Orange = unqtText "orange" unqtDot Orange1 = unqtText "orange1" unqtDot Orange2 = unqtText "orange2" unqtDot Orange3 = unqtText "orange3" unqtDot Orange4 = unqtText "orange4" unqtDot OrangeRed = unqtText "orangered" unqtDot OrangeRed1 = unqtText "orangered1" unqtDot OrangeRed2 = unqtText "orangered2" unqtDot OrangeRed3 = unqtText "orangered3" unqtDot OrangeRed4 = unqtText "orangered4" unqtDot Orchid = unqtText "orchid" unqtDot Orchid1 = unqtText "orchid1" unqtDot Orchid2 = unqtText "orchid2" unqtDot Orchid3 = unqtText "orchid3" unqtDot Orchid4 = unqtText "orchid4" unqtDot PaleGoldenrod = unqtText "palegoldenrod" unqtDot PaleGreen = unqtText "palegreen" unqtDot PaleGreen1 = unqtText "palegreen1" unqtDot PaleGreen2 = unqtText "palegreen2" unqtDot PaleGreen3 = unqtText "palegreen3" unqtDot PaleGreen4 = unqtText "palegreen4" unqtDot PaleTurquoise = unqtText "paleturquoise" unqtDot PaleTurquoise1 = unqtText "paleturquoise1" unqtDot PaleTurquoise2 = unqtText "paleturquoise2" unqtDot PaleTurquoise3 = unqtText "paleturquoise3" unqtDot PaleTurquoise4 = unqtText "paleturquoise4" unqtDot PaleVioletRed = unqtText "palevioletred" unqtDot PaleVioletRed1 = unqtText "palevioletred1" unqtDot PaleVioletRed2 = unqtText "palevioletred2" unqtDot PaleVioletRed3 = unqtText "palevioletred3" unqtDot PaleVioletRed4 = unqtText "palevioletred4" unqtDot PapayaWhip = unqtText "papayawhip" unqtDot PeachPuff = unqtText "peachpuff" unqtDot PeachPuff1 = unqtText "peachpuff1" unqtDot PeachPuff2 = unqtText "peachpuff2" unqtDot PeachPuff3 = unqtText "peachpuff3" unqtDot PeachPuff4 = unqtText "peachpuff4" unqtDot Peru = unqtText "peru" unqtDot Pink = unqtText "pink" unqtDot Pink1 = unqtText "pink1" unqtDot Pink2 = unqtText "pink2" unqtDot Pink3 = unqtText "pink3" unqtDot Pink4 = unqtText "pink4" unqtDot Plum = unqtText "plum" unqtDot Plum1 = unqtText "plum1" unqtDot Plum2 = unqtText "plum2" unqtDot Plum3 = unqtText "plum3" unqtDot Plum4 = unqtText "plum4" unqtDot PowderBlue = unqtText "powderblue" unqtDot Purple = unqtText "purple" unqtDot Purple1 = unqtText "purple1" unqtDot Purple2 = unqtText "purple2" unqtDot Purple3 = unqtText "purple3" unqtDot Purple4 = unqtText "purple4" unqtDot Red = unqtText "red" unqtDot Red1 = unqtText "red1" unqtDot Red2 = unqtText "red2" unqtDot Red3 = unqtText "red3" unqtDot Red4 = unqtText "red4" unqtDot RosyBrown = unqtText "rosybrown" unqtDot RosyBrown1 = unqtText "rosybrown1" unqtDot RosyBrown2 = unqtText "rosybrown2" unqtDot RosyBrown3 = unqtText "rosybrown3" unqtDot RosyBrown4 = unqtText "rosybrown4" unqtDot RoyalBlue = unqtText "royalblue" unqtDot RoyalBlue1 = unqtText "royalblue1" unqtDot RoyalBlue2 = unqtText "royalblue2" unqtDot RoyalBlue3 = unqtText "royalblue3" unqtDot RoyalBlue4 = unqtText "royalblue4" unqtDot SaddleBrown = unqtText "saddlebrown" unqtDot Salmon = unqtText "salmon" unqtDot Salmon1 = unqtText "salmon1" unqtDot Salmon2 = unqtText "salmon2" unqtDot Salmon3 = unqtText "salmon3" unqtDot Salmon4 = unqtText "salmon4" unqtDot SandyBrown = unqtText "sandybrown" unqtDot SeaGreen = unqtText "seagreen" unqtDot SeaGreen1 = unqtText "seagreen1" unqtDot SeaGreen2 = unqtText "seagreen2" unqtDot SeaGreen3 = unqtText "seagreen3" unqtDot SeaGreen4 = unqtText "seagreen4" unqtDot SeaShell = unqtText "seashell" unqtDot SeaShell1 = unqtText "seashell1" unqtDot SeaShell2 = unqtText "seashell2" unqtDot SeaShell3 = unqtText "seashell3" unqtDot SeaShell4 = unqtText "seashell4" unqtDot Sienna = unqtText "sienna" unqtDot Sienna1 = unqtText "sienna1" unqtDot Sienna2 = unqtText "sienna2" unqtDot Sienna3 = unqtText "sienna3" unqtDot Sienna4 = unqtText "sienna4" unqtDot SkyBlue = unqtText "skyblue" unqtDot SkyBlue1 = unqtText "skyblue1" unqtDot SkyBlue2 = unqtText "skyblue2" unqtDot SkyBlue3 = unqtText "skyblue3" unqtDot SkyBlue4 = unqtText "skyblue4" unqtDot SlateBlue = unqtText "slateblue" unqtDot SlateBlue1 = unqtText "slateblue1" unqtDot SlateBlue2 = unqtText "slateblue2" unqtDot SlateBlue3 = unqtText "slateblue3" unqtDot SlateBlue4 = unqtText "slateblue4" unqtDot SlateGray = unqtText "slategray" unqtDot SlateGray1 = unqtText "slategray1" unqtDot SlateGray2 = unqtText "slategray2" unqtDot SlateGray3 = unqtText "slategray3" unqtDot SlateGray4 = unqtText "slategray4" unqtDot Snow = unqtText "snow" unqtDot Snow1 = unqtText "snow1" unqtDot Snow2 = unqtText "snow2" unqtDot Snow3 = unqtText "snow3" unqtDot Snow4 = unqtText "snow4" unqtDot SpringGreen = unqtText "springgreen" unqtDot SpringGreen1 = unqtText "springgreen1" unqtDot SpringGreen2 = unqtText "springgreen2" unqtDot SpringGreen3 = unqtText "springgreen3" unqtDot SpringGreen4 = unqtText "springgreen4" unqtDot SteelBlue = unqtText "steelblue" unqtDot SteelBlue1 = unqtText "steelblue1" unqtDot SteelBlue2 = unqtText "steelblue2" unqtDot SteelBlue3 = unqtText "steelblue3" unqtDot SteelBlue4 = unqtText "steelblue4" unqtDot Tan = unqtText "tan" unqtDot Tan1 = unqtText "tan1" unqtDot Tan2 = unqtText "tan2" unqtDot Tan3 = unqtText "tan3" unqtDot Tan4 = unqtText "tan4" unqtDot Thistle = unqtText "thistle" unqtDot Thistle1 = unqtText "thistle1" unqtDot Thistle2 = unqtText "thistle2" unqtDot Thistle3 = unqtText "thistle3" unqtDot Thistle4 = unqtText "thistle4" unqtDot Tomato = unqtText "tomato" unqtDot Tomato1 = unqtText "tomato1" unqtDot Tomato2 = unqtText "tomato2" unqtDot Tomato3 = unqtText "tomato3" unqtDot Tomato4 = unqtText "tomato4" unqtDot Transparent = unqtText "transparent" unqtDot Turquoise = unqtText "turquoise" unqtDot Turquoise1 = unqtText "turquoise1" unqtDot Turquoise2 = unqtText "turquoise2" unqtDot Turquoise3 = unqtText "turquoise3" unqtDot Turquoise4 = unqtText "turquoise4" unqtDot Violet = unqtText "violet" unqtDot VioletRed = unqtText "violetred" unqtDot VioletRed1 = unqtText "violetred1" unqtDot VioletRed2 = unqtText "violetred2" unqtDot VioletRed3 = unqtText "violetred3" unqtDot VioletRed4 = unqtText "violetred4" unqtDot Wheat = unqtText "wheat" unqtDot Wheat1 = unqtText "wheat1" unqtDot Wheat2 = unqtText "wheat2" unqtDot Wheat3 = unqtText "wheat3" unqtDot Wheat4 = unqtText "wheat4" unqtDot White = unqtText "white" unqtDot WhiteSmoke = unqtText "whitesmoke" unqtDot Yellow = unqtText "yellow" unqtDot Yellow1 = unqtText "yellow1" unqtDot Yellow2 = unqtText "yellow2" unqtDot Yellow3 = unqtText "yellow3" unqtDot Yellow4 = unqtText "yellow4" unqtDot YellowGreen = unqtText "yellowgreen" instance ParseDot X11Color where parseUnqt = stringValue [ ("aliceblue", AliceBlue) , ("antiquewhite", AntiqueWhite) , ("antiquewhite1", AntiqueWhite1) , ("antiquewhite2", AntiqueWhite2) , ("antiquewhite3", AntiqueWhite3) , ("antiquewhite4", AntiqueWhite4) , ("aquamarine", Aquamarine) , ("aquamarine1", Aquamarine1) , ("aquamarine2", Aquamarine2) , ("aquamarine3", Aquamarine3) , ("aquamarine4", Aquamarine4) , ("azure", Azure) , ("azure1", Azure1) , ("azure2", Azure2) , ("azure3", Azure3) , ("azure4", Azure4) , ("beige", Beige) , ("bisque", Bisque) , ("bisque1", Bisque1) , ("bisque2", Bisque2) , ("bisque3", Bisque3) , ("bisque4", Bisque4) , ("black", Black) , ("blanchedalmond", BlanchedAlmond) , ("blue", Blue) , ("blue1", Blue1) , ("blue2", Blue2) , ("blue3", Blue3) , ("blue4", Blue4) , ("blueviolet", BlueViolet) , ("brown", Brown) , ("brown1", Brown1) , ("brown2", Brown2) , ("brown3", Brown3) , ("brown4", Brown4) , ("burlywood", Burlywood) , ("burlywood1", Burlywood1) , ("burlywood2", Burlywood2) , ("burlywood3", Burlywood3) , ("burlywood4", Burlywood4) , ("cadetblue", CadetBlue) , ("cadetblue1", CadetBlue1) , ("cadetblue2", CadetBlue2) , ("cadetblue3", CadetBlue3) , ("cadetblue4", CadetBlue4) , ("chartreuse", Chartreuse) , ("chartreuse1", Chartreuse1) , ("chartreuse2", Chartreuse2) , ("chartreuse3", Chartreuse3) , ("chartreuse4", Chartreuse4) , ("chocolate", Chocolate) , ("chocolate1", Chocolate1) , ("chocolate2", Chocolate2) , ("chocolate3", Chocolate3) , ("chocolate4", Chocolate4) , ("coral", Coral) , ("coral1", Coral1) , ("coral2", Coral2) , ("coral3", Coral3) , ("coral4", Coral4) , ("cornflowerblue", CornFlowerBlue) , ("cornsilk", CornSilk) , ("cornsilk1", CornSilk1) , ("cornsilk2", CornSilk2) , ("cornsilk3", CornSilk3) , ("cornsilk4", CornSilk4) , ("crimson", Crimson) , ("cyan", Cyan) , ("cyan1", Cyan1) , ("cyan2", Cyan2) , ("cyan3", Cyan3) , ("cyan4", Cyan4) , ("darkgoldenrod", DarkGoldenrod) , ("darkgoldenrod1", DarkGoldenrod1) , ("darkgoldenrod2", DarkGoldenrod2) , ("darkgoldenrod3", DarkGoldenrod3) , ("darkgoldenrod4", DarkGoldenrod4) , ("darkgreen", DarkGreen) , ("darkkhaki", Darkkhaki) , ("darkolivegreen", DarkOliveGreen) , ("darkolivegreen1", DarkOliveGreen1) , ("darkolivegreen2", DarkOliveGreen2) , ("darkolivegreen3", DarkOliveGreen3) , ("darkolivegreen4", DarkOliveGreen4) , ("darkorange", DarkOrange) , ("darkorange1", DarkOrange1) , ("darkorange2", DarkOrange2) , ("darkorange3", DarkOrange3) , ("darkorange4", DarkOrange4) , ("darkorchid", DarkOrchid) , ("darkorchid1", DarkOrchid1) , ("darkorchid2", DarkOrchid2) , ("darkorchid3", DarkOrchid3) , ("darkorchid4", DarkOrchid4) , ("darksalmon", DarkSalmon) , ("darkseagreen", DarkSeaGreen) , ("darkseagreen1", DarkSeaGreen1) , ("darkseagreen2", DarkSeaGreen2) , ("darkseagreen3", DarkSeaGreen3) , ("darkseagreen4", DarkSeaGreen4) , ("darkslateblue", DarkSlateBlue) , ("darkslategray", DarkSlateGray) , ("darkslategrey", DarkSlateGray) , ("darkslategray1", DarkSlateGray1) , ("darkslategrey1", DarkSlateGray1) , ("darkslategray2", DarkSlateGray2) , ("darkslategrey2", DarkSlateGray2) , ("darkslategray3", DarkSlateGray3) , ("darkslategrey3", DarkSlateGray3) , ("darkslategray4", DarkSlateGray4) , ("darkslategrey4", DarkSlateGray4) , ("darkturquoise", DarkTurquoise) , ("darkviolet", DarkViolet) , ("deeppink", DeepPink) , ("deeppink1", DeepPink1) , ("deeppink2", DeepPink2) , ("deeppink3", DeepPink3) , ("deeppink4", DeepPink4) , ("deepskyblue", DeepSkyBlue) , ("deepskyblue1", DeepSkyBlue1) , ("deepskyblue2", DeepSkyBlue2) , ("deepskyblue3", DeepSkyBlue3) , ("deepskyblue4", DeepSkyBlue4) , ("dimgray", DimGray) , ("dimgrey", DimGray) , ("dodgerblue", DodgerBlue) , ("dodgerblue1", DodgerBlue1) , ("dodgerblue2", DodgerBlue2) , ("dodgerblue3", DodgerBlue3) , ("dodgerblue4", DodgerBlue4) , ("firebrick", Firebrick) , ("firebrick1", Firebrick1) , ("firebrick2", Firebrick2) , ("firebrick3", Firebrick3) , ("firebrick4", Firebrick4) , ("floralwhite", FloralWhite) , ("forestgreen", ForestGreen) , ("gainsboro", Gainsboro) , ("ghostwhite", GhostWhite) , ("gold", Gold) , ("gold1", Gold1) , ("gold2", Gold2) , ("gold3", Gold3) , ("gold4", Gold4) , ("goldenrod", Goldenrod) , ("goldenrod1", Goldenrod1) , ("goldenrod2", Goldenrod2) , ("goldenrod3", Goldenrod3) , ("goldenrod4", Goldenrod4) , ("gray", Gray) , ("grey", Gray) , ("gray0", Gray0) , ("grey0", Gray0) , ("gray1", Gray1) , ("grey1", Gray1) , ("gray2", Gray2) , ("grey2", Gray2) , ("gray3", Gray3) , ("grey3", Gray3) , ("gray4", Gray4) , ("grey4", Gray4) , ("gray5", Gray5) , ("grey5", Gray5) , ("gray6", Gray6) , ("grey6", Gray6) , ("gray7", Gray7) , ("grey7", Gray7) , ("gray8", Gray8) , ("grey8", Gray8) , ("gray9", Gray9) , ("grey9", Gray9) , ("gray10", Gray10) , ("grey10", Gray10) , ("gray11", Gray11) , ("grey11", Gray11) , ("gray12", Gray12) , ("grey12", Gray12) , ("gray13", Gray13) , ("grey13", Gray13) , ("gray14", Gray14) , ("grey14", Gray14) , ("gray15", Gray15) , ("grey15", Gray15) , ("gray16", Gray16) , ("grey16", Gray16) , ("gray17", Gray17) , ("grey17", Gray17) , ("gray18", Gray18) , ("grey18", Gray18) , ("gray19", Gray19) , ("grey19", Gray19) , ("gray20", Gray20) , ("grey20", Gray20) , ("gray21", Gray21) , ("grey21", Gray21) , ("gray22", Gray22) , ("grey22", Gray22) , ("gray23", Gray23) , ("grey23", Gray23) , ("gray24", Gray24) , ("grey24", Gray24) , ("gray25", Gray25) , ("grey25", Gray25) , ("gray26", Gray26) , ("grey26", Gray26) , ("gray27", Gray27) , ("grey27", Gray27) , ("gray28", Gray28) , ("grey28", Gray28) , ("gray29", Gray29) , ("grey29", Gray29) , ("gray30", Gray30) , ("grey30", Gray30) , ("gray31", Gray31) , ("grey31", Gray31) , ("gray32", Gray32) , ("grey32", Gray32) , ("gray33", Gray33) , ("grey33", Gray33) , ("gray34", Gray34) , ("grey34", Gray34) , ("gray35", Gray35) , ("grey35", Gray35) , ("gray36", Gray36) , ("grey36", Gray36) , ("gray37", Gray37) , ("grey37", Gray37) , ("gray38", Gray38) , ("grey38", Gray38) , ("gray39", Gray39) , ("grey39", Gray39) , ("gray40", Gray40) , ("grey40", Gray40) , ("gray41", Gray41) , ("grey41", Gray41) , ("gray42", Gray42) , ("grey42", Gray42) , ("gray43", Gray43) , ("grey43", Gray43) , ("gray44", Gray44) , ("grey44", Gray44) , ("gray45", Gray45) , ("grey45", Gray45) , ("gray46", Gray46) , ("grey46", Gray46) , ("gray47", Gray47) , ("grey47", Gray47) , ("gray48", Gray48) , ("grey48", Gray48) , ("gray49", Gray49) , ("grey49", Gray49) , ("gray50", Gray50) , ("grey50", Gray50) , ("gray51", Gray51) , ("grey51", Gray51) , ("gray52", Gray52) , ("grey52", Gray52) , ("gray53", Gray53) , ("grey53", Gray53) , ("gray54", Gray54) , ("grey54", Gray54) , ("gray55", Gray55) , ("grey55", Gray55) , ("gray56", Gray56) , ("grey56", Gray56) , ("gray57", Gray57) , ("grey57", Gray57) , ("gray58", Gray58) , ("grey58", Gray58) , ("gray59", Gray59) , ("grey59", Gray59) , ("gray60", Gray60) , ("grey60", Gray60) , ("gray61", Gray61) , ("grey61", Gray61) , ("gray62", Gray62) , ("grey62", Gray62) , ("gray63", Gray63) , ("grey63", Gray63) , ("gray64", Gray64) , ("grey64", Gray64) , ("gray65", Gray65) , ("grey65", Gray65) , ("gray66", Gray66) , ("grey66", Gray66) , ("gray67", Gray67) , ("grey67", Gray67) , ("gray68", Gray68) , ("grey68", Gray68) , ("gray69", Gray69) , ("grey69", Gray69) , ("gray70", Gray70) , ("grey70", Gray70) , ("gray71", Gray71) , ("grey71", Gray71) , ("gray72", Gray72) , ("grey72", Gray72) , ("gray73", Gray73) , ("grey73", Gray73) , ("gray74", Gray74) , ("grey74", Gray74) , ("gray75", Gray75) , ("grey75", Gray75) , ("gray76", Gray76) , ("grey76", Gray76) , ("gray77", Gray77) , ("grey77", Gray77) , ("gray78", Gray78) , ("grey78", Gray78) , ("gray79", Gray79) , ("grey79", Gray79) , ("gray80", Gray80) , ("grey80", Gray80) , ("gray81", Gray81) , ("grey81", Gray81) , ("gray82", Gray82) , ("grey82", Gray82) , ("gray83", Gray83) , ("grey83", Gray83) , ("gray84", Gray84) , ("grey84", Gray84) , ("gray85", Gray85) , ("grey85", Gray85) , ("gray86", Gray86) , ("grey86", Gray86) , ("gray87", Gray87) , ("grey87", Gray87) , ("gray88", Gray88) , ("grey88", Gray88) , ("gray89", Gray89) , ("grey89", Gray89) , ("gray90", Gray90) , ("grey90", Gray90) , ("gray91", Gray91) , ("grey91", Gray91) , ("gray92", Gray92) , ("grey92", Gray92) , ("gray93", Gray93) , ("grey93", Gray93) , ("gray94", Gray94) , ("grey94", Gray94) , ("gray95", Gray95) , ("grey95", Gray95) , ("gray96", Gray96) , ("grey96", Gray96) , ("gray97", Gray97) , ("grey97", Gray97) , ("gray98", Gray98) , ("grey98", Gray98) , ("gray99", Gray99) , ("grey99", Gray99) , ("gray100", Gray100) , ("grey100", Gray100) , ("green", Green) , ("green1", Green1) , ("green2", Green2) , ("green3", Green3) , ("green4", Green4) , ("greenyellow", GreenYellow) , ("honeydew", HoneyDew) , ("honeydew1", HoneyDew1) , ("honeydew2", HoneyDew2) , ("honeydew3", HoneyDew3) , ("honeydew4", HoneyDew4) , ("hotpink", HotPink) , ("hotpink1", HotPink1) , ("hotpink2", HotPink2) , ("hotpink3", HotPink3) , ("hotpink4", HotPink4) , ("indianred", IndianRed) , ("indianred1", IndianRed1) , ("indianred2", IndianRed2) , ("indianred3", IndianRed3) , ("indianred4", IndianRed4) , ("indigo", Indigo) , ("ivory", Ivory) , ("ivory1", Ivory1) , ("ivory2", Ivory2) , ("ivory3", Ivory3) , ("ivory4", Ivory4) , ("khaki", Khaki) , ("khaki1", Khaki1) , ("khaki2", Khaki2) , ("khaki3", Khaki3) , ("khaki4", Khaki4) , ("lavender", Lavender) , ("lavenderblush", LavenderBlush) , ("lavenderblush1", LavenderBlush1) , ("lavenderblush2", LavenderBlush2) , ("lavenderblush3", LavenderBlush3) , ("lavenderblush4", LavenderBlush4) , ("lawngreen", LawnGreen) , ("lemonchiffon", LemonChiffon) , ("lemonchiffon1", LemonChiffon1) , ("lemonchiffon2", LemonChiffon2) , ("lemonchiffon3", LemonChiffon3) , ("lemonchiffon4", LemonChiffon4) , ("lightblue", LightBlue) , ("lightblue1", LightBlue1) , ("lightblue2", LightBlue2) , ("lightblue3", LightBlue3) , ("lightblue4", LightBlue4) , ("lightcoral", LightCoral) , ("lightcyan", LightCyan) , ("lightcyan1", LightCyan1) , ("lightcyan2", LightCyan2) , ("lightcyan3", LightCyan3) , ("lightcyan4", LightCyan4) , ("lightgoldenrod", LightGoldenrod) , ("lightgoldenrod1", LightGoldenrod1) , ("lightgoldenrod2", LightGoldenrod2) , ("lightgoldenrod3", LightGoldenrod3) , ("lightgoldenrod4", LightGoldenrod4) , ("lightgoldenrodyellow", LightGoldenrodYellow) , ("lightgray", LightGray) , ("lightgrey", LightGray) , ("lightpink", LightPink) , ("lightpink1", LightPink1) , ("lightpink2", LightPink2) , ("lightpink3", LightPink3) , ("lightpink4", LightPink4) , ("lightsalmon", LightSalmon) , ("lightsalmon1", LightSalmon1) , ("lightsalmon2", LightSalmon2) , ("lightsalmon3", LightSalmon3) , ("lightsalmon4", LightSalmon4) , ("lightseagreen", LightSeaGreen) , ("lightskyblue", LightSkyBlue) , ("lightskyblue1", LightSkyBlue1) , ("lightskyblue2", LightSkyBlue2) , ("lightskyblue3", LightSkyBlue3) , ("lightskyblue4", LightSkyBlue4) , ("lightslateblue", LightSlateBlue) , ("lightslategray", LightSlateGray) , ("lightslategrey", LightSlateGray) , ("lightsteelblue", LightSteelBlue) , ("lightsteelblue1", LightSteelBlue1) , ("lightsteelblue2", LightSteelBlue2) , ("lightsteelblue3", LightSteelBlue3) , ("lightsteelblue4", LightSteelBlue4) , ("lightyellow", LightYellow) , ("lightyellow1", LightYellow1) , ("lightyellow2", LightYellow2) , ("lightyellow3", LightYellow3) , ("lightyellow4", LightYellow4) , ("limegreen", LimeGreen) , ("linen", Linen) , ("magenta", Magenta) , ("magenta1", Magenta1) , ("magenta2", Magenta2) , ("magenta3", Magenta3) , ("magenta4", Magenta4) , ("maroon", Maroon) , ("maroon1", Maroon1) , ("maroon2", Maroon2) , ("maroon3", Maroon3) , ("maroon4", Maroon4) , ("mediumaquamarine", MediumAquamarine) , ("mediumblue", MediumBlue) , ("mediumorchid", MediumOrchid) , ("mediumorchid1", MediumOrchid1) , ("mediumorchid2", MediumOrchid2) , ("mediumorchid3", MediumOrchid3) , ("mediumorchid4", MediumOrchid4) , ("mediumpurple", MediumPurple) , ("mediumpurple1", MediumPurple1) , ("mediumpurple2", MediumPurple2) , ("mediumpurple3", MediumPurple3) , ("mediumpurple4", MediumPurple4) , ("mediumseagreen", MediumSeaGreen) , ("mediumslateblue", MediumSlateBlue) , ("mediumspringgreen", MediumSpringGreen) , ("mediumturquoise", MediumTurquoise) , ("mediumvioletred", MediumVioletRed) , ("midnightblue", MidnightBlue) , ("mintcream", MintCream) , ("mistyrose", MistyRose) , ("mistyrose1", MistyRose1) , ("mistyrose2", MistyRose2) , ("mistyrose3", MistyRose3) , ("mistyrose4", MistyRose4) , ("moccasin", Moccasin) , ("navajowhite", NavajoWhite) , ("navajowhite1", NavajoWhite1) , ("navajowhite2", NavajoWhite2) , ("navajowhite3", NavajoWhite3) , ("navajowhite4", NavajoWhite4) , ("navy", Navy) , ("navyblue", NavyBlue) , ("oldlace", OldLace) , ("olivedrab", OliveDrab) , ("olivedrab1", OliveDrab1) , ("olivedrab2", OliveDrab2) , ("olivedrab3", OliveDrab3) , ("olivedrab4", OliveDrab4) , ("orange", Orange) , ("orange1", Orange1) , ("orange2", Orange2) , ("orange3", Orange3) , ("orange4", Orange4) , ("orangered", OrangeRed) , ("orangered1", OrangeRed1) , ("orangered2", OrangeRed2) , ("orangered3", OrangeRed3) , ("orangered4", OrangeRed4) , ("orchid", Orchid) , ("orchid1", Orchid1) , ("orchid2", Orchid2) , ("orchid3", Orchid3) , ("orchid4", Orchid4) , ("palegoldenrod", PaleGoldenrod) , ("palegreen", PaleGreen) , ("palegreen1", PaleGreen1) , ("palegreen2", PaleGreen2) , ("palegreen3", PaleGreen3) , ("palegreen4", PaleGreen4) , ("paleturquoise", PaleTurquoise) , ("paleturquoise1", PaleTurquoise1) , ("paleturquoise2", PaleTurquoise2) , ("paleturquoise3", PaleTurquoise3) , ("paleturquoise4", PaleTurquoise4) , ("palevioletred", PaleVioletRed) , ("palevioletred1", PaleVioletRed1) , ("palevioletred2", PaleVioletRed2) , ("palevioletred3", PaleVioletRed3) , ("palevioletred4", PaleVioletRed4) , ("papayawhip", PapayaWhip) , ("peachpuff", PeachPuff) , ("peachpuff1", PeachPuff1) , ("peachpuff2", PeachPuff2) , ("peachpuff3", PeachPuff3) , ("peachpuff4", PeachPuff4) , ("peru", Peru) , ("pink", Pink) , ("pink1", Pink1) , ("pink2", Pink2) , ("pink3", Pink3) , ("pink4", Pink4) , ("plum", Plum) , ("plum1", Plum1) , ("plum2", Plum2) , ("plum3", Plum3) , ("plum4", Plum4) , ("powderblue", PowderBlue) , ("purple", Purple) , ("purple1", Purple1) , ("purple2", Purple2) , ("purple3", Purple3) , ("purple4", Purple4) , ("red", Red) , ("red1", Red1) , ("red2", Red2) , ("red3", Red3) , ("red4", Red4) , ("rosybrown", RosyBrown) , ("rosybrown1", RosyBrown1) , ("rosybrown2", RosyBrown2) , ("rosybrown3", RosyBrown3) , ("rosybrown4", RosyBrown4) , ("royalblue", RoyalBlue) , ("royalblue1", RoyalBlue1) , ("royalblue2", RoyalBlue2) , ("royalblue3", RoyalBlue3) , ("royalblue4", RoyalBlue4) , ("saddlebrown", SaddleBrown) , ("salmon", Salmon) , ("salmon1", Salmon1) , ("salmon2", Salmon2) , ("salmon3", Salmon3) , ("salmon4", Salmon4) , ("sandybrown", SandyBrown) , ("seagreen", SeaGreen) , ("seagreen1", SeaGreen1) , ("seagreen2", SeaGreen2) , ("seagreen3", SeaGreen3) , ("seagreen4", SeaGreen4) , ("seashell", SeaShell) , ("seashell1", SeaShell1) , ("seashell2", SeaShell2) , ("seashell3", SeaShell3) , ("seashell4", SeaShell4) , ("sienna", Sienna) , ("sienna1", Sienna1) , ("sienna2", Sienna2) , ("sienna3", Sienna3) , ("sienna4", Sienna4) , ("skyblue", SkyBlue) , ("skyblue1", SkyBlue1) , ("skyblue2", SkyBlue2) , ("skyblue3", SkyBlue3) , ("skyblue4", SkyBlue4) , ("slateblue", SlateBlue) , ("slateblue1", SlateBlue1) , ("slateblue2", SlateBlue2) , ("slateblue3", SlateBlue3) , ("slateblue4", SlateBlue4) , ("slategray", SlateGray) , ("slategrey", SlateGray) , ("slategray1", SlateGray1) , ("slategrey1", SlateGray1) , ("slategray2", SlateGray2) , ("slategrey2", SlateGray2) , ("slategray3", SlateGray3) , ("slategrey3", SlateGray3) , ("slategray4", SlateGray4) , ("slategrey4", SlateGray4) , ("snow", Snow) , ("snow1", Snow1) , ("snow2", Snow2) , ("snow3", Snow3) , ("snow4", Snow4) , ("springgreen", SpringGreen) , ("springgreen1", SpringGreen1) , ("springgreen2", SpringGreen2) , ("springgreen3", SpringGreen3) , ("springgreen4", SpringGreen4) , ("steelblue", SteelBlue) , ("steelblue1", SteelBlue1) , ("steelblue2", SteelBlue2) , ("steelblue3", SteelBlue3) , ("steelblue4", SteelBlue4) , ("tan", Tan) , ("tan1", Tan1) , ("tan2", Tan2) , ("tan3", Tan3) , ("tan4", Tan4) , ("thistle", Thistle) , ("thistle1", Thistle1) , ("thistle2", Thistle2) , ("thistle3", Thistle3) , ("thistle4", Thistle4) , ("tomato", Tomato) , ("tomato1", Tomato1) , ("tomato2", Tomato2) , ("tomato3", Tomato3) , ("tomato4", Tomato4) , ("transparent", Transparent) , ("invis", Transparent) , ("none", Transparent) , ("turquoise", Turquoise) , ("turquoise1", Turquoise1) , ("turquoise2", Turquoise2) , ("turquoise3", Turquoise3) , ("turquoise4", Turquoise4) , ("violet", Violet) , ("violetred", VioletRed) , ("violetred1", VioletRed1) , ("violetred2", VioletRed2) , ("violetred3", VioletRed3) , ("violetred4", VioletRed4) , ("wheat", Wheat) , ("wheat1", Wheat1) , ("wheat2", Wheat2) , ("wheat3", Wheat3) , ("wheat4", Wheat4) , ("white", White) , ("whitesmoke", WhiteSmoke) , ("yellow", Yellow) , ("yellow1", Yellow1) , ("yellow2", Yellow2) , ("yellow3", Yellow3) , ("yellow4", Yellow4) , ("yellowgreen", YellowGreen) ] x11Colour :: X11Color -> AlphaColour Double x11Colour AliceBlue = opaque $ sRGB24 240 248 255 x11Colour AntiqueWhite = opaque $ sRGB24 250 235 215 x11Colour AntiqueWhite1 = opaque $ sRGB24 255 239 219 x11Colour AntiqueWhite2 = opaque $ sRGB24 238 223 204 x11Colour AntiqueWhite3 = opaque $ sRGB24 205 192 176 x11Colour AntiqueWhite4 = opaque $ sRGB24 139 131 120 x11Colour Aquamarine = opaque $ sRGB24 127 255 212 x11Colour Aquamarine1 = opaque $ sRGB24 127 255 212 x11Colour Aquamarine2 = opaque $ sRGB24 118 238 198 x11Colour Aquamarine3 = opaque $ sRGB24 102 205 170 x11Colour Aquamarine4 = opaque $ sRGB24 69 139 116 x11Colour Azure = opaque $ sRGB24 240 255 255 x11Colour Azure1 = opaque $ sRGB24 240 255 255 x11Colour Azure2 = opaque $ sRGB24 224 238 238 x11Colour Azure3 = opaque $ sRGB24 193 205 205 x11Colour Azure4 = opaque $ sRGB24 131 139 139 x11Colour Beige = opaque $ sRGB24 245 245 220 x11Colour Bisque = opaque $ sRGB24 255 228 196 x11Colour Bisque1 = opaque $ sRGB24 255 228 196 x11Colour Bisque2 = opaque $ sRGB24 238 213 183 x11Colour Bisque3 = opaque $ sRGB24 205 183 158 x11Colour Bisque4 = opaque $ sRGB24 139 125 107 x11Colour Black = opaque $ sRGB24 0 0 0 x11Colour BlanchedAlmond = opaque $ sRGB24 255 235 205 x11Colour Blue = opaque $ sRGB24 0 0 255 x11Colour Blue1 = opaque $ sRGB24 0 0 255 x11Colour Blue2 = opaque $ sRGB24 0 0 238 x11Colour Blue3 = opaque $ sRGB24 0 0 205 x11Colour Blue4 = opaque $ sRGB24 0 0 139 x11Colour BlueViolet = opaque $ sRGB24 138 43 226 x11Colour Brown = opaque $ sRGB24 165 42 42 x11Colour Brown1 = opaque $ sRGB24 255 64 64 x11Colour Brown2 = opaque $ sRGB24 238 59 59 x11Colour Brown3 = opaque $ sRGB24 205 51 51 x11Colour Brown4 = opaque $ sRGB24 139 35 35 x11Colour Burlywood = opaque $ sRGB24 222 184 135 x11Colour Burlywood1 = opaque $ sRGB24 255 211 155 x11Colour Burlywood2 = opaque $ sRGB24 238 197 145 x11Colour Burlywood3 = opaque $ sRGB24 205 170 125 x11Colour Burlywood4 = opaque $ sRGB24 139 115 85 x11Colour CadetBlue = opaque $ sRGB24 95 158 160 x11Colour CadetBlue1 = opaque $ sRGB24 152 245 255 x11Colour CadetBlue2 = opaque $ sRGB24 142 229 238 x11Colour CadetBlue3 = opaque $ sRGB24 122 197 205 x11Colour CadetBlue4 = opaque $ sRGB24 83 134 139 x11Colour Chartreuse = opaque $ sRGB24 127 255 0 x11Colour Chartreuse1 = opaque $ sRGB24 127 255 0 x11Colour Chartreuse2 = opaque $ sRGB24 118 238 0 x11Colour Chartreuse3 = opaque $ sRGB24 102 205 0 x11Colour Chartreuse4 = opaque $ sRGB24 69 139 0 x11Colour Chocolate = opaque $ sRGB24 210 105 30 x11Colour Chocolate1 = opaque $ sRGB24 255 127 36 x11Colour Chocolate2 = opaque $ sRGB24 238 118 33 x11Colour Chocolate3 = opaque $ sRGB24 205 102 29 x11Colour Chocolate4 = opaque $ sRGB24 139 69 19 x11Colour Coral = opaque $ sRGB24 255 127 80 x11Colour Coral1 = opaque $ sRGB24 255 114 86 x11Colour Coral2 = opaque $ sRGB24 238 106 80 x11Colour Coral3 = opaque $ sRGB24 205 91 69 x11Colour Coral4 = opaque $ sRGB24 139 62 47 x11Colour CornFlowerBlue = opaque $ sRGB24 100 149 237 x11Colour CornSilk = opaque $ sRGB24 255 248 220 x11Colour CornSilk1 = opaque $ sRGB24 255 248 220 x11Colour CornSilk2 = opaque $ sRGB24 238 232 205 x11Colour CornSilk3 = opaque $ sRGB24 205 200 177 x11Colour CornSilk4 = opaque $ sRGB24 139 136 120 x11Colour Crimson = opaque $ sRGB24 220 20 60 x11Colour Cyan = opaque $ sRGB24 0 255 255 x11Colour Cyan1 = opaque $ sRGB24 0 255 255 x11Colour Cyan2 = opaque $ sRGB24 0 238 238 x11Colour Cyan3 = opaque $ sRGB24 0 205 205 x11Colour Cyan4 = opaque $ sRGB24 0 139 139 x11Colour DarkGoldenrod = opaque $ sRGB24 184 134 11 x11Colour DarkGoldenrod1 = opaque $ sRGB24 255 185 15 x11Colour DarkGoldenrod2 = opaque $ sRGB24 238 173 14 x11Colour DarkGoldenrod3 = opaque $ sRGB24 205 149 12 x11Colour DarkGoldenrod4 = opaque $ sRGB24 139 101 8 x11Colour DarkGreen = opaque $ sRGB24 0 100 0 x11Colour Darkkhaki = opaque $ sRGB24 189 183 107 x11Colour DarkOliveGreen = opaque $ sRGB24 85 107 47 x11Colour DarkOliveGreen1 = opaque $ sRGB24 202 255 112 x11Colour DarkOliveGreen2 = opaque $ sRGB24 188 238 104 x11Colour DarkOliveGreen3 = opaque $ sRGB24 162 205 90 x11Colour DarkOliveGreen4 = opaque $ sRGB24 110 139 61 x11Colour DarkOrange = opaque $ sRGB24 255 140 0 x11Colour DarkOrange1 = opaque $ sRGB24 255 127 0 x11Colour DarkOrange2 = opaque $ sRGB24 238 118 0 x11Colour DarkOrange3 = opaque $ sRGB24 205 102 0 x11Colour DarkOrange4 = opaque $ sRGB24 139 69 0 x11Colour DarkOrchid = opaque $ sRGB24 153 50 204 x11Colour DarkOrchid1 = opaque $ sRGB24 191 62 255 x11Colour DarkOrchid2 = opaque $ sRGB24 178 58 238 x11Colour DarkOrchid3 = opaque $ sRGB24 154 50 205 x11Colour DarkOrchid4 = opaque $ sRGB24 104 34 139 x11Colour DarkSalmon = opaque $ sRGB24 233 150 122 x11Colour DarkSeaGreen = opaque $ sRGB24 143 188 143 x11Colour DarkSeaGreen1 = opaque $ sRGB24 193 255 193 x11Colour DarkSeaGreen2 = opaque $ sRGB24 180 238 180 x11Colour DarkSeaGreen3 = opaque $ sRGB24 155 205 155 x11Colour DarkSeaGreen4 = opaque $ sRGB24 105 139 105 x11Colour DarkSlateBlue = opaque $ sRGB24 72 61 139 x11Colour DarkSlateGray = opaque $ sRGB24 47 79 79 x11Colour DarkSlateGray1 = opaque $ sRGB24 151 255 255 x11Colour DarkSlateGray2 = opaque $ sRGB24 141 238 238 x11Colour DarkSlateGray3 = opaque $ sRGB24 121 205 205 x11Colour DarkSlateGray4 = opaque $ sRGB24 82 139 139 x11Colour DarkTurquoise = opaque $ sRGB24 0 206 209 x11Colour DarkViolet = opaque $ sRGB24 148 0 211 x11Colour DeepPink = opaque $ sRGB24 255 20 147 x11Colour DeepPink1 = opaque $ sRGB24 255 20 147 x11Colour DeepPink2 = opaque $ sRGB24 238 18 137 x11Colour DeepPink3 = opaque $ sRGB24 205 16 118 x11Colour DeepPink4 = opaque $ sRGB24 139 10 80 x11Colour DeepSkyBlue = opaque $ sRGB24 0 191 255 x11Colour DeepSkyBlue1 = opaque $ sRGB24 0 191 255 x11Colour DeepSkyBlue2 = opaque $ sRGB24 0 178 238 x11Colour DeepSkyBlue3 = opaque $ sRGB24 0 154 205 x11Colour DeepSkyBlue4 = opaque $ sRGB24 0 104 139 x11Colour DimGray = opaque $ sRGB24 105 105 105 x11Colour DodgerBlue = opaque $ sRGB24 30 144 255 x11Colour DodgerBlue1 = opaque $ sRGB24 30 144 255 x11Colour DodgerBlue2 = opaque $ sRGB24 28 134 238 x11Colour DodgerBlue3 = opaque $ sRGB24 24 116 205 x11Colour DodgerBlue4 = opaque $ sRGB24 16 78 139 x11Colour Firebrick = opaque $ sRGB24 178 34 34 x11Colour Firebrick1 = opaque $ sRGB24 255 48 48 x11Colour Firebrick2 = opaque $ sRGB24 238 44 44 x11Colour Firebrick3 = opaque $ sRGB24 205 38 38 x11Colour Firebrick4 = opaque $ sRGB24 139 26 26 x11Colour FloralWhite = opaque $ sRGB24 255 250 240 x11Colour ForestGreen = opaque $ sRGB24 34 139 34 x11Colour Gainsboro = opaque $ sRGB24 220 220 220 x11Colour GhostWhite = opaque $ sRGB24 248 248 255 x11Colour Gold = opaque $ sRGB24 255 215 0 x11Colour Gold1 = opaque $ sRGB24 255 215 0 x11Colour Gold2 = opaque $ sRGB24 238 201 0 x11Colour Gold3 = opaque $ sRGB24 205 173 0 x11Colour Gold4 = opaque $ sRGB24 139 117 0 x11Colour Goldenrod = opaque $ sRGB24 218 165 32 x11Colour Goldenrod1 = opaque $ sRGB24 255 193 37 x11Colour Goldenrod2 = opaque $ sRGB24 238 180 34 x11Colour Goldenrod3 = opaque $ sRGB24 205 155 29 x11Colour Goldenrod4 = opaque $ sRGB24 139 105 20 x11Colour Gray = opaque $ sRGB24 192 192 192 x11Colour Gray0 = opaque $ sRGB24 0 0 0 x11Colour Gray1 = opaque $ sRGB24 3 3 3 x11Colour Gray2 = opaque $ sRGB24 5 5 5 x11Colour Gray3 = opaque $ sRGB24 8 8 8 x11Colour Gray4 = opaque $ sRGB24 10 10 10 x11Colour Gray5 = opaque $ sRGB24 13 13 13 x11Colour Gray6 = opaque $ sRGB24 15 15 15 x11Colour Gray7 = opaque $ sRGB24 18 18 18 x11Colour Gray8 = opaque $ sRGB24 20 20 20 x11Colour Gray9 = opaque $ sRGB24 23 23 23 x11Colour Gray10 = opaque $ sRGB24 26 26 26 x11Colour Gray11 = opaque $ sRGB24 28 28 28 x11Colour Gray12 = opaque $ sRGB24 31 31 31 x11Colour Gray13 = opaque $ sRGB24 33 33 33 x11Colour Gray14 = opaque $ sRGB24 36 36 36 x11Colour Gray15 = opaque $ sRGB24 38 38 38 x11Colour Gray16 = opaque $ sRGB24 41 41 41 x11Colour Gray17 = opaque $ sRGB24 43 43 43 x11Colour Gray18 = opaque $ sRGB24 46 46 46 x11Colour Gray19 = opaque $ sRGB24 48 48 48 x11Colour Gray20 = opaque $ sRGB24 51 51 51 x11Colour Gray21 = opaque $ sRGB24 54 54 54 x11Colour Gray22 = opaque $ sRGB24 56 56 56 x11Colour Gray23 = opaque $ sRGB24 59 59 59 x11Colour Gray24 = opaque $ sRGB24 61 61 61 x11Colour Gray25 = opaque $ sRGB24 64 64 64 x11Colour Gray26 = opaque $ sRGB24 66 66 66 x11Colour Gray27 = opaque $ sRGB24 69 69 69 x11Colour Gray28 = opaque $ sRGB24 71 71 71 x11Colour Gray29 = opaque $ sRGB24 74 74 74 x11Colour Gray30 = opaque $ sRGB24 77 77 77 x11Colour Gray31 = opaque $ sRGB24 79 79 79 x11Colour Gray32 = opaque $ sRGB24 82 82 82 x11Colour Gray33 = opaque $ sRGB24 84 84 84 x11Colour Gray34 = opaque $ sRGB24 87 87 87 x11Colour Gray35 = opaque $ sRGB24 89 89 89 x11Colour Gray36 = opaque $ sRGB24 92 92 92 x11Colour Gray37 = opaque $ sRGB24 94 94 94 x11Colour Gray38 = opaque $ sRGB24 97 97 97 x11Colour Gray39 = opaque $ sRGB24 99 99 99 x11Colour Gray40 = opaque $ sRGB24 102 102 102 x11Colour Gray41 = opaque $ sRGB24 105 105 105 x11Colour Gray42 = opaque $ sRGB24 107 107 107 x11Colour Gray43 = opaque $ sRGB24 110 110 110 x11Colour Gray44 = opaque $ sRGB24 112 112 112 x11Colour Gray45 = opaque $ sRGB24 115 115 115 x11Colour Gray46 = opaque $ sRGB24 117 117 117 x11Colour Gray47 = opaque $ sRGB24 120 120 120 x11Colour Gray48 = opaque $ sRGB24 122 122 122 x11Colour Gray49 = opaque $ sRGB24 125 125 125 x11Colour Gray50 = opaque $ sRGB24 127 127 127 x11Colour Gray51 = opaque $ sRGB24 130 130 130 x11Colour Gray52 = opaque $ sRGB24 133 133 133 x11Colour Gray53 = opaque $ sRGB24 135 135 135 x11Colour Gray54 = opaque $ sRGB24 138 138 138 x11Colour Gray55 = opaque $ sRGB24 140 140 140 x11Colour Gray56 = opaque $ sRGB24 143 143 143 x11Colour Gray57 = opaque $ sRGB24 145 145 145 x11Colour Gray58 = opaque $ sRGB24 148 148 148 x11Colour Gray59 = opaque $ sRGB24 150 150 150 x11Colour Gray60 = opaque $ sRGB24 153 153 153 x11Colour Gray61 = opaque $ sRGB24 156 156 156 x11Colour Gray62 = opaque $ sRGB24 158 158 158 x11Colour Gray63 = opaque $ sRGB24 161 161 161 x11Colour Gray64 = opaque $ sRGB24 163 163 163 x11Colour Gray65 = opaque $ sRGB24 166 166 166 x11Colour Gray66 = opaque $ sRGB24 168 168 168 x11Colour Gray67 = opaque $ sRGB24 171 171 171 x11Colour Gray68 = opaque $ sRGB24 173 173 173 x11Colour Gray69 = opaque $ sRGB24 176 176 176 x11Colour Gray70 = opaque $ sRGB24 179 179 179 x11Colour Gray71 = opaque $ sRGB24 181 181 181 x11Colour Gray72 = opaque $ sRGB24 184 184 184 x11Colour Gray73 = opaque $ sRGB24 186 186 186 x11Colour Gray74 = opaque $ sRGB24 189 189 189 x11Colour Gray75 = opaque $ sRGB24 191 191 191 x11Colour Gray76 = opaque $ sRGB24 194 194 194 x11Colour Gray77 = opaque $ sRGB24 196 196 196 x11Colour Gray78 = opaque $ sRGB24 199 199 199 x11Colour Gray79 = opaque $ sRGB24 201 201 201 x11Colour Gray80 = opaque $ sRGB24 204 204 204 x11Colour Gray81 = opaque $ sRGB24 207 207 207 x11Colour Gray82 = opaque $ sRGB24 209 209 209 x11Colour Gray83 = opaque $ sRGB24 212 212 212 x11Colour Gray84 = opaque $ sRGB24 214 214 214 x11Colour Gray85 = opaque $ sRGB24 217 217 217 x11Colour Gray86 = opaque $ sRGB24 219 219 219 x11Colour Gray87 = opaque $ sRGB24 222 222 222 x11Colour Gray88 = opaque $ sRGB24 224 224 224 x11Colour Gray89 = opaque $ sRGB24 227 227 227 x11Colour Gray90 = opaque $ sRGB24 229 229 229 x11Colour Gray91 = opaque $ sRGB24 232 232 232 x11Colour Gray92 = opaque $ sRGB24 235 235 235 x11Colour Gray93 = opaque $ sRGB24 237 237 237 x11Colour Gray94 = opaque $ sRGB24 240 240 240 x11Colour Gray95 = opaque $ sRGB24 242 242 242 x11Colour Gray96 = opaque $ sRGB24 245 245 245 x11Colour Gray97 = opaque $ sRGB24 247 247 247 x11Colour Gray98 = opaque $ sRGB24 250 250 250 x11Colour Gray99 = opaque $ sRGB24 252 252 252 x11Colour Gray100 = opaque $ sRGB24 255 255 255 x11Colour Green = opaque $ sRGB24 0 255 0 x11Colour Green1 = opaque $ sRGB24 0 255 0 x11Colour Green2 = opaque $ sRGB24 0 238 0 x11Colour Green3 = opaque $ sRGB24 0 205 0 x11Colour Green4 = opaque $ sRGB24 0 139 0 x11Colour GreenYellow = opaque $ sRGB24 173 255 47 x11Colour HoneyDew = opaque $ sRGB24 240 255 240 x11Colour HoneyDew1 = opaque $ sRGB24 240 255 240 x11Colour HoneyDew2 = opaque $ sRGB24 224 238 224 x11Colour HoneyDew3 = opaque $ sRGB24 193 205 193 x11Colour HoneyDew4 = opaque $ sRGB24 131 139 131 x11Colour HotPink = opaque $ sRGB24 255 105 180 x11Colour HotPink1 = opaque $ sRGB24 255 110 180 x11Colour HotPink2 = opaque $ sRGB24 238 106 167 x11Colour HotPink3 = opaque $ sRGB24 205 96 144 x11Colour HotPink4 = opaque $ sRGB24 139 58 98 x11Colour IndianRed = opaque $ sRGB24 205 92 92 x11Colour IndianRed1 = opaque $ sRGB24 255 106 106 x11Colour IndianRed2 = opaque $ sRGB24 238 99 99 x11Colour IndianRed3 = opaque $ sRGB24 205 85 85 x11Colour IndianRed4 = opaque $ sRGB24 139 58 58 x11Colour Indigo = opaque $ sRGB24 75 0 130 x11Colour Ivory = opaque $ sRGB24 255 255 240 x11Colour Ivory1 = opaque $ sRGB24 255 255 240 x11Colour Ivory2 = opaque $ sRGB24 238 238 224 x11Colour Ivory3 = opaque $ sRGB24 205 205 193 x11Colour Ivory4 = opaque $ sRGB24 139 139 131 x11Colour Khaki = opaque $ sRGB24 240 230 140 x11Colour Khaki1 = opaque $ sRGB24 255 246 143 x11Colour Khaki2 = opaque $ sRGB24 238 230 133 x11Colour Khaki3 = opaque $ sRGB24 205 198 115 x11Colour Khaki4 = opaque $ sRGB24 139 134 78 x11Colour Lavender = opaque $ sRGB24 230 230 250 x11Colour LavenderBlush = opaque $ sRGB24 255 240 245 x11Colour LavenderBlush1 = opaque $ sRGB24 255 240 245 x11Colour LavenderBlush2 = opaque $ sRGB24 238 224 229 x11Colour LavenderBlush3 = opaque $ sRGB24 205 193 197 x11Colour LavenderBlush4 = opaque $ sRGB24 139 131 134 x11Colour LawnGreen = opaque $ sRGB24 124 252 0 x11Colour LemonChiffon = opaque $ sRGB24 255 250 205 x11Colour LemonChiffon1 = opaque $ sRGB24 255 250 205 x11Colour LemonChiffon2 = opaque $ sRGB24 238 233 191 x11Colour LemonChiffon3 = opaque $ sRGB24 205 201 165 x11Colour LemonChiffon4 = opaque $ sRGB24 139 137 112 x11Colour LightBlue = opaque $ sRGB24 173 216 230 x11Colour LightBlue1 = opaque $ sRGB24 191 239 255 x11Colour LightBlue2 = opaque $ sRGB24 178 223 238 x11Colour LightBlue3 = opaque $ sRGB24 154 192 205 x11Colour LightBlue4 = opaque $ sRGB24 104 131 139 x11Colour LightCoral = opaque $ sRGB24 240 128 128 x11Colour LightCyan = opaque $ sRGB24 224 255 255 x11Colour LightCyan1 = opaque $ sRGB24 224 255 255 x11Colour LightCyan2 = opaque $ sRGB24 209 238 238 x11Colour LightCyan3 = opaque $ sRGB24 180 205 205 x11Colour LightCyan4 = opaque $ sRGB24 122 139 139 x11Colour LightGoldenrod = opaque $ sRGB24 238 221 130 x11Colour LightGoldenrod1 = opaque $ sRGB24 255 236 139 x11Colour LightGoldenrod2 = opaque $ sRGB24 238 220 130 x11Colour LightGoldenrod3 = opaque $ sRGB24 205 190 112 x11Colour LightGoldenrod4 = opaque $ sRGB24 139 129 76 x11Colour LightGoldenrodYellow = opaque $ sRGB24 250 250 210 x11Colour LightGray = opaque $ sRGB24 211 211 211 x11Colour LightPink = opaque $ sRGB24 255 182 193 x11Colour LightPink1 = opaque $ sRGB24 255 174 185 x11Colour LightPink2 = opaque $ sRGB24 238 162 173 x11Colour LightPink3 = opaque $ sRGB24 205 140 149 x11Colour LightPink4 = opaque $ sRGB24 139 95 101 x11Colour LightSalmon = opaque $ sRGB24 255 160 122 x11Colour LightSalmon1 = opaque $ sRGB24 255 160 122 x11Colour LightSalmon2 = opaque $ sRGB24 238 149 114 x11Colour LightSalmon3 = opaque $ sRGB24 205 129 98 x11Colour LightSalmon4 = opaque $ sRGB24 139 87 66 x11Colour LightSeaGreen = opaque $ sRGB24 32 178 170 x11Colour LightSkyBlue = opaque $ sRGB24 135 206 250 x11Colour LightSkyBlue1 = opaque $ sRGB24 176 226 255 x11Colour LightSkyBlue2 = opaque $ sRGB24 164 211 238 x11Colour LightSkyBlue3 = opaque $ sRGB24 141 182 205 x11Colour LightSkyBlue4 = opaque $ sRGB24 96 123 139 x11Colour LightSlateBlue = opaque $ sRGB24 132 112 255 x11Colour LightSlateGray = opaque $ sRGB24 119 136 153 x11Colour LightSteelBlue = opaque $ sRGB24 176 196 222 x11Colour LightSteelBlue1 = opaque $ sRGB24 202 225 255 x11Colour LightSteelBlue2 = opaque $ sRGB24 188 210 238 x11Colour LightSteelBlue3 = opaque $ sRGB24 162 181 205 x11Colour LightSteelBlue4 = opaque $ sRGB24 110 123 139 x11Colour LightYellow = opaque $ sRGB24 255 255 224 x11Colour LightYellow1 = opaque $ sRGB24 255 255 224 x11Colour LightYellow2 = opaque $ sRGB24 238 238 209 x11Colour LightYellow3 = opaque $ sRGB24 205 205 180 x11Colour LightYellow4 = opaque $ sRGB24 139 139 122 x11Colour LimeGreen = opaque $ sRGB24 50 205 50 x11Colour Linen = opaque $ sRGB24 250 240 230 x11Colour Magenta = opaque $ sRGB24 255 0 255 x11Colour Magenta1 = opaque $ sRGB24 255 0 255 x11Colour Magenta2 = opaque $ sRGB24 238 0 238 x11Colour Magenta3 = opaque $ sRGB24 205 0 205 x11Colour Magenta4 = opaque $ sRGB24 139 0 139 x11Colour Maroon = opaque $ sRGB24 176 48 96 x11Colour Maroon1 = opaque $ sRGB24 255 52 179 x11Colour Maroon2 = opaque $ sRGB24 238 48 167 x11Colour Maroon3 = opaque $ sRGB24 205 41 144 x11Colour Maroon4 = opaque $ sRGB24 139 28 98 x11Colour MediumAquamarine = opaque $ sRGB24 102 205 170 x11Colour MediumBlue = opaque $ sRGB24 0 0 205 x11Colour MediumOrchid = opaque $ sRGB24 186 85 211 x11Colour MediumOrchid1 = opaque $ sRGB24 224 102 255 x11Colour MediumOrchid2 = opaque $ sRGB24 209 95 238 x11Colour MediumOrchid3 = opaque $ sRGB24 180 82 205 x11Colour MediumOrchid4 = opaque $ sRGB24 122 55 139 x11Colour MediumPurple = opaque $ sRGB24 147 112 219 x11Colour MediumPurple1 = opaque $ sRGB24 171 130 255 x11Colour MediumPurple2 = opaque $ sRGB24 159 121 238 x11Colour MediumPurple3 = opaque $ sRGB24 137 104 205 x11Colour MediumPurple4 = opaque $ sRGB24 93 71 139 x11Colour MediumSeaGreen = opaque $ sRGB24 60 179 113 x11Colour MediumSlateBlue = opaque $ sRGB24 123 104 238 x11Colour MediumSpringGreen = opaque $ sRGB24 0 250 154 x11Colour MediumTurquoise = opaque $ sRGB24 72 209 204 x11Colour MediumVioletRed = opaque $ sRGB24 199 21 133 x11Colour MidnightBlue = opaque $ sRGB24 25 25 112 x11Colour MintCream = opaque $ sRGB24 245 255 250 x11Colour MistyRose = opaque $ sRGB24 255 228 225 x11Colour MistyRose1 = opaque $ sRGB24 255 228 225 x11Colour MistyRose2 = opaque $ sRGB24 238 213 210 x11Colour MistyRose3 = opaque $ sRGB24 205 183 181 x11Colour MistyRose4 = opaque $ sRGB24 139 125 123 x11Colour Moccasin = opaque $ sRGB24 255 228 181 x11Colour NavajoWhite = opaque $ sRGB24 255 222 173 x11Colour NavajoWhite1 = opaque $ sRGB24 255 222 173 x11Colour NavajoWhite2 = opaque $ sRGB24 238 207 161 x11Colour NavajoWhite3 = opaque $ sRGB24 205 179 139 x11Colour NavajoWhite4 = opaque $ sRGB24 139 121 94 x11Colour Navy = opaque $ sRGB24 0 0 128 x11Colour NavyBlue = opaque $ sRGB24 0 0 128 x11Colour OldLace = opaque $ sRGB24 253 245 230 x11Colour OliveDrab = opaque $ sRGB24 107 142 35 x11Colour OliveDrab1 = opaque $ sRGB24 192 255 62 x11Colour OliveDrab2 = opaque $ sRGB24 179 238 58 x11Colour OliveDrab3 = opaque $ sRGB24 154 205 50 x11Colour OliveDrab4 = opaque $ sRGB24 105 139 34 x11Colour Orange = opaque $ sRGB24 255 165 0 x11Colour Orange1 = opaque $ sRGB24 255 165 0 x11Colour Orange2 = opaque $ sRGB24 238 154 0 x11Colour Orange3 = opaque $ sRGB24 205 133 0 x11Colour Orange4 = opaque $ sRGB24 139 90 0 x11Colour OrangeRed = opaque $ sRGB24 255 69 0 x11Colour OrangeRed1 = opaque $ sRGB24 255 69 0 x11Colour OrangeRed2 = opaque $ sRGB24 238 64 0 x11Colour OrangeRed3 = opaque $ sRGB24 205 55 0 x11Colour OrangeRed4 = opaque $ sRGB24 139 37 0 x11Colour Orchid = opaque $ sRGB24 218 112 214 x11Colour Orchid1 = opaque $ sRGB24 255 131 250 x11Colour Orchid2 = opaque $ sRGB24 238 122 233 x11Colour Orchid3 = opaque $ sRGB24 205 105 201 x11Colour Orchid4 = opaque $ sRGB24 139 71 137 x11Colour PaleGoldenrod = opaque $ sRGB24 238 232 170 x11Colour PaleGreen = opaque $ sRGB24 152 251 152 x11Colour PaleGreen1 = opaque $ sRGB24 154 255 154 x11Colour PaleGreen2 = opaque $ sRGB24 144 238 144 x11Colour PaleGreen3 = opaque $ sRGB24 124 205 124 x11Colour PaleGreen4 = opaque $ sRGB24 84 139 84 x11Colour PaleTurquoise = opaque $ sRGB24 175 238 238 x11Colour PaleTurquoise1 = opaque $ sRGB24 187 255 255 x11Colour PaleTurquoise2 = opaque $ sRGB24 174 238 238 x11Colour PaleTurquoise3 = opaque $ sRGB24 150 205 205 x11Colour PaleTurquoise4 = opaque $ sRGB24 102 139 139 x11Colour PaleVioletRed = opaque $ sRGB24 219 112 147 x11Colour PaleVioletRed1 = opaque $ sRGB24 255 130 171 x11Colour PaleVioletRed2 = opaque $ sRGB24 238 121 159 x11Colour PaleVioletRed3 = opaque $ sRGB24 205 104 137 x11Colour PaleVioletRed4 = opaque $ sRGB24 139 71 93 x11Colour PapayaWhip = opaque $ sRGB24 255 239 213 x11Colour PeachPuff = opaque $ sRGB24 255 218 185 x11Colour PeachPuff1 = opaque $ sRGB24 255 218 185 x11Colour PeachPuff2 = opaque $ sRGB24 238 203 173 x11Colour PeachPuff3 = opaque $ sRGB24 205 175 149 x11Colour PeachPuff4 = opaque $ sRGB24 139 119 101 x11Colour Peru = opaque $ sRGB24 205 133 63 x11Colour Pink = opaque $ sRGB24 255 192 203 x11Colour Pink1 = opaque $ sRGB24 255 181 197 x11Colour Pink2 = opaque $ sRGB24 238 169 184 x11Colour Pink3 = opaque $ sRGB24 205 145 158 x11Colour Pink4 = opaque $ sRGB24 139 99 108 x11Colour Plum = opaque $ sRGB24 221 160 221 x11Colour Plum1 = opaque $ sRGB24 255 187 255 x11Colour Plum2 = opaque $ sRGB24 238 174 238 x11Colour Plum3 = opaque $ sRGB24 205 150 205 x11Colour Plum4 = opaque $ sRGB24 139 102 139 x11Colour PowderBlue = opaque $ sRGB24 176 224 230 x11Colour Purple = opaque $ sRGB24 160 32 240 x11Colour Purple1 = opaque $ sRGB24 155 48 255 x11Colour Purple2 = opaque $ sRGB24 145 44 238 x11Colour Purple3 = opaque $ sRGB24 125 38 205 x11Colour Purple4 = opaque $ sRGB24 85 26 139 x11Colour Red = opaque $ sRGB24 255 0 0 x11Colour Red1 = opaque $ sRGB24 255 0 0 x11Colour Red2 = opaque $ sRGB24 238 0 0 x11Colour Red3 = opaque $ sRGB24 205 0 0 x11Colour Red4 = opaque $ sRGB24 139 0 0 x11Colour RosyBrown = opaque $ sRGB24 188 143 143 x11Colour RosyBrown1 = opaque $ sRGB24 255 193 193 x11Colour RosyBrown2 = opaque $ sRGB24 238 180 180 x11Colour RosyBrown3 = opaque $ sRGB24 205 155 155 x11Colour RosyBrown4 = opaque $ sRGB24 139 105 105 x11Colour RoyalBlue = opaque $ sRGB24 65 105 225 x11Colour RoyalBlue1 = opaque $ sRGB24 72 118 255 x11Colour RoyalBlue2 = opaque $ sRGB24 67 110 238 x11Colour RoyalBlue3 = opaque $ sRGB24 58 95 205 x11Colour RoyalBlue4 = opaque $ sRGB24 39 64 139 x11Colour SaddleBrown = opaque $ sRGB24 139 69 19 x11Colour Salmon = opaque $ sRGB24 250 128 114 x11Colour Salmon1 = opaque $ sRGB24 255 140 105 x11Colour Salmon2 = opaque $ sRGB24 238 130 98 x11Colour Salmon3 = opaque $ sRGB24 205 112 84 x11Colour Salmon4 = opaque $ sRGB24 139 76 57 x11Colour SandyBrown = opaque $ sRGB24 244 164 96 x11Colour SeaGreen = opaque $ sRGB24 46 139 87 x11Colour SeaGreen1 = opaque $ sRGB24 84 255 159 x11Colour SeaGreen2 = opaque $ sRGB24 78 238 148 x11Colour SeaGreen3 = opaque $ sRGB24 67 205 128 x11Colour SeaGreen4 = opaque $ sRGB24 46 139 87 x11Colour SeaShell = opaque $ sRGB24 255 245 238 x11Colour SeaShell1 = opaque $ sRGB24 255 245 238 x11Colour SeaShell2 = opaque $ sRGB24 238 229 222 x11Colour SeaShell3 = opaque $ sRGB24 205 197 191 x11Colour SeaShell4 = opaque $ sRGB24 139 134 130 x11Colour Sienna = opaque $ sRGB24 160 82 45 x11Colour Sienna1 = opaque $ sRGB24 255 130 71 x11Colour Sienna2 = opaque $ sRGB24 238 121 66 x11Colour Sienna3 = opaque $ sRGB24 205 104 57 x11Colour Sienna4 = opaque $ sRGB24 139 71 38 x11Colour SkyBlue = opaque $ sRGB24 135 206 235 x11Colour SkyBlue1 = opaque $ sRGB24 135 206 255 x11Colour SkyBlue2 = opaque $ sRGB24 126 192 238 x11Colour SkyBlue3 = opaque $ sRGB24 108 166 205 x11Colour SkyBlue4 = opaque $ sRGB24 74 112 139 x11Colour SlateBlue = opaque $ sRGB24 106 90 205 x11Colour SlateBlue1 = opaque $ sRGB24 131 111 255 x11Colour SlateBlue2 = opaque $ sRGB24 122 103 238 x11Colour SlateBlue3 = opaque $ sRGB24 105 89 205 x11Colour SlateBlue4 = opaque $ sRGB24 71 60 139 x11Colour SlateGray = opaque $ sRGB24 112 128 144 x11Colour SlateGray1 = opaque $ sRGB24 198 226 255 x11Colour SlateGray2 = opaque $ sRGB24 185 211 238 x11Colour SlateGray3 = opaque $ sRGB24 159 182 205 x11Colour SlateGray4 = opaque $ sRGB24 108 123 139 x11Colour Snow = opaque $ sRGB24 255 250 250 x11Colour Snow1 = opaque $ sRGB24 255 250 250 x11Colour Snow2 = opaque $ sRGB24 238 233 233 x11Colour Snow3 = opaque $ sRGB24 205 201 201 x11Colour Snow4 = opaque $ sRGB24 139 137 137 x11Colour SpringGreen = opaque $ sRGB24 0 255 127 x11Colour SpringGreen1 = opaque $ sRGB24 0 255 127 x11Colour SpringGreen2 = opaque $ sRGB24 0 238 118 x11Colour SpringGreen3 = opaque $ sRGB24 0 205 102 x11Colour SpringGreen4 = opaque $ sRGB24 0 139 69 x11Colour SteelBlue = opaque $ sRGB24 70 130 180 x11Colour SteelBlue1 = opaque $ sRGB24 99 184 255 x11Colour SteelBlue2 = opaque $ sRGB24 92 172 238 x11Colour SteelBlue3 = opaque $ sRGB24 79 148 205 x11Colour SteelBlue4 = opaque $ sRGB24 54 100 139 x11Colour Tan = opaque $ sRGB24 210 180 140 x11Colour Tan1 = opaque $ sRGB24 255 165 79 x11Colour Tan2 = opaque $ sRGB24 238 154 73 x11Colour Tan3 = opaque $ sRGB24 205 133 63 x11Colour Tan4 = opaque $ sRGB24 139 90 43 x11Colour Thistle = opaque $ sRGB24 216 191 216 x11Colour Thistle1 = opaque $ sRGB24 255 225 255 x11Colour Thistle2 = opaque $ sRGB24 238 210 238 x11Colour Thistle3 = opaque $ sRGB24 205 181 205 x11Colour Thistle4 = opaque $ sRGB24 139 123 139 x11Colour Tomato = opaque $ sRGB24 255 99 71 x11Colour Tomato1 = opaque $ sRGB24 255 99 71 x11Colour Tomato2 = opaque $ sRGB24 238 92 66 x11Colour Tomato3 = opaque $ sRGB24 205 79 57 x11Colour Tomato4 = opaque $ sRGB24 139 54 38 x11Colour Transparent = transparent x11Colour Turquoise = opaque $ sRGB24 64 224 208 x11Colour Turquoise1 = opaque $ sRGB24 0 245 255 x11Colour Turquoise2 = opaque $ sRGB24 0 229 238 x11Colour Turquoise3 = opaque $ sRGB24 0 197 205 x11Colour Turquoise4 = opaque $ sRGB24 0 134 139 x11Colour Violet = opaque $ sRGB24 238 130 238 x11Colour VioletRed = opaque $ sRGB24 208 32 144 x11Colour VioletRed1 = opaque $ sRGB24 255 62 150 x11Colour VioletRed2 = opaque $ sRGB24 238 58 140 x11Colour VioletRed3 = opaque $ sRGB24 205 50 120 x11Colour VioletRed4 = opaque $ sRGB24 139 34 82 x11Colour Wheat = opaque $ sRGB24 245 222 179 x11Colour Wheat1 = opaque $ sRGB24 255 231 186 x11Colour Wheat2 = opaque $ sRGB24 238 216 174 x11Colour Wheat3 = opaque $ sRGB24 205 186 150 x11Colour Wheat4 = opaque $ sRGB24 139 126 102 x11Colour White = opaque $ sRGB24 255 255 255 x11Colour WhiteSmoke = opaque $ sRGB24 245 245 245 x11Colour Yellow = opaque $ sRGB24 255 255 0 x11Colour Yellow1 = opaque $ sRGB24 255 255 0 x11Colour Yellow2 = opaque $ sRGB24 238 238 0 x11Colour Yellow3 = opaque $ sRGB24 205 205 0 x11Colour Yellow4 = opaque $ sRGB24 139 139 0 x11Colour YellowGreen = opaque $ sRGB24 154 205 50
aaba2f31162c6912e1014a37e8eabc1242050e514cd23b4e0d3fd97eb4f999b7
bootstrapworld/curr
DrivingGame.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname DrivingGame) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) (require "Teachpacks/bootstrap-teachpack.rkt") ;; GRAPHICS (define ROAD (bitmap "Teachpacks/teachpack-images/ROAD.jpg")) (define CAR-LEFT (scale .55 (bitmap "Teachpacks/teachpack-images/MYCARLEFT.png"))) (define CAR-REAR (scale .8 (bitmap "Teachpacks/teachpack-images/MYCAR.png"))) (define CAR-RIGHT (flip-horizontal CAR-LEFT)) (define CAR1 (scale .8 (bitmap "Teachpacks/teachpack-images/CAR1.png"))) (define CAR2 (scale .8 (bitmap "Teachpacks/teachpack-images/CAR2.png"))) (define CAR3 (scale .8 (bitmap "Teachpacks/teachpack-images/CAR3.png"))) (define CAR4 (scale .8 (bitmap "Teachpacks/teachpack-images/CAR4.png"))) (define CAR5 (scale .8 (bitmap "Teachpacks/teachpack-images/CAR5.png"))) (define CAR6 (scale .8 (bitmap "Teachpacks/teachpack-images/CAR6.png"))) (define DANGERS (list CAR1 CAR2 CAR3 CAR4 CAR5 CAR6)) ;; DATA: ;; An object is a: number image number number number number number from 1 to 3 , image of vehicle , scale factor , distance DOWN ROAD , speed at which the object is driving , x - coord , y - coord (define-struct object (lane img scale dist speed x y)) (define thing1 (make-object (+ (random 3) 1) (list-ref DANGERS (random (length DANGERS))) 10 (+ 250 (random 250)) (+ 5 (random 8)) 60 60)) (define thing2 (make-object (+ (random 3) 1) (list-ref DANGERS (random (length DANGERS))) 10 (+ 250 (random 250)) (+ 5 (random 8)) 60 60)) The World is a : image number number number object - struct object - struct (define-struct world (img lane timePassed timer obj1 obj2)) ;; STARTING WORLD (define START (make-world CAR-REAR 2 0 0 thing1 thing2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; GRAPHICS FUNCTIONS: ;; draw-world: world -> Image place DANGER , TARGET , and PLAYER onto BACKGROUND at the right coordinates (define (draw-world w) (cond [(gameover? w) (put-image (text (string-append "OH NO! YOU LOST! You drove for " (number->string (world-timePassed w)) " seconds.") 30 "green") 500 400 (rectangle 1000 800 "solid" "black"))] [(= (world-lane w) 1) (put-image (img-time (world-timer w) w) 200 40 (put-image (image-scale (world-obj1 w)) (object-x (world-obj1 w)) (object-y (world-obj1 w)) (put-image (image-scale (world-obj2 w)) (object-x (world-obj2 w)) (object-y (world-obj2 w)) ROAD)))] [(= (world-lane w) 2) (put-image (img-time (world-timer w) w) 500 40 (put-image (image-scale (world-obj1 w)) (object-x (world-obj1 w)) (object-y (world-obj1 w)) (put-image (image-scale (world-obj2 w)) (object-x (world-obj2 w)) (object-y (world-obj2 w)) ROAD)))] [(= (world-lane w) 3) (put-image (img-time (world-timer w) w) 800 40 (put-image (image-scale (world-obj1 w)) (object-x (world-obj1 w)) (object-y (world-obj1 w)) (put-image (image-scale (world-obj2 w)) (object-x (world-obj2 w)) (object-y (world-obj2 w)) ROAD)))])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; UPDATING FUNCTIONS: ;; update-world: world -> world ;; What does your update-world function do? (define (update-world w) (cond [(gameover? w) w] [(off-bottom? (object-y (world-obj1 w))) (make-world (world-img w) (world-lane w) (+ (world-timePassed w) 1) (+ (world-timer w) 1) (reset-object w (world-obj1 w)) (world-obj2 w))] [(off-bottom? (object-y (world-obj2 w))) (make-world (world-img w) (world-lane w) (+ (world-timePassed w) 1) (+ (world-timer w) 1) (world-obj1 w) (reset-object w (world-obj2 w)))] [else (make-world (world-img w) (world-lane w) (+ (world-timePassed w) 1) (+ (world-timer w) 1) (move-object (world-obj1 w)) (move-object (world-obj2 w)))])) ;; image-scale: object -> image ;; How large should the image be, based on its y-coordinate? (define (image-scale o) (scale (/ (+ 102 (/ (object-y o) -5.25)) 100) (object-img o))) ;; move-object: object -> object ;; Apply the functions which update distance, x, and y coordinates (define (move-object o) (make-object (object-lane o) (object-img o) (object-scale o) (update-dist o) (object-speed o) (update-x o) (update-y o))) ;; update-dist: object -> number ;; Change the distance, at a rate dependant on the speed of the object (define (update-dist o) (- (object-dist o) (object-speed o))) ;; update-y: object -> number ;; Uses arctan to approximate a constant speed approach (define (update-y o) (- 1000 (* 450 (/ 1 (atan (* (object-dist o) (/ pi 1100)) ))))) ;; update-x: object -> number ;; Update's the object's x-coordinate, depending on the lane it is in (define (update-x o) (cond [(= (object-lane o) 2) 500] [(= (object-lane o) 3) (+ 925 (* -16/20 (object-y o)))] [(= (object-lane o) 1) (+ 75 (* 16/20 (object-y o)))])) ;; reset-object: world -> object ;; Resets the object at the vanishing point (new image, new lane, speed based on time that has passed) (define (reset-object w o) (make-object (+ (random 3) 1) (list-ref DANGERS (random (length DANGERS))) (object-scale o) 500 (+ 10 (/ (world-timePassed w) 100)) (update-x o) (update-y o))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; KEY EVENTS: ;; keypress: world string -> world ;; Left and Right control the movement of your car between lanes (define (keypress w key) (cond [(gameover? w) (make-world CAR-LEFT (world-lane w) (world-timePassed w) 0 (world-obj1 w) (world-obj2 w) )] [else (cond [(and (string=? key "left") (> (world-lane w) 1)) (make-world CAR-LEFT (- (world-lane w) 1) (world-timePassed w) 0 (world-obj1 w) (world-obj2 w))] [(and (string=? key "right") (< (world-lane w) 3)) (make-world CAR-RIGHT (+ (world-lane w) 1) (world-timePassed w) 0 (world-obj1 w) (world-obj2 w))] [else w])])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TESTS FOR COND: ;; img-time : number -> image Is the world 's timer field greater than 5 ? If so , you should see the back of the car . ;; If not? Check the world for the appropriately turned image. (define (img-time timer w) (cond [(> timer 5) CAR-REAR] [else (world-img w)])) ;; off-bottom? : number -> boolean ;; Checks whether an object has gone off the right side of the screen (define (off-bottom? y) (< y 5)) ;; lane-collide? : world -> boolean checks whether object - dist is zero and object - lane = car lane (define (lane-collide? w o) (and (<= (object-dist o) 200) (= (object-lane o) (world-lane w)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; RESULTS FOR COND: ;; gameover? : world -> boolean ;; Should the program end? (define (gameover? w) (or (lane-collide? w (world-obj1 w)) (lane-collide? w (world-obj2 w)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; big - bang using the START world ;; on a tick-event, use update-world ;; on a draw-event, use draw-world ;; on a key-event, use keypress (big-bang START (on-tick update-world) (on-draw draw-world) (on-key keypress) )
null
https://raw.githubusercontent.com/bootstrapworld/curr/443015255eacc1c902a29978df0e3e8e8f3b9430/courses/reactive/resources/source-files/DrivingGame.rkt
racket
about the language level of this file in a form that our tools can easily process. GRAPHICS DATA: An object is a: number image number number number number number STARTING WORLD GRAPHICS FUNCTIONS: draw-world: world -> Image UPDATING FUNCTIONS: update-world: world -> world What does your update-world function do? image-scale: object -> image How large should the image be, based on its y-coordinate? move-object: object -> object Apply the functions which update distance, x, and y coordinates update-dist: object -> number Change the distance, at a rate dependant on the speed of the object update-y: object -> number Uses arctan to approximate a constant speed approach update-x: object -> number Update's the object's x-coordinate, depending on the lane it is in reset-object: world -> object Resets the object at the vanishing point (new image, new lane, speed based on time that has passed) KEY EVENTS: keypress: world string -> world Left and Right control the movement of your car between lanes TESTS FOR COND: img-time : number -> image If not? Check the world for the appropriately turned image. off-bottom? : number -> boolean Checks whether an object has gone off the right side of the screen lane-collide? : world -> boolean RESULTS FOR COND: gameover? : world -> boolean Should the program end? on a tick-event, use update-world on a draw-event, use draw-world on a key-event, use keypress
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname DrivingGame) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) (require "Teachpacks/bootstrap-teachpack.rkt") (define ROAD (bitmap "Teachpacks/teachpack-images/ROAD.jpg")) (define CAR-LEFT (scale .55 (bitmap "Teachpacks/teachpack-images/MYCARLEFT.png"))) (define CAR-REAR (scale .8 (bitmap "Teachpacks/teachpack-images/MYCAR.png"))) (define CAR-RIGHT (flip-horizontal CAR-LEFT)) (define CAR1 (scale .8 (bitmap "Teachpacks/teachpack-images/CAR1.png"))) (define CAR2 (scale .8 (bitmap "Teachpacks/teachpack-images/CAR2.png"))) (define CAR3 (scale .8 (bitmap "Teachpacks/teachpack-images/CAR3.png"))) (define CAR4 (scale .8 (bitmap "Teachpacks/teachpack-images/CAR4.png"))) (define CAR5 (scale .8 (bitmap "Teachpacks/teachpack-images/CAR5.png"))) (define CAR6 (scale .8 (bitmap "Teachpacks/teachpack-images/CAR6.png"))) (define DANGERS (list CAR1 CAR2 CAR3 CAR4 CAR5 CAR6)) from 1 to 3 , image of vehicle , scale factor , distance DOWN ROAD , speed at which the object is driving , x - coord , y - coord (define-struct object (lane img scale dist speed x y)) (define thing1 (make-object (+ (random 3) 1) (list-ref DANGERS (random (length DANGERS))) 10 (+ 250 (random 250)) (+ 5 (random 8)) 60 60)) (define thing2 (make-object (+ (random 3) 1) (list-ref DANGERS (random (length DANGERS))) 10 (+ 250 (random 250)) (+ 5 (random 8)) 60 60)) The World is a : image number number number object - struct object - struct (define-struct world (img lane timePassed timer obj1 obj2)) (define START (make-world CAR-REAR 2 0 0 thing1 thing2)) place DANGER , TARGET , and PLAYER onto BACKGROUND at the right coordinates (define (draw-world w) (cond [(gameover? w) (put-image (text (string-append "OH NO! YOU LOST! You drove for " (number->string (world-timePassed w)) " seconds.") 30 "green") 500 400 (rectangle 1000 800 "solid" "black"))] [(= (world-lane w) 1) (put-image (img-time (world-timer w) w) 200 40 (put-image (image-scale (world-obj1 w)) (object-x (world-obj1 w)) (object-y (world-obj1 w)) (put-image (image-scale (world-obj2 w)) (object-x (world-obj2 w)) (object-y (world-obj2 w)) ROAD)))] [(= (world-lane w) 2) (put-image (img-time (world-timer w) w) 500 40 (put-image (image-scale (world-obj1 w)) (object-x (world-obj1 w)) (object-y (world-obj1 w)) (put-image (image-scale (world-obj2 w)) (object-x (world-obj2 w)) (object-y (world-obj2 w)) ROAD)))] [(= (world-lane w) 3) (put-image (img-time (world-timer w) w) 800 40 (put-image (image-scale (world-obj1 w)) (object-x (world-obj1 w)) (object-y (world-obj1 w)) (put-image (image-scale (world-obj2 w)) (object-x (world-obj2 w)) (object-y (world-obj2 w)) ROAD)))])) (define (update-world w) (cond [(gameover? w) w] [(off-bottom? (object-y (world-obj1 w))) (make-world (world-img w) (world-lane w) (+ (world-timePassed w) 1) (+ (world-timer w) 1) (reset-object w (world-obj1 w)) (world-obj2 w))] [(off-bottom? (object-y (world-obj2 w))) (make-world (world-img w) (world-lane w) (+ (world-timePassed w) 1) (+ (world-timer w) 1) (world-obj1 w) (reset-object w (world-obj2 w)))] [else (make-world (world-img w) (world-lane w) (+ (world-timePassed w) 1) (+ (world-timer w) 1) (move-object (world-obj1 w)) (move-object (world-obj2 w)))])) (define (image-scale o) (scale (/ (+ 102 (/ (object-y o) -5.25)) 100) (object-img o))) (define (move-object o) (make-object (object-lane o) (object-img o) (object-scale o) (update-dist o) (object-speed o) (update-x o) (update-y o))) (define (update-dist o) (- (object-dist o) (object-speed o))) (define (update-y o) (- 1000 (* 450 (/ 1 (atan (* (object-dist o) (/ pi 1100)) ))))) (define (update-x o) (cond [(= (object-lane o) 2) 500] [(= (object-lane o) 3) (+ 925 (* -16/20 (object-y o)))] [(= (object-lane o) 1) (+ 75 (* 16/20 (object-y o)))])) (define (reset-object w o) (make-object (+ (random 3) 1) (list-ref DANGERS (random (length DANGERS))) (object-scale o) 500 (+ 10 (/ (world-timePassed w) 100)) (update-x o) (update-y o))) (define (keypress w key) (cond [(gameover? w) (make-world CAR-LEFT (world-lane w) (world-timePassed w) 0 (world-obj1 w) (world-obj2 w) )] [else (cond [(and (string=? key "left") (> (world-lane w) 1)) (make-world CAR-LEFT (- (world-lane w) 1) (world-timePassed w) 0 (world-obj1 w) (world-obj2 w))] [(and (string=? key "right") (< (world-lane w) 3)) (make-world CAR-RIGHT (+ (world-lane w) 1) (world-timePassed w) 0 (world-obj1 w) (world-obj2 w))] [else w])])) Is the world 's timer field greater than 5 ? If so , you should see the back of the car . (define (img-time timer w) (cond [(> timer 5) CAR-REAR] [else (world-img w)])) (define (off-bottom? y) (< y 5)) checks whether object - dist is zero and object - lane = car lane (define (lane-collide? w o) (and (<= (object-dist o) 200) (= (object-lane o) (world-lane w)))) (define (gameover? w) (or (lane-collide? w (world-obj1 w)) (lane-collide? w (world-obj2 w)))) big - bang using the START world (big-bang START (on-tick update-world) (on-draw draw-world) (on-key keypress) )
7cd8a91bbfffd96b2d4c670c528eb47e1e494da3fa6b6bee6d3278163fd0c68a
haskell/stm
Issue17.hs
# LANGUAGE CPP # see -- Test - case contributed by < > -- This bug is observable in all versions with TBQueue from ` stm-2.4 ` to ` stm-2.4.5.1 ` inclusive . module Issue17 (main) where import Control.Concurrent.STM import Test.HUnit.Base (assertBool, assertEqual) main :: IO () main = do New queue capacity is set to 0 queueIO <- newTBQueueIO 0 assertNoCapacityTBQueue queueIO Same as above , except created within STM queueSTM <- atomically $ newTBQueue 0 assertNoCapacityTBQueue queueSTM #if !MIN_VERSION_stm(2,5,0) NB : below are expected failures -- New queue capacity is set to a negative numer queueIO' <- newTBQueueIO (-1 :: Int) assertNoCapacityTBQueue queueIO' Same as above , except created within STM and different negative number queueSTM' <- atomically $ newTBQueue (minBound :: Int) assertNoCapacityTBQueue queueSTM' #endif assertNoCapacityTBQueue :: TBQueue Int -> IO () assertNoCapacityTBQueue queue = do assertEmptyTBQueue queue assertFullTBQueue queue -- Attempt to write into the queue. eValWrite <- atomically $ orElse (fmap Left (writeTBQueue queue 217)) (fmap Right (tryReadTBQueue queue)) assertEqual "Expected queue with no capacity: writeTBQueue" eValWrite (Right Nothing) eValUnGet <- atomically $ orElse (fmap Left (unGetTBQueue queue 218)) (fmap Right (tryReadTBQueue queue)) assertEqual "Expected queue with no capacity: unGetTBQueue" eValUnGet (Right Nothing) -- Make sure that attempt to write didn't affect the queue assertEmptyTBQueue queue assertFullTBQueue queue assertEmptyTBQueue :: TBQueue Int -> IO () assertEmptyTBQueue queue = do atomically (isEmptyTBQueue queue) >>= assertBool "Expected empty: isEmptyTBQueue should return True" atomically (tryReadTBQueue queue) >>= assertEqual "Expected empty: tryReadTBQueue should return Nothing" Nothing atomically (tryPeekTBQueue queue) >>= assertEqual "Expected empty: tryPeekTBQueue should return Nothing" Nothing atomically (flushTBQueue queue) >>= assertEqual "Expected empty: flushTBQueue should return []" [] assertFullTBQueue :: TBQueue Int -> IO () assertFullTBQueue queue = do atomically (isFullTBQueue queue) >>= assertBool "Expected full: isFullTBQueue shoule return True"
null
https://raw.githubusercontent.com/haskell/stm/319e380ab2ddfb99ab499b6783e22f2b4faaee38/testsuite/src/Issue17.hs
haskell
New queue capacity is set to a negative numer Attempt to write into the queue. Make sure that attempt to write didn't affect the queue
# LANGUAGE CPP # see Test - case contributed by < > This bug is observable in all versions with TBQueue from ` stm-2.4 ` to ` stm-2.4.5.1 ` inclusive . module Issue17 (main) where import Control.Concurrent.STM import Test.HUnit.Base (assertBool, assertEqual) main :: IO () main = do New queue capacity is set to 0 queueIO <- newTBQueueIO 0 assertNoCapacityTBQueue queueIO Same as above , except created within STM queueSTM <- atomically $ newTBQueue 0 assertNoCapacityTBQueue queueSTM #if !MIN_VERSION_stm(2,5,0) NB : below are expected failures queueIO' <- newTBQueueIO (-1 :: Int) assertNoCapacityTBQueue queueIO' Same as above , except created within STM and different negative number queueSTM' <- atomically $ newTBQueue (minBound :: Int) assertNoCapacityTBQueue queueSTM' #endif assertNoCapacityTBQueue :: TBQueue Int -> IO () assertNoCapacityTBQueue queue = do assertEmptyTBQueue queue assertFullTBQueue queue eValWrite <- atomically $ orElse (fmap Left (writeTBQueue queue 217)) (fmap Right (tryReadTBQueue queue)) assertEqual "Expected queue with no capacity: writeTBQueue" eValWrite (Right Nothing) eValUnGet <- atomically $ orElse (fmap Left (unGetTBQueue queue 218)) (fmap Right (tryReadTBQueue queue)) assertEqual "Expected queue with no capacity: unGetTBQueue" eValUnGet (Right Nothing) assertEmptyTBQueue queue assertFullTBQueue queue assertEmptyTBQueue :: TBQueue Int -> IO () assertEmptyTBQueue queue = do atomically (isEmptyTBQueue queue) >>= assertBool "Expected empty: isEmptyTBQueue should return True" atomically (tryReadTBQueue queue) >>= assertEqual "Expected empty: tryReadTBQueue should return Nothing" Nothing atomically (tryPeekTBQueue queue) >>= assertEqual "Expected empty: tryPeekTBQueue should return Nothing" Nothing atomically (flushTBQueue queue) >>= assertEqual "Expected empty: flushTBQueue should return []" [] assertFullTBQueue :: TBQueue Int -> IO () assertFullTBQueue queue = do atomically (isFullTBQueue queue) >>= assertBool "Expected full: isFullTBQueue shoule return True"
8386a936778e58a99964eac7d98741111fe6e58d8b69470ed17d554029572878
Bwooce/open-cgf
open-cgf_state.erl
%%%------------------------------------------------------------------- %%% File : open-cgf_state.erl Author : < > %%% Description : %%% Copyright 2008 %%% %%% This file is part of open-cgf. %%% %%% open-cgf is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation . %%% %%% open-cgf 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 open-cgf. If not, see </>. %%%------------------------------------------------------------------- -module('open-cgf_state'). -behaviour(gen_server). -define(SERVER, ?MODULE). -include("open-cgf.hrl"). -include("gtp.hrl"). %% API -export([start_link/0, get_next_seqnum/1, get_restart_counter/0, inc_restart_counter/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {sequence_numbers, restart_counter }). %%==================================================================== %% API %%==================================================================== %%-------------------------------------------------------------------- Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } %% Description: Starts the server %%-------------------------------------------------------------------- start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). get_next_seqnum(Key) -> gen_server:call(?SERVER, {seqnum, Key}). get_restart_counter() -> gen_server:call(?SERVER, {restart_counter}). inc_restart_counter() -> gen_server:call(?SERVER, {inc_restart_counter}). %%==================================================================== %% gen_server callbacks %%==================================================================== %%-------------------------------------------------------------------- %% Function: init(Args) -> {ok, State} | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% Description: Initiates the server %%-------------------------------------------------------------------- init([]) -> %% read state from dets {ok, _} = dets:open_file(cgf_state_dets, [{ram_file, true}]), %% we're storing nothing that isn't sync'd (for the moment) {_, RC} = case dets:lookup(cgf_state_dets, restart_counter) of [C] -> C; [] -> ok = dets:insert(cgf_state_dets, {restart_counter, 0}), {nothing, 0} end, {ok, #state{restart_counter=RC, sequence_numbers=orddict:new()}}. %%-------------------------------------------------------------------- Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% Description: Handling call messages %%-------------------------------------------------------------------- handle_call({seqnum, Key}, _, State) -> NewDict = orddict:update_counter(Key, 1, State#state.sequence_numbers), SeqNum = orddict:fetch(Key, NewDict), ?PRINTDEBUG2("Next seqnum for key ~p is ~p",[Key, SeqNum]), {reply, SeqNum rem 65536, State#state{sequence_numbers=NewDict}}; handle_call({restart_counter}, _, State) -> ?PRINTDEBUG2("Restart counter is ~p",[State#state.restart_counter]), {reply, State#state.restart_counter, State}; handle_call({inc_restart_counter}, _, State) -> RC = dets:update_counter(cgf_state_dets, restart_counter, 1) rem 256, dets:sync(cgf_state_dets), {reply, RC, State#state{restart_counter=RC}}; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. %%-------------------------------------------------------------------- Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling cast messages %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling all non call/cast messages %%-------------------------------------------------------------------- handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% Function: terminate(Reason, State) -> void() %% Description: This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any necessary %% cleaning up. When it returns, the gen_server terminates with Reason. %% The return value is ignored. %%-------------------------------------------------------------------- terminate(_Reason, _State) -> dets:sync(cgf_state_dets), ok. %%-------------------------------------------------------------------- Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } %% Description: Convert process state when code is changed %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- Internal functions %%--------------------------------------------------------------------
null
https://raw.githubusercontent.com/Bwooce/open-cgf/929f7e280493ca4bc47be05bb931044ee1321594/src/open-cgf_state.erl
erlang
------------------------------------------------------------------- File : open-cgf_state.erl Description : This file is part of open-cgf. open-cgf is free software: you can redistribute it and/or modify open-cgf 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. along with open-cgf. If not, see </>. ------------------------------------------------------------------- API gen_server callbacks ==================================================================== API ==================================================================== -------------------------------------------------------------------- Description: Starts the server -------------------------------------------------------------------- ==================================================================== gen_server callbacks ==================================================================== -------------------------------------------------------------------- Function: init(Args) -> {ok, State} | ignore | {stop, Reason} Description: Initiates the server -------------------------------------------------------------------- read state from dets we're storing nothing that isn't sync'd (for the moment) -------------------------------------------------------------------- % handle_call(Request , From , State ) - > { reply , Reply , State } | {stop, Reason, Reply, State} | {stop, Reason, State} Description: Handling call messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling all non call/cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- Function: terminate(Reason, State) -> void() Description: This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates with Reason. The return value is ignored. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Convert process state when code is changed -------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
Author : < > Copyright 2008 it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation . You should have received a copy of the GNU General Public License -module('open-cgf_state'). -behaviour(gen_server). -define(SERVER, ?MODULE). -include("open-cgf.hrl"). -include("gtp.hrl"). -export([start_link/0, get_next_seqnum/1, get_restart_counter/0, inc_restart_counter/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {sequence_numbers, restart_counter }). Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). get_next_seqnum(Key) -> gen_server:call(?SERVER, {seqnum, Key}). get_restart_counter() -> gen_server:call(?SERVER, {restart_counter}). inc_restart_counter() -> gen_server:call(?SERVER, {inc_restart_counter}). { ok , State , Timeout } | init([]) -> {_, RC} = case dets:lookup(cgf_state_dets, restart_counter) of [C] -> C; [] -> ok = dets:insert(cgf_state_dets, {restart_counter, 0}), {nothing, 0} end, {ok, #state{restart_counter=RC, sequence_numbers=orddict:new()}}. { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call({seqnum, Key}, _, State) -> NewDict = orddict:update_counter(Key, 1, State#state.sequence_numbers), SeqNum = orddict:fetch(Key, NewDict), ?PRINTDEBUG2("Next seqnum for key ~p is ~p",[Key, SeqNum]), {reply, SeqNum rem 65536, State#state{sequence_numbers=NewDict}}; handle_call({restart_counter}, _, State) -> ?PRINTDEBUG2("Restart counter is ~p",[State#state.restart_counter]), {reply, State#state.restart_counter, State}; handle_call({inc_restart_counter}, _, State) -> RC = dets:update_counter(cgf_state_dets, restart_counter, 1) rem 256, dets:sync(cgf_state_dets), {reply, RC, State#state{restart_counter=RC}}; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast(_Msg, State) -> {noreply, State}. Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> dets:sync(cgf_state_dets), ok. Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions
aee5c95cb6951fd8ee6bb9b0f901a4596903b81343b0c1fcd608937ef7d0206f
kendroe/CoqRewriter
inner.ml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * REWRITELIB * * inner.ml * * This file contains the code for the inner rewrite routines . * * ( C ) 2017 , * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program . If not , see < / > . * will be provided when the work is complete . * * For a commercial license , contact Roe Mobile Development , LLC at * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * REWRITELIB * * inner.ml * * This file contains the code for the inner rewrite routines. * * (C) 2017, Kenneth Roe * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see </>. * will be provided when the work is complete. * * For a commercial license, contact Roe Mobile Development, LLC at * * *****************************************************************************) (* require "list.sml" ; *) (* require "exp.sml" ; *) (* require "env.sml" ; *) require " intern.sml " ; (* require "expint.sml" ; *) (* require "kbrewrit.sml" ; *) (* require "context.sml" ; *) (* require "derive.sml" ; *) (* require "builtin.sml" ; *) (* require "match.sml" ; *) require " trace.sml " ; (* require "cache.sml" ; *) (* require "crewrite.sml" ; *) (* require "rule_app.sml" ; *) (* require "rewrit-s.sml" ; *) require " basis.__list " ; (* open listimpl ; *) infix 2 * | ; infix 2 < | ; infix 2 | > ; infix 2 < > ; infix 3 > < ; open Exp ;; open ENVimpl ; open Intern ;; (* open EXP_INTERNimpl ; *) open KBREWRITEimpl ; (* open CONTEXTimpl ; *) open DERIVEimpl ; open BUILTINimpl ; open MATCHimpl ; open TRACEimpl ; open CACHEimpl ; open CREWRITEimpl ; open RULE_APPimpl ; let replace_appl_n (APPL (f,l)) n a = (APPL (f,Mylist.replace_nth l n a)) ;; let rec rewrite_list rewrite env l = match l with | [] -> [[]] | (a::b) -> (List.map (fun (x,y) -> x::y) (List.combine (rewrite env a) (rewrite_list rewrite env b))) ;; let rec remove_normals e = match e with | (NORMAL x) -> x | (APPL (f,l)) -> (APPL (f,List.map remove_normals l)) | y -> y ;; let rec mark_vars env x = (try let (REF n) = ExpIntern.intern_exp (Renv.isACorC env) x in let res = Cache.get_mark_vars n in (REF res) with Cache.NoEntry -> let (REF n) = ExpIntern.intern_exp (Renv.isACorC env) x in let (REF res) = ExpIntern.intern_exp (Renv.isACorC env) (Rcontext.markVars (ExpIntern.decode_exp x)) in Cache.add_mark_vars n res ; (REF res) ) ;; let generate_rules r env e = match r with | 9 -> (List.filter (fun (r) -> (match (ExpIntern.decode_exp r) with | (APPL (f,[APPL (4,[]);_;c])) -> false | (APPL (f,[APPL (5,[]);_;c])) -> false | (APPL (1,[l;r;c])) -> not(l=r) | _ -> false)) (List.map remove_normals (Derive.derive env (ExpIntern.intern_exp (Renv.isACorC env) (APPL (intern_oriented_rule,[mark_vars env (remove_normals e);(APPL (intern_true,[]));(APPL (intern_true,[]))])))))) |10 -> (List.filter (fun (r) -> (match (ExpIntern.decode_exp r) with | (APPL (f,[APPL (4,[]);_;c])) -> false | (APPL (f,[APPL (5,[]);_;c])) -> false | (APPL (1,[l;r;c])) -> true | _ -> false)) (List.map remove_normals (Derive.derive env (ExpIntern.intern_exp (Renv.isACorC env) (APPL (intern_oriented_rule,[mark_vars env e;(APPL (intern_false,[]));(APPL (intern_true,[]))])))))) ;; let rec generate_rules_list f env l = match l with | [] -> [] | (a::b) -> (generate_rules f env a)::(generate_rules_list f env b) ;; let rec add_c_rules env l = match l with | [] -> env | (a::b) -> add_c_rules (Renv.addProperty env a) b ;; let rec add_context_rules env l n term = let _ = ( " Adding " ^ ( string_of_int n ) ^ " \n " ) in let l = Mylist.delete_nth l n in let _ = ( fun x - > ( List.map ( fun y - > print_string ( " Rule " ^ ( prExp ( ExpIntern.decode_exp y ) ) ^ " \n " ) ) x ) ) l in addContextRules env ( List.map ( fun ( x ) - > ( REF x ) ) ( junction_filter_rule_list env term ( List.map ( fun ( x ) - > let val REF x = ExpIntern.intern_exp ( ) x in x end ) ( foldr append [ ] l ) ) ) ) Renv.addContextRules env (List.fold_right List.append l []) ;; let rec context_rewrite_list rewrite env f rules l n = if (List.length l)=n then ((l,env),rules) else let t = List.nth l n in let (x,_) = rewrite (t,(add_context_rules env rules n t)) in let gr = if Match.equal env x t then List.nth rules n else (generate_rules f env x) in context_rewrite_list rewrite env f (Mylist.replace_nth rules n gr) (Mylist.replace_nth l n x) (n+1) ;; let rec repeat_context_rewrite_list rewrite env f rules l = let ((l2,env),new_rules) = context_rewrite_list rewrite env f rules l 0 in if l2=l then (APPL (f,l2),env) else repeat_context_rewrite_list rewrite env f new_rules l2 ;; let rec repeat_rewrite rewrite ((APPL (f,l)),env) = let rules = generate_rules_list f env l in let (r,env) = repeat_context_rewrite_list rewrite env f rules l in (Renv.flatten_top env r,env) ;; exception NoRewrite ;; let intern_exp_true = ExpIntern.intern_exp (fun (x) -> false) (parseExp "True") ;; let intern_exp_false = ExpIntern.intern_exp (fun (x) -> false) (parseExp "False") ;; let flt (e,env) = (Renv.flatten_top env e,env) ;; let kbmode = ref true ;; let rec rewriteTop (exp,env) kb = (let _ = Rtrace.trace "rewrite" (fun (x) -> "builtin " ^ (prExp exp)) in let _ = Rtrace.indent () in let exp = ExpIntern.decode_two_exp (ExpIntern.intern_exp (Renv.isACorC env) exp) in let rew = Builtin.builtin rewrite2_front env exp in let _ = ( " exp = " ^ ( prExp exp ) ^ " \n " ) in let _ = ( " builtin results " ^ ( string_of_int ( ) ) ^ " \n " ) in let _ = print_string ("builtin results " ^ (string_of_int (List.length rew)) ^ "\n") in*) let _ = Rtrace.trace_list "rewrite" (fun (x) -> List.map prExp rew) in let _ = Rtrace.undent () in let _ = Rtrace.trace "rewrite" (fun (x) -> "end builtin " ^ (prExp (List.hd (rew@[exp])))) in let (res,env,kb) = (if rew = [] || rew=[exp] then let x = (Rule_app.rewriteRule rewrite2_front env exp []) in if x=[] || x==[exp] then (if (!kbmode) && kb && (Kbrewrite.useful_subterm env exp []) then let n = Kbrewrite.kbrewrite2 rewrite2_front env (ExpIntern.decode_two_exp exp) [] in if n=[] then raise NoRewrite else (List.hd n,env,false) else raise NoRewrite) else (List.hd x,env,kb) else (List.hd rew,env,kb)) in (Renv.flatten env res,env,kb)) and rewriteTopCont orig (f,env) kb = (try let (x,env,kb) = rewriteTop (f,env) kb (*val _ = print ("[Pre: " ^ (prExp f) ^ "]\n[Post: " ^ (prExp x) ^ "]\n")*) in if (ExpIntern.intern_exp (Renv.isACorC env) orig)=(ExpIntern.intern_exp (Renv.isACorC env) x) then (x,env) else try if kb then rewrite_front (x,env) else rewrite_nokb_front (x,env) with NoRewrite -> (x,env) with NoRewrite -> (f,env)) and int_rewrite e kb = (match e with | ((APPL (18,[c;e1;e2])),env) -> (let (x,env) = rewrite_front (ExpIntern.decode_two_exp c,env) in let res = if x=intern_exp_true then rewrite_front (ExpIntern.decode_two_exp e1,env) else if x=intern_exp_false then rewrite_front (e2,env) else let env1 = Crewrite.create_rules (fun (x) -> [remove_normals x]) env (APPL (intern_if,[x;e1;e2])) 1 in let (res1,env1b) = rewrite_front (e1,env1) in let env2 = Crewrite.create_rules (fun (x) -> [remove_normals x]) env (APPL (intern_if,[x;e1;e2])) 2 in let (res2,env2b) = rewrite_front (e2,env2) in rewriteTopCont (APPL (18,[c;e1;e2])) ((APPL (intern_if,[x;res1;res2])),env) kb in res) | ((APPL (90,[APPL (5,[]);_])),env) -> (intern_exp_true,env) | ((APPL (90,[APPL (4,[]);x])),env) -> (x,env) | ((APPL (90,[x;APPL (4,[])])),env) -> (intern_exp_true,env) | ((APPL (90,[x;APPL (5,[])])),env) -> ((APPL (17,[x])),env) | (APPL (90,[l;r]),env) -> let (l',env) = rewrite_front (l,env) in let e2 = Crewrite.create_rules (fun (x) -> [remove_normals x]) env (APPL (intern_implies,[l';r])) 1 in let (r',_) = rewrite_front (r,e2) in rewriteTopCont (APPL (intern_implies,[l;r])) (APPL (intern_implies,[l';r']),env) kb | ((APPL (9,[])),env) -> (intern_exp_true,env) | ((APPL (9,[(APPL (17,[x]))])),env) -> if (!kbmode) && kb && Kbrewrite.useful_subterm env x [] then let (x,_) = rewrite_front (x,env) in let x = List.hd ((Kbrewrite.kbrewrite2 rewrite2_front env x [])@[x]) in rewriteTopCont (APPL (9,[(APPL (17,[x]))])) (APPL (intern_not,[x]),env) kb else let (x,_) = rewrite_front (x,env) in rewriteTopCont (APPL (9,[(APPL (17,[x]))])) (APPL (intern_not,[x]),env) kb | ((APPL (9,[x])),env) -> if (!kbmode) && kb && Kbrewrite.useful_subterm env x [] then let (x,_) = rewrite_front (x,env) in let x = List.hd ((Kbrewrite.kbrewrite2 rewrite2_front env x [])@[x]) in rewriteTopCont (APPL (9,[x])) (x,env) kb else rewrite_front (x,env) | (APPL (9,l),env) -> rewriteTopCont (APPL (9,l)) (flt (repeat_rewrite rewrite_front ((APPL (intern_and,l)),env))) kb | ((APPL (10,[])),env) -> (intern_exp_false,env) | ((APPL (10,[x])),env) -> rewrite_front (ExpIntern.intern_exp (Renv.isACorC env) x,env) | (APPL (10,l),env) -> rewriteTopCont (APPL (10,l)) (flt (repeat_rewrite rewrite_front ((APPL (intern_or,l)),env))) kb | (APPL (1,[l;r;c]),env) -> let (c,env) = rewrite_front (c,env) in let e2 = Crewrite.create_rules (fun (x) -> [remove_normals x]) env (APPL (intern_oriented_rule,[l;r;c])) 0 in let _ = Rtrace.trace_list "rewrite" (fun (x) -> List.map (fun (x) -> "contadd " ^ (prExp (ExpIntern.decode_exp (REF x)))) (Renv.getContextList e2)) in let (l,_) = rewrite_front (l,e2) in let (r,_) = rewrite_front (r,e2) in rewriteTopCont (APPL (1,[l;r;c])) (APPL (intern_oriented_rule,[l;r;c]),env) kb | (APPL (2,[l;r;c]),env) -> let (c,env) = rewrite_front (c,env) in let e2 = Crewrite.create_rules (fun (x) -> [remove_normals x]) env (APPL (intern_unoriented_rule,[l;r;c])) 0 in let (l,_) = rewrite_front (l,e2) in let (r,_) = rewrite_front (r,e2) in rewriteTopCont (APPL (2,[l;r;c])) (APPL (intern_unoriented_rule,[l;r;c]),env) kb | (APPL (17,[e]),env) -> if (!kbmode) && kb && Kbrewrite.useful_subterm env e [] then let (ff,_) = rewrite_front (e,env) in let f = (APPL (17,[e])) in let f = List.hd ((Kbrewrite.kbrewrite2 rewrite2_front env f [])@[f]) in rewriteTopCont f (f,env) kb else let (e2,envs) = if kb then rewrite_sub env e 0 else rewrite_nokb_sub env e 0 in let (res,env) = rewriteTopCont (APPL (17,[e])) ((APPL (intern_not,[e2])),envs) kb in (res,env) | (APPL (71,l),env) -> rewriteTopCont (APPL (71,l)) (APPL (71,l),env) kb | (APPL (72,l),env) -> rewriteTopCont (APPL (72,l)) (APPL (72,l),env) kb | (APPL (s,l2),env) -> let (l,envs,_) = List.fold_left (fun (r,env,n) -> (fun e -> let (e,env) = (rewrite_sub env e n) in (r@[e],env,n+1) )) ([],env,0) l2 in let (res,env) = rewriteTopCont (APPL (s,l2)) ((Renv.flatten_top env (APPL (s,l))),envs) kb in if l=l2 then (Renv.flatten_top env res,env) else (res,env) | ((QUANT (v,t,e,p)),env) -> let (r_e,env) = try rewrite_front (e,env) with NoRewrite -> (e,env) in let (r_p,env) = try rewrite_front (p,env) with NoRewrite -> (p,env) in rewriteTopCont (QUANT (v,t,e,p)) ((QUANT (v,t,r_e,r_p)),env) kb | (LET (v,t,e,p),env) -> let (r_e,env) = rewrite_front (e,env) in let (r_p,env) = rewrite_front (p,env) in rewriteTopCont (LET (v,t,e,p)) (LET (v,t,r_e,r_p),env) kb | (CASE (e,t,c),env) -> let (r_e,env) = rewrite_front (e,env) in let r_c = List.map (fun (p,e) -> (p,let (e,_) = rewrite_front (e,env) in e)) c in rewriteTopCont (CASE (e,t,c)) (CASE (r_e,t,r_c),env) kb | (x,env) -> rewriteTopCont x (x,env) kb) and rewrite_sub env x n = try rewrite_front (x,env) with NoRewrite -> (x,env) and rewrite_nokb_sub env x n = rewrite_nokb_front (x,env) and rewrite2_front env x = (let _ = Rtrace.trace "rewrite" (fun (xx) -> "rewriting subterm: " ^ (prExp x)) in let _ = Rtrace.indent () in (*val _ = print ("[Rewriting " ^ (prExp x) ^ "]\n")*) (*val _ = flush_out std_out*) let (res1,_) = rewrite_front (x,env) in let res = [res1] in (*val _ = print ("[ Result " ^ (prExp res1) ^ "]\n")*) (*val _ = flush_out std_out*) let _ = Rtrace.trace "rewrite" (fun (x) -> "Result:") in let _ = Rtrace.indent () in let _ = Rtrace.trace_list "rewrite" (fun (x) -> List.map prExp res) in let _ = Rtrace.trace_list "rewrite" (fun (x) -> List.map (fun (x) -> prExp (ExpIntern.decode_exp x)) res) in let _ = (Rtrace.undent () ; Rtrace.undent ()) in let _ = Rtrace.trace "rewrite" (fun (xx) -> "end rewrite subterm: " ^ (prExp x)) in let _ = (Rtrace.indent () ; Rtrace.undent ()) in List.map (ExpIntern.intern_exp (Renv.isACorC env)) res) and rewrite2 env x = (Cache.save_good_rewrites () ; [(ExpIntern.decode_exp (List.hd (rewrite2_front env x)))]) and rewrite_front_k (x,env) kb = let _ = Rtrace.trace "rewrite" (fun (xx) -> "rewriting expression3: " ^ (prExp x)) in let _ = Rtrace.indent () in let (REF x1) = ExpIntern.intern_exp (Renv.isACorC env) x in let (res1,env) = if Cache.is_rewrite_failure (Renv.getContextList env) x1 then (REF x1,env) else (try ((REF (Cache.get_rewrite (Renv.getContextList env) x1)),env) with Cache.NoEntry -> let x = ExpIntern.decode_two_exp (REF x1) in let (r,env) = int_rewrite (x,env) kb in let (REF res) = ExpIntern.intern_exp (Renv.isACorC env) r in if x1=res then Cache.add_rewrite_failure (Renv.getContextList env) x1 else Cache.add_rewrite (Renv.getContextList env) x1 res ; ((REF res),env) ) in let _ = Rtrace.trace "rewrite" (fun (x) -> "Result:") in let _ = Rtrace.indent () in let _ = Rtrace.trace "rewrite" (fun (x) -> prExp res1) in let _ = Rtrace.trace "rewrite" (fun (x) -> prExp (ExpIntern.decode_exp res1)) in let _ = (Rtrace.undent () ; Rtrace.undent ()) in let _ = Rtrace.trace "rewrite" (fun (xx) -> "end rewrite for: " ^ (prExp x)) in let _ = (Rtrace.indent () ; Rtrace.undent ()) in (ExpIntern.intern_exp (Renv.isACorC env) res1,env) and rewrite_front (x,env) = let _ = Rtrace.trace "rewrite" (fun (xx) -> "rewriting expression1: " ^ (prExp x)) in let _ = Rtrace.indent () in let (REF x1) = ExpIntern.intern_exp (Renv.isACorC env) x in let (res1,env) = if Cache.is_rewrite_failure (Renv.getContextList env) x1 then (REF x1,env) else (try ((REF (Cache.get_rewrite (Renv.getContextList env) x1)),env) with Cache.NoEntry -> let x = ExpIntern.decode_two_exp (REF x1) in let (r,env) = int_rewrite (x,env) true in let (REF res) = ExpIntern.intern_exp (Renv.isACorC env) r in if x1=res then Cache.add_rewrite_failure (Renv.getContextList env) x1 else Cache.add_rewrite (Renv.getContextList env) x1 res ; ((REF res),env) ) in let _ = Rtrace.trace "rewrite" (fun (x) -> "Result:") in let _ = Rtrace.indent () in let _ = Rtrace.trace "rewrite" (fun (x) -> prExp res1) in let _ = Rtrace.trace "rewrite" (fun (x) -> prExp (ExpIntern.decode_exp res1)) in let _ = (Rtrace.undent () ; Rtrace.undent ()) in let _ = Rtrace.trace "rewrite" (fun (xx) -> "end rewrite for: " ^ (prExp x)) in let _ = (Rtrace.indent () ; Rtrace.undent ()) in (ExpIntern.intern_exp (Renv.isACorC env) res1,env) and rewrite_nokb_front (x,env) = let _ = Rtrace.trace "rewrite" (fun (xx) -> "rewriting expression2: " ^ (prExp x)) in let _ = Rtrace.indent () in let (REF x1) = ExpIntern.intern_exp (Renv.isACorC env) x in let (res1,env) = if Cache.is_rewrite_failure (Renv.getContextList env) x1 then (REF x1,env) else (try ((REF (Cache.get_rewrite (Renv.getContextList env) x1)),env) with Cache.NoEntry -> let x = ExpIntern.decode_two_exp (REF x1) in let (r,env) = int_rewrite (x,env) false in let (REF res) = ExpIntern.intern_exp (Renv.isACorC env) r in if x1=res then Cache.add_rewrite_failure (Renv.getContextList env) x1 else Cache.add_rewrite (Renv.getContextList env) x1 res ; ((REF res),env) ) in let _ = Rtrace.trace "rewrite" (fun (x) -> "Result:") in let _ = Rtrace.indent () in let _ = Rtrace.trace "rewrite" (fun (x) -> prExp res1) in let _ = (Rtrace.undent () ; Rtrace.undent ()) in let _ = Rtrace.trace "rewrite" (fun (xx) -> "end rewrite for: " ^ (prExp x)) in let _ = (Rtrace.indent () ; Rtrace.undent ()) in (ExpIntern.intern_exp (Renv.isACorC env) res1,env) and rewrite_nokb (x,env) = let _ = Cache.save_good_rewrites () in let (x,env) = rewrite_nokb_front (x,env) in (ExpIntern.decode_exp x,env) and rewrite (x,env) = let _ = Cache.save_good_rewrites () in let (x,env) = rewrite_front (x,env) in (Renv.flatten env (ExpIntern.decode_exp x),env) ;; let rewrite_in_context (e,c,d,env) = let e2 = Crewrite.create_rules (fun (x) -> [remove_normals x]) env (APPL (intern_unoriented_rule,[e;(APPL (intern_true,[]));c])) 0 in (*val _ = print ("d(1) = " ^ (prExp d) ^ "\n")*) let (d,_) = rewrite_front (d,e2) in val _ = print ( " ) = " ^ ( prExp d ) ^ " \n " ) let e3 = Crewrite.create_rules (fun (x) -> [remove_normals x]) e2 (APPL (intern_unoriented_rule,[e;(APPL (intern_true,[]));d])) 0 in (*val _ = print ("e(1) = " ^ (prExp e) ^ "\n")*) let (e,_) = rewrite_front (e,e3) in (*val _ = print ("e(2) = " ^ (prExp (ExpIntern.decode_exp e)) ^ "\n")*) val _ = map ( fun ( x ) - > print ( " r " ^ ( prExp ( ExpIntern.decode_exp ( REF x ) ) ) ^ " \n " ) ) ( Renv.getContextList e3 ) let e = List.hd ((Kbrewrite.kbrewrite2 rewrite2 e3 (ExpIntern.decode_exp e) [])@[e]) val _ = print ( " e(3 ) = " ^ ( prExp ( ExpIntern.decode_exp e ) ) ^ " \n " ) in e ;;
null
https://raw.githubusercontent.com/kendroe/CoqRewriter/ddf5dc2ea51105d5a2dc87c99f0d364cf2b8ebf5/plugin/src/inner.ml
ocaml
require "list.sml" ; require "exp.sml" ; require "env.sml" ; require "expint.sml" ; require "kbrewrit.sml" ; require "context.sml" ; require "derive.sml" ; require "builtin.sml" ; require "match.sml" ; require "cache.sml" ; require "crewrite.sml" ; require "rule_app.sml" ; require "rewrit-s.sml" ; open listimpl ; open EXP_INTERNimpl ; open CONTEXTimpl ; val _ = print ("[Pre: " ^ (prExp f) ^ "]\n[Post: " ^ (prExp x) ^ "]\n") val _ = print ("[Rewriting " ^ (prExp x) ^ "]\n") val _ = flush_out std_out val _ = print ("[ Result " ^ (prExp res1) ^ "]\n") val _ = flush_out std_out val _ = print ("d(1) = " ^ (prExp d) ^ "\n") val _ = print ("e(1) = " ^ (prExp e) ^ "\n") val _ = print ("e(2) = " ^ (prExp (ExpIntern.decode_exp e)) ^ "\n")
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * REWRITELIB * * inner.ml * * This file contains the code for the inner rewrite routines . * * ( C ) 2017 , * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program . If not , see < / > . * will be provided when the work is complete . * * For a commercial license , contact Roe Mobile Development , LLC at * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * REWRITELIB * * inner.ml * * This file contains the code for the inner rewrite routines. * * (C) 2017, Kenneth Roe * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see </>. * will be provided when the work is complete. * * For a commercial license, contact Roe Mobile Development, LLC at * * *****************************************************************************) require " intern.sml " ; require " trace.sml " ; require " basis.__list " ; infix 2 * | ; infix 2 < | ; infix 2 | > ; infix 2 < > ; infix 3 > < ; open Exp ;; open ENVimpl ; open Intern ;; open KBREWRITEimpl ; open DERIVEimpl ; open BUILTINimpl ; open MATCHimpl ; open TRACEimpl ; open CACHEimpl ; open CREWRITEimpl ; open RULE_APPimpl ; let replace_appl_n (APPL (f,l)) n a = (APPL (f,Mylist.replace_nth l n a)) ;; let rec rewrite_list rewrite env l = match l with | [] -> [[]] | (a::b) -> (List.map (fun (x,y) -> x::y) (List.combine (rewrite env a) (rewrite_list rewrite env b))) ;; let rec remove_normals e = match e with | (NORMAL x) -> x | (APPL (f,l)) -> (APPL (f,List.map remove_normals l)) | y -> y ;; let rec mark_vars env x = (try let (REF n) = ExpIntern.intern_exp (Renv.isACorC env) x in let res = Cache.get_mark_vars n in (REF res) with Cache.NoEntry -> let (REF n) = ExpIntern.intern_exp (Renv.isACorC env) x in let (REF res) = ExpIntern.intern_exp (Renv.isACorC env) (Rcontext.markVars (ExpIntern.decode_exp x)) in Cache.add_mark_vars n res ; (REF res) ) ;; let generate_rules r env e = match r with | 9 -> (List.filter (fun (r) -> (match (ExpIntern.decode_exp r) with | (APPL (f,[APPL (4,[]);_;c])) -> false | (APPL (f,[APPL (5,[]);_;c])) -> false | (APPL (1,[l;r;c])) -> not(l=r) | _ -> false)) (List.map remove_normals (Derive.derive env (ExpIntern.intern_exp (Renv.isACorC env) (APPL (intern_oriented_rule,[mark_vars env (remove_normals e);(APPL (intern_true,[]));(APPL (intern_true,[]))])))))) |10 -> (List.filter (fun (r) -> (match (ExpIntern.decode_exp r) with | (APPL (f,[APPL (4,[]);_;c])) -> false | (APPL (f,[APPL (5,[]);_;c])) -> false | (APPL (1,[l;r;c])) -> true | _ -> false)) (List.map remove_normals (Derive.derive env (ExpIntern.intern_exp (Renv.isACorC env) (APPL (intern_oriented_rule,[mark_vars env e;(APPL (intern_false,[]));(APPL (intern_true,[]))])))))) ;; let rec generate_rules_list f env l = match l with | [] -> [] | (a::b) -> (generate_rules f env a)::(generate_rules_list f env b) ;; let rec add_c_rules env l = match l with | [] -> env | (a::b) -> add_c_rules (Renv.addProperty env a) b ;; let rec add_context_rules env l n term = let _ = ( " Adding " ^ ( string_of_int n ) ^ " \n " ) in let l = Mylist.delete_nth l n in let _ = ( fun x - > ( List.map ( fun y - > print_string ( " Rule " ^ ( prExp ( ExpIntern.decode_exp y ) ) ^ " \n " ) ) x ) ) l in addContextRules env ( List.map ( fun ( x ) - > ( REF x ) ) ( junction_filter_rule_list env term ( List.map ( fun ( x ) - > let val REF x = ExpIntern.intern_exp ( ) x in x end ) ( foldr append [ ] l ) ) ) ) Renv.addContextRules env (List.fold_right List.append l []) ;; let rec context_rewrite_list rewrite env f rules l n = if (List.length l)=n then ((l,env),rules) else let t = List.nth l n in let (x,_) = rewrite (t,(add_context_rules env rules n t)) in let gr = if Match.equal env x t then List.nth rules n else (generate_rules f env x) in context_rewrite_list rewrite env f (Mylist.replace_nth rules n gr) (Mylist.replace_nth l n x) (n+1) ;; let rec repeat_context_rewrite_list rewrite env f rules l = let ((l2,env),new_rules) = context_rewrite_list rewrite env f rules l 0 in if l2=l then (APPL (f,l2),env) else repeat_context_rewrite_list rewrite env f new_rules l2 ;; let rec repeat_rewrite rewrite ((APPL (f,l)),env) = let rules = generate_rules_list f env l in let (r,env) = repeat_context_rewrite_list rewrite env f rules l in (Renv.flatten_top env r,env) ;; exception NoRewrite ;; let intern_exp_true = ExpIntern.intern_exp (fun (x) -> false) (parseExp "True") ;; let intern_exp_false = ExpIntern.intern_exp (fun (x) -> false) (parseExp "False") ;; let flt (e,env) = (Renv.flatten_top env e,env) ;; let kbmode = ref true ;; let rec rewriteTop (exp,env) kb = (let _ = Rtrace.trace "rewrite" (fun (x) -> "builtin " ^ (prExp exp)) in let _ = Rtrace.indent () in let exp = ExpIntern.decode_two_exp (ExpIntern.intern_exp (Renv.isACorC env) exp) in let rew = Builtin.builtin rewrite2_front env exp in let _ = ( " exp = " ^ ( prExp exp ) ^ " \n " ) in let _ = ( " builtin results " ^ ( string_of_int ( ) ) ^ " \n " ) in let _ = print_string ("builtin results " ^ (string_of_int (List.length rew)) ^ "\n") in*) let _ = Rtrace.trace_list "rewrite" (fun (x) -> List.map prExp rew) in let _ = Rtrace.undent () in let _ = Rtrace.trace "rewrite" (fun (x) -> "end builtin " ^ (prExp (List.hd (rew@[exp])))) in let (res,env,kb) = (if rew = [] || rew=[exp] then let x = (Rule_app.rewriteRule rewrite2_front env exp []) in if x=[] || x==[exp] then (if (!kbmode) && kb && (Kbrewrite.useful_subterm env exp []) then let n = Kbrewrite.kbrewrite2 rewrite2_front env (ExpIntern.decode_two_exp exp) [] in if n=[] then raise NoRewrite else (List.hd n,env,false) else raise NoRewrite) else (List.hd x,env,kb) else (List.hd rew,env,kb)) in (Renv.flatten env res,env,kb)) and rewriteTopCont orig (f,env) kb = (try let (x,env,kb) = rewriteTop (f,env) kb in if (ExpIntern.intern_exp (Renv.isACorC env) orig)=(ExpIntern.intern_exp (Renv.isACorC env) x) then (x,env) else try if kb then rewrite_front (x,env) else rewrite_nokb_front (x,env) with NoRewrite -> (x,env) with NoRewrite -> (f,env)) and int_rewrite e kb = (match e with | ((APPL (18,[c;e1;e2])),env) -> (let (x,env) = rewrite_front (ExpIntern.decode_two_exp c,env) in let res = if x=intern_exp_true then rewrite_front (ExpIntern.decode_two_exp e1,env) else if x=intern_exp_false then rewrite_front (e2,env) else let env1 = Crewrite.create_rules (fun (x) -> [remove_normals x]) env (APPL (intern_if,[x;e1;e2])) 1 in let (res1,env1b) = rewrite_front (e1,env1) in let env2 = Crewrite.create_rules (fun (x) -> [remove_normals x]) env (APPL (intern_if,[x;e1;e2])) 2 in let (res2,env2b) = rewrite_front (e2,env2) in rewriteTopCont (APPL (18,[c;e1;e2])) ((APPL (intern_if,[x;res1;res2])),env) kb in res) | ((APPL (90,[APPL (5,[]);_])),env) -> (intern_exp_true,env) | ((APPL (90,[APPL (4,[]);x])),env) -> (x,env) | ((APPL (90,[x;APPL (4,[])])),env) -> (intern_exp_true,env) | ((APPL (90,[x;APPL (5,[])])),env) -> ((APPL (17,[x])),env) | (APPL (90,[l;r]),env) -> let (l',env) = rewrite_front (l,env) in let e2 = Crewrite.create_rules (fun (x) -> [remove_normals x]) env (APPL (intern_implies,[l';r])) 1 in let (r',_) = rewrite_front (r,e2) in rewriteTopCont (APPL (intern_implies,[l;r])) (APPL (intern_implies,[l';r']),env) kb | ((APPL (9,[])),env) -> (intern_exp_true,env) | ((APPL (9,[(APPL (17,[x]))])),env) -> if (!kbmode) && kb && Kbrewrite.useful_subterm env x [] then let (x,_) = rewrite_front (x,env) in let x = List.hd ((Kbrewrite.kbrewrite2 rewrite2_front env x [])@[x]) in rewriteTopCont (APPL (9,[(APPL (17,[x]))])) (APPL (intern_not,[x]),env) kb else let (x,_) = rewrite_front (x,env) in rewriteTopCont (APPL (9,[(APPL (17,[x]))])) (APPL (intern_not,[x]),env) kb | ((APPL (9,[x])),env) -> if (!kbmode) && kb && Kbrewrite.useful_subterm env x [] then let (x,_) = rewrite_front (x,env) in let x = List.hd ((Kbrewrite.kbrewrite2 rewrite2_front env x [])@[x]) in rewriteTopCont (APPL (9,[x])) (x,env) kb else rewrite_front (x,env) | (APPL (9,l),env) -> rewriteTopCont (APPL (9,l)) (flt (repeat_rewrite rewrite_front ((APPL (intern_and,l)),env))) kb | ((APPL (10,[])),env) -> (intern_exp_false,env) | ((APPL (10,[x])),env) -> rewrite_front (ExpIntern.intern_exp (Renv.isACorC env) x,env) | (APPL (10,l),env) -> rewriteTopCont (APPL (10,l)) (flt (repeat_rewrite rewrite_front ((APPL (intern_or,l)),env))) kb | (APPL (1,[l;r;c]),env) -> let (c,env) = rewrite_front (c,env) in let e2 = Crewrite.create_rules (fun (x) -> [remove_normals x]) env (APPL (intern_oriented_rule,[l;r;c])) 0 in let _ = Rtrace.trace_list "rewrite" (fun (x) -> List.map (fun (x) -> "contadd " ^ (prExp (ExpIntern.decode_exp (REF x)))) (Renv.getContextList e2)) in let (l,_) = rewrite_front (l,e2) in let (r,_) = rewrite_front (r,e2) in rewriteTopCont (APPL (1,[l;r;c])) (APPL (intern_oriented_rule,[l;r;c]),env) kb | (APPL (2,[l;r;c]),env) -> let (c,env) = rewrite_front (c,env) in let e2 = Crewrite.create_rules (fun (x) -> [remove_normals x]) env (APPL (intern_unoriented_rule,[l;r;c])) 0 in let (l,_) = rewrite_front (l,e2) in let (r,_) = rewrite_front (r,e2) in rewriteTopCont (APPL (2,[l;r;c])) (APPL (intern_unoriented_rule,[l;r;c]),env) kb | (APPL (17,[e]),env) -> if (!kbmode) && kb && Kbrewrite.useful_subterm env e [] then let (ff,_) = rewrite_front (e,env) in let f = (APPL (17,[e])) in let f = List.hd ((Kbrewrite.kbrewrite2 rewrite2_front env f [])@[f]) in rewriteTopCont f (f,env) kb else let (e2,envs) = if kb then rewrite_sub env e 0 else rewrite_nokb_sub env e 0 in let (res,env) = rewriteTopCont (APPL (17,[e])) ((APPL (intern_not,[e2])),envs) kb in (res,env) | (APPL (71,l),env) -> rewriteTopCont (APPL (71,l)) (APPL (71,l),env) kb | (APPL (72,l),env) -> rewriteTopCont (APPL (72,l)) (APPL (72,l),env) kb | (APPL (s,l2),env) -> let (l,envs,_) = List.fold_left (fun (r,env,n) -> (fun e -> let (e,env) = (rewrite_sub env e n) in (r@[e],env,n+1) )) ([],env,0) l2 in let (res,env) = rewriteTopCont (APPL (s,l2)) ((Renv.flatten_top env (APPL (s,l))),envs) kb in if l=l2 then (Renv.flatten_top env res,env) else (res,env) | ((QUANT (v,t,e,p)),env) -> let (r_e,env) = try rewrite_front (e,env) with NoRewrite -> (e,env) in let (r_p,env) = try rewrite_front (p,env) with NoRewrite -> (p,env) in rewriteTopCont (QUANT (v,t,e,p)) ((QUANT (v,t,r_e,r_p)),env) kb | (LET (v,t,e,p),env) -> let (r_e,env) = rewrite_front (e,env) in let (r_p,env) = rewrite_front (p,env) in rewriteTopCont (LET (v,t,e,p)) (LET (v,t,r_e,r_p),env) kb | (CASE (e,t,c),env) -> let (r_e,env) = rewrite_front (e,env) in let r_c = List.map (fun (p,e) -> (p,let (e,_) = rewrite_front (e,env) in e)) c in rewriteTopCont (CASE (e,t,c)) (CASE (r_e,t,r_c),env) kb | (x,env) -> rewriteTopCont x (x,env) kb) and rewrite_sub env x n = try rewrite_front (x,env) with NoRewrite -> (x,env) and rewrite_nokb_sub env x n = rewrite_nokb_front (x,env) and rewrite2_front env x = (let _ = Rtrace.trace "rewrite" (fun (xx) -> "rewriting subterm: " ^ (prExp x)) in let _ = Rtrace.indent () in let (res1,_) = rewrite_front (x,env) in let res = [res1] in let _ = Rtrace.trace "rewrite" (fun (x) -> "Result:") in let _ = Rtrace.indent () in let _ = Rtrace.trace_list "rewrite" (fun (x) -> List.map prExp res) in let _ = Rtrace.trace_list "rewrite" (fun (x) -> List.map (fun (x) -> prExp (ExpIntern.decode_exp x)) res) in let _ = (Rtrace.undent () ; Rtrace.undent ()) in let _ = Rtrace.trace "rewrite" (fun (xx) -> "end rewrite subterm: " ^ (prExp x)) in let _ = (Rtrace.indent () ; Rtrace.undent ()) in List.map (ExpIntern.intern_exp (Renv.isACorC env)) res) and rewrite2 env x = (Cache.save_good_rewrites () ; [(ExpIntern.decode_exp (List.hd (rewrite2_front env x)))]) and rewrite_front_k (x,env) kb = let _ = Rtrace.trace "rewrite" (fun (xx) -> "rewriting expression3: " ^ (prExp x)) in let _ = Rtrace.indent () in let (REF x1) = ExpIntern.intern_exp (Renv.isACorC env) x in let (res1,env) = if Cache.is_rewrite_failure (Renv.getContextList env) x1 then (REF x1,env) else (try ((REF (Cache.get_rewrite (Renv.getContextList env) x1)),env) with Cache.NoEntry -> let x = ExpIntern.decode_two_exp (REF x1) in let (r,env) = int_rewrite (x,env) kb in let (REF res) = ExpIntern.intern_exp (Renv.isACorC env) r in if x1=res then Cache.add_rewrite_failure (Renv.getContextList env) x1 else Cache.add_rewrite (Renv.getContextList env) x1 res ; ((REF res),env) ) in let _ = Rtrace.trace "rewrite" (fun (x) -> "Result:") in let _ = Rtrace.indent () in let _ = Rtrace.trace "rewrite" (fun (x) -> prExp res1) in let _ = Rtrace.trace "rewrite" (fun (x) -> prExp (ExpIntern.decode_exp res1)) in let _ = (Rtrace.undent () ; Rtrace.undent ()) in let _ = Rtrace.trace "rewrite" (fun (xx) -> "end rewrite for: " ^ (prExp x)) in let _ = (Rtrace.indent () ; Rtrace.undent ()) in (ExpIntern.intern_exp (Renv.isACorC env) res1,env) and rewrite_front (x,env) = let _ = Rtrace.trace "rewrite" (fun (xx) -> "rewriting expression1: " ^ (prExp x)) in let _ = Rtrace.indent () in let (REF x1) = ExpIntern.intern_exp (Renv.isACorC env) x in let (res1,env) = if Cache.is_rewrite_failure (Renv.getContextList env) x1 then (REF x1,env) else (try ((REF (Cache.get_rewrite (Renv.getContextList env) x1)),env) with Cache.NoEntry -> let x = ExpIntern.decode_two_exp (REF x1) in let (r,env) = int_rewrite (x,env) true in let (REF res) = ExpIntern.intern_exp (Renv.isACorC env) r in if x1=res then Cache.add_rewrite_failure (Renv.getContextList env) x1 else Cache.add_rewrite (Renv.getContextList env) x1 res ; ((REF res),env) ) in let _ = Rtrace.trace "rewrite" (fun (x) -> "Result:") in let _ = Rtrace.indent () in let _ = Rtrace.trace "rewrite" (fun (x) -> prExp res1) in let _ = Rtrace.trace "rewrite" (fun (x) -> prExp (ExpIntern.decode_exp res1)) in let _ = (Rtrace.undent () ; Rtrace.undent ()) in let _ = Rtrace.trace "rewrite" (fun (xx) -> "end rewrite for: " ^ (prExp x)) in let _ = (Rtrace.indent () ; Rtrace.undent ()) in (ExpIntern.intern_exp (Renv.isACorC env) res1,env) and rewrite_nokb_front (x,env) = let _ = Rtrace.trace "rewrite" (fun (xx) -> "rewriting expression2: " ^ (prExp x)) in let _ = Rtrace.indent () in let (REF x1) = ExpIntern.intern_exp (Renv.isACorC env) x in let (res1,env) = if Cache.is_rewrite_failure (Renv.getContextList env) x1 then (REF x1,env) else (try ((REF (Cache.get_rewrite (Renv.getContextList env) x1)),env) with Cache.NoEntry -> let x = ExpIntern.decode_two_exp (REF x1) in let (r,env) = int_rewrite (x,env) false in let (REF res) = ExpIntern.intern_exp (Renv.isACorC env) r in if x1=res then Cache.add_rewrite_failure (Renv.getContextList env) x1 else Cache.add_rewrite (Renv.getContextList env) x1 res ; ((REF res),env) ) in let _ = Rtrace.trace "rewrite" (fun (x) -> "Result:") in let _ = Rtrace.indent () in let _ = Rtrace.trace "rewrite" (fun (x) -> prExp res1) in let _ = (Rtrace.undent () ; Rtrace.undent ()) in let _ = Rtrace.trace "rewrite" (fun (xx) -> "end rewrite for: " ^ (prExp x)) in let _ = (Rtrace.indent () ; Rtrace.undent ()) in (ExpIntern.intern_exp (Renv.isACorC env) res1,env) and rewrite_nokb (x,env) = let _ = Cache.save_good_rewrites () in let (x,env) = rewrite_nokb_front (x,env) in (ExpIntern.decode_exp x,env) and rewrite (x,env) = let _ = Cache.save_good_rewrites () in let (x,env) = rewrite_front (x,env) in (Renv.flatten env (ExpIntern.decode_exp x),env) ;; let rewrite_in_context (e,c,d,env) = let e2 = Crewrite.create_rules (fun (x) -> [remove_normals x]) env (APPL (intern_unoriented_rule,[e;(APPL (intern_true,[]));c])) 0 in let (d,_) = rewrite_front (d,e2) in val _ = print ( " ) = " ^ ( prExp d ) ^ " \n " ) let e3 = Crewrite.create_rules (fun (x) -> [remove_normals x]) e2 (APPL (intern_unoriented_rule,[e;(APPL (intern_true,[]));d])) 0 in let (e,_) = rewrite_front (e,e3) in val _ = map ( fun ( x ) - > print ( " r " ^ ( prExp ( ExpIntern.decode_exp ( REF x ) ) ) ^ " \n " ) ) ( Renv.getContextList e3 ) let e = List.hd ((Kbrewrite.kbrewrite2 rewrite2 e3 (ExpIntern.decode_exp e) [])@[e]) val _ = print ( " e(3 ) = " ^ ( prExp ( ExpIntern.decode_exp e ) ) ^ " \n " ) in e ;;
56746a47db3eb018c9960136a4c3da8dfe89a84e433a1e2d95ae1dd6326a675e
ninenines/gun
delayed_hello_h.erl
%% Feel free to use, reuse and abuse the code in this file. -module(delayed_hello_h). -export([init/2]). init(Req, Timeout) -> timer:sleep(Timeout), {ok, cowboy_req:reply(200, #{ <<"content-type">> => <<"text/plain">> }, <<"Hello world!">>, Req), Timeout}.
null
https://raw.githubusercontent.com/ninenines/gun/fe25965f3a2f1347529fec8c7afa981313378e31/test/handlers/delayed_hello_h.erl
erlang
Feel free to use, reuse and abuse the code in this file.
-module(delayed_hello_h). -export([init/2]). init(Req, Timeout) -> timer:sleep(Timeout), {ok, cowboy_req:reply(200, #{ <<"content-type">> => <<"text/plain">> }, <<"Hello world!">>, Req), Timeout}.
255e91c1e4a9a5084327ee834a2182c640468f0675ccbf7764b2ab7f81590099
takikawa/racket-ppa
schedule.rkt
#lang racket/base (require "config.rkt" "place-local.rkt" "place-object.rkt" "atomic.rkt" "host.rkt" "internal-error.rkt" "sandman.rkt" "parameter.rkt" "thread-group.rkt" "schedule-info.rkt" (submod "thread.rkt" scheduling) (submod "sync.rkt" scheduling) "system-idle-evt.rkt" "exit.rkt" "future.rkt" "custodian.rkt" (submod "custodian.rkt" scheduling) "pre-poll.rkt" "future-logging.rkt") ;; Many scheduler details are implemented in "thread.rkt", but this ;; module handles the thread selection, thread swapping, and ;; process sleeping. (provide call-in-main-thread call-in-another-main-thread set-atomic-timeout-callback! set-check-place-activity! thread-swap-count) ;; Initializes the thread system: (define (call-in-main-thread thunk) (call-in-new-main-thread (lambda () (set-place-host-roots! initial-place (host:current-place-roots)) (thunk)))) ;; Initializes the thread system in a new place: (define (call-in-another-main-thread c thunk) (make-another-initial-thread-group) (set-root-custodian! c) (init-system-idle-evt!) (init-future-place!) (init-schedule-counters!) (init-sync-place!) (call-in-new-main-thread thunk)) ;; Finish initializing the thread system within a place: (define (call-in-new-main-thread thunk) (make-initial-thread thunk) (call-with-engine-completion (lambda (done) (poll-and-select-thread! 0)))) ;; ---------------------------------------- (define-place-local recent-process-milliseconds 0) (define-place-local skipped-time-accums 0) (define-place-local thread-swap-count 0) (define (init-schedule-counters!) (set! recent-process-milliseconds 0) (set! skipped-time-accums 0) (set! thread-swap-count 0)) (define (poll-and-select-thread! leftover-ticks [pending-callbacks null]) (define callbacks (if (null? pending-callbacks) (host:poll-async-callbacks) pending-callbacks)) ;; Perform any expensive polls (such as ones that consult the OS) ;; only after ticks have been used up: (define poll-now? (leftover-ticks . <= . 0)) (host:poll-will-executors) (poll-custodian-will-executor) (when poll-now? (check-external-events)) (call-pre-poll-external-callbacks) (check-place-activity callbacks) (when (check-queued-custodian-shutdown) (when (thread-dead? root-thread) (force-exit 0))) (flush-future-log) (cond [(all-threads-poll-done?) May need to sleep (cond [(not (null? callbacks)) Need to run atomic callbacks in some thread , so make one (do-make-thread 'callbacks (lambda () (void)) #:custodian #f #:at-root? #t) (poll-and-select-thread! TICKS callbacks)] [(and (not poll-now?) (check-external-events)) ;; Retry and reset counter for checking external events (poll-and-select-thread! TICKS callbacks)] [(try-post-idle) ;; Enabled a thread that was waiting for idle (select-thread! leftover-ticks callbacks)] [else (process-sleep) ;; Retry, checking right away for external events (poll-and-select-thread! 0 callbacks)])] [else ;; Looks like some thread can work now (select-thread! (if poll-now? TICKS leftover-ticks) callbacks)])) (define (select-thread! leftover-ticks callbacks) (let loop ([g root-thread-group] [callbacks callbacks] [none-k maybe-done]) (define child (thread-group-next! g)) (cond [(not child) (none-k callbacks)] [(thread? child) (swap-in-thread child leftover-ticks callbacks)] [else (loop child callbacks (lambda (callbacks) (loop g none-k callbacks)))]))) (define (swap-in-thread t leftover-ticks callbacks) (current-thread/in-atomic t) (define e (thread-engine t)) ;; Remove `e` from the thread in `check-breaks-prefix`, in case a GC happens between here and there , because ` e ` needs to be attached to the thread for accounting purposes at a GC . (clear-sched-info! t) (current-future (thread-future t)) (set-place-current-thread! current-place t) (set! thread-swap-count (add1 thread-swap-count)) (run-callbacks-in-engine e callbacks t leftover-ticks)) (define (clear-sched-info! t) (define sched-info (thread-sched-info t)) (when sched-info (set-thread-sched-info! t #f) ;; Maybe `sched-info` wasn't used by `process-sleep`, in which ;; case the conservative assumption is that we might make progress ;; if `sched-info` waits on anything (when (schedule-info-repoll? sched-info) (thread-poll-not-done! t)))) (define (current-thread-now-running!) (set-thread-engine! (current-thread/in-atomic) 'running)) (define (swap-in-engine e t leftover-ticks) (assert-no-end-atomic-callbacks) (let loop ([e e] [prefix check-break-prefix]) (end-implicit-atomic-mode) (e TICKS prefix (lambda (e results remaining-ticks) (start-implicit-atomic-mode) (cond [(not e) ;; Thread completed (accum-cpu-time! t #t) (set-thread-future! t #f) (current-thread/in-atomic #f) (set-place-current-thread! current-place #f) (current-future #f) (unless (zero? (current-atomic)) (abort-atomic) (internal-error "terminated in atomic mode!")) (flush-end-atomic-callbacks!) (thread-dead! t) (when (eq? root-thread t) (force-exit 0)) (thread-did-work!) (poll-and-select-thread! (- leftover-ticks (- TICKS remaining-ticks)))] [else ;; Thread continues (cond [(zero? (current-atomic)) (when (thread-dead? root-thread) (force-exit 0)) (define new-leftover-ticks (- leftover-ticks (- TICKS remaining-ticks))) (accum-cpu-time! t (new-leftover-ticks . <= . 0)) (set-thread-future! t (current-future)) (current-future #f) (set-place-current-thread! current-place #f) (unless (eq? (thread-engine t) 'done) (set-thread-engine! t e)) (current-thread/in-atomic #f) (poll-and-select-thread! new-leftover-ticks)] [else ;; Swap out when the atomic region ends and at a point ;; where host-system interrupts are not disabled (i.e., ;; don't use `engine-block` instead of `engine-timeout`): (add-end-atomic-callback! engine-timeout) (loop e check-for-atomic-timeout)])]))))) (define (check-break-prefix) (current-thread-now-running!) (check-for-break) (check-for-atomic-timeout)) (define (check-for-atomic-timeout) (when atomic-timeout-callback (when (eq? atomic-timeout-level (current-atomic)) (atomic-timeout-callback #f)))) (define (maybe-done callbacks) (cond [(pair? callbacks) ;; We have callbacks to run and no thread willing ;; to run them. Make a new thread. (do-make-thread 'scheduler-make-thread void #:custodian #f) (poll-and-select-thread! 0 callbacks)] [(and (not (sandman-any-sleepers?)) (not (any-idle-waiters?))) ;; all threads done or blocked (cond [(thread-running? root-thread) ;; we shouldn't exit, because the main thread is ;; blocked, but it's not going to become unblocked; ;; sleep forever or until a signal changes things (process-sleep) (poll-and-select-thread! 0)] [else (void)])] [else ;; try again, which should lead to `process-sleep` (poll-and-select-thread! 0)])) ;; Check for threads that have been suspended until a particular time, ;; etc., as registered with the sandman (define (check-external-events) (define did? #f) (sandman-poll (lambda (t) (when t (thread-reschedule! t)) (set! did? #t))) (when did? ;; We've lost track of exactly which thread might get a different ;; poll result, so just mark them all as needing polling (thread-did-work!)) did?) ;; Run callbacks within the thread for `e`, and don't give up until ;; the callbacks are done (define (run-callbacks-in-engine e callbacks t leftover-ticks) (cond [(null? callbacks) (swap-in-engine e t leftover-ticks)] [else (define done? #f) (let loop ([e e] [callbacks callbacks]) (end-implicit-atomic-mode) (e TICKS (if (pair? callbacks) ;; run callbacks as a "prefix" callback (lambda () (current-thread-now-running!) (run-callbacks callbacks) (set! done? #t) (engine-block)) ;; still running callbacks, so no new prefix void) (lambda (e result remaining) (start-implicit-atomic-mode) (unless e (internal-error "thread ended while it should run callbacks atomically")) (if done? (swap-in-engine e t leftover-ticks) (loop e null)))))])) ;; Run foreign "async-apply" callbacks, now that we're in some thread (define (run-callbacks callbacks) (start-atomic) (for ([callback (in-list callbacks)]) (callback)) (end-atomic)) ;; ---------------------------------------- ;; Have we tried all threads since most recently making ;; progress on some thread? (define (all-threads-poll-done?) (= (hash-count poll-done-threads) num-threads-in-groups)) ;; Stop using the CPU for a while (define (process-sleep) (define ts (thread-group-all-threads root-thread-group null)) (define sleeping-exts (sandman-sleepers-external-events)) (define exts (for/fold ([exts sleeping-exts]) ([t (in-list ts)]) (define sched-info (thread-sched-info t)) (define t-exts (and sched-info (schedule-info-exts sched-info))) (sandman-merge-exts exts t-exts))) (sandman-sleep exts) ;; Maybe some thread can proceed: (thread-did-work!)) (define (try-post-idle) (and (post-idle) (begin (thread-did-work!) #t))) ;; ---------------------------------------- ;; Getting CPU time is expensive relative to a thread ;; switch, so limit precision in the case that the thread ;; did not use up its quantum. This loss of precision ;; should be ok, since `(current-process-milliseconds <thread>)` ;; is used rarely, and it makes the most sense for threads ;; that don't keep swapping themselves out. (define (accum-cpu-time! t timeout?) (cond [(not timeout?) (define n skipped-time-accums) (set! skipped-time-accums (add1 n)) (when (= n 100) (accum-cpu-time! t #t))] [else (define start recent-process-milliseconds) (define now (current-process-milliseconds)) (set! recent-process-milliseconds now) (set! skipped-time-accums 0) (set-thread-cpu-time! t (+ (thread-cpu-time t) (- now start)))])) ;; ---------------------------------------- (define-place-local atomic-timeout-callback #f) (define-place-local atomic-timeout-level #f) (define (set-atomic-timeout-callback! cb) (begin0 atomic-timeout-callback (set! atomic-timeout-level (current-atomic)) (set! atomic-timeout-callback cb))) (void (set-force-atomic-timeout-callback! (lambda () (and atomic-timeout-callback (eq? atomic-timeout-level (current-atomic)) (begin (atomic-timeout-callback #t) #t))))) ;; ---------------------------------------- (define check-place-activity void) (define (set-check-place-activity! proc) (set! check-place-activity proc))
null
https://raw.githubusercontent.com/takikawa/racket-ppa/26d6ae74a1b19258c9789b7c14c074d867a4b56b/src/thread/schedule.rkt
racket
Many scheduler details are implemented in "thread.rkt", but this module handles the thread selection, thread swapping, and process sleeping. Initializes the thread system: Initializes the thread system in a new place: Finish initializing the thread system within a place: ---------------------------------------- Perform any expensive polls (such as ones that consult the OS) only after ticks have been used up: Retry and reset counter for checking external events Enabled a thread that was waiting for idle Retry, checking right away for external events Looks like some thread can work now Remove `e` from the thread in `check-breaks-prefix`, in case Maybe `sched-info` wasn't used by `process-sleep`, in which case the conservative assumption is that we might make progress if `sched-info` waits on anything Thread completed Thread continues Swap out when the atomic region ends and at a point where host-system interrupts are not disabled (i.e., don't use `engine-block` instead of `engine-timeout`): We have callbacks to run and no thread willing to run them. Make a new thread. all threads done or blocked we shouldn't exit, because the main thread is blocked, but it's not going to become unblocked; sleep forever or until a signal changes things try again, which should lead to `process-sleep` Check for threads that have been suspended until a particular time, etc., as registered with the sandman We've lost track of exactly which thread might get a different poll result, so just mark them all as needing polling Run callbacks within the thread for `e`, and don't give up until the callbacks are done run callbacks as a "prefix" callback still running callbacks, so no new prefix Run foreign "async-apply" callbacks, now that we're in some thread ---------------------------------------- Have we tried all threads since most recently making progress on some thread? Stop using the CPU for a while Maybe some thread can proceed: ---------------------------------------- Getting CPU time is expensive relative to a thread switch, so limit precision in the case that the thread did not use up its quantum. This loss of precision should be ok, since `(current-process-milliseconds <thread>)` is used rarely, and it makes the most sense for threads that don't keep swapping themselves out. ---------------------------------------- ----------------------------------------
#lang racket/base (require "config.rkt" "place-local.rkt" "place-object.rkt" "atomic.rkt" "host.rkt" "internal-error.rkt" "sandman.rkt" "parameter.rkt" "thread-group.rkt" "schedule-info.rkt" (submod "thread.rkt" scheduling) (submod "sync.rkt" scheduling) "system-idle-evt.rkt" "exit.rkt" "future.rkt" "custodian.rkt" (submod "custodian.rkt" scheduling) "pre-poll.rkt" "future-logging.rkt") (provide call-in-main-thread call-in-another-main-thread set-atomic-timeout-callback! set-check-place-activity! thread-swap-count) (define (call-in-main-thread thunk) (call-in-new-main-thread (lambda () (set-place-host-roots! initial-place (host:current-place-roots)) (thunk)))) (define (call-in-another-main-thread c thunk) (make-another-initial-thread-group) (set-root-custodian! c) (init-system-idle-evt!) (init-future-place!) (init-schedule-counters!) (init-sync-place!) (call-in-new-main-thread thunk)) (define (call-in-new-main-thread thunk) (make-initial-thread thunk) (call-with-engine-completion (lambda (done) (poll-and-select-thread! 0)))) (define-place-local recent-process-milliseconds 0) (define-place-local skipped-time-accums 0) (define-place-local thread-swap-count 0) (define (init-schedule-counters!) (set! recent-process-milliseconds 0) (set! skipped-time-accums 0) (set! thread-swap-count 0)) (define (poll-and-select-thread! leftover-ticks [pending-callbacks null]) (define callbacks (if (null? pending-callbacks) (host:poll-async-callbacks) pending-callbacks)) (define poll-now? (leftover-ticks . <= . 0)) (host:poll-will-executors) (poll-custodian-will-executor) (when poll-now? (check-external-events)) (call-pre-poll-external-callbacks) (check-place-activity callbacks) (when (check-queued-custodian-shutdown) (when (thread-dead? root-thread) (force-exit 0))) (flush-future-log) (cond [(all-threads-poll-done?) May need to sleep (cond [(not (null? callbacks)) Need to run atomic callbacks in some thread , so make one (do-make-thread 'callbacks (lambda () (void)) #:custodian #f #:at-root? #t) (poll-and-select-thread! TICKS callbacks)] [(and (not poll-now?) (check-external-events)) (poll-and-select-thread! TICKS callbacks)] [(try-post-idle) (select-thread! leftover-ticks callbacks)] [else (process-sleep) (poll-and-select-thread! 0 callbacks)])] [else (select-thread! (if poll-now? TICKS leftover-ticks) callbacks)])) (define (select-thread! leftover-ticks callbacks) (let loop ([g root-thread-group] [callbacks callbacks] [none-k maybe-done]) (define child (thread-group-next! g)) (cond [(not child) (none-k callbacks)] [(thread? child) (swap-in-thread child leftover-ticks callbacks)] [else (loop child callbacks (lambda (callbacks) (loop g none-k callbacks)))]))) (define (swap-in-thread t leftover-ticks callbacks) (current-thread/in-atomic t) (define e (thread-engine t)) a GC happens between here and there , because ` e ` needs to be attached to the thread for accounting purposes at a GC . (clear-sched-info! t) (current-future (thread-future t)) (set-place-current-thread! current-place t) (set! thread-swap-count (add1 thread-swap-count)) (run-callbacks-in-engine e callbacks t leftover-ticks)) (define (clear-sched-info! t) (define sched-info (thread-sched-info t)) (when sched-info (set-thread-sched-info! t #f) (when (schedule-info-repoll? sched-info) (thread-poll-not-done! t)))) (define (current-thread-now-running!) (set-thread-engine! (current-thread/in-atomic) 'running)) (define (swap-in-engine e t leftover-ticks) (assert-no-end-atomic-callbacks) (let loop ([e e] [prefix check-break-prefix]) (end-implicit-atomic-mode) (e TICKS prefix (lambda (e results remaining-ticks) (start-implicit-atomic-mode) (cond [(not e) (accum-cpu-time! t #t) (set-thread-future! t #f) (current-thread/in-atomic #f) (set-place-current-thread! current-place #f) (current-future #f) (unless (zero? (current-atomic)) (abort-atomic) (internal-error "terminated in atomic mode!")) (flush-end-atomic-callbacks!) (thread-dead! t) (when (eq? root-thread t) (force-exit 0)) (thread-did-work!) (poll-and-select-thread! (- leftover-ticks (- TICKS remaining-ticks)))] [else (cond [(zero? (current-atomic)) (when (thread-dead? root-thread) (force-exit 0)) (define new-leftover-ticks (- leftover-ticks (- TICKS remaining-ticks))) (accum-cpu-time! t (new-leftover-ticks . <= . 0)) (set-thread-future! t (current-future)) (current-future #f) (set-place-current-thread! current-place #f) (unless (eq? (thread-engine t) 'done) (set-thread-engine! t e)) (current-thread/in-atomic #f) (poll-and-select-thread! new-leftover-ticks)] [else (add-end-atomic-callback! engine-timeout) (loop e check-for-atomic-timeout)])]))))) (define (check-break-prefix) (current-thread-now-running!) (check-for-break) (check-for-atomic-timeout)) (define (check-for-atomic-timeout) (when atomic-timeout-callback (when (eq? atomic-timeout-level (current-atomic)) (atomic-timeout-callback #f)))) (define (maybe-done callbacks) (cond [(pair? callbacks) (do-make-thread 'scheduler-make-thread void #:custodian #f) (poll-and-select-thread! 0 callbacks)] [(and (not (sandman-any-sleepers?)) (not (any-idle-waiters?))) (cond [(thread-running? root-thread) (process-sleep) (poll-and-select-thread! 0)] [else (void)])] [else (poll-and-select-thread! 0)])) (define (check-external-events) (define did? #f) (sandman-poll (lambda (t) (when t (thread-reschedule! t)) (set! did? #t))) (when did? (thread-did-work!)) did?) (define (run-callbacks-in-engine e callbacks t leftover-ticks) (cond [(null? callbacks) (swap-in-engine e t leftover-ticks)] [else (define done? #f) (let loop ([e e] [callbacks callbacks]) (end-implicit-atomic-mode) (e TICKS (if (pair? callbacks) (lambda () (current-thread-now-running!) (run-callbacks callbacks) (set! done? #t) (engine-block)) void) (lambda (e result remaining) (start-implicit-atomic-mode) (unless e (internal-error "thread ended while it should run callbacks atomically")) (if done? (swap-in-engine e t leftover-ticks) (loop e null)))))])) (define (run-callbacks callbacks) (start-atomic) (for ([callback (in-list callbacks)]) (callback)) (end-atomic)) (define (all-threads-poll-done?) (= (hash-count poll-done-threads) num-threads-in-groups)) (define (process-sleep) (define ts (thread-group-all-threads root-thread-group null)) (define sleeping-exts (sandman-sleepers-external-events)) (define exts (for/fold ([exts sleeping-exts]) ([t (in-list ts)]) (define sched-info (thread-sched-info t)) (define t-exts (and sched-info (schedule-info-exts sched-info))) (sandman-merge-exts exts t-exts))) (sandman-sleep exts) (thread-did-work!)) (define (try-post-idle) (and (post-idle) (begin (thread-did-work!) #t))) (define (accum-cpu-time! t timeout?) (cond [(not timeout?) (define n skipped-time-accums) (set! skipped-time-accums (add1 n)) (when (= n 100) (accum-cpu-time! t #t))] [else (define start recent-process-milliseconds) (define now (current-process-milliseconds)) (set! recent-process-milliseconds now) (set! skipped-time-accums 0) (set-thread-cpu-time! t (+ (thread-cpu-time t) (- now start)))])) (define-place-local atomic-timeout-callback #f) (define-place-local atomic-timeout-level #f) (define (set-atomic-timeout-callback! cb) (begin0 atomic-timeout-callback (set! atomic-timeout-level (current-atomic)) (set! atomic-timeout-callback cb))) (void (set-force-atomic-timeout-callback! (lambda () (and atomic-timeout-callback (eq? atomic-timeout-level (current-atomic)) (begin (atomic-timeout-callback #t) #t))))) (define check-place-activity void) (define (set-check-place-activity! proc) (set! check-place-activity proc))
722f71ece11ee42fa07f669f77ac0c2cd028eafc77be3cb490f2c42e4d1675a4
knupfer/type-of-html
Aria.hs
# OPTIONS_GHC -fno - warn - unticked - promoted - constructors # # LANGUAGE TypeFamilies # {-# LANGUAGE DataKinds #-} module Html.Aria ( module Html.Aria , module Html.Type ) where import Html.Type [ 2020 - 11 - 03 ] ARIA /#states_and_properties newtype instance Attribute "role" True v = RoleA v 6.7 Definitios of States and Properties ( all aria- * attributes ) newtype instance Attribute "aria-activedescendant" True v = AriaActivedescendantA v newtype instance Attribute "aria-atomic" True v = AriaAtomicA v newtype instance Attribute "aria-autocomplete" True v = AriaAutocompleteA v newtype instance Attribute "aria-braillelable" True v = AriaBraillelableA v newtype instance Attribute "aria-brailleroledescription" True v = AriaBrailleroledescriptionA v newtype instance Attribute "aria-busy" True v = AriaBusyA v newtype instance Attribute "aria-checked" True v = AriaCheckedA v newtype instance Attribute "aria-colcount" True v = AriaColcountA v newtype instance Attribute "aria-colindex" True v = AriaColindexA v newtype instance Attribute "aria-colindextext" True v = AriaColindextextA v newtype instance Attribute "aria-colspan" True v = AriaColspanA v newtype instance Attribute "aria-controls" True v = AriaControlsA v newtype instance Attribute "aria-current" True v = AriaCurrentA v newtype instance Attribute "aria-describedby" True v = AriaDescribedbyA v newtype instance Attribute "aria-description" True v = AriaDescriptionA v newtype instance Attribute "aria-details" True v = AriaDetailsA v newtype instance Attribute "aria-disabled" True v = AriaDisabledA v newtype instance Attribute "aria-dropeffect" True v = AriaDropeffectA v newtype instance Attribute "aria-errormessage" True v = AriaErrormessageA v newtype instance Attribute "aria-expanded" True v = AriaExpandedA v newtype instance Attribute "aria-flowto" True v = AriaFlowtoA v newtype instance Attribute "aria-grabbed" True v = AriaGrabbedA v newtype instance Attribute "aria-haspopup" True v = AriaHaspopupA v newtype instance Attribute "aria-hidden" True v = AriaHiddenA v newtype instance Attribute "aria-invalid" True v = AriaInvalidA v newtype instance Attribute "aria-keyshortcuts" True v = AriaKeyshortcutsA v newtype instance Attribute "aria-label" True v = AriaLabelA v newtype instance Attribute "aria-labelledBy" True v = AriaLabelledByA v newtype instance Attribute "aria-level" True v = AriaLevelA v newtype instance Attribute "aria-live" True v = AriaLiveA v newtype instance Attribute "aria-modal" True v = AriaModalA v newtype instance Attribute "aria-multiline" True v = AriaMultilineA v newtype instance Attribute "aria-multiselectable" True v = AriaMultiselectableA v newtype instance Attribute "aria-orientation" True v = AriaOrientationA v newtype instance Attribute "aria-owns" True v = AriaOwnsA v newtype instance Attribute "aria-placeholder" True v = AriaPlaceholderA v newtype instance Attribute "aria-posinset" True v = AriaPosinsetA v newtype instance Attribute "aria-pressed" True v = AriaPressedA v newtype instance Attribute "aria-readonly" True v = AriaReadonlyA v newtype instance Attribute "aria-relevant" True v = AriaRelevantA v newtype instance Attribute "aria-required" True v = AriaRequiredA v newtype instance Attribute "aria-roledescription" True v = AriaRoledescriptionA v newtype instance Attribute "aria-rowcount" True v = AriaRowcountA v newtype instance Attribute "aria-rowindex" True v = AriaRowindexA v newtype instance Attribute "aria-rowindextext" True v = AriaRowindextextA v newtype instance Attribute "aria-rowspan" True v = AriaRowspanA v newtype instance Attribute "aria-selected" True v = AriaSelectedA v newtype instance Attribute "aria-setsize" True v = AriaSetsizeA v newtype instance Attribute "aria-sort" True v = AriaSortA v newtype instance Attribute "aria-valuemax" True v = AriaValuemaxA v newtype instance Attribute "aria-valuemin" True v = AriaValueminA v newtype instance Attribute "aria-valuenow" True v = AriaValuenowA v newtype instance Attribute "aria-valuetext" True v = AriaValuetextA v
null
https://raw.githubusercontent.com/knupfer/type-of-html/981e2c2c4f90e57a55e00e18db6f6c0623292851/src/Html/Aria.hs
haskell
# LANGUAGE DataKinds #
# OPTIONS_GHC -fno - warn - unticked - promoted - constructors # # LANGUAGE TypeFamilies # module Html.Aria ( module Html.Aria , module Html.Type ) where import Html.Type [ 2020 - 11 - 03 ] ARIA /#states_and_properties newtype instance Attribute "role" True v = RoleA v 6.7 Definitios of States and Properties ( all aria- * attributes ) newtype instance Attribute "aria-activedescendant" True v = AriaActivedescendantA v newtype instance Attribute "aria-atomic" True v = AriaAtomicA v newtype instance Attribute "aria-autocomplete" True v = AriaAutocompleteA v newtype instance Attribute "aria-braillelable" True v = AriaBraillelableA v newtype instance Attribute "aria-brailleroledescription" True v = AriaBrailleroledescriptionA v newtype instance Attribute "aria-busy" True v = AriaBusyA v newtype instance Attribute "aria-checked" True v = AriaCheckedA v newtype instance Attribute "aria-colcount" True v = AriaColcountA v newtype instance Attribute "aria-colindex" True v = AriaColindexA v newtype instance Attribute "aria-colindextext" True v = AriaColindextextA v newtype instance Attribute "aria-colspan" True v = AriaColspanA v newtype instance Attribute "aria-controls" True v = AriaControlsA v newtype instance Attribute "aria-current" True v = AriaCurrentA v newtype instance Attribute "aria-describedby" True v = AriaDescribedbyA v newtype instance Attribute "aria-description" True v = AriaDescriptionA v newtype instance Attribute "aria-details" True v = AriaDetailsA v newtype instance Attribute "aria-disabled" True v = AriaDisabledA v newtype instance Attribute "aria-dropeffect" True v = AriaDropeffectA v newtype instance Attribute "aria-errormessage" True v = AriaErrormessageA v newtype instance Attribute "aria-expanded" True v = AriaExpandedA v newtype instance Attribute "aria-flowto" True v = AriaFlowtoA v newtype instance Attribute "aria-grabbed" True v = AriaGrabbedA v newtype instance Attribute "aria-haspopup" True v = AriaHaspopupA v newtype instance Attribute "aria-hidden" True v = AriaHiddenA v newtype instance Attribute "aria-invalid" True v = AriaInvalidA v newtype instance Attribute "aria-keyshortcuts" True v = AriaKeyshortcutsA v newtype instance Attribute "aria-label" True v = AriaLabelA v newtype instance Attribute "aria-labelledBy" True v = AriaLabelledByA v newtype instance Attribute "aria-level" True v = AriaLevelA v newtype instance Attribute "aria-live" True v = AriaLiveA v newtype instance Attribute "aria-modal" True v = AriaModalA v newtype instance Attribute "aria-multiline" True v = AriaMultilineA v newtype instance Attribute "aria-multiselectable" True v = AriaMultiselectableA v newtype instance Attribute "aria-orientation" True v = AriaOrientationA v newtype instance Attribute "aria-owns" True v = AriaOwnsA v newtype instance Attribute "aria-placeholder" True v = AriaPlaceholderA v newtype instance Attribute "aria-posinset" True v = AriaPosinsetA v newtype instance Attribute "aria-pressed" True v = AriaPressedA v newtype instance Attribute "aria-readonly" True v = AriaReadonlyA v newtype instance Attribute "aria-relevant" True v = AriaRelevantA v newtype instance Attribute "aria-required" True v = AriaRequiredA v newtype instance Attribute "aria-roledescription" True v = AriaRoledescriptionA v newtype instance Attribute "aria-rowcount" True v = AriaRowcountA v newtype instance Attribute "aria-rowindex" True v = AriaRowindexA v newtype instance Attribute "aria-rowindextext" True v = AriaRowindextextA v newtype instance Attribute "aria-rowspan" True v = AriaRowspanA v newtype instance Attribute "aria-selected" True v = AriaSelectedA v newtype instance Attribute "aria-setsize" True v = AriaSetsizeA v newtype instance Attribute "aria-sort" True v = AriaSortA v newtype instance Attribute "aria-valuemax" True v = AriaValuemaxA v newtype instance Attribute "aria-valuemin" True v = AriaValueminA v newtype instance Attribute "aria-valuenow" True v = AriaValuenowA v newtype instance Attribute "aria-valuetext" True v = AriaValuetextA v
7df3d99e47b56efef06f1f251e75dae56d5dac1cdae825e6e995b9322c4efdb8
GlideAngle/flare-timing
Sample.hs
module Flight.Zone.Cylinder.Sample ( TrueCourse(..) , Samples(..) , Tolerance(..) , ZonePoint(..) , SampleParams(..) , fromRationalZonePoint ) where import Data.UnitsOfMeasure (u, fromRational', toRational') import Data.UnitsOfMeasure.Internal (Quantity(..)) import Flight.LatLng (LatLng(..), QLat, QLng) import Flight.Zone ( Zone(..) , Bearing(..) , fromRationalRadius , fromRationalZone , fromRationalLatLng ) import Flight.Units (showRadian) import Flight.Zone.Radius (QRadius) import Flight.Zone.Bearing (QBearing) newtype TrueCourse a = TrueCourse (Quantity a [u| rad |]) deriving (Eq, Ord) instance Real a => Show (TrueCourse a) where show (TrueCourse tc) = "tc = " ++ showRadian (toRational' tc) instance Num a => Num (TrueCourse a) where (+) (TrueCourse (MkQuantity a)) (TrueCourse (MkQuantity b)) = TrueCourse (MkQuantity $ a + b) (*) (TrueCourse (MkQuantity a)) (TrueCourse (MkQuantity b)) = TrueCourse (MkQuantity $ a * b) negate (TrueCourse (MkQuantity tc)) = TrueCourse (MkQuantity $ negate tc) abs (TrueCourse (MkQuantity tc)) = TrueCourse (MkQuantity $ abs tc) signum (TrueCourse (MkQuantity tc)) = TrueCourse (MkQuantity $ signum tc) fromInteger x = TrueCourse (MkQuantity $ fromInteger x) instance Fractional a => Fractional (TrueCourse a) where fromRational tc = TrueCourse (MkQuantity $ fromRational tc) recip (TrueCourse (MkQuantity x)) = TrueCourse (MkQuantity $ recip x) newtype Samples = Samples { unSamples :: Int } deriving (Eq, Ord, Show) newtype Tolerance a = Tolerance { unTolerance :: a } deriving (Eq, Ord, Show) data ZonePoint a = ZonePoint { sourceZone :: Zone a -- ^ The zone for which the point is on the edge. , point :: LatLng a [u| rad |] -- ^ A point on the edge of this zone. , radial :: QBearing a [u| rad |] -- ^ The point's bearing from the origin. , orbit :: QRadius a [u| m |] -- ^ The point's distance from the origin. } deriving Eq deriving instance ( Show a , Real a , Fractional a , Show (QLat a [u| rad |]) , Show (QLng a [u| rad |]) ) => Show (ZonePoint a) fromRationalZonePoint :: (Eq a, Ord a, Fractional a) => ZonePoint Rational -> ZonePoint a fromRationalZonePoint ZonePoint{..} = ZonePoint { sourceZone = fromRationalZone sourceZone , point = fromRationalLatLng point , radial = let Bearing b = radial in Bearing $ fromRational' b , orbit = fromRationalRadius orbit } data SampleParams a = SampleParams { spSamples :: [Samples] -- ^ How many samples at each iteration? , spTolerance :: Tolerance a -- ^ What is the acceptable tolerance? }
null
https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/zone/library/Flight/Zone/Cylinder/Sample.hs
haskell
^ The zone for which the point is on the edge. ^ A point on the edge of this zone. ^ The point's bearing from the origin. ^ The point's distance from the origin. ^ How many samples at each iteration? ^ What is the acceptable tolerance?
module Flight.Zone.Cylinder.Sample ( TrueCourse(..) , Samples(..) , Tolerance(..) , ZonePoint(..) , SampleParams(..) , fromRationalZonePoint ) where import Data.UnitsOfMeasure (u, fromRational', toRational') import Data.UnitsOfMeasure.Internal (Quantity(..)) import Flight.LatLng (LatLng(..), QLat, QLng) import Flight.Zone ( Zone(..) , Bearing(..) , fromRationalRadius , fromRationalZone , fromRationalLatLng ) import Flight.Units (showRadian) import Flight.Zone.Radius (QRadius) import Flight.Zone.Bearing (QBearing) newtype TrueCourse a = TrueCourse (Quantity a [u| rad |]) deriving (Eq, Ord) instance Real a => Show (TrueCourse a) where show (TrueCourse tc) = "tc = " ++ showRadian (toRational' tc) instance Num a => Num (TrueCourse a) where (+) (TrueCourse (MkQuantity a)) (TrueCourse (MkQuantity b)) = TrueCourse (MkQuantity $ a + b) (*) (TrueCourse (MkQuantity a)) (TrueCourse (MkQuantity b)) = TrueCourse (MkQuantity $ a * b) negate (TrueCourse (MkQuantity tc)) = TrueCourse (MkQuantity $ negate tc) abs (TrueCourse (MkQuantity tc)) = TrueCourse (MkQuantity $ abs tc) signum (TrueCourse (MkQuantity tc)) = TrueCourse (MkQuantity $ signum tc) fromInteger x = TrueCourse (MkQuantity $ fromInteger x) instance Fractional a => Fractional (TrueCourse a) where fromRational tc = TrueCourse (MkQuantity $ fromRational tc) recip (TrueCourse (MkQuantity x)) = TrueCourse (MkQuantity $ recip x) newtype Samples = Samples { unSamples :: Int } deriving (Eq, Ord, Show) newtype Tolerance a = Tolerance { unTolerance :: a } deriving (Eq, Ord, Show) data ZonePoint a = ZonePoint { sourceZone :: Zone a , point :: LatLng a [u| rad |] , radial :: QBearing a [u| rad |] , orbit :: QRadius a [u| m |] } deriving Eq deriving instance ( Show a , Real a , Fractional a , Show (QLat a [u| rad |]) , Show (QLng a [u| rad |]) ) => Show (ZonePoint a) fromRationalZonePoint :: (Eq a, Ord a, Fractional a) => ZonePoint Rational -> ZonePoint a fromRationalZonePoint ZonePoint{..} = ZonePoint { sourceZone = fromRationalZone sourceZone , point = fromRationalLatLng point , radial = let Bearing b = radial in Bearing $ fromRational' b , orbit = fromRationalRadius orbit } data SampleParams a = SampleParams { spSamples :: [Samples] , spTolerance :: Tolerance a }
fc9b393823b0162d71acb3bb80cbad2c1949977919f6bbaef95c2974652e7e23
aartaka/nyxt-config
ace.lisp
(in-package #:nyxt-user) This is a configuration for the Ace editor Nyxt integration ( -engineer/nx-ace ) . (define-configuration nx-ace:ace-mode ((nx-ace:extensions (mapcar (lambda (name) (quri:merge-uris (quri:uri name) (quri:uri "/"))) '("keybinding-emacs.min.js" ;; Themes "theme-twilight.min.js" "theme-github.min.js" ;; Language modes "mode-c_cpp.min.js" "mode-asciidoc.min.js" "mode-clojure.min.js" "mode-csharp.min.js" "mode-css.min.js" "mode-diff.min.js" "mode-dot.min.js" "mode-forth.min.js" "mode-fsharp.min.js" "mode-gitignore.min.js" "mode-glsl.min.js" "mode-golang.min.js" "mode-haskell.min.js" "mode-html.min.js" "mode-ini.min.js" "mode-java.min.js" "mode-javascript.min.js" "mode-json.min.js" "mode-jsx.min.js" "mode-julia.min.js" "mode-kotlin.min.js" "mode-latex.min.js" "mode-lisp.min.js" "mode-lua.min.js" "mode-makefile.min.js" "mode-markdown.min.js" "mode-mediawiki.min.js" "mode-nix.min.js" "mode-objectivec.min.js" "mode-perl.min.js" "mode-plain_text.min.js" "mode-python.min.js" "mode-r.min.js" "mode-robot.min.js" "mode-ruby.min.js" "mode-rust.min.js" "mode-scala.min.js" "mode-scheme.min.js" "mode-sh.min.js" "mode-snippets.min.js" "mode-sql.min.js" "mode-svg.min.js" "mode-tex.min.js" "mode-text.min.js" "mode-tsx.min.js" "mode-typescript.min.js" "mode-xml.min.js" "mode-yaml.min.js" ;; Snippets "snippets/c_cpp.min.js" "snippets/css.min.js" "snippets/html.min.js" "snippets/javascript.min.js" "snippets/json.min.js" "snippets/latex.min.js" "snippets/lisp.min.js" "snippets/makefile.min.js" "snippets/markdown.min.js" "snippets/plain_text.min.js" "snippets/python.min.js" "snippets/scheme.min.js" "snippets/snippets.min.js" "snippets/tex.min.js" "snippets/text.min.js" "snippets/yaml.min.js" Language Workers "worker-base.min.js" "worker-css.min.js" "worker-html.min.js" "worker-javascript.min.js" "worker-json.min.js" "worker-xml.min.js" "worker-yaml.min.js" ;; Extensions "ext-language_tools.min.js" "ext-emmet.min.js" "ext-keybinding_menu.min.js" "ext-modelist.min.js" "ext-searchbox.min.js" "ext-settings_menu.min.js" "ext-themelist.min.js" "ext-beautify.min.js" "ext-prompt.min.js" "ext-split.min.js" "ext-whitespace.min.js" "ext-statusbar.min.js"))))) (define-configuration nx-ace:ace-mode ((nx-ace::theme "ace/theme/twilight") (nx-ace::keybindings "ace/keyboard/emacs"))) (define-configuration nx-ace:ace-mode ((nx-ace:epilogue (str:concat (ps:ps (flet ((req (ext) (ps:chain ace (require ext))) (bind (key command) (ps:chain editor commands (bind-key key command)))) (req "ace/ext/searchbox") (req "ace/ext/split") (req "ace/ext/themelist") (req "ace/ext/emmet") (req "ace/ext/language_tools") (req "ace/worker/javascript") (ps:chain editor (set-option "fontSize" 18)) (ps:chain editor (set-option "enableBasicAutocompletion" t)) (ps:chain editor (set-option "enableSnippets" t)) (ps:chain editor session (set-mode (ps:chain (req "ace/ext/modelist") (get-mode-for-path (ps:@ window location href)) mode))) (bind "Shift-space" "setMark") (bind "Ctrl-\\" "toggleFoldWidget") (bind "Ctrl-c ;" "toggleComment") (bind "Ctrl-Alt-b" "jumptomatching") (bind "Ctrl-Alt-f" "jumptomatching") (bind "Alt-space" "expandToMatching") (bind "Alt-%" "replace") (req "ace/ext/split") (ps:chain (req "ace/ext/settings_menu") (init editor)) (ps:chain (req "ace/ext/keybinding_menu") (init editor)) (bind "Ctrl-h m" (lambda (editor) (ps:chain editor (show-keyboard-shortcuts)))) (bind "C-i" "indent") (ps:chain editor commands (add-command (ps:chain ace (require "ace/ext/beautify") commands 0))))))))) (define-configuration nx-ace:ace-mode ((style (str:concat %slot-value% (theme:themed-css (theme *browser*) #+nyxt-3-pre-release-1 ("#kbshortcutmenu" :background-color theme:background :color theme:on-background) #+(and nyxt-3 (not nyxt-3-pre-release-1)) `("#kbshortcutmenu" :background-color ,theme:background :color ,theme:on-background)))) (nx-ace::keybindings "ace/keyboard/emacs"))) (define-configuration nyxt/editor-mode::editor-buffer ((default-modes `(nx-ace:ace-mode ,@%slot-value%))))
null
https://raw.githubusercontent.com/aartaka/nyxt-config/3c94673a0ca3ccb449879c5a2a9814d81ed55f0c/ace.lisp
lisp
Themes Language modes Snippets Extensions
(in-package #:nyxt-user) This is a configuration for the Ace editor Nyxt integration ( -engineer/nx-ace ) . (define-configuration nx-ace:ace-mode ((nx-ace:extensions (mapcar (lambda (name) (quri:merge-uris (quri:uri name) (quri:uri "/"))) '("keybinding-emacs.min.js" "theme-twilight.min.js" "theme-github.min.js" "mode-c_cpp.min.js" "mode-asciidoc.min.js" "mode-clojure.min.js" "mode-csharp.min.js" "mode-css.min.js" "mode-diff.min.js" "mode-dot.min.js" "mode-forth.min.js" "mode-fsharp.min.js" "mode-gitignore.min.js" "mode-glsl.min.js" "mode-golang.min.js" "mode-haskell.min.js" "mode-html.min.js" "mode-ini.min.js" "mode-java.min.js" "mode-javascript.min.js" "mode-json.min.js" "mode-jsx.min.js" "mode-julia.min.js" "mode-kotlin.min.js" "mode-latex.min.js" "mode-lisp.min.js" "mode-lua.min.js" "mode-makefile.min.js" "mode-markdown.min.js" "mode-mediawiki.min.js" "mode-nix.min.js" "mode-objectivec.min.js" "mode-perl.min.js" "mode-plain_text.min.js" "mode-python.min.js" "mode-r.min.js" "mode-robot.min.js" "mode-ruby.min.js" "mode-rust.min.js" "mode-scala.min.js" "mode-scheme.min.js" "mode-sh.min.js" "mode-snippets.min.js" "mode-sql.min.js" "mode-svg.min.js" "mode-tex.min.js" "mode-text.min.js" "mode-tsx.min.js" "mode-typescript.min.js" "mode-xml.min.js" "mode-yaml.min.js" "snippets/c_cpp.min.js" "snippets/css.min.js" "snippets/html.min.js" "snippets/javascript.min.js" "snippets/json.min.js" "snippets/latex.min.js" "snippets/lisp.min.js" "snippets/makefile.min.js" "snippets/markdown.min.js" "snippets/plain_text.min.js" "snippets/python.min.js" "snippets/scheme.min.js" "snippets/snippets.min.js" "snippets/tex.min.js" "snippets/text.min.js" "snippets/yaml.min.js" Language Workers "worker-base.min.js" "worker-css.min.js" "worker-html.min.js" "worker-javascript.min.js" "worker-json.min.js" "worker-xml.min.js" "worker-yaml.min.js" "ext-language_tools.min.js" "ext-emmet.min.js" "ext-keybinding_menu.min.js" "ext-modelist.min.js" "ext-searchbox.min.js" "ext-settings_menu.min.js" "ext-themelist.min.js" "ext-beautify.min.js" "ext-prompt.min.js" "ext-split.min.js" "ext-whitespace.min.js" "ext-statusbar.min.js"))))) (define-configuration nx-ace:ace-mode ((nx-ace::theme "ace/theme/twilight") (nx-ace::keybindings "ace/keyboard/emacs"))) (define-configuration nx-ace:ace-mode ((nx-ace:epilogue (str:concat (ps:ps (flet ((req (ext) (ps:chain ace (require ext))) (bind (key command) (ps:chain editor commands (bind-key key command)))) (req "ace/ext/searchbox") (req "ace/ext/split") (req "ace/ext/themelist") (req "ace/ext/emmet") (req "ace/ext/language_tools") (req "ace/worker/javascript") (ps:chain editor (set-option "fontSize" 18)) (ps:chain editor (set-option "enableBasicAutocompletion" t)) (ps:chain editor (set-option "enableSnippets" t)) (ps:chain editor session (set-mode (ps:chain (req "ace/ext/modelist") (get-mode-for-path (ps:@ window location href)) mode))) (bind "Shift-space" "setMark") (bind "Ctrl-\\" "toggleFoldWidget") (bind "Ctrl-c ;" "toggleComment") (bind "Ctrl-Alt-b" "jumptomatching") (bind "Ctrl-Alt-f" "jumptomatching") (bind "Alt-space" "expandToMatching") (bind "Alt-%" "replace") (req "ace/ext/split") (ps:chain (req "ace/ext/settings_menu") (init editor)) (ps:chain (req "ace/ext/keybinding_menu") (init editor)) (bind "Ctrl-h m" (lambda (editor) (ps:chain editor (show-keyboard-shortcuts)))) (bind "C-i" "indent") (ps:chain editor commands (add-command (ps:chain ace (require "ace/ext/beautify") commands 0))))))))) (define-configuration nx-ace:ace-mode ((style (str:concat %slot-value% (theme:themed-css (theme *browser*) #+nyxt-3-pre-release-1 ("#kbshortcutmenu" :background-color theme:background :color theme:on-background) #+(and nyxt-3 (not nyxt-3-pre-release-1)) `("#kbshortcutmenu" :background-color ,theme:background :color ,theme:on-background)))) (nx-ace::keybindings "ace/keyboard/emacs"))) (define-configuration nyxt/editor-mode::editor-buffer ((default-modes `(nx-ace:ace-mode ,@%slot-value%))))
4bf62cdcbd4189e90a0f2bcabb430868dc4fc26fc90cdbe83bb47a704f1e7046
cyverse-archive/DiscoveryEnvironmentBackend
query.clj
(ns notification-agent.query (:use [notification-agent.common] [notification-agent.messages :only [reformat-message]] [clojure.string :only [blank? lower-case upper-case]] [slingshot.slingshot :only [throw+]]) (:require [cheshire.core :as cheshire] [clojure.string :as string] [clojure.tools.logging :as log] [notification-agent.db :as db])) (defn- reformat "Reformats a message corresponding to a notification that was retrieved from the database." [{:keys [uuid message seen deleted]}] (reformat-message (upper-case (str uuid)) (cheshire/decode message true) :seen seen :deleted deleted)) (defn- count-messages* "Counts the number of matching messages. The user messages are filtered with the provided query." [user user-query] (let [user-total (db/count-matching-messages user user-query) sys-total (db/count-active-system-notifications user) new-sys-total (db/count-new-system-notifications user) unseen-sys-total (db/count-unseen-system-notifications user)] {:user-total user-total :system-total sys-total :system-total-new new-sys-total :system-total-unseen unseen-sys-total})) (defn- get-messages* "Retrieves notification messages." [user query] (let [body {:total (str (db/count-matching-messages user query)) :messages (map reformat (db/find-matching-messages user query)) :system-messages (db/get-active-system-notifications user)}] body)) (defn- required-string "Extracts a required string argument from the query-string map." [k m] (let [v (m k)] (when (blank? v) (throw+ {:type :clojure-commons.exception/illegal-argument :code ::missing-or-empty-param :param (name k)})) v)) (defn- optional-long "Extracts an optional long argument from the query-string map, using a default value if the argument wasn't provided." [k m d] (let [v (k m)] (if-not (nil? v) (string->long v ::invalid-long-integer-param {:param (name k) :value v}) d))) (defn- optional-boolean "Extracts an optional Boolean argument from the query-string map." ([k m] (optional-boolean k m nil)) ([k m d] (let [v (k m)] (if (nil? v) d (Boolean/valueOf v))))) (defn- as-keyword "Converts a string to a lower-case keyword." [s] (keyword (lower-case s))) (defn- mangle-filter "Converts a filter to lower case with underscores replacing spaces." [filt] (when-not (nil? filt) (string/lower-case (string/replace filt #" " "_")))) (defn- get-seen-flag "Gets the seen flag from the query parameters." [query-params] (let [seen (optional-boolean :seen query-params) filt (mangle-filter (:filter query-params))] (if (= filt "new") false seen))) (defn- get-filter "Gets the filter from the query parameters." [query-params] (let [filt (mangle-filter (:filter query-params))] (when-not (or (nil? filt) (= filt "new")) filt))) (defn get-unseen-messages "Looks up all messages in the that have not been seen yet for a specified user." [query-params] (let [user (required-string :user query-params)] (log/debug "retrieving unseen messages for" user) (get-messages* user {:limit 0 :offset 0 :seen false :sort-field :timestamp :sort-dir :asc}))) (defn get-paginated-messages "Provides a paginated view for notification messages. This endpoint takes several query-string parameters: user - the name of the user to get notifications for limit - the maximum number of messages to return or zero if there is no limit - optional (0) offset - the number of leading messages to skip - optional (0) seen - specify 'true' for only seen messages or 'false' for only unseen messages - optional (defaults to displaying both seen and unseen messages) sortField - the field to use when sorting the messages - optional (currently, only 'timestamp' can be used) sortDir - the sort direction, 'asc' or 'desc' - optional (desc) filter - filter by message type ('data', 'analysis', etc.)" [query-params] (let [user (required-string :user query-params) query {:limit (optional-long :limit query-params 0) :offset (optional-long :offset query-params 0) :seen (get-seen-flag query-params) :sort-field (as-keyword (:sortfield query-params "timestamp")) :sort-dir (as-keyword (:sortdir query-params "desc")) :filter (get-filter query-params)}] (get-messages* user query))) (defn count-messages "Provides a way to retrieve the system message counts along with the number of user messages that match a set of criteria. This endpoint takes several query-string parameters: user - the name of the user to count messages for seen - specify 'true' for only seen user messages or 'false' for only unseen user messages - optional (defaults to counting both seen and unseen user messages) filter - filter user messages by message type ('data', 'analysis', etc.)" [query-params] (let [user (required-string :user query-params) user-query {:seen (optional-boolean :seen query-params) :filter (mangle-filter (:filter query-params))}] (count-messages* user user-query))) (defn last-ten-messages "Obtains the ten most recent notifications for the user in ascending order." [query-params] (let [user (required-string :user query-params) query {:limit 10 :offset 0 :sort-field :timestamp :sort-dir :desc} total (db/count-matching-messages user query) results (->> (db/find-matching-messages user query) (map reformat) (sort-by #(get-in % [:message :timestamp])))] {:total (str total) :messages results})) (defn- get-sys-msgs-with [db-get query-params] (let [user (required-string :user query-params) results (db-get user)] {:system-messages results})) (defn get-system-messages "Obtains the system messages that apply to a user." [query-params] (get-sys-msgs-with db/get-active-system-notifications query-params)) (defn get-new-system-messages "Obtains the active system messages for a given user that have not been marked as retrieved. Parameters: query-params - The query-params as provided by ring. Return: It returns the list of new system messages in a map that ring can understand." [query-params] (get-sys-msgs-with db/get-new-system-notifications query-params)) (defn get-unseen-system-messages [query-params] (get-sys-msgs-with db/get-unseen-system-notifications query-params))
null
https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/services/NotificationAgent/src/notification_agent/query.clj
clojure
(ns notification-agent.query (:use [notification-agent.common] [notification-agent.messages :only [reformat-message]] [clojure.string :only [blank? lower-case upper-case]] [slingshot.slingshot :only [throw+]]) (:require [cheshire.core :as cheshire] [clojure.string :as string] [clojure.tools.logging :as log] [notification-agent.db :as db])) (defn- reformat "Reformats a message corresponding to a notification that was retrieved from the database." [{:keys [uuid message seen deleted]}] (reformat-message (upper-case (str uuid)) (cheshire/decode message true) :seen seen :deleted deleted)) (defn- count-messages* "Counts the number of matching messages. The user messages are filtered with the provided query." [user user-query] (let [user-total (db/count-matching-messages user user-query) sys-total (db/count-active-system-notifications user) new-sys-total (db/count-new-system-notifications user) unseen-sys-total (db/count-unseen-system-notifications user)] {:user-total user-total :system-total sys-total :system-total-new new-sys-total :system-total-unseen unseen-sys-total})) (defn- get-messages* "Retrieves notification messages." [user query] (let [body {:total (str (db/count-matching-messages user query)) :messages (map reformat (db/find-matching-messages user query)) :system-messages (db/get-active-system-notifications user)}] body)) (defn- required-string "Extracts a required string argument from the query-string map." [k m] (let [v (m k)] (when (blank? v) (throw+ {:type :clojure-commons.exception/illegal-argument :code ::missing-or-empty-param :param (name k)})) v)) (defn- optional-long "Extracts an optional long argument from the query-string map, using a default value if the argument wasn't provided." [k m d] (let [v (k m)] (if-not (nil? v) (string->long v ::invalid-long-integer-param {:param (name k) :value v}) d))) (defn- optional-boolean "Extracts an optional Boolean argument from the query-string map." ([k m] (optional-boolean k m nil)) ([k m d] (let [v (k m)] (if (nil? v) d (Boolean/valueOf v))))) (defn- as-keyword "Converts a string to a lower-case keyword." [s] (keyword (lower-case s))) (defn- mangle-filter "Converts a filter to lower case with underscores replacing spaces." [filt] (when-not (nil? filt) (string/lower-case (string/replace filt #" " "_")))) (defn- get-seen-flag "Gets the seen flag from the query parameters." [query-params] (let [seen (optional-boolean :seen query-params) filt (mangle-filter (:filter query-params))] (if (= filt "new") false seen))) (defn- get-filter "Gets the filter from the query parameters." [query-params] (let [filt (mangle-filter (:filter query-params))] (when-not (or (nil? filt) (= filt "new")) filt))) (defn get-unseen-messages "Looks up all messages in the that have not been seen yet for a specified user." [query-params] (let [user (required-string :user query-params)] (log/debug "retrieving unseen messages for" user) (get-messages* user {:limit 0 :offset 0 :seen false :sort-field :timestamp :sort-dir :asc}))) (defn get-paginated-messages "Provides a paginated view for notification messages. This endpoint takes several query-string parameters: user - the name of the user to get notifications for limit - the maximum number of messages to return or zero if there is no limit - optional (0) offset - the number of leading messages to skip - optional (0) seen - specify 'true' for only seen messages or 'false' for only unseen messages - optional (defaults to displaying both seen and unseen messages) sortField - the field to use when sorting the messages - optional (currently, only 'timestamp' can be used) sortDir - the sort direction, 'asc' or 'desc' - optional (desc) filter - filter by message type ('data', 'analysis', etc.)" [query-params] (let [user (required-string :user query-params) query {:limit (optional-long :limit query-params 0) :offset (optional-long :offset query-params 0) :seen (get-seen-flag query-params) :sort-field (as-keyword (:sortfield query-params "timestamp")) :sort-dir (as-keyword (:sortdir query-params "desc")) :filter (get-filter query-params)}] (get-messages* user query))) (defn count-messages "Provides a way to retrieve the system message counts along with the number of user messages that match a set of criteria. This endpoint takes several query-string parameters: user - the name of the user to count messages for seen - specify 'true' for only seen user messages or 'false' for only unseen user messages - optional (defaults to counting both seen and unseen user messages) filter - filter user messages by message type ('data', 'analysis', etc.)" [query-params] (let [user (required-string :user query-params) user-query {:seen (optional-boolean :seen query-params) :filter (mangle-filter (:filter query-params))}] (count-messages* user user-query))) (defn last-ten-messages "Obtains the ten most recent notifications for the user in ascending order." [query-params] (let [user (required-string :user query-params) query {:limit 10 :offset 0 :sort-field :timestamp :sort-dir :desc} total (db/count-matching-messages user query) results (->> (db/find-matching-messages user query) (map reformat) (sort-by #(get-in % [:message :timestamp])))] {:total (str total) :messages results})) (defn- get-sys-msgs-with [db-get query-params] (let [user (required-string :user query-params) results (db-get user)] {:system-messages results})) (defn get-system-messages "Obtains the system messages that apply to a user." [query-params] (get-sys-msgs-with db/get-active-system-notifications query-params)) (defn get-new-system-messages "Obtains the active system messages for a given user that have not been marked as retrieved. Parameters: query-params - The query-params as provided by ring. Return: It returns the list of new system messages in a map that ring can understand." [query-params] (get-sys-msgs-with db/get-new-system-notifications query-params)) (defn get-unseen-system-messages [query-params] (get-sys-msgs-with db/get-unseen-system-notifications query-params))
144f1217ec95956a5930cc1598df319c8f90adb2139578405529a673b68ebf77
ivanjovanovic/sicp
e-3.19.scm
Exercise 3.19 . ; Redo exercise 3.18 using an algorithm that takes only a ; constant amount of space. (This requires a very clever idea.) ; ------------------------------------------------------------ First to analyze a bit the solution in 3.18 . ; We are storing every visited node in the history object. Therefore, ; dependent on the length of the list this will grow over time. ; Its space growth is characterized by O(n) asymptotic approximation. ( ) has found in the late 1960s a very clever way to find the cycle in any part of the list . We just have to make two pointers on the top of the list and then go through the list in a way that we increase first one to the next position and second one for two positions . If there is a cycle in the list these two ; pointers will eventually meet, otherwise they will both end in null end and ; exit the algorithm loop. ; For more formal information about the approach ; @see (load "../helpers.scm") (define (cycled? l) (if (null? (cdr l)) '#f (let ((slow l) (fast (cdr l))) (define (recur) (cond ((or (null? (cdr slow)) (or (null? (cdr fast)) (null? (cddr fast)))) '#f) ((eq? slow fast) '#t) (else (begin (set! slow (cdr slow)) (set! fast (cddr fast)) (recur))))) (recur)))) ; no cycle in simple linked list (output (cycled? (list 1 2 3))) ; #f ; build cycled list out of pairs (define first (cons 1 2)) (define second (cons 1 2)) (define third (cons 1 2)) (define forth (cons 1 2)) (define fifth (cons 1 2)) (set-cdr! first second) (set-cdr! second third) (set-cdr! third forth) (set-cdr! forth fifth) (set-cdr! fifth second) (output (cycled? first)) ; #t
null
https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/3.3/e-3.19.scm
scheme
constant amount of space. (This requires a very clever idea.) ------------------------------------------------------------ We are storing every visited node in the history object. Therefore, dependent on the length of the list this will grow over time. Its space growth is characterized by O(n) asymptotic approximation. pointers will eventually meet, otherwise they will both end in null end and exit the algorithm loop. For more formal information about the approach @see no cycle in simple linked list #f build cycled list out of pairs #t
Exercise 3.19 . Redo exercise 3.18 using an algorithm that takes only a First to analyze a bit the solution in 3.18 . ( ) has found in the late 1960s a very clever way to find the cycle in any part of the list . We just have to make two pointers on the top of the list and then go through the list in a way that we increase first one to the next position and second one for two positions . If there is a cycle in the list these two (load "../helpers.scm") (define (cycled? l) (if (null? (cdr l)) '#f (let ((slow l) (fast (cdr l))) (define (recur) (cond ((or (null? (cdr slow)) (or (null? (cdr fast)) (null? (cddr fast)))) '#f) ((eq? slow fast) '#t) (else (begin (set! slow (cdr slow)) (set! fast (cddr fast)) (recur))))) (recur)))) (define first (cons 1 2)) (define second (cons 1 2)) (define third (cons 1 2)) (define forth (cons 1 2)) (define fifth (cons 1 2)) (set-cdr! first second) (set-cdr! second third) (set-cdr! third forth) (set-cdr! forth fifth) (set-cdr! fifth second)
65c6845091d596017e85a69882686a0e413644ab3baa15b10b2ce517a44a5b98
heyoka/faxe
graph_node_registry.erl
%%%------------------------------------------------------------------- @author ( C ) 2021 , < COMPANY > %%% @doc %%% @end %%%------------------------------------------------------------------- -module(graph_node_registry). -behaviour(gen_server). -export([start_link/0, register_graph_nodes/2, get_graph/1, get_graph_table/0, unregister_graph_nodes/2]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -define(NODE_TO_GRAPH_ETS, node_to_graph). -define(GRAPH_TO_NODES_ETS, graph_to_nodes). -record(state, {}). %%%=================================================================== %%% Spawning and gen_server implementation %%%=================================================================== -spec register_graph_nodes(pid(), list(pid())) -> list(true). register_graph_nodes(GraphPid, ComponentPids) when is_pid(GraphPid), is_list(ComponentPids) -> AllNodes = case ets:lookup(?GRAPH_TO_NODES_ETS, GraphPid) of [] -> %% first register ?SERVER ! {monitor_graph, GraphPid}, ComponentPids; [{GraphPid, Nodes}] -> Nodes ++ ComponentPids end, ets:insert(?GRAPH_TO_NODES_ETS, {GraphPid, AllNodes}), [ets:insert(?NODE_TO_GRAPH_ETS, {CPid, GraphPid}) || CPid <- ComponentPids]. -spec unregister_graph_nodes(pid(), list(pid)) -> list(true). unregister_graph_nodes(GraphPid, ComponentPids) when is_pid(GraphPid), is_list(ComponentPids) -> case ets:lookup(?GRAPH_TO_NODES_ETS, GraphPid) of [] -> ok; [{GraphPid, NodePids}] -> ets:insert(?GRAPH_TO_NODES_ETS, {GraphPid, NodePids--ComponentPids}) end, [ets:delete(?NODE_TO_GRAPH_ETS, CPid) || CPid <- ComponentPids]. get_graph_table() -> % get graph pid case get_graph(self()) of {ok, GraphPid} -> case ets:lookup(graph_ets, GraphPid) of [] -> TableId = ets:new(graph_ets_table, [set, public,{read_concurrency,true},{write_concurrency,true}]), ets:insert(graph_ets, {GraphPid, TableId}), TableId; [{GraphPid, Table}] -> Table end; {error, What} -> {error, What} end. get_graph(ComponentPid) when is_pid(ComponentPid) -> case ets:lookup(?NODE_TO_GRAPH_ETS, ComponentPid) of [] -> {error, not_found}; [{ComponentPid, GraphPid}] -> {ok, GraphPid} end. delete_graph_table(GraphPid) -> case ets:lookup(graph_ets, GraphPid) of [] -> ok; [{GraphPid, Table}] -> catch ets:delete(Table), ets:delete(graph_ets, GraphPid) end. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). init([]) -> {ok, #state{}}. handle_call(_Request, _From, State = #state{}) -> {reply, ok, State}. handle_cast(_Request, State = #state{}) -> {noreply, State}. handle_info({monitor_graph, GraphPid}, State = #state{}) -> erlang:monitor(process, GraphPid), {noreply, State}; handle_info({'DOWN', _MonitorRef, process, Pid, _Info}, State=#state{}) -> %% lager:info("Graph is down: ~p",[Pid]), %% graph is down, delete ets table and from lookup table catch delete_graph_table(Pid), case ets:lookup(?GRAPH_TO_NODES_ETS, Pid) of [{Pid, Nodes}] -> [ets:delete(?NODE_TO_GRAPH_ETS, NPid) || NPid <- Nodes]; _ -> ok end, ets:delete(?GRAPH_TO_NODES_ETS, Pid), {noreply, State}; handle_info(_Req, State = #state{}) -> {noreply, State}. terminate(_Reason, _State = #state{}) -> ok. code_change(_OldVsn, State = #state{}, _Extra) -> {ok, State}. %%%=================================================================== Internal functions %%%===================================================================
null
https://raw.githubusercontent.com/heyoka/faxe/93098305f064e0e0c2f1ec7995b4c3854ceb1ac5/apps/faxe/src/lib/graph_node_registry.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- =================================================================== Spawning and gen_server implementation =================================================================== first register get graph pid lager:info("Graph is down: ~p",[Pid]), graph is down, delete ets table and from lookup table =================================================================== ===================================================================
@author ( C ) 2021 , < COMPANY > -module(graph_node_registry). -behaviour(gen_server). -export([start_link/0, register_graph_nodes/2, get_graph/1, get_graph_table/0, unregister_graph_nodes/2]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -define(NODE_TO_GRAPH_ETS, node_to_graph). -define(GRAPH_TO_NODES_ETS, graph_to_nodes). -record(state, {}). -spec register_graph_nodes(pid(), list(pid())) -> list(true). register_graph_nodes(GraphPid, ComponentPids) when is_pid(GraphPid), is_list(ComponentPids) -> AllNodes = case ets:lookup(?GRAPH_TO_NODES_ETS, GraphPid) of [] -> ?SERVER ! {monitor_graph, GraphPid}, ComponentPids; [{GraphPid, Nodes}] -> Nodes ++ ComponentPids end, ets:insert(?GRAPH_TO_NODES_ETS, {GraphPid, AllNodes}), [ets:insert(?NODE_TO_GRAPH_ETS, {CPid, GraphPid}) || CPid <- ComponentPids]. -spec unregister_graph_nodes(pid(), list(pid)) -> list(true). unregister_graph_nodes(GraphPid, ComponentPids) when is_pid(GraphPid), is_list(ComponentPids) -> case ets:lookup(?GRAPH_TO_NODES_ETS, GraphPid) of [] -> ok; [{GraphPid, NodePids}] -> ets:insert(?GRAPH_TO_NODES_ETS, {GraphPid, NodePids--ComponentPids}) end, [ets:delete(?NODE_TO_GRAPH_ETS, CPid) || CPid <- ComponentPids]. get_graph_table() -> case get_graph(self()) of {ok, GraphPid} -> case ets:lookup(graph_ets, GraphPid) of [] -> TableId = ets:new(graph_ets_table, [set, public,{read_concurrency,true},{write_concurrency,true}]), ets:insert(graph_ets, {GraphPid, TableId}), TableId; [{GraphPid, Table}] -> Table end; {error, What} -> {error, What} end. get_graph(ComponentPid) when is_pid(ComponentPid) -> case ets:lookup(?NODE_TO_GRAPH_ETS, ComponentPid) of [] -> {error, not_found}; [{ComponentPid, GraphPid}] -> {ok, GraphPid} end. delete_graph_table(GraphPid) -> case ets:lookup(graph_ets, GraphPid) of [] -> ok; [{GraphPid, Table}] -> catch ets:delete(Table), ets:delete(graph_ets, GraphPid) end. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). init([]) -> {ok, #state{}}. handle_call(_Request, _From, State = #state{}) -> {reply, ok, State}. handle_cast(_Request, State = #state{}) -> {noreply, State}. handle_info({monitor_graph, GraphPid}, State = #state{}) -> erlang:monitor(process, GraphPid), {noreply, State}; handle_info({'DOWN', _MonitorRef, process, Pid, _Info}, State=#state{}) -> catch delete_graph_table(Pid), case ets:lookup(?GRAPH_TO_NODES_ETS, Pid) of [{Pid, Nodes}] -> [ets:delete(?NODE_TO_GRAPH_ETS, NPid) || NPid <- Nodes]; _ -> ok end, ets:delete(?GRAPH_TO_NODES_ETS, Pid), {noreply, State}; handle_info(_Req, State = #state{}) -> {noreply, State}. terminate(_Reason, _State = #state{}) -> ok. code_change(_OldVsn, State = #state{}, _Extra) -> {ok, State}. Internal functions
b07bb595a54bb78110b77e55ea318d57809a05b245cfadd916d8ebe00bd515d1
dnadales/sandbox
Lib.hs
# LANGUAGE NamedFieldPuns # module Lib where import Control.Monad import Control.Exception.Base import Control.Exception import Control.Concurrent import Network.TextViaSockets readThreeTimes :: IO () readThreeTimes = readLines `catch` handler where readLines = do conn <- connectTo "localhost" "9090" line <- readLineFrom conn print line line <- readLineFrom conn print line line <- readLineFrom conn print line line <- readLineFrom conn print line close conn print "Bye bye!" handler :: BlockedIndefinitelyOnSTM -> IO () handler ex = putStrLn $ "I'm swallowing this: " ++ show ex readAndCancel :: IO () readAndCancel = forever $ do tid <- forkIO readThreeTimes threadDelay (1 * 10^6) putStrLn "Killing the reader thread..." killThread tid putStrLn "Reader thread killed"
null
https://raw.githubusercontent.com/dnadales/sandbox/401c4f0fac5f8044fb6e2e443bacddce6f135b4b/receiving-strings-via-sockets/src/Lib.hs
haskell
# LANGUAGE NamedFieldPuns # module Lib where import Control.Monad import Control.Exception.Base import Control.Exception import Control.Concurrent import Network.TextViaSockets readThreeTimes :: IO () readThreeTimes = readLines `catch` handler where readLines = do conn <- connectTo "localhost" "9090" line <- readLineFrom conn print line line <- readLineFrom conn print line line <- readLineFrom conn print line line <- readLineFrom conn print line close conn print "Bye bye!" handler :: BlockedIndefinitelyOnSTM -> IO () handler ex = putStrLn $ "I'm swallowing this: " ++ show ex readAndCancel :: IO () readAndCancel = forever $ do tid <- forkIO readThreeTimes threadDelay (1 * 10^6) putStrLn "Killing the reader thread..." killThread tid putStrLn "Reader thread killed"
c741c98097dcb5db4663e0652c51ebcb945ca44081ddcff29fbf5864a3431983
AndrasKovacs/ELTE-func-lang
Ora4_Pre.hs
Ha ez valakinek {-# LANGUAGE DeriveFunctor, InstanceSigs #-} module Ora4 where import Control.Monad import Prelude hiding (Maybe(..), Either(..)) -- pl Maybe -- Nothing a hiba eset data Maybe a = Just a | Nothing deriving Functor -- pl Either -- Left a hibaüzenetek esete data Either a b = Left a | Right b deriving Functor Ha egy hiba is van , case - of is nagyon hasznos ennél mapMaybe :: (a -> Maybe b) -> [a] -> Maybe [b] mapMaybe = undefined -- e a hibaüzenet komponens mapEither :: (a -> Either b e) -> [a] -> Either [b] e mapEither = undefined Ilyesfajta a " bind " függvény A maybe belső eleme kihat a ( mellékhatás ) - > Justból is Nothing bindMaybe :: (a -> Maybe b) -> Maybe a -> Maybe b bindMaybe = undefined bindEither :: (a -> Either e b) -> Either e a -> Either e b bindEither = undefined class Applicative m = > Monad m where return : : a - > m a ( > > : m a - > ( a - > m b ) - > m b class Applicative m => Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b -} Az applikatív kicsitt , Annyi releváns , hogy minden applicative egy functor is tehát -- class Functor f => Applicative f where instance Applicative Maybe where (<*>) = ap pure = return instance Monad Maybe where return :: a -> Maybe a return = undefined (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b m >>= f = undefined instance Applicative (Either e) where (<*>) = ap pure = return instance Monad (Either e) where return :: a -> Either e a return = undefined (>>=) :: Either e a -> (a -> Either e b) -> Either e b eth >>= f = undefined járnak a Monad - al ? -- Pl konstans bind ( > > ) : : = > m a - > m b - > m b -- a >> b = a >>= \_ -> b Szekvenciálásra jó , fontos monád Nagyon sok ( see Control . Monad ) Általános függvények map : : ( a - > b ) - > [ a ] - > [ b ] mapM : : = > ( a - > m b ) - > [ a ] - > m [ b ] mapM _ : : = > ( a - > m b ) - > [ a ] - > m ( ) < - eldobjuk a listát , csak a mellékhatás érdekel filter : : ( a - > Bool ) - > [ a ] - > [ a ] filterM : : = > ( a - > m ) - > [ a ] - > m [ a ] Ebből filterM _ nincs de lehetne map :: (a -> b) -> [a] -> [b] mapM :: Monad m => (a -> m b) -> [a] -> m [b] mapM_ :: Monad m => (a -> m b) -> [a] -> m () <- eldobjuk a listát, csak a mellékhatás érdekel filter :: (a -> Bool) -> [a] -> [a] filterM :: Monad m => (a -> m Bool) -> [a] -> m [a] Ebből filterM_ nincs de lehetne simán írni -} a mapMaybe és mapEither feljebb -- írjunk még monád fv-eket -- replicate :: Int -> a -> [a] replicateM : : = > Int - > m a - > m [ a ] replicateM _ : : = > Int - > m a - > m ( ) replicateM' :: Monad m => Int -> m a -> m [a] replicateM' = undefined filterM' :: Monad m => (a -> m Bool) -> [a] -> m [a] filterM' = undefined Most még csak tesztelésre : -- I/O haskellben: IO monád standard konzol műveletek -- getLine :: IO String -- print :: Show a => a -> IO () -- putStr :: String -> IO () -- putStrLn :: String -> IO () -- readLn :: Read a => IO a komibálni > > = -al ( readLn : : IO Int ) > > = print beolvas egy számot terminálra - 1x próbálkozik majd do - notáció : Imperatív do b < - a ≡ a > > = \b - > ... do a b ≡ a > > b do b < - a c < - a return $ b + c ≡ a > > = \b - > a > > = - > return $ b + c do b <- a ≡ a >>= \b -> ... do a b ≡ a >> b do b <- a c <- a return $ b + c ≡ a >>= \b -> a >>= \c -> return $ b + c -} a fenti függvényeket do - notációval mapM' :: Monad m => (a -> m b) -> [a] -> m [b] mapM' = undefined filterM'' :: Monad m => (a -> m Bool) -> [a] -> m [a] filterM'' = undefined replicateM'' :: Monad m => Int -> [a] -> m [a] replicateM'' = undefined
null
https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/b43200a54ec54a2103f49440479e406e02d490db/2022-23-1/gyak2/Ora4_Pre.hs
haskell
# LANGUAGE DeriveFunctor, InstanceSigs # pl Maybe Nothing a hiba eset pl Either Left a hibaüzenetek esete e a hibaüzenet komponens class Functor f => Applicative f where Pl konstans bind a >> b = a >>= \_ -> b írjunk még monád fv-eket replicate :: Int -> a -> [a] I/O haskellben: IO monád getLine :: IO String print :: Show a => a -> IO () putStr :: String -> IO () putStrLn :: String -> IO () readLn :: Read a => IO a
Ha ez valakinek module Ora4 where import Control.Monad import Prelude hiding (Maybe(..), Either(..)) data Maybe a = Just a | Nothing deriving Functor data Either a b = Left a | Right b deriving Functor Ha egy hiba is van , case - of is nagyon hasznos ennél mapMaybe :: (a -> Maybe b) -> [a] -> Maybe [b] mapMaybe = undefined mapEither :: (a -> Either b e) -> [a] -> Either [b] e mapEither = undefined Ilyesfajta a " bind " függvény A maybe belső eleme kihat a ( mellékhatás ) - > Justból is Nothing bindMaybe :: (a -> Maybe b) -> Maybe a -> Maybe b bindMaybe = undefined bindEither :: (a -> Either e b) -> Either e a -> Either e b bindEither = undefined class Applicative m = > Monad m where return : : a - > m a ( > > : m a - > ( a - > m b ) - > m b class Applicative m => Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b -} Az applikatív kicsitt , Annyi releváns , hogy minden applicative egy functor is tehát instance Applicative Maybe where (<*>) = ap pure = return instance Monad Maybe where return :: a -> Maybe a return = undefined (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b m >>= f = undefined instance Applicative (Either e) where (<*>) = ap pure = return instance Monad (Either e) where return :: a -> Either e a return = undefined (>>=) :: Either e a -> (a -> Either e b) -> Either e b eth >>= f = undefined járnak a Monad - al ? ( > > ) : : = > m a - > m b - > m b Szekvenciálásra jó , fontos monád Nagyon sok ( see Control . Monad ) Általános függvények map : : ( a - > b ) - > [ a ] - > [ b ] mapM : : = > ( a - > m b ) - > [ a ] - > m [ b ] mapM _ : : = > ( a - > m b ) - > [ a ] - > m ( ) < - eldobjuk a listát , csak a mellékhatás érdekel filter : : ( a - > Bool ) - > [ a ] - > [ a ] filterM : : = > ( a - > m ) - > [ a ] - > m [ a ] Ebből filterM _ nincs de lehetne map :: (a -> b) -> [a] -> [b] mapM :: Monad m => (a -> m b) -> [a] -> m [b] mapM_ :: Monad m => (a -> m b) -> [a] -> m () <- eldobjuk a listát, csak a mellékhatás érdekel filter :: (a -> Bool) -> [a] -> [a] filterM :: Monad m => (a -> m Bool) -> [a] -> m [a] Ebből filterM_ nincs de lehetne simán írni -} a mapMaybe és mapEither feljebb replicateM : : = > Int - > m a - > m [ a ] replicateM _ : : = > Int - > m a - > m ( ) replicateM' :: Monad m => Int -> m a -> m [a] replicateM' = undefined filterM' :: Monad m => (a -> m Bool) -> [a] -> m [a] filterM' = undefined Most még csak tesztelésre : standard konzol műveletek komibálni > > = -al ( readLn : : IO Int ) > > = print beolvas egy számot terminálra - 1x próbálkozik majd do - notáció : Imperatív do b < - a ≡ a > > = \b - > ... do a b ≡ a > > b do b < - a c < - a return $ b + c ≡ a > > = \b - > a > > = - > return $ b + c do b <- a ≡ a >>= \b -> ... do a b ≡ a >> b do b <- a c <- a return $ b + c ≡ a >>= \b -> a >>= \c -> return $ b + c -} a fenti függvényeket do - notációval mapM' :: Monad m => (a -> m b) -> [a] -> m [b] mapM' = undefined filterM'' :: Monad m => (a -> m Bool) -> [a] -> m [a] filterM'' = undefined replicateM'' :: Monad m => Int -> [a] -> m [a] replicateM'' = undefined
d1816b6c97100646be68e33fd9d748e6964f82ff1ec30d09b7589841910a853b
wh5a/thih
FacAndFibWithGuards.hs
-- FacAndfibWithGuards.hs Output : 123 -- fac :: Int -> Int fac n | n == 0 = 1 | n == 1 = 1 | otherwise = n * fac (n - 1) -- fib :: Int -> Int fib n | n == 0 = 1 | n == 1 = 1 | otherwise = (fib (n - 1)) + (fib (n - 2)) -- main :: Int main = fac 5 + fib 3
null
https://raw.githubusercontent.com/wh5a/thih/dc5cb16ba4e998097135beb0c7b0b416cac7bfae/hatchet/examples/FacAndFibWithGuards.hs
haskell
FacAndfibWithGuards.hs fac :: Int -> Int fib :: Int -> Int main :: Int
Output : 123 fac n | n == 0 = 1 | n == 1 = 1 | otherwise = n * fac (n - 1) fib n | n == 0 = 1 | n == 1 = 1 | otherwise = (fib (n - 1)) + (fib (n - 2)) main = fac 5 + fib 3
88cdcbcbab483b9220c5b067976541917af926e3b369ceafdd4ab4f88ac43041
open-company/open-company-web
dashboard_layout.cljs
(ns oc.web.components.dashboard-layout (:require [rum.core :as rum] [org.martinklepsch.derivatives :as drv] [oc.web.dispatcher :as dis] [oc.web.lib.utils :as utils] [oc.lib.cljs.useragent :as ua] [oc.web.mixins.ui :as ui-mixins] [oc.web.actions.user :as user-actions] [oc.web.lib.responsive :as responsive] [oc.web.actions.cmail :as cmail-actions] [oc.web.components.cmail :refer (cmail)] [oc.web.actions.label :as label-actions] [oc.web.actions.nav-sidebar :as nav-actions] [oc.web.components.user-profile :refer (user-profile)] [oc.web.components.explore-view :refer (explore-view)] [oc.web.components.user-notifications :as user-notifications] [oc.web.components.ui.follow-button :refer (follow-banner)] [oc.web.components.ui.empty-org :refer (empty-org)] [oc.web.components.ui.lazy-stream :refer (lazy-stream)] [oc.web.components.ui.empty-board :refer (empty-board)] [oc.web.components.ui.mobile-tabbar :refer (mobile-tabbar)] [oc.web.components.navigation-sidebar :refer (navigation-sidebar)])) (rum/defcs dashboard-layout < rum/static rum/reactive ;; Derivative (drv/drv :org-data) (drv/drv :contributions-user-data) (drv/drv :label-data) (drv/drv :container-data) (drv/drv :org-slug) (drv/drv :board-slug) (drv/drv :label-slug) (drv/drv :contributions-id) (drv/drv :activity-uuid) (drv/drv :filtered-posts) (drv/drv :items-to-render) (drv/drv :show-add-post-tooltip) (drv/drv :current-user-data) (drv/drv :cmail-state) (drv/drv :mobile-user-notifications) (drv/drv :user-notifications) (drv/drv :show-invite-box) (drv/drv :foc-menu) (drv/drv :activities-read) ui-mixins/strict-refresh-tooltips-mixin {:did-mount (fn [s] ;; Reopen cmail if it was open (when-let [org-data @(drv/get-ref s :org-data)] (when (:can-compose? org-data) (cmail-actions/cmail-reopen?))) (set! (.. js/document -scrollingElement -scrollTop) (utils/page-scroll-top)) s)} [s] (let [org-data (drv/react s :org-data) contributions-user-data (drv/react s :contributions-user-data) container-data* (drv/react s :container-data) label-data (drv/react s :label-data) _items-to-render (drv/react s :items-to-render) _foc-menu (drv/react s :foc-menu) _activities-read (drv/react s :activities-read) current-board-slug (drv/react s :board-slug) current-label-slug (drv/react s :label-slug) current-contributions-id (drv/react s :contributions-id) current-activity-id (drv/react s :activity-uuid) current-org-slug (drv/react s :org-slug) current-user-data (drv/react s :current-user-data) mobile-user-notifications (drv/react s :mobile-user-notifications) user-notifications-data (drv/react s :user-notifications) add-post-tooltip (drv/react s :show-add-post-tooltip) show-invite-box (drv/react s :show-invite-box) is-mobile? (responsive/is-mobile-size?) is-admin-or-author (#{:admin :author} (:role current-user-data)) show-mobile-invite-people? (and is-mobile? current-org-slug is-admin-or-author show-invite-box) ;; Board data used as fallback until the board is completely loaded org-board-data (dis/org-board-data org-data current-board-slug) is-inbox (= current-board-slug "inbox") is-all-posts (= current-board-slug "all-posts") is-bookmarks (= current-board-slug "bookmarks") is-following (= current-board-slug "following") is-replies (= current-board-slug "replies") is-unfollowing (= current-board-slug "unfollowing") is-topics (= current-board-slug "topics") is-contributions (seq current-contributions-id) is-label (seq current-label-slug) is-tablet-or-mobile? (responsive/is-tablet-or-mobile?) is-container? (dis/is-container? current-board-slug) container-data (if (and (not is-contributions) (not is-label) (not is-container?) (not container-data*)) org-board-data container-data*) loading-container? (or (not (map? container-data*)) (not (contains? container-data* :links))) empty-container? (and (not loading-container?) (not (seq (:posts-list container-data*)))) is-drafts-board (= current-board-slug utils/default-drafts-board-slug) should-show-settings-bt (and current-board-slug (not is-container?) (not is-topics) (not is-contributions) (not (:read-only container-data))) should-show-label-edit-bt (and current-label-slug (:can-edit? label-data)) cmail-state (drv/react s :cmail-state) member? (:member? org-data) show-follow-banner? (and (not is-container?) (not (seq current-contributions-id)) (not (seq current-label-slug)) (not is-drafts-board) (map? org-board-data) (false? (:following org-board-data))) can-compose? (:can-compose? org-data) show-desktop-cmail? (and (not is-mobile?) can-compose? (or (not is-contributions) (not (:collapsed cmail-state)))) paginated-stream-key (str "ps-" current-org-slug "-" (cond is-contributions current-contributions-id is-label current-label-slug current-board-slug (name current-board-slug)) (when (:last-seen-at container-data) (str "-" (:last-seen-at container-data)))) no-phisical-home-button (and (exists? js/isiPhoneWithoutPhysicalHomeBt) (^js js/isiPhoneWithoutPhysicalHomeBt)) can-create-topic? (utils/link-for (:links org-data) "create" "POST") contrib-headline (if (map? contributions-user-data) (str "Latest from " (:short-name contributions-user-data)) "Latest posts")] Entries list [:div.dashboard-layout.group [:div.mobile-more-menu] [:div.dashboard-layout-container.group {:class (utils/class-set {:has-mobile-invite-box show-mobile-invite-people? :ios-app-tabbar (and ua/mobile-app? no-phisical-home-button) :ios-web-tabbar (and (not ua/mobile-app?) no-phisical-home-button)})} (navigation-sidebar) (when show-mobile-invite-people? [:div.mobile-invite-box [:button.mlb-reset.mobile-invite-box-bt {:on-click #(nav-actions/show-org-settings :invite-picker)} "Explore together - " [:span.invite-teammates "Invite your teammates"] "!"] [:button.mlb-reset.close-mobile-invite-box {:on-click #(user-actions/dismiss-invite-box (:user-id current-user-data) true)}]]) (when (and is-mobile? (or (:collapsed cmail-state) (not cmail-state)) member?) (mobile-tabbar {:active-tab (cond mobile-user-notifications :user-notifications is-following :following is-replies :replies (or is-topics (seq current-board-slug) (not is-container?)) :topics :else :none) :can-compose? can-compose? :user-notifications-data user-notifications-data :show-add-post-tooltip add-post-tooltip})) (when (and is-mobile? mobile-user-notifications) (user-notifications/user-notifications)) ;; Show the board always on desktop except when there is an expanded post and ;; on mobile only when the navigation menu is not visible [:div.board-container.group (when show-desktop-cmail? (cmail)) (when is-contributions (user-profile contributions-user-data)) (when (and show-desktop-cmail? (not (:collapsed cmail-state)) (:fullscreen cmail-state)) [:div.dashboard-layout-cmail-placeholder]) (when show-follow-banner? [:div.dashboard-layout-follow-banner (follow-banner container-data)]) ;; Board name row: board name, settings button and say something button [:div.board-name-container.group {:class (utils/class-set {:drafts-board is-drafts-board :topics-view is-topics})} ;; Board name and settings button [:div.board-name {:class (when is-topics "topics-header")} [:div.board-name-with-icon {:class (when is-contributions "contributions")} [:div.board-name-with-icon-internal {:class (utils/class-set {:private (and (= (:access container-data) "private") (not is-drafts-board)) :public (= (:access container-data) "public") :contributions is-contributions :label-icon is-label :home-icon is-following :unfollowing-icon is-unfollowing :all-icon is-all-posts :topics-icon is-topics :saved-icon is-bookmarks :drafts-icon is-drafts-board :replies-icon is-replies :board-icon (and (not is-container?) (not is-contributions) (not is-topics) (not is-drafts-board) (not is-label) (not current-activity-id))})} (cond is-contributions contrib-headline is-inbox "Unread" is-all-posts "All" is-topics "Explore" is-bookmarks "Bookmarks" is-following "Home" is-unfollowing "Unfollowing" is-replies "Activity" is-label (or (:name label-data) (:slug label-data) current-label-slug) :else Fallback to the org board data ;; to avoid showing an empty name while loading ;; the board data (:name container-data))]] (when (and (= (:access container-data) "private") (not is-drafts-board)) [:div.private-board {:data-toggle "tooltip" :data-placement "top" :data-container "body" :data-delay "{\"show\":\"500\", \"hide\":\"0\"}" :title (if (= current-board-slug utils/default-drafts-board-slug) "Only visible to you" "Only visible to invited team members")}]) (when (= (:access container-data) "public") [:div.public-board {:data-toggle "tooltip" :data-placement "top" :data-container "body" :data-delay "{\"show\":\"500\", \"hide\":\"0\"}" :title "Visible to the world, including search engines"}]) (when (and is-topics can-create-topic?) [:button.mlb-reset.explore-view-block.create-topic-bt {:on-click #(nav-actions/show-section-add)} [:span.plus] [:span.new-topic "Add new topic"]]) (when (and is-topics (:can-create-label? org-data)) [:button.mlb-reset.explore-view-block.manage-labels-bt {:on-click #(label-actions/show-labels-manager)} [:span.manage-labels-bt-icon] [:span.manage-labels-bt-text "Manage labels"]])] (when-not is-topics [:div.board-name-right (when should-show-settings-bt [:div.board-settings-container ;; Settings button [:button.mlb-reset.board-settings-bt {:data-toggle (when-not is-tablet-or-mobile? "tooltip") :data-placement "top" :data-container "body" :title (str (:name container-data) " settings") :on-click #(nav-actions/show-section-editor (:slug container-data))}]]) (when should-show-label-edit-bt [:div.board-settings-container ;; Settings button [:button.mlb-reset.board-settings-bt {:data-toggle (when-not is-tablet-or-mobile? "tooltip") :data-placement "top" :data-container "body" :title (str (:name label-data) " edit") :on-click #(label-actions/edit-label label-data)}]])])] ;; Board content: empty org, all posts, empty board, drafts view, entries view (cond ;; Explore view is-topics (explore-view) ;; No boards (zero? (count (:boards org-data))) (empty-org) ;; Empty board empty-container? (empty-board) Paginated board / container :else (rum/with-key (lazy-stream) paginated-stream-key))]]]))
null
https://raw.githubusercontent.com/open-company/open-company-web/246cccb2818cc3bb9f05adeea4364ffa7171a586/src/main/oc/web/components/dashboard_layout.cljs
clojure
Derivative Reopen cmail if it was open Board data used as fallback until the board is completely loaded Show the board always on desktop except when there is an expanded post and on mobile only when the navigation menu is not visible Board name row: board name, settings button and say something button Board name and settings button to avoid showing an empty name while loading the board data Settings button Settings button Board content: empty org, all posts, empty board, drafts view, entries view Explore view No boards Empty board
(ns oc.web.components.dashboard-layout (:require [rum.core :as rum] [org.martinklepsch.derivatives :as drv] [oc.web.dispatcher :as dis] [oc.web.lib.utils :as utils] [oc.lib.cljs.useragent :as ua] [oc.web.mixins.ui :as ui-mixins] [oc.web.actions.user :as user-actions] [oc.web.lib.responsive :as responsive] [oc.web.actions.cmail :as cmail-actions] [oc.web.components.cmail :refer (cmail)] [oc.web.actions.label :as label-actions] [oc.web.actions.nav-sidebar :as nav-actions] [oc.web.components.user-profile :refer (user-profile)] [oc.web.components.explore-view :refer (explore-view)] [oc.web.components.user-notifications :as user-notifications] [oc.web.components.ui.follow-button :refer (follow-banner)] [oc.web.components.ui.empty-org :refer (empty-org)] [oc.web.components.ui.lazy-stream :refer (lazy-stream)] [oc.web.components.ui.empty-board :refer (empty-board)] [oc.web.components.ui.mobile-tabbar :refer (mobile-tabbar)] [oc.web.components.navigation-sidebar :refer (navigation-sidebar)])) (rum/defcs dashboard-layout < rum/static rum/reactive (drv/drv :org-data) (drv/drv :contributions-user-data) (drv/drv :label-data) (drv/drv :container-data) (drv/drv :org-slug) (drv/drv :board-slug) (drv/drv :label-slug) (drv/drv :contributions-id) (drv/drv :activity-uuid) (drv/drv :filtered-posts) (drv/drv :items-to-render) (drv/drv :show-add-post-tooltip) (drv/drv :current-user-data) (drv/drv :cmail-state) (drv/drv :mobile-user-notifications) (drv/drv :user-notifications) (drv/drv :show-invite-box) (drv/drv :foc-menu) (drv/drv :activities-read) ui-mixins/strict-refresh-tooltips-mixin {:did-mount (fn [s] (when-let [org-data @(drv/get-ref s :org-data)] (when (:can-compose? org-data) (cmail-actions/cmail-reopen?))) (set! (.. js/document -scrollingElement -scrollTop) (utils/page-scroll-top)) s)} [s] (let [org-data (drv/react s :org-data) contributions-user-data (drv/react s :contributions-user-data) container-data* (drv/react s :container-data) label-data (drv/react s :label-data) _items-to-render (drv/react s :items-to-render) _foc-menu (drv/react s :foc-menu) _activities-read (drv/react s :activities-read) current-board-slug (drv/react s :board-slug) current-label-slug (drv/react s :label-slug) current-contributions-id (drv/react s :contributions-id) current-activity-id (drv/react s :activity-uuid) current-org-slug (drv/react s :org-slug) current-user-data (drv/react s :current-user-data) mobile-user-notifications (drv/react s :mobile-user-notifications) user-notifications-data (drv/react s :user-notifications) add-post-tooltip (drv/react s :show-add-post-tooltip) show-invite-box (drv/react s :show-invite-box) is-mobile? (responsive/is-mobile-size?) is-admin-or-author (#{:admin :author} (:role current-user-data)) show-mobile-invite-people? (and is-mobile? current-org-slug is-admin-or-author show-invite-box) org-board-data (dis/org-board-data org-data current-board-slug) is-inbox (= current-board-slug "inbox") is-all-posts (= current-board-slug "all-posts") is-bookmarks (= current-board-slug "bookmarks") is-following (= current-board-slug "following") is-replies (= current-board-slug "replies") is-unfollowing (= current-board-slug "unfollowing") is-topics (= current-board-slug "topics") is-contributions (seq current-contributions-id) is-label (seq current-label-slug) is-tablet-or-mobile? (responsive/is-tablet-or-mobile?) is-container? (dis/is-container? current-board-slug) container-data (if (and (not is-contributions) (not is-label) (not is-container?) (not container-data*)) org-board-data container-data*) loading-container? (or (not (map? container-data*)) (not (contains? container-data* :links))) empty-container? (and (not loading-container?) (not (seq (:posts-list container-data*)))) is-drafts-board (= current-board-slug utils/default-drafts-board-slug) should-show-settings-bt (and current-board-slug (not is-container?) (not is-topics) (not is-contributions) (not (:read-only container-data))) should-show-label-edit-bt (and current-label-slug (:can-edit? label-data)) cmail-state (drv/react s :cmail-state) member? (:member? org-data) show-follow-banner? (and (not is-container?) (not (seq current-contributions-id)) (not (seq current-label-slug)) (not is-drafts-board) (map? org-board-data) (false? (:following org-board-data))) can-compose? (:can-compose? org-data) show-desktop-cmail? (and (not is-mobile?) can-compose? (or (not is-contributions) (not (:collapsed cmail-state)))) paginated-stream-key (str "ps-" current-org-slug "-" (cond is-contributions current-contributions-id is-label current-label-slug current-board-slug (name current-board-slug)) (when (:last-seen-at container-data) (str "-" (:last-seen-at container-data)))) no-phisical-home-button (and (exists? js/isiPhoneWithoutPhysicalHomeBt) (^js js/isiPhoneWithoutPhysicalHomeBt)) can-create-topic? (utils/link-for (:links org-data) "create" "POST") contrib-headline (if (map? contributions-user-data) (str "Latest from " (:short-name contributions-user-data)) "Latest posts")] Entries list [:div.dashboard-layout.group [:div.mobile-more-menu] [:div.dashboard-layout-container.group {:class (utils/class-set {:has-mobile-invite-box show-mobile-invite-people? :ios-app-tabbar (and ua/mobile-app? no-phisical-home-button) :ios-web-tabbar (and (not ua/mobile-app?) no-phisical-home-button)})} (navigation-sidebar) (when show-mobile-invite-people? [:div.mobile-invite-box [:button.mlb-reset.mobile-invite-box-bt {:on-click #(nav-actions/show-org-settings :invite-picker)} "Explore together - " [:span.invite-teammates "Invite your teammates"] "!"] [:button.mlb-reset.close-mobile-invite-box {:on-click #(user-actions/dismiss-invite-box (:user-id current-user-data) true)}]]) (when (and is-mobile? (or (:collapsed cmail-state) (not cmail-state)) member?) (mobile-tabbar {:active-tab (cond mobile-user-notifications :user-notifications is-following :following is-replies :replies (or is-topics (seq current-board-slug) (not is-container?)) :topics :else :none) :can-compose? can-compose? :user-notifications-data user-notifications-data :show-add-post-tooltip add-post-tooltip})) (when (and is-mobile? mobile-user-notifications) (user-notifications/user-notifications)) [:div.board-container.group (when show-desktop-cmail? (cmail)) (when is-contributions (user-profile contributions-user-data)) (when (and show-desktop-cmail? (not (:collapsed cmail-state)) (:fullscreen cmail-state)) [:div.dashboard-layout-cmail-placeholder]) (when show-follow-banner? [:div.dashboard-layout-follow-banner (follow-banner container-data)]) [:div.board-name-container.group {:class (utils/class-set {:drafts-board is-drafts-board :topics-view is-topics})} [:div.board-name {:class (when is-topics "topics-header")} [:div.board-name-with-icon {:class (when is-contributions "contributions")} [:div.board-name-with-icon-internal {:class (utils/class-set {:private (and (= (:access container-data) "private") (not is-drafts-board)) :public (= (:access container-data) "public") :contributions is-contributions :label-icon is-label :home-icon is-following :unfollowing-icon is-unfollowing :all-icon is-all-posts :topics-icon is-topics :saved-icon is-bookmarks :drafts-icon is-drafts-board :replies-icon is-replies :board-icon (and (not is-container?) (not is-contributions) (not is-topics) (not is-drafts-board) (not is-label) (not current-activity-id))})} (cond is-contributions contrib-headline is-inbox "Unread" is-all-posts "All" is-topics "Explore" is-bookmarks "Bookmarks" is-following "Home" is-unfollowing "Unfollowing" is-replies "Activity" is-label (or (:name label-data) (:slug label-data) current-label-slug) :else Fallback to the org board data (:name container-data))]] (when (and (= (:access container-data) "private") (not is-drafts-board)) [:div.private-board {:data-toggle "tooltip" :data-placement "top" :data-container "body" :data-delay "{\"show\":\"500\", \"hide\":\"0\"}" :title (if (= current-board-slug utils/default-drafts-board-slug) "Only visible to you" "Only visible to invited team members")}]) (when (= (:access container-data) "public") [:div.public-board {:data-toggle "tooltip" :data-placement "top" :data-container "body" :data-delay "{\"show\":\"500\", \"hide\":\"0\"}" :title "Visible to the world, including search engines"}]) (when (and is-topics can-create-topic?) [:button.mlb-reset.explore-view-block.create-topic-bt {:on-click #(nav-actions/show-section-add)} [:span.plus] [:span.new-topic "Add new topic"]]) (when (and is-topics (:can-create-label? org-data)) [:button.mlb-reset.explore-view-block.manage-labels-bt {:on-click #(label-actions/show-labels-manager)} [:span.manage-labels-bt-icon] [:span.manage-labels-bt-text "Manage labels"]])] (when-not is-topics [:div.board-name-right (when should-show-settings-bt [:div.board-settings-container [:button.mlb-reset.board-settings-bt {:data-toggle (when-not is-tablet-or-mobile? "tooltip") :data-placement "top" :data-container "body" :title (str (:name container-data) " settings") :on-click #(nav-actions/show-section-editor (:slug container-data))}]]) (when should-show-label-edit-bt [:div.board-settings-container [:button.mlb-reset.board-settings-bt {:data-toggle (when-not is-tablet-or-mobile? "tooltip") :data-placement "top" :data-container "body" :title (str (:name label-data) " edit") :on-click #(label-actions/edit-label label-data)}]])])] (cond is-topics (explore-view) (zero? (count (:boards org-data))) (empty-org) empty-container? (empty-board) Paginated board / container :else (rum/with-key (lazy-stream) paginated-stream-key))]]]))
3199e122b8186aea62145376b60d6442b88894bcac3233fbe683c2bb4168fd14
archimag/rulisp
planet-feeds.lisp
(feed "-univ-etc.blogspot.com/feeds/posts/default/-/lisp/ru") (feed "/") (feed "-ru.blogspot.com/feeds/posts/default/-/lisp") (feed "") (feed "-vk.livejournal.com/data/rss" :category "lisp") (feed "" :category "lisp") (feed "" :category "lisp") (feed "/-/lisp-ru") (feed "/-/lisp") (feed "-49-ru.blogspot.com/feeds/posts/default/-/lisp") (feed "" :category "lisp") (feed "-cad.blogspot.com/feeds/posts/default/-/lisp") (feed "" :category "lisp") (feed "/-/lisp") (feed "/-/lisp") (feed "/-/lisp") (feed "-bazon.blogspot.com/feeds/posts/default/-/lisp") (feed "/-/lisp") (feed "") (feed "" :category "lisp") (feed "" :category "лисп") (feed "-mikhail.blogspot.com/feeds/posts/default/-/common%20lisp") (feed "/-/lisp") (feed "" :category "lisp") (feed "-Lisp/rss")
null
https://raw.githubusercontent.com/archimag/rulisp/2af0d92066572c4665d14dc3ee001c0c5ff84e84/planet-feeds.lisp
lisp
(feed "-univ-etc.blogspot.com/feeds/posts/default/-/lisp/ru") (feed "/") (feed "-ru.blogspot.com/feeds/posts/default/-/lisp") (feed "") (feed "-vk.livejournal.com/data/rss" :category "lisp") (feed "" :category "lisp") (feed "" :category "lisp") (feed "/-/lisp-ru") (feed "/-/lisp") (feed "-49-ru.blogspot.com/feeds/posts/default/-/lisp") (feed "" :category "lisp") (feed "-cad.blogspot.com/feeds/posts/default/-/lisp") (feed "" :category "lisp") (feed "/-/lisp") (feed "/-/lisp") (feed "/-/lisp") (feed "-bazon.blogspot.com/feeds/posts/default/-/lisp") (feed "/-/lisp") (feed "") (feed "" :category "lisp") (feed "" :category "лисп") (feed "-mikhail.blogspot.com/feeds/posts/default/-/common%20lisp") (feed "/-/lisp") (feed "" :category "lisp") (feed "-Lisp/rss")
7f77a8dba9d61121500ea13e77b630764158d8780c658a0760cbe44131e3d635
bcc32/advent-of-code
b.ml
open! Core open! Async open! Import let main () = let%bind events = Reader.with_file "input" ~f:(fun r -> r |> Reader.lines |> Pipe.to_list) (* times can be compared lexicographically *) >>| List.sort ~compare:String.compare >>| List.map ~f:Event.of_string in let guard_minute_count = Hashtbl.create (module Tuple.Hashable_t (Int) (Int)) in events |> Event.analyze |> List.iter ~f:(fun (guard_id, (x, y)) -> for m = x to y - 1 do Hashtbl.incr guard_minute_count (guard_id, m) done); let guard, minute = Hashtbl.to_alist guard_minute_count |> List.max_elt ~compare:(Comparable.lift [%compare: int] ~f:snd) |> Option.value_exn |> fst in printf "%d\n" (guard * minute); return () ;; let%expect_test "b" = let%bind () = main () in [%expect {| 56901 |}]; return () ;;
null
https://raw.githubusercontent.com/bcc32/advent-of-code/86a9387c3d6be2afe07d2657a0607749217b1b77/2018/04/b.ml
ocaml
times can be compared lexicographically
open! Core open! Async open! Import let main () = let%bind events = Reader.with_file "input" ~f:(fun r -> r |> Reader.lines |> Pipe.to_list) >>| List.sort ~compare:String.compare >>| List.map ~f:Event.of_string in let guard_minute_count = Hashtbl.create (module Tuple.Hashable_t (Int) (Int)) in events |> Event.analyze |> List.iter ~f:(fun (guard_id, (x, y)) -> for m = x to y - 1 do Hashtbl.incr guard_minute_count (guard_id, m) done); let guard, minute = Hashtbl.to_alist guard_minute_count |> List.max_elt ~compare:(Comparable.lift [%compare: int] ~f:snd) |> Option.value_exn |> fst in printf "%d\n" (guard * minute); return () ;; let%expect_test "b" = let%bind () = main () in [%expect {| 56901 |}]; return () ;;
4dcb56081a5a74d6a794c4988209ef4b0be120c8f660524fb3bd54ea0728b036
sjl/flax
letters.lisp
(in-package :flax.drawing) (defgeneric letter-paths (character)) (defmethod letter-paths ((character (eql #\Space))) (list)) (defmethod letter-paths ((character (eql #\+))) ;; p₁ ;; | ;; | ;; p₃ ----+---- p₄ ;; | ;; | ;; p₂ (let ((p1 (vec 0.25 0.35)) (p2 (vec 0.25 0.75)) (p3 (vec 0.05 0.55)) (p4 (vec 0.45 0.55))) (list (path (list p1 p2)) (path (list p3 p4))))) (defmethod letter-paths ((character (eql #\-))) (let ((p1 (vec 0.05 0.55)) (p2 (vec 0.45 0.55))) (list (path (list p1 p2))))) (defmethod letter-paths ((character (eql #\L))) ;; p₁ ;; | ;; | ;; | ;; | ;; p₂|______ p₃ (let ((p1 (vec 0.05 0.10)) (p2 (vec 0.05 1.00)) (p3 (vec 0.45 1.00))) (list (path (list p1 p2 p3))))) (defmethod letter-paths ((character (eql #\R))) ;; p₁___ p₃ ;; | \ ;; p₆|___/ p₄ ;; | \ ;; | \ ;; p₂| \ p₅ (let ((p1 (vec 0.05 0.10)) (p2 (vec 0.05 1.00)) (p3 (vec 0.25 0.10)) (p4 (vec 0.25 0.55)) (p5 (vec 0.45 1.00)) (p6 (vec 0.05 0.55))) (list (path (list p1 p2)) (path (list p1 p3 (list p4 (vec 0.45 0.10) (vec 0.45 0.55)) p5)) (path (list p4 p6))))) (defmethod letter-paths ((character (eql #\→))) (let ((p1 (vec 0.05 0.55)) (p2 (vec 0.45 0.55)) (p3 (vec 0.30 0.45)) (p4 (vec 0.30 0.65))) (list (path (list p1 p2)) (path (list p3 p2 p4))))) (defmethod letter-paths ((character (eql #\())) (let ((p1 (vec 0.40 0.10)) (p2 (vec 0.40 1.00))) (list (path (list p1 (list p2 (vec 0.05 0.25) (vec 0.05 0.85))))))) (defmethod letter-paths ((character (eql #\)))) (let ((p1 (vec 0.10 0.10)) (p2 (vec 0.10 1.00))) (list (path (list p1 (list p2 (vec 0.45 0.25) (vec 0.45 0.85))))))) (defgeneric kern (a b)) (defmethod kern ((a character) (b character)) 0.0) (defmethod kern ((a null) b) 0.0) (defmethod kern ((a (eql #\L)) (b (eql #\+))) -0.15) (defmethod kern ((a (eql #\L)) (b (eql #\-))) -0.15) (defmethod kern ((a (eql #\L)) (b (eql #\→))) -0.15) (defmethod kern ((a (eql #\L)) (b (eql #\())) -0.07) (defmethod kern ((a (eql #\R)) (b (eql #\→))) -0.05) (defmethod kern ((a (eql #\R)) (b (eql #\L))) 0.05) (defmethod kern ((a (eql #\→)) (b (eql #\L))) 0.05) (defmethod kern ((a (eql #\→)) (b (eql #\R))) 0.05) (defmethod kern ((a (eql #\()) (b (eql #\-))) -0.05) (defmethod kern ((a (eql #\()) (b (eql #\+))) -0.05) (defmethod kern ((a (eql #\-)) (b (eql #\)))) -0.05) (defmethod kern ((a (eql #\+)) (b (eql #\)))) -0.05)
null
https://raw.githubusercontent.com/sjl/flax/0dc4e7c0d096cd01a1009c8fbd0d96174ed48090/src/drawing/letters.lisp
lisp
p₁ | | p₃ ----+---- p₄ | | p₂ p₁ | | | | p₂|______ p₃ p₁___ p₃ | \ p₆|___/ p₄ | \ | \ p₂| \ p₅
(in-package :flax.drawing) (defgeneric letter-paths (character)) (defmethod letter-paths ((character (eql #\Space))) (list)) (defmethod letter-paths ((character (eql #\+))) (let ((p1 (vec 0.25 0.35)) (p2 (vec 0.25 0.75)) (p3 (vec 0.05 0.55)) (p4 (vec 0.45 0.55))) (list (path (list p1 p2)) (path (list p3 p4))))) (defmethod letter-paths ((character (eql #\-))) (let ((p1 (vec 0.05 0.55)) (p2 (vec 0.45 0.55))) (list (path (list p1 p2))))) (defmethod letter-paths ((character (eql #\L))) (let ((p1 (vec 0.05 0.10)) (p2 (vec 0.05 1.00)) (p3 (vec 0.45 1.00))) (list (path (list p1 p2 p3))))) (defmethod letter-paths ((character (eql #\R))) (let ((p1 (vec 0.05 0.10)) (p2 (vec 0.05 1.00)) (p3 (vec 0.25 0.10)) (p4 (vec 0.25 0.55)) (p5 (vec 0.45 1.00)) (p6 (vec 0.05 0.55))) (list (path (list p1 p2)) (path (list p1 p3 (list p4 (vec 0.45 0.10) (vec 0.45 0.55)) p5)) (path (list p4 p6))))) (defmethod letter-paths ((character (eql #\→))) (let ((p1 (vec 0.05 0.55)) (p2 (vec 0.45 0.55)) (p3 (vec 0.30 0.45)) (p4 (vec 0.30 0.65))) (list (path (list p1 p2)) (path (list p3 p2 p4))))) (defmethod letter-paths ((character (eql #\())) (let ((p1 (vec 0.40 0.10)) (p2 (vec 0.40 1.00))) (list (path (list p1 (list p2 (vec 0.05 0.25) (vec 0.05 0.85))))))) (defmethod letter-paths ((character (eql #\)))) (let ((p1 (vec 0.10 0.10)) (p2 (vec 0.10 1.00))) (list (path (list p1 (list p2 (vec 0.45 0.25) (vec 0.45 0.85))))))) (defgeneric kern (a b)) (defmethod kern ((a character) (b character)) 0.0) (defmethod kern ((a null) b) 0.0) (defmethod kern ((a (eql #\L)) (b (eql #\+))) -0.15) (defmethod kern ((a (eql #\L)) (b (eql #\-))) -0.15) (defmethod kern ((a (eql #\L)) (b (eql #\→))) -0.15) (defmethod kern ((a (eql #\L)) (b (eql #\())) -0.07) (defmethod kern ((a (eql #\R)) (b (eql #\→))) -0.05) (defmethod kern ((a (eql #\R)) (b (eql #\L))) 0.05) (defmethod kern ((a (eql #\→)) (b (eql #\L))) 0.05) (defmethod kern ((a (eql #\→)) (b (eql #\R))) 0.05) (defmethod kern ((a (eql #\()) (b (eql #\-))) -0.05) (defmethod kern ((a (eql #\()) (b (eql #\+))) -0.05) (defmethod kern ((a (eql #\-)) (b (eql #\)))) -0.05) (defmethod kern ((a (eql #\+)) (b (eql #\)))) -0.05)
1038d517cd9d43af78f86224d77d1f4f66fc46d4ee8335c85ff1d579e997a370
tonyg/kali-scheme
check.scm
Copyright ( c ) 1993 , 1994 by and . Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING . ; The barest skeleton of a test suite. ; Mostly it makes sure that many of the external packages load without ; error. ; ,exec ,load debug/check.scm ; (done) (load-package 'testing) (config '(run (define-structure bar (export) (open scheme testing)))) These do n't work in , which lacks shadowing ;(in 'bar '(bench off)) ( in ' bar ' ( run ( define ( foo ) ( cadr ' ( a b ) ) ) ) ) ( in ' bar ' ( run ( define cadr list ) ) ) ;(in 'bar '(run (test "non-bench" equal? '((a b)) (foo)))) ; ;(in 'bar '(bench on)) ;(in 'bar '(run (define (foo) (car '(a b))))) ;(in 'bar '(run (define car list))) ;(in 'bar '(run (test "bench" equal? 'a (foo)))) (config '(run (define-structure test1 (export x) (open scheme testing) (begin (define x 10) (define (z) x))))) (config '(run (define-structure test2 (export) (open scheme test1 testing) (begin (define (z) x))))) (config '(run (define-structure test3 (export) (open scheme test1 testing) (begin (define (z) x))))) (load-package 'test2) (load-package 'test3) (in 'test3 '(run (define x 20))) (in 'test3 '(open test2)) (in 'test2 '(run (test "shadowing" = 10 (z)))) Shadowing does n't work in ( in ' test3 ' ( run ( test " shadowing " = 20 ( z ) ) ) ) (in 'test1 '(run (test "shadowing" = 10 (z)))) (config '(run (define-structure foo (export) (open scheme testing assembler code-vectors ports queues random sort big-scheme arrays dump/restore search-trees threads placeholders locks interrupts sicp) (begin (test "1000 args" equal? '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 ) (let ((f (lambda (x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29 x30 x31 x32 x33 x34 x35 x36 x37 x38 x39 x40 x41 x42 x43 x44 x45 x46 x47 x48 x49 x50 x51 x52 x53 x54 x55 x56 x57 x58 x59 x60 x61 x62 x63 x64 x65 x66 x67 x68 x69 x70 x71 x72 x73 x74 x75 x76 x77 x78 x79 x80 x81 x82 x83 x84 x85 x86 x87 x88 x89 x90 x91 x92 x93 x94 x95 x96 x97 x98 x99 x100 x101 x102 x103 x104 x105 x106 x107 x108 x109 x110 x111 x112 x113 x114 x115 x116 x117 x118 x119 x120 x121 x122 x123 x124 x125 x126 x127 x128 x129 x130 x131 x132 x133 x134 x135 x136 x137 x138 x139 x140 x141 x142 x143 x144 x145 x146 x147 x148 x149 x150 x151 x152 x153 x154 x155 x156 x157 x158 x159 x160 x161 x162 x163 x164 x165 x166 x167 x168 x169 x170 x171 x172 x173 x174 x175 x176 x177 x178 x179 x180 x181 x182 x183 x184 x185 x186 x187 x188 x189 x190 x191 x192 x193 x194 x195 x196 x197 x198 x199 x200 x201 x202 x203 x204 x205 x206 x207 x208 x209 x210 x211 x212 x213 x214 x215 x216 x217 x218 x219 x220 x221 x222 x223 x224 x225 x226 x227 x228 x229 x230 x231 x232 x233 x234 x235 x236 x237 x238 x239 x240 x241 x242 x243 x244 x245 x246 x247 x248 x249 x250 x251 x252 x253 x254 x255 x256 x257 x258 x259 x260 x261 x262 x263 x264 x265 x266 x267 x268 x269 x270 x271 x272 x273 x274 x275 x276 x277 x278 x279 x280 x281 x282 x283 x284 x285 x286 x287 x288 x289 x290 x291 x292 x293 x294 x295 x296 x297 x298 x299 x300 x301 x302 x303 x304 x305 x306 x307 x308 x309 x310 x311 x312 x313 x314 x315 x316 x317 x318 x319 x320 x321 x322 x323 x324 x325 x326 x327 x328 x329 x330 x331 x332 x333 x334 x335 x336 x337 x338 x339 x340 x341 x342 x343 x344 x345 x346 x347 x348 x349 x350 x351 x352 x353 x354 x355 x356 x357 x358 x359 x360 x361 x362 x363 x364 x365 x366 x367 x368 x369 x370 x371 x372 x373 x374 x375 x376 x377 x378 x379 x380 x381 x382 x383 x384 x385 x386 x387 x388 x389 x390 x391 x392 x393 x394 x395 x396 x397 x398 x399 x400 x401 x402 x403 x404 x405 x406 x407 x408 x409 x410 x411 x412 x413 x414 x415 x416 x417 x418 x419 x420 x421 x422 x423 x424 x425 x426 x427 x428 x429 x430 x431 x432 x433 x434 x435 x436 x437 x438 x439 x440 x441 x442 x443 x444 x445 x446 x447 x448 x449 x450 x451 x452 x453 x454 x455 x456 x457 x458 x459 x460 x461 x462 x463 x464 x465 x466 x467 x468 x469 x470 x471 x472 x473 x474 x475 x476 x477 x478 x479 x480 x481 x482 x483 x484 x485 x486 x487 x488 x489 x490 x491 x492 x493 x494 x495 x496 x497 x498 x499 x500 x501 x502 x503 x504 x505 x506 x507 x508 x509 x510 x511 x512 x513 x514 x515 x516 x517 x518 x519 x520 x521 x522 x523 x524 x525 x526 x527 x528 x529 x530 x531 x532 x533 x534 x535 x536 x537 x538 x539 x540 x541 x542 x543 x544 x545 x546 x547 x548 x549 x550 x551 x552 x553 x554 x555 x556 x557 x558 x559 x560 x561 x562 x563 x564 x565 x566 x567 x568 x569 x570 x571 x572 x573 x574 x575 x576 x577 x578 x579 x580 x581 x582 x583 x584 x585 x586 x587 x588 x589 x590 x591 x592 x593 x594 x595 x596 x597 x598 x599 x600 x601 x602 x603 x604 x605 x606 x607 x608 x609 x610 x611 x612 x613 x614 x615 x616 x617 x618 x619 x620 x621 x622 x623 x624 x625 x626 x627 x628 x629 x630 x631 x632 x633 x634 x635 x636 x637 x638 x639 x640 x641 x642 x643 x644 x645 x646 x647 x648 x649 x650 x651 x652 x653 x654 x655 x656 x657 x658 x659 x660 x661 x662 x663 x664 x665 x666 x667 x668 x669 x670 x671 x672 x673 x674 x675 x676 x677 x678 x679 x680 x681 x682 x683 x684 x685 x686 x687 x688 x689 x690 x691 x692 x693 x694 x695 x696 x697 x698 x699 x700 x701 x702 x703 x704 x705 x706 x707 x708 x709 x710 x711 x712 x713 x714 x715 x716 x717 x718 x719 x720 x721 x722 x723 x724 x725 x726 x727 x728 x729 x730 x731 x732 x733 x734 x735 x736 x737 x738 x739 x740 x741 x742 x743 x744 x745 x746 x747 x748 x749 x750 x751 x752 x753 x754 x755 x756 x757 x758 x759 x760 x761 x762 x763 x764 x765 x766 x767 x768 x769 x770 x771 x772 x773 x774 x775 x776 x777 x778 x779 x780 x781 x782 x783 x784 x785 x786 x787 x788 x789 x790 x791 x792 x793 x794 x795 x796 x797 x798 x799 x800 x801 x802 x803 x804 x805 x806 x807 x808 x809 x810 x811 x812 x813 x814 x815 x816 x817 x818 x819 x820 x821 x822 x823 x824 x825 x826 x827 x828 x829 x830 x831 x832 x833 x834 x835 x836 x837 x838 x839 x840 x841 x842 x843 x844 x845 x846 x847 x848 x849 x850 x851 x852 x853 x854 x855 x856 x857 x858 x859 x860 x861 x862 x863 x864 x865 x866 x867 x868 x869 x870 x871 x872 x873 x874 x875 x876 x877 x878 x879 x880 x881 x882 x883 x884 x885 x886 x887 x888 x889 x890 x891 x892 x893 x894 x895 x896 x897 x898 x899 x900 x901 x902 x903 x904 x905 x906 x907 x908 x909 x910 x911 x912 x913 x914 x915 x916 x917 x918 x919 x920 x921 x922 x923 x924 x925 x926 x927 x928 x929 x930 x931 x932 x933 x934 x935 x936 x937 x938 x939 x940 x941 x942 x943 x944 x945 x946 x947 x948 x949 x950 x951 x952 x953 x954 x955 x956 x957 x958 x959 x960 x961 x962 x963 x964 x965 x966 x967 x968 x969 x970 x971 x972 x973 x974 x975 x976 x977 x978 x979 x980 x981 x982 x983 x984 x985 x986 x987 x988 x989 x990 x991 x992 x993 x994 x995 x996 x997 x998 x999 ) (list x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29 x30 x31 x32 x33 x34 x35 x36 x37 x38 x39 x40 x41 x42 x43 x44 x45 x46 x47 x48 x49 x50 x51 x52 x53 x54 x55 x56 x57 x58 x59 x60 x61 x62 x63 x64 x65 x66 x67 x68 x69 x70 x71 x72 x73 x74 x75 x76 x77 x78 x79 x80 x81 x82 x83 x84 x85 x86 x87 x88 x89 x90 x91 x92 x93 x94 x95 x96 x97 x98 x99 x100 x101 x102 x103 x104 x105 x106 x107 x108 x109 x110 x111 x112 x113 x114 x115 x116 x117 x118 x119 x120 x121 x122 x123 x124 x125 x126 x127 x128 x129 x130 x131 x132 x133 x134 x135 x136 x137 x138 x139 x140 x141 x142 x143 x144 x145 x146 x147 x148 x149 x150 x151 x152 x153 x154 x155 x156 x157 x158 x159 x160 x161 x162 x163 x164 x165 x166 x167 x168 x169 x170 x171 x172 x173 x174 x175 x176 x177 x178 x179 x180 x181 x182 x183 x184 x185 x186 x187 x188 x189 x190 x191 x192 x193 x194 x195 x196 x197 x198 x199 x200 x201 x202 x203 x204 x205 x206 x207 x208 x209 x210 x211 x212 x213 x214 x215 x216 x217 x218 x219 x220 x221 x222 x223 x224 x225 x226 x227 x228 x229 x230 x231 x232 x233 x234 x235 x236 x237 x238 x239 x240 x241 x242 x243 x244 x245 x246 x247 x248 x249 x250 x251 x252 x253 x254 x255 x256 x257 x258 x259 x260 x261 x262 x263 x264 x265 x266 x267 x268 x269 x270 x271 x272 x273 x274 x275 x276 x277 x278 x279 x280 x281 x282 x283 x284 x285 x286 x287 x288 x289 x290 x291 x292 x293 x294 x295 x296 x297 x298 x299 x300 x301 x302 x303 x304 x305 x306 x307 x308 x309 x310 x311 x312 x313 x314 x315 x316 x317 x318 x319 x320 x321 x322 x323 x324 x325 x326 x327 x328 x329 x330 x331 x332 x333 x334 x335 x336 x337 x338 x339 x340 x341 x342 x343 x344 x345 x346 x347 x348 x349 x350 x351 x352 x353 x354 x355 x356 x357 x358 x359 x360 x361 x362 x363 x364 x365 x366 x367 x368 x369 x370 x371 x372 x373 x374 x375 x376 x377 x378 x379 x380 x381 x382 x383 x384 x385 x386 x387 x388 x389 x390 x391 x392 x393 x394 x395 x396 x397 x398 x399 x400 x401 x402 x403 x404 x405 x406 x407 x408 x409 x410 x411 x412 x413 x414 x415 x416 x417 x418 x419 x420 x421 x422 x423 x424 x425 x426 x427 x428 x429 x430 x431 x432 x433 x434 x435 x436 x437 x438 x439 x440 x441 x442 x443 x444 x445 x446 x447 x448 x449 x450 x451 x452 x453 x454 x455 x456 x457 x458 x459 x460 x461 x462 x463 x464 x465 x466 x467 x468 x469 x470 x471 x472 x473 x474 x475 x476 x477 x478 x479 x480 x481 x482 x483 x484 x485 x486 x487 x488 x489 x490 x491 x492 x493 x494 x495 x496 x497 x498 x499 x500 x501 x502 x503 x504 x505 x506 x507 x508 x509 x510 x511 x512 x513 x514 x515 x516 x517 x518 x519 x520 x521 x522 x523 x524 x525 x526 x527 x528 x529 x530 x531 x532 x533 x534 x535 x536 x537 x538 x539 x540 x541 x542 x543 x544 x545 x546 x547 x548 x549 x550 x551 x552 x553 x554 x555 x556 x557 x558 x559 x560 x561 x562 x563 x564 x565 x566 x567 x568 x569 x570 x571 x572 x573 x574 x575 x576 x577 x578 x579 x580 x581 x582 x583 x584 x585 x586 x587 x588 x589 x590 x591 x592 x593 x594 x595 x596 x597 x598 x599 x600 x601 x602 x603 x604 x605 x606 x607 x608 x609 x610 x611 x612 x613 x614 x615 x616 x617 x618 x619 x620 x621 x622 x623 x624 x625 x626 x627 x628 x629 x630 x631 x632 x633 x634 x635 x636 x637 x638 x639 x640 x641 x642 x643 x644 x645 x646 x647 x648 x649 x650 x651 x652 x653 x654 x655 x656 x657 x658 x659 x660 x661 x662 x663 x664 x665 x666 x667 x668 x669 x670 x671 x672 x673 x674 x675 x676 x677 x678 x679 x680 x681 x682 x683 x684 x685 x686 x687 x688 x689 x690 x691 x692 x693 x694 x695 x696 x697 x698 x699 x700 x701 x702 x703 x704 x705 x706 x707 x708 x709 x710 x711 x712 x713 x714 x715 x716 x717 x718 x719 x720 x721 x722 x723 x724 x725 x726 x727 x728 x729 x730 x731 x732 x733 x734 x735 x736 x737 x738 x739 x740 x741 x742 x743 x744 x745 x746 x747 x748 x749 x750 x751 x752 x753 x754 x755 x756 x757 x758 x759 x760 x761 x762 x763 x764 x765 x766 x767 x768 x769 x770 x771 x772 x773 x774 x775 x776 x777 x778 x779 x780 x781 x782 x783 x784 x785 x786 x787 x788 x789 x790 x791 x792 x793 x794 x795 x796 x797 x798 x799 x800 x801 x802 x803 x804 x805 x806 x807 x808 x809 x810 x811 x812 x813 x814 x815 x816 x817 x818 x819 x820 x821 x822 x823 x824 x825 x826 x827 x828 x829 x830 x831 x832 x833 x834 x835 x836 x837 x838 x839 x840 x841 x842 x843 x844 x845 x846 x847 x848 x849 x850 x851 x852 x853 x854 x855 x856 x857 x858 x859 x860 x861 x862 x863 x864 x865 x866 x867 x868 x869 x870 x871 x872 x873 x874 x875 x876 x877 x878 x879 x880 x881 x882 x883 x884 x885 x886 x887 x888 x889 x890 x891 x892 x893 x894 x895 x896 x897 x898 x899 x900 x901 x902 x903 x904 x905 x906 x907 x908 x909 x910 x911 x912 x913 x914 x915 x916 x917 x918 x919 x920 x921 x922 x923 x924 x925 x926 x927 x928 x929 x930 x931 x932 x933 x934 x935 x936 x937 x938 x939 x940 x941 x942 x943 x944 x945 x946 x947 x948 x949 x950 x951 x952 x953 x954 x955 x956 x957 x958 x959 x960 x961 x962 x963 x964 x965 x966 x967 x968 x969 x970 x971 x972 x973 x974 x975 x976 x977 x978 x979 x980 x981 x982 x983 x984 x985 x986 x987 x988 x989 x990 x991 x992 x993 x994 x995 x996 x997 x998 x999 )))) (f 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 ))) (test "* 1" = 6 (* 1 2 3)) (test "* 2" = (* 214760876 10) 2147608760) (test "* 3" = (* 47123 46039) 2169495797) (test "internal define" equal? '(20 20 20 20) (list (let () (define a 5) (define b 15) (+ a b)) (let ((b 10)) (define (a) b) (define b 20) (a)) (let ((b 10)) (define b 20) (define (a) b) (a)) (let ((b 10) (a (lambda () 20)) (define (lambda args 30))) (define b 40) (define (a) b) (a)))) (define (identity x) x) ; handy for preventing inlining (let ((port (make-port #f -1 0 #f 0 (make-code-vector 1024 25) 0 1023 #f))) (set-port-index! port 0) (test "read-char0" = 25 (char->ascii (read-char port))) (test "read-char1" = 25 (char->ascii ((identity read-char) port)))) (test "apply" equal? '(1 2 3 4) (apply list 1 2 '(3 4))) (test "char<->integer" eq? #\a (integer->char (char->integer #\a))) (test "lap" equal? #f ((lap #f () (protocol 0) (false) (return)))) (let ((q (make-queue))) (enqueue! q 'a) (test "q" eq? 'a (dequeue! q))) (test "random" <= 0 ((make-random 7))) (test "sort" equal? '(1 2 3 3) (sort-list '(2 3 1 3) <)) (test "bigbit" = (expt 2 100) (arithmetic-shift 1 100)) (test "format" string=? "x(1 2)" (format #f "x~s" '(1 2))) (test "fancy input ports" equal? '(3 5) (let ((p1 (make-tracking-input-port (make-string-input-port " 2 3")))) (read p1) (list (current-row p1) (current-column p1)))) (test "fancy output ports" equal? '(1 4 "8 9") (let* ((r 0) (c 0) (s (call-with-string-output-port (lambda (out) (let ((out (make-tracking-output-port out))) (write 8 out) (fresh-line out) (fresh-line out) (display " 9" out) (set! r (current-row out)) (set! c (current-column out)) (close-output-port out)))))) (list r c s))) (test "write-one-line" string=? "(1 2 3 4 5" (call-with-string-output-port (lambda (out) (write-one-line out 10 (lambda (out) (display '(1 2 3 4 5 6) out)))))) (test "destructure" eq? 'a (destructure (((x (y) z) '(b (a) c))) y)) (test "array" eq? 'a (let ((a (make-array 'b 3 4))) (array-set! a 'a 1 2) (array-ref a 1 2))) (test "R4RS delay" = 3 (letrec ((p (delay (if c 3 (begin (set! c #t) (+ (force p) 1))))) (c #f)) (force p))) (test "receive" equal? '(a b) (receive stuff (values 'a 'b) stuff)) (let ((z '(a "b" 3 #t))) (test "dump" equal? z (let ((q (make-queue))) (dump z (lambda (c) (enqueue! q c)) -1) (restore (lambda () (dequeue! q)))))) (let ((r 0) (l1 (make-lock)) (l2 (make-lock)) (ph (make-placeholder))) (let ((f (lambda (i lock) (spawn (lambda () (let ((v (placeholder-value ph))) (with-interrupts-inhibited (lambda () (set! r (+ i v r)))) (release-lock lock))))))) (obtain-lock l1) (obtain-lock l2) (f 1 l1) (f 2 l2) (placeholder-set! ph 10) (obtain-lock l1) (obtain-lock l2) (test "placeholders" = r 23))) (test "explode" equal? 'ab3 (implode (explode 'ab3))) (test "get/put" equal? 'a (begin (put 'foo 'prop 'a) (get 'foo 'prop))) (test "search-trees" eq? 'a (let ((t (make-search-tree = <))) (search-tree-set! t 3 'b) (search-tree-set! t 4 'a) (search-tree-set! t 5 'c) (search-tree-ref t 4))) )))) (load-package 'foo) (load-package 'floatnums) (in 'foo '(run (let* ((one (exact->inexact 1)) (three (exact->inexact 3)) (third (/ one three)) (xthird (inexact->exact third))) (test "float" eq? #f (= 1/3 xthird)) (test "exact<->inexact" = third (exact->inexact xthird))))) ; All done. (if (in 'testing '(run (lost?))) (display "Some tests failed.") (display "All tests succeeded.")) (newline) (define (done) (exit (if (in 'testing '(run (lost?))) 1 0)))
null
https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/scheme/debug/check.scm
scheme
The barest skeleton of a test suite. Mostly it makes sure that many of the external packages load without error. ,exec ,load debug/check.scm (done) (in 'bar '(bench off)) (in 'bar '(run (test "non-bench" equal? '((a b)) (foo)))) (in 'bar '(bench on)) (in 'bar '(run (define (foo) (car '(a b))))) (in 'bar '(run (define car list))) (in 'bar '(run (test "bench" equal? 'a (foo)))) handy for preventing inlining All done.
Copyright ( c ) 1993 , 1994 by and . Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING . (load-package 'testing) (config '(run (define-structure bar (export) (open scheme testing)))) These do n't work in , which lacks shadowing ( in ' bar ' ( run ( define ( foo ) ( cadr ' ( a b ) ) ) ) ) ( in ' bar ' ( run ( define cadr list ) ) ) (config '(run (define-structure test1 (export x) (open scheme testing) (begin (define x 10) (define (z) x))))) (config '(run (define-structure test2 (export) (open scheme test1 testing) (begin (define (z) x))))) (config '(run (define-structure test3 (export) (open scheme test1 testing) (begin (define (z) x))))) (load-package 'test2) (load-package 'test3) (in 'test3 '(run (define x 20))) (in 'test3 '(open test2)) (in 'test2 '(run (test "shadowing" = 10 (z)))) Shadowing does n't work in ( in ' test3 ' ( run ( test " shadowing " = 20 ( z ) ) ) ) (in 'test1 '(run (test "shadowing" = 10 (z)))) (config '(run (define-structure foo (export) (open scheme testing assembler code-vectors ports queues random sort big-scheme arrays dump/restore search-trees threads placeholders locks interrupts sicp) (begin (test "1000 args" equal? '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 ) (let ((f (lambda (x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29 x30 x31 x32 x33 x34 x35 x36 x37 x38 x39 x40 x41 x42 x43 x44 x45 x46 x47 x48 x49 x50 x51 x52 x53 x54 x55 x56 x57 x58 x59 x60 x61 x62 x63 x64 x65 x66 x67 x68 x69 x70 x71 x72 x73 x74 x75 x76 x77 x78 x79 x80 x81 x82 x83 x84 x85 x86 x87 x88 x89 x90 x91 x92 x93 x94 x95 x96 x97 x98 x99 x100 x101 x102 x103 x104 x105 x106 x107 x108 x109 x110 x111 x112 x113 x114 x115 x116 x117 x118 x119 x120 x121 x122 x123 x124 x125 x126 x127 x128 x129 x130 x131 x132 x133 x134 x135 x136 x137 x138 x139 x140 x141 x142 x143 x144 x145 x146 x147 x148 x149 x150 x151 x152 x153 x154 x155 x156 x157 x158 x159 x160 x161 x162 x163 x164 x165 x166 x167 x168 x169 x170 x171 x172 x173 x174 x175 x176 x177 x178 x179 x180 x181 x182 x183 x184 x185 x186 x187 x188 x189 x190 x191 x192 x193 x194 x195 x196 x197 x198 x199 x200 x201 x202 x203 x204 x205 x206 x207 x208 x209 x210 x211 x212 x213 x214 x215 x216 x217 x218 x219 x220 x221 x222 x223 x224 x225 x226 x227 x228 x229 x230 x231 x232 x233 x234 x235 x236 x237 x238 x239 x240 x241 x242 x243 x244 x245 x246 x247 x248 x249 x250 x251 x252 x253 x254 x255 x256 x257 x258 x259 x260 x261 x262 x263 x264 x265 x266 x267 x268 x269 x270 x271 x272 x273 x274 x275 x276 x277 x278 x279 x280 x281 x282 x283 x284 x285 x286 x287 x288 x289 x290 x291 x292 x293 x294 x295 x296 x297 x298 x299 x300 x301 x302 x303 x304 x305 x306 x307 x308 x309 x310 x311 x312 x313 x314 x315 x316 x317 x318 x319 x320 x321 x322 x323 x324 x325 x326 x327 x328 x329 x330 x331 x332 x333 x334 x335 x336 x337 x338 x339 x340 x341 x342 x343 x344 x345 x346 x347 x348 x349 x350 x351 x352 x353 x354 x355 x356 x357 x358 x359 x360 x361 x362 x363 x364 x365 x366 x367 x368 x369 x370 x371 x372 x373 x374 x375 x376 x377 x378 x379 x380 x381 x382 x383 x384 x385 x386 x387 x388 x389 x390 x391 x392 x393 x394 x395 x396 x397 x398 x399 x400 x401 x402 x403 x404 x405 x406 x407 x408 x409 x410 x411 x412 x413 x414 x415 x416 x417 x418 x419 x420 x421 x422 x423 x424 x425 x426 x427 x428 x429 x430 x431 x432 x433 x434 x435 x436 x437 x438 x439 x440 x441 x442 x443 x444 x445 x446 x447 x448 x449 x450 x451 x452 x453 x454 x455 x456 x457 x458 x459 x460 x461 x462 x463 x464 x465 x466 x467 x468 x469 x470 x471 x472 x473 x474 x475 x476 x477 x478 x479 x480 x481 x482 x483 x484 x485 x486 x487 x488 x489 x490 x491 x492 x493 x494 x495 x496 x497 x498 x499 x500 x501 x502 x503 x504 x505 x506 x507 x508 x509 x510 x511 x512 x513 x514 x515 x516 x517 x518 x519 x520 x521 x522 x523 x524 x525 x526 x527 x528 x529 x530 x531 x532 x533 x534 x535 x536 x537 x538 x539 x540 x541 x542 x543 x544 x545 x546 x547 x548 x549 x550 x551 x552 x553 x554 x555 x556 x557 x558 x559 x560 x561 x562 x563 x564 x565 x566 x567 x568 x569 x570 x571 x572 x573 x574 x575 x576 x577 x578 x579 x580 x581 x582 x583 x584 x585 x586 x587 x588 x589 x590 x591 x592 x593 x594 x595 x596 x597 x598 x599 x600 x601 x602 x603 x604 x605 x606 x607 x608 x609 x610 x611 x612 x613 x614 x615 x616 x617 x618 x619 x620 x621 x622 x623 x624 x625 x626 x627 x628 x629 x630 x631 x632 x633 x634 x635 x636 x637 x638 x639 x640 x641 x642 x643 x644 x645 x646 x647 x648 x649 x650 x651 x652 x653 x654 x655 x656 x657 x658 x659 x660 x661 x662 x663 x664 x665 x666 x667 x668 x669 x670 x671 x672 x673 x674 x675 x676 x677 x678 x679 x680 x681 x682 x683 x684 x685 x686 x687 x688 x689 x690 x691 x692 x693 x694 x695 x696 x697 x698 x699 x700 x701 x702 x703 x704 x705 x706 x707 x708 x709 x710 x711 x712 x713 x714 x715 x716 x717 x718 x719 x720 x721 x722 x723 x724 x725 x726 x727 x728 x729 x730 x731 x732 x733 x734 x735 x736 x737 x738 x739 x740 x741 x742 x743 x744 x745 x746 x747 x748 x749 x750 x751 x752 x753 x754 x755 x756 x757 x758 x759 x760 x761 x762 x763 x764 x765 x766 x767 x768 x769 x770 x771 x772 x773 x774 x775 x776 x777 x778 x779 x780 x781 x782 x783 x784 x785 x786 x787 x788 x789 x790 x791 x792 x793 x794 x795 x796 x797 x798 x799 x800 x801 x802 x803 x804 x805 x806 x807 x808 x809 x810 x811 x812 x813 x814 x815 x816 x817 x818 x819 x820 x821 x822 x823 x824 x825 x826 x827 x828 x829 x830 x831 x832 x833 x834 x835 x836 x837 x838 x839 x840 x841 x842 x843 x844 x845 x846 x847 x848 x849 x850 x851 x852 x853 x854 x855 x856 x857 x858 x859 x860 x861 x862 x863 x864 x865 x866 x867 x868 x869 x870 x871 x872 x873 x874 x875 x876 x877 x878 x879 x880 x881 x882 x883 x884 x885 x886 x887 x888 x889 x890 x891 x892 x893 x894 x895 x896 x897 x898 x899 x900 x901 x902 x903 x904 x905 x906 x907 x908 x909 x910 x911 x912 x913 x914 x915 x916 x917 x918 x919 x920 x921 x922 x923 x924 x925 x926 x927 x928 x929 x930 x931 x932 x933 x934 x935 x936 x937 x938 x939 x940 x941 x942 x943 x944 x945 x946 x947 x948 x949 x950 x951 x952 x953 x954 x955 x956 x957 x958 x959 x960 x961 x962 x963 x964 x965 x966 x967 x968 x969 x970 x971 x972 x973 x974 x975 x976 x977 x978 x979 x980 x981 x982 x983 x984 x985 x986 x987 x988 x989 x990 x991 x992 x993 x994 x995 x996 x997 x998 x999 ) (list x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21 x22 x23 x24 x25 x26 x27 x28 x29 x30 x31 x32 x33 x34 x35 x36 x37 x38 x39 x40 x41 x42 x43 x44 x45 x46 x47 x48 x49 x50 x51 x52 x53 x54 x55 x56 x57 x58 x59 x60 x61 x62 x63 x64 x65 x66 x67 x68 x69 x70 x71 x72 x73 x74 x75 x76 x77 x78 x79 x80 x81 x82 x83 x84 x85 x86 x87 x88 x89 x90 x91 x92 x93 x94 x95 x96 x97 x98 x99 x100 x101 x102 x103 x104 x105 x106 x107 x108 x109 x110 x111 x112 x113 x114 x115 x116 x117 x118 x119 x120 x121 x122 x123 x124 x125 x126 x127 x128 x129 x130 x131 x132 x133 x134 x135 x136 x137 x138 x139 x140 x141 x142 x143 x144 x145 x146 x147 x148 x149 x150 x151 x152 x153 x154 x155 x156 x157 x158 x159 x160 x161 x162 x163 x164 x165 x166 x167 x168 x169 x170 x171 x172 x173 x174 x175 x176 x177 x178 x179 x180 x181 x182 x183 x184 x185 x186 x187 x188 x189 x190 x191 x192 x193 x194 x195 x196 x197 x198 x199 x200 x201 x202 x203 x204 x205 x206 x207 x208 x209 x210 x211 x212 x213 x214 x215 x216 x217 x218 x219 x220 x221 x222 x223 x224 x225 x226 x227 x228 x229 x230 x231 x232 x233 x234 x235 x236 x237 x238 x239 x240 x241 x242 x243 x244 x245 x246 x247 x248 x249 x250 x251 x252 x253 x254 x255 x256 x257 x258 x259 x260 x261 x262 x263 x264 x265 x266 x267 x268 x269 x270 x271 x272 x273 x274 x275 x276 x277 x278 x279 x280 x281 x282 x283 x284 x285 x286 x287 x288 x289 x290 x291 x292 x293 x294 x295 x296 x297 x298 x299 x300 x301 x302 x303 x304 x305 x306 x307 x308 x309 x310 x311 x312 x313 x314 x315 x316 x317 x318 x319 x320 x321 x322 x323 x324 x325 x326 x327 x328 x329 x330 x331 x332 x333 x334 x335 x336 x337 x338 x339 x340 x341 x342 x343 x344 x345 x346 x347 x348 x349 x350 x351 x352 x353 x354 x355 x356 x357 x358 x359 x360 x361 x362 x363 x364 x365 x366 x367 x368 x369 x370 x371 x372 x373 x374 x375 x376 x377 x378 x379 x380 x381 x382 x383 x384 x385 x386 x387 x388 x389 x390 x391 x392 x393 x394 x395 x396 x397 x398 x399 x400 x401 x402 x403 x404 x405 x406 x407 x408 x409 x410 x411 x412 x413 x414 x415 x416 x417 x418 x419 x420 x421 x422 x423 x424 x425 x426 x427 x428 x429 x430 x431 x432 x433 x434 x435 x436 x437 x438 x439 x440 x441 x442 x443 x444 x445 x446 x447 x448 x449 x450 x451 x452 x453 x454 x455 x456 x457 x458 x459 x460 x461 x462 x463 x464 x465 x466 x467 x468 x469 x470 x471 x472 x473 x474 x475 x476 x477 x478 x479 x480 x481 x482 x483 x484 x485 x486 x487 x488 x489 x490 x491 x492 x493 x494 x495 x496 x497 x498 x499 x500 x501 x502 x503 x504 x505 x506 x507 x508 x509 x510 x511 x512 x513 x514 x515 x516 x517 x518 x519 x520 x521 x522 x523 x524 x525 x526 x527 x528 x529 x530 x531 x532 x533 x534 x535 x536 x537 x538 x539 x540 x541 x542 x543 x544 x545 x546 x547 x548 x549 x550 x551 x552 x553 x554 x555 x556 x557 x558 x559 x560 x561 x562 x563 x564 x565 x566 x567 x568 x569 x570 x571 x572 x573 x574 x575 x576 x577 x578 x579 x580 x581 x582 x583 x584 x585 x586 x587 x588 x589 x590 x591 x592 x593 x594 x595 x596 x597 x598 x599 x600 x601 x602 x603 x604 x605 x606 x607 x608 x609 x610 x611 x612 x613 x614 x615 x616 x617 x618 x619 x620 x621 x622 x623 x624 x625 x626 x627 x628 x629 x630 x631 x632 x633 x634 x635 x636 x637 x638 x639 x640 x641 x642 x643 x644 x645 x646 x647 x648 x649 x650 x651 x652 x653 x654 x655 x656 x657 x658 x659 x660 x661 x662 x663 x664 x665 x666 x667 x668 x669 x670 x671 x672 x673 x674 x675 x676 x677 x678 x679 x680 x681 x682 x683 x684 x685 x686 x687 x688 x689 x690 x691 x692 x693 x694 x695 x696 x697 x698 x699 x700 x701 x702 x703 x704 x705 x706 x707 x708 x709 x710 x711 x712 x713 x714 x715 x716 x717 x718 x719 x720 x721 x722 x723 x724 x725 x726 x727 x728 x729 x730 x731 x732 x733 x734 x735 x736 x737 x738 x739 x740 x741 x742 x743 x744 x745 x746 x747 x748 x749 x750 x751 x752 x753 x754 x755 x756 x757 x758 x759 x760 x761 x762 x763 x764 x765 x766 x767 x768 x769 x770 x771 x772 x773 x774 x775 x776 x777 x778 x779 x780 x781 x782 x783 x784 x785 x786 x787 x788 x789 x790 x791 x792 x793 x794 x795 x796 x797 x798 x799 x800 x801 x802 x803 x804 x805 x806 x807 x808 x809 x810 x811 x812 x813 x814 x815 x816 x817 x818 x819 x820 x821 x822 x823 x824 x825 x826 x827 x828 x829 x830 x831 x832 x833 x834 x835 x836 x837 x838 x839 x840 x841 x842 x843 x844 x845 x846 x847 x848 x849 x850 x851 x852 x853 x854 x855 x856 x857 x858 x859 x860 x861 x862 x863 x864 x865 x866 x867 x868 x869 x870 x871 x872 x873 x874 x875 x876 x877 x878 x879 x880 x881 x882 x883 x884 x885 x886 x887 x888 x889 x890 x891 x892 x893 x894 x895 x896 x897 x898 x899 x900 x901 x902 x903 x904 x905 x906 x907 x908 x909 x910 x911 x912 x913 x914 x915 x916 x917 x918 x919 x920 x921 x922 x923 x924 x925 x926 x927 x928 x929 x930 x931 x932 x933 x934 x935 x936 x937 x938 x939 x940 x941 x942 x943 x944 x945 x946 x947 x948 x949 x950 x951 x952 x953 x954 x955 x956 x957 x958 x959 x960 x961 x962 x963 x964 x965 x966 x967 x968 x969 x970 x971 x972 x973 x974 x975 x976 x977 x978 x979 x980 x981 x982 x983 x984 x985 x986 x987 x988 x989 x990 x991 x992 x993 x994 x995 x996 x997 x998 x999 )))) (f 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 ))) (test "* 1" = 6 (* 1 2 3)) (test "* 2" = (* 214760876 10) 2147608760) (test "* 3" = (* 47123 46039) 2169495797) (test "internal define" equal? '(20 20 20 20) (list (let () (define a 5) (define b 15) (+ a b)) (let ((b 10)) (define (a) b) (define b 20) (a)) (let ((b 10)) (define b 20) (define (a) b) (a)) (let ((b 10) (a (lambda () 20)) (define (lambda args 30))) (define b 40) (define (a) b) (a)))) (let ((port (make-port #f -1 0 #f 0 (make-code-vector 1024 25) 0 1023 #f))) (set-port-index! port 0) (test "read-char0" = 25 (char->ascii (read-char port))) (test "read-char1" = 25 (char->ascii ((identity read-char) port)))) (test "apply" equal? '(1 2 3 4) (apply list 1 2 '(3 4))) (test "char<->integer" eq? #\a (integer->char (char->integer #\a))) (test "lap" equal? #f ((lap #f () (protocol 0) (false) (return)))) (let ((q (make-queue))) (enqueue! q 'a) (test "q" eq? 'a (dequeue! q))) (test "random" <= 0 ((make-random 7))) (test "sort" equal? '(1 2 3 3) (sort-list '(2 3 1 3) <)) (test "bigbit" = (expt 2 100) (arithmetic-shift 1 100)) (test "format" string=? "x(1 2)" (format #f "x~s" '(1 2))) (test "fancy input ports" equal? '(3 5) (let ((p1 (make-tracking-input-port (make-string-input-port " 2 3")))) (read p1) (list (current-row p1) (current-column p1)))) (test "fancy output ports" equal? '(1 4 "8 9") (let* ((r 0) (c 0) (s (call-with-string-output-port (lambda (out) (let ((out (make-tracking-output-port out))) (write 8 out) (fresh-line out) (fresh-line out) (display " 9" out) (set! r (current-row out)) (set! c (current-column out)) (close-output-port out)))))) (list r c s))) (test "write-one-line" string=? "(1 2 3 4 5" (call-with-string-output-port (lambda (out) (write-one-line out 10 (lambda (out) (display '(1 2 3 4 5 6) out)))))) (test "destructure" eq? 'a (destructure (((x (y) z) '(b (a) c))) y)) (test "array" eq? 'a (let ((a (make-array 'b 3 4))) (array-set! a 'a 1 2) (array-ref a 1 2))) (test "R4RS delay" = 3 (letrec ((p (delay (if c 3 (begin (set! c #t) (+ (force p) 1))))) (c #f)) (force p))) (test "receive" equal? '(a b) (receive stuff (values 'a 'b) stuff)) (let ((z '(a "b" 3 #t))) (test "dump" equal? z (let ((q (make-queue))) (dump z (lambda (c) (enqueue! q c)) -1) (restore (lambda () (dequeue! q)))))) (let ((r 0) (l1 (make-lock)) (l2 (make-lock)) (ph (make-placeholder))) (let ((f (lambda (i lock) (spawn (lambda () (let ((v (placeholder-value ph))) (with-interrupts-inhibited (lambda () (set! r (+ i v r)))) (release-lock lock))))))) (obtain-lock l1) (obtain-lock l2) (f 1 l1) (f 2 l2) (placeholder-set! ph 10) (obtain-lock l1) (obtain-lock l2) (test "placeholders" = r 23))) (test "explode" equal? 'ab3 (implode (explode 'ab3))) (test "get/put" equal? 'a (begin (put 'foo 'prop 'a) (get 'foo 'prop))) (test "search-trees" eq? 'a (let ((t (make-search-tree = <))) (search-tree-set! t 3 'b) (search-tree-set! t 4 'a) (search-tree-set! t 5 'c) (search-tree-ref t 4))) )))) (load-package 'foo) (load-package 'floatnums) (in 'foo '(run (let* ((one (exact->inexact 1)) (three (exact->inexact 3)) (third (/ one three)) (xthird (inexact->exact third))) (test "float" eq? #f (= 1/3 xthird)) (test "exact<->inexact" = third (exact->inexact xthird))))) (if (in 'testing '(run (lost?))) (display "Some tests failed.") (display "All tests succeeded.")) (newline) (define (done) (exit (if (in 'testing '(run (lost?))) 1 0)))
2cb0d19b749da14a116a117b651fe5851b4ea96ac3318b7e92fca51fc1620420
privet-kitty/cl-competitive
quicksort.lisp
(defpackage :cp/test/quicksort (:use :cl :fiveam :cp/quicksort :cp/displace) (:import-from :cp/test/base #:base-suite)) (in-package :cp/test/quicksort) (in-suite base-suite) ;; FIXME: Resorting to displacement to sort subsequence may be non-standard, though it is no problem on SBCL . (defun sort* (vector order start end) (sort (displace vector start end) order) vector) (defun sort-by2 (vector order) (let* ((n (length vector)) (pair-vector (make-array (ash n -1)))) (dotimes (i (ash n -1)) (setf (aref pair-vector i) (cons (aref vector (* 2 i)) (aref vector (+ 1 (* 2 i)))))) (setq pair-vector (sort pair-vector order :key #'car)) (dotimes (i (ash n -1)) (let ((pair (aref pair-vector i))) (setf (aref vector (* 2 i)) (car pair) (aref vector (+ 1 (* 2 i))) (cdr pair)))) vector)) (test quicksort (let ((*test-dribble* nil)) (dotimes (i 100) (let ((vec (coerce (loop repeat i collect (random 100)) 'vector))) (is (equalp (sort (copy-seq vec) #'>) (quicksort! (copy-seq vec) #'>))))) (dotimes (i 1000) (let ((vec (coerce (loop repeat 10 collect (code-char (+ 97 (random 10)))) 'vector)) (start (random 11)) (end (random 11))) (when (> start end) (rotatef start end)) (is (equalp (quicksort! (copy-seq vec) #'char< :start start :end end) (sort* (copy-seq vec) #'char< start end))))))) (test quicksort-by2 (let ((*test-dribble* nil)) (dotimes (i 1000) (let ((vec (coerce (loop repeat (random 100) for code = (random 50) for char = (code-char code) append (list char code)) 'vector))) (is (equalp (quicksort-by2! (copy-seq vec) #'char<) (sort-by2 (copy-seq vec) #'char<)))))))
null
https://raw.githubusercontent.com/privet-kitty/cl-competitive/4d1c601ff42b10773a5d0c5989b1234da5bb98b6/module/test/quicksort.lisp
lisp
FIXME: Resorting to displacement to sort subsequence may be non-standard,
(defpackage :cp/test/quicksort (:use :cl :fiveam :cp/quicksort :cp/displace) (:import-from :cp/test/base #:base-suite)) (in-package :cp/test/quicksort) (in-suite base-suite) though it is no problem on SBCL . (defun sort* (vector order start end) (sort (displace vector start end) order) vector) (defun sort-by2 (vector order) (let* ((n (length vector)) (pair-vector (make-array (ash n -1)))) (dotimes (i (ash n -1)) (setf (aref pair-vector i) (cons (aref vector (* 2 i)) (aref vector (+ 1 (* 2 i)))))) (setq pair-vector (sort pair-vector order :key #'car)) (dotimes (i (ash n -1)) (let ((pair (aref pair-vector i))) (setf (aref vector (* 2 i)) (car pair) (aref vector (+ 1 (* 2 i))) (cdr pair)))) vector)) (test quicksort (let ((*test-dribble* nil)) (dotimes (i 100) (let ((vec (coerce (loop repeat i collect (random 100)) 'vector))) (is (equalp (sort (copy-seq vec) #'>) (quicksort! (copy-seq vec) #'>))))) (dotimes (i 1000) (let ((vec (coerce (loop repeat 10 collect (code-char (+ 97 (random 10)))) 'vector)) (start (random 11)) (end (random 11))) (when (> start end) (rotatef start end)) (is (equalp (quicksort! (copy-seq vec) #'char< :start start :end end) (sort* (copy-seq vec) #'char< start end))))))) (test quicksort-by2 (let ((*test-dribble* nil)) (dotimes (i 1000) (let ((vec (coerce (loop repeat (random 100) for code = (random 50) for char = (code-char code) append (list char code)) 'vector))) (is (equalp (quicksort-by2! (copy-seq vec) #'char<) (sort-by2 (copy-seq vec) #'char<)))))))
6a66f66cdc34494979fb38dc99ea6a00ca51adfb74bf9e4dcc3a6dc1b8b9a9ca
webyrd/n-grams-for-synthesis
srfi-14-s48-module.scm
SRFI-14 interface for Scheme48 -*- Scheme -*- ;;; Complete interface spec for the SRFI-14 char - set - lib library in the ;;; Scheme48 interface and module language. The interface is fully typed, in ;;; the Scheme48 type notation. The structure definitions also provide a ;;; formal description of the external dependencies of the source code. (define-interface char-set-interface (export (char-set? (proc (:value) :boolean)) ((char-set= char-set<=) (proc (&rest :value) :boolean)) (char-set-hash (proc (:value &opt :exact-integer) :exact-integer)) ;; Cursors are exact integers in the reference implementation. ;; These typings would be different with a different cursor ;; implementation. ;; Too bad Scheme doesn't have abstract data types. (char-set-cursor (proc (:value) :exact-integer)) (char-set-ref (proc (:value :exact-integer) :char)) (char-set-cursor-next (proc (:value :exact-integer) :exact-integer)) (end-of-char-set? (proc (:value) :boolean)) (char-set-fold (proc ((proc (:char :value) :value) :value :value) :value)) (char-set-unfold (proc ((proc (:value) :boolean) (proc (:value) :value) (proc (:value) :value) :value &opt :value) :value)) (char-set-unfold! (proc ((proc (:value) :boolean) (proc (:value) :value) (proc (:value) :value) :value :value) :value)) (char-set-for-each (proc ((proc (:char) :values) :value) :unspecific)) (char-set-map (proc ((proc (:char) :char) :value) :value)) (char-set-copy (proc (:value) :value)) (char-set (proc (&rest :char) :value)) (list->char-set (proc (:value &opt :value) :value)) (list->char-set! (proc (:value :value) :value)) (string->char-set (proc (:value &opt :value) :value)) (string->char-set! (proc (:value :value) :value)) (ucs-range->char-set (proc (:exact-integer :exact-integer &opt :boolean :value) :value)) (ucs-range->char-set! (proc (:exact-integer :exact-integer :boolean :value) :value)) (char-set-filter (proc ((proc (:char) :boolean) :value &opt :value) :value)) (char-set-filter! (proc ((proc (:char) :boolean) :value :value) :value)) (->char-set (proc (:value) :value)) (char-set-size (proc (:value) :exact-integer)) (char-set-count (proc ((proc (:char) :boolean) :value) :exact-integer)) (char-set-contains? (proc (:char :value) :boolean)) (char-set-every (proc ((proc (:char) :boolean) :value) :boolean)) (char-set-any (proc ((proc (:char) :boolean) :value) :value)) ((char-set-adjoin char-set-delete char-set-adjoin! char-set-delete!) (proc (:value &rest :char) :value)) (char-set->list (proc (:value) :value)) (char-set->string (proc (:value) :string)) (char-set-complement (proc (:value) :value)) ((char-set-union char-set-intersection char-set-xor) (proc (&opt :value) :value)) (char-set-difference (proc (:value &opt :value) :value)) (char-set-diff+intersection (proc (:value &rest :value) (some-values :value :value))) (char-set-complement! (proc (:value) :value)) ((char-set-union! char-set-intersection! char-set-xor! char-set-difference!) (proc (:value &opt :value) :value)) (char-set-diff+intersection! (proc (:value :value &rest :value) (some-values :value :value))) char-set:lower-case char-set:upper-case char-set:letter char-set:digit char-set:letter+digit char-set:graphic char-set:printing char-set:whitespace char-set:blank char-set:iso-control char-set:punctuation char-set:symbol char-set:hex-digit char-set:ascii char-set:empty char-set:full )) (define-structure char-set-lib char-set-interface (open error-package ; ERROR procedure nlet-opt ; LET-OPTIONALS* and :OPTIONAL CHAR->ASCII ASCII->CHAR BITWISE - AND DEFINE - RECORD - TYPE / JAR macro . scheme) (begin (define (check-arg pred val caller) (let lp ((val val)) (if (pred val) val (lp (error "Bad argument" val pred caller))))) (define %latin1->char ascii->char) ; Works for S48 (define %char->latin1 char->ascii) ; Works for S48 ;; Here's a SRFI-19 d-r-t defined in terms of jar's almost-identical ;; d-r-t. (define-syntax define-record-type (syntax-rules () ((define-record-type ?name ?stuff ...) (define-record-type/jar ?name ?name ?stuff ...))))) (files srfi-14) (optimize auto-integrate)) ;;; Import jar's DEFINE-RECORD-TYPE macro, and export it under the name DEFINE - RECORD - TYPE / JAR . (define-structure jar-d-r-t-package (export (define-record-type/jar :syntax)) JAR 's record macro scheme) (begin (define-syntax define-record-type/jar (syntax-rules () ((define-record-type/jar ?stuff ...) (define-record-type ?stuff ...))))))
null
https://raw.githubusercontent.com/webyrd/n-grams-for-synthesis/b53b071e53445337d3fe20db0249363aeb9f3e51/datasets/srfi/srfi-14/srfi-14-s48-module.scm
scheme
Scheme48 interface and module language. The interface is fully typed, in the Scheme48 type notation. The structure definitions also provide a formal description of the external dependencies of the source code. Cursors are exact integers in the reference implementation. These typings would be different with a different cursor implementation. Too bad Scheme doesn't have abstract data types. ERROR procedure LET-OPTIONALS* and :OPTIONAL Works for S48 Works for S48 Here's a SRFI-19 d-r-t defined in terms of jar's almost-identical d-r-t. Import jar's DEFINE-RECORD-TYPE macro, and export it under the
SRFI-14 interface for Scheme48 -*- Scheme -*- Complete interface spec for the SRFI-14 char - set - lib library in the (define-interface char-set-interface (export (char-set? (proc (:value) :boolean)) ((char-set= char-set<=) (proc (&rest :value) :boolean)) (char-set-hash (proc (:value &opt :exact-integer) :exact-integer)) (char-set-cursor (proc (:value) :exact-integer)) (char-set-ref (proc (:value :exact-integer) :char)) (char-set-cursor-next (proc (:value :exact-integer) :exact-integer)) (end-of-char-set? (proc (:value) :boolean)) (char-set-fold (proc ((proc (:char :value) :value) :value :value) :value)) (char-set-unfold (proc ((proc (:value) :boolean) (proc (:value) :value) (proc (:value) :value) :value &opt :value) :value)) (char-set-unfold! (proc ((proc (:value) :boolean) (proc (:value) :value) (proc (:value) :value) :value :value) :value)) (char-set-for-each (proc ((proc (:char) :values) :value) :unspecific)) (char-set-map (proc ((proc (:char) :char) :value) :value)) (char-set-copy (proc (:value) :value)) (char-set (proc (&rest :char) :value)) (list->char-set (proc (:value &opt :value) :value)) (list->char-set! (proc (:value :value) :value)) (string->char-set (proc (:value &opt :value) :value)) (string->char-set! (proc (:value :value) :value)) (ucs-range->char-set (proc (:exact-integer :exact-integer &opt :boolean :value) :value)) (ucs-range->char-set! (proc (:exact-integer :exact-integer :boolean :value) :value)) (char-set-filter (proc ((proc (:char) :boolean) :value &opt :value) :value)) (char-set-filter! (proc ((proc (:char) :boolean) :value :value) :value)) (->char-set (proc (:value) :value)) (char-set-size (proc (:value) :exact-integer)) (char-set-count (proc ((proc (:char) :boolean) :value) :exact-integer)) (char-set-contains? (proc (:char :value) :boolean)) (char-set-every (proc ((proc (:char) :boolean) :value) :boolean)) (char-set-any (proc ((proc (:char) :boolean) :value) :value)) ((char-set-adjoin char-set-delete char-set-adjoin! char-set-delete!) (proc (:value &rest :char) :value)) (char-set->list (proc (:value) :value)) (char-set->string (proc (:value) :string)) (char-set-complement (proc (:value) :value)) ((char-set-union char-set-intersection char-set-xor) (proc (&opt :value) :value)) (char-set-difference (proc (:value &opt :value) :value)) (char-set-diff+intersection (proc (:value &rest :value) (some-values :value :value))) (char-set-complement! (proc (:value) :value)) ((char-set-union! char-set-intersection! char-set-xor! char-set-difference!) (proc (:value &opt :value) :value)) (char-set-diff+intersection! (proc (:value :value &rest :value) (some-values :value :value))) char-set:lower-case char-set:upper-case char-set:letter char-set:digit char-set:letter+digit char-set:graphic char-set:printing char-set:whitespace char-set:blank char-set:iso-control char-set:punctuation char-set:symbol char-set:hex-digit char-set:ascii char-set:empty char-set:full )) (define-structure char-set-lib char-set-interface CHAR->ASCII ASCII->CHAR BITWISE - AND DEFINE - RECORD - TYPE / JAR macro . scheme) (begin (define (check-arg pred val caller) (let lp ((val val)) (if (pred val) val (lp (error "Bad argument" val pred caller))))) (define-syntax define-record-type (syntax-rules () ((define-record-type ?name ?stuff ...) (define-record-type/jar ?name ?name ?stuff ...))))) (files srfi-14) (optimize auto-integrate)) name DEFINE - RECORD - TYPE / JAR . (define-structure jar-d-r-t-package (export (define-record-type/jar :syntax)) JAR 's record macro scheme) (begin (define-syntax define-record-type/jar (syntax-rules () ((define-record-type/jar ?stuff ...) (define-record-type ?stuff ...))))))
1ebd6dde383abf7ecbc8d3da442f333ea7895953d75930d9c82e8c71181cb21e
haskell/HTTP
Browser.hs
# LANGUAGE MultiParamTypeClasses , GeneralizedNewtypeDeriving , CPP , FlexibleContexts # | Module : Network . Browser Copyright : See LICENSE file License : BSD Maintainer : Ganesh Sittampalam < > Stability : experimental Portability : non - portable ( not tested ) Session - level interactions over HTTP . The " Network . Browser " goes beyond the basic " Network . HTTP " functionality in providing support for more involved , and real , request / response interactions over HTTP . Additional features supported are : * HTTP Authentication handling * Transparent handling of redirects * Cookie stores + transmission . * Transaction logging * Proxy - mediated connections . Example use : > do > ( _ , ) > < - Network.Browser.browse $ do > setAllowRedirects True -- handle HTTP redirects > request " / " > return ( take 100 ( rspBody rsp ) ) Module : Network.Browser Copyright : See LICENSE file License : BSD Maintainer : Ganesh Sittampalam <> Stability : experimental Portability : non-portable (not tested) Session-level interactions over HTTP. The "Network.Browser" goes beyond the basic "Network.HTTP" functionality in providing support for more involved, and real, request/response interactions over HTTP. Additional features supported are: * HTTP Authentication handling * Transparent handling of redirects * Cookie stores + transmission. * Transaction logging * Proxy-mediated connections. Example use: > do > (_, rsp) > <- Network.Browser.browse $ do > setAllowRedirects True -- handle HTTP redirects > request $ getRequest "/" > return (take 100 (rspBody rsp)) -} module Network.Browser ( BrowserState , BrowserAction -- browser monad, effectively a state monad. , Proxy(..) : : BrowserAction a - > IO a , request -- :: Request -> BrowserAction Response : : BrowserAction t ( BrowserState t ) , withBrowserState -- :: BrowserState t -> BrowserAction t a -> BrowserAction t a : : BrowserAction t ( ) : : BrowserAction t , setMaxRedirects -- :: Int -> BrowserAction t () , getMaxRedirects -- :: BrowserAction t (Maybe Int) , Authority(..) , getAuthorities , setAuthorities , addAuthority , Challenge(..) , Qop(..) , Algorithm(..) , getAuthorityGen , setAuthorityGen , setAllowBasicAuth , getAllowBasicAuth , setMaxErrorRetries -- :: Maybe Int -> BrowserAction t () , getMaxErrorRetries -- :: BrowserAction t (Maybe Int) , setMaxPoolSize -- :: Int -> BrowserAction t () , getMaxPoolSize -- :: BrowserAction t (Maybe Int) , setMaxAuthAttempts -- :: Maybe Int -> BrowserAction t () , getMaxAuthAttempts -- :: BrowserAction t (Maybe Int) , setCookieFilter -- :: (URI -> Cookie -> IO Bool) -> BrowserAction t () , getCookieFilter -- :: BrowserAction t (URI -> Cookie -> IO Bool) , defaultCookieFilter -- :: URI -> Cookie -> IO Bool , userCookieFilter -- :: URI -> Cookie -> IO Bool , Cookie(..) : : BrowserAction t [ Cookie ] , setCookies -- :: [Cookie] -> BrowserAction t () , addCookie -- :: Cookie -> BrowserAction t () , setErrHandler -- :: (String -> IO ()) -> BrowserAction t () , setOutHandler -- :: (String -> IO ()) -> BrowserAction t () , setEventHandler -- :: (BrowserEvent -> BrowserAction t ()) -> BrowserAction t () , BrowserEvent(..) , BrowserEventType(..) , RequestID , setProxy -- :: Proxy -> BrowserAction t () , getProxy -- :: BrowserAction t Proxy : : BrowserAction t ( ) : : BrowserAction t , setDebugLog -- :: Maybe String -> BrowserAction t () , getUserAgent -- :: BrowserAction t String , setUserAgent -- :: String -> BrowserAction t () , out -- :: String -> BrowserAction t () , err -- :: String -> BrowserAction t () , ioAction -- :: IO a -> BrowserAction a , defaultGETRequest , defaultGETRequest_ , formToRequest , uriDefaultTo old and half - baked ; do n't use : , Form(..) , FormVar ) where import Network.URI ( URI(..) , URIAuth(..) , parseURI, parseURIReference, relativeTo ) import Network.StreamDebugger (debugByteStream) import Network.HTTP hiding ( sendHTTP_notify ) import Network.HTTP.HandleStream ( sendHTTP_notify ) import Network.HTTP.Auth import Network.HTTP.Cookie import Network.HTTP.Proxy import Network.Stream ( ConnError(..), Result ) import Network.BufferType #if (MIN_VERSION_base(4,9,0)) && !(MIN_VERSION_base(4,13,0)) import Control.Monad.Fail #endif import Data.Char (toLower) import Data.List (isPrefixOf) import Data.Maybe (fromMaybe, listToMaybe, catMaybes ) #if !MIN_VERSION_base(4,8,0) import Control.Applicative (Applicative (..), (<$>)) #endif import Control.Monad (filterM, forM_, when) import Control.Monad.IO.Class ( MonadIO (..) ) import Control.Monad.State ( MonadState(..), gets, modify, StateT (..), evalStateT, withStateT ) import qualified System.IO ( hSetBuffering, hPutStr, stdout, stdin, hGetChar , BufferMode(NoBuffering, LineBuffering) ) import Data.Time.Clock ( UTCTime, getCurrentTime ) ------------------------------------------------------------------ ----------------------- Cookie Stuff ----------------------------- ------------------------------------------------------------------ -- | @defaultCookieFilter@ is the initial cookie acceptance filter. It welcomes them all into the store @:-)@ defaultCookieFilter :: URI -> Cookie -> IO Bool defaultCookieFilter _url _cky = return True -- | @userCookieFilter@ is a handy acceptance filter, asking the -- user if he/she is willing to accept an incoming cookie before -- adding it to the store. userCookieFilter :: URI -> Cookie -> IO Bool userCookieFilter url cky = do do putStrLn ("Set-Cookie received when requesting: " ++ show url) case ckComment cky of Nothing -> return () Just x -> putStrLn ("Cookie Comment:\n" ++ x) let pth = maybe "" ('/':) (ckPath cky) putStrLn ("Domain/Path: " ++ ckDomain cky ++ pth) putStrLn (ckName cky ++ '=' : ckValue cky) System.IO.hSetBuffering System.IO.stdout System.IO.NoBuffering System.IO.hSetBuffering System.IO.stdin System.IO.NoBuffering System.IO.hPutStr System.IO.stdout "Accept [y/n]? " x <- System.IO.hGetChar System.IO.stdin System.IO.hSetBuffering System.IO.stdin System.IO.LineBuffering System.IO.hSetBuffering System.IO.stdout System.IO.LineBuffering return (toLower x == 'y') | c@ adds a cookie to the browser state , removing duplicates . addCookie :: Cookie -> BrowserAction t () addCookie c = modify (\b -> b{bsCookies = c : filter (/=c) (bsCookies b) }) -- | @setCookies cookies@ replaces the set of cookies known to -- the browser to @cookies@. Useful when wanting to restore cookies -- used across 'browse' invocations. setCookies :: [Cookie] -> BrowserAction t () setCookies cs = modify (\b -> b { bsCookies=cs }) | @getCookies@ returns the current set of cookies known to -- the browser. getCookies :: BrowserAction t [Cookie] getCookies = gets bsCookies -- ...get domain specific cookies... -- ... this needs changing for consistency with rfc2109... -- ... currently too broad. getCookiesFor :: String -> String -> BrowserAction t [Cookie] getCookiesFor dom path = do cks <- getCookies return (filter cookiematch cks) where cookiematch :: Cookie -> Bool cookiematch = cookieMatch (dom,path) -- | @setCookieFilter fn@ sets the cookie acceptance filter to @fn@. setCookieFilter :: (URI -> Cookie -> IO Bool) -> BrowserAction t () setCookieFilter f = modify (\b -> b { bsCookieFilter=f }) -- | @getCookieFilter@ returns the current cookie acceptance filter. getCookieFilter :: BrowserAction t (URI -> Cookie -> IO Bool) getCookieFilter = gets bsCookieFilter ------------------------------------------------------------------ ----------------------- Authorisation Stuff ---------------------- ------------------------------------------------------------------ The browser handles 401 responses in the following manner : 1 ) extract all WWW - Authenticate headers from a 401 response 2 ) rewrite each as a Challenge object , using " headerToChallenge " 3 ) pick a challenge to respond to , usually the strongest challenge understood by the client , using " pickChallenge " 4 ) generate a username / password combination using the browsers " bsAuthorityGen " function ( the default behaviour is to ask the user ) 5 ) build an Authority object based upon the challenge and user data , store this new Authority in the browser state 6 ) convert the Authority to a request header and add this to a request using " withAuthority " 7 ) send the amended request Note that by default requests are annotated with authority headers before the first sending , based upon previously generated Authority objects ( which contain domain information ) . Once a specific authority is added to a rejected request this predictive annotation is suppressed . 407 responses are handled in a similar manner , except a ) Authorities are not collected , only a single proxy authority is kept by the browser b ) If the proxy used by the browser ( type Proxy ) is NoProxy , then a 407 response will generate output on the " err " stream and the response will be returned . Notes : - digest authentication so far ignores qop , so fails to authenticate properly with qop = auth - int challenges - calculates a1 more than necessary - does n't reverse authenticate - does n't properly receive AuthenticationInfo headers , so fails to use next - nonce etc The browser handles 401 responses in the following manner: 1) extract all WWW-Authenticate headers from a 401 response 2) rewrite each as a Challenge object, using "headerToChallenge" 3) pick a challenge to respond to, usually the strongest challenge understood by the client, using "pickChallenge" 4) generate a username/password combination using the browsers "bsAuthorityGen" function (the default behaviour is to ask the user) 5) build an Authority object based upon the challenge and user data, store this new Authority in the browser state 6) convert the Authority to a request header and add this to a request using "withAuthority" 7) send the amended request Note that by default requests are annotated with authority headers before the first sending, based upon previously generated Authority objects (which contain domain information). Once a specific authority is added to a rejected request this predictive annotation is suppressed. 407 responses are handled in a similar manner, except a) Authorities are not collected, only a single proxy authority is kept by the browser b) If the proxy used by the browser (type Proxy) is NoProxy, then a 407 response will generate output on the "err" stream and the response will be returned. Notes: - digest authentication so far ignores qop, so fails to authenticate properly with qop=auth-int challenges - calculates a1 more than necessary - doesn't reverse authenticate - doesn't properly receive AuthenticationInfo headers, so fails to use next-nonce etc -} -- | Return authorities for a given domain and path. -- Assumes "dom" is lower case getAuthFor :: String -> String -> BrowserAction t [Authority] getAuthFor dom pth = getAuthorities >>= return . (filter match) where match :: Authority -> Bool match au@AuthBasic{} = matchURI (auSite au) match au@AuthDigest{} = or (map matchURI (auDomain au)) matchURI :: URI -> Bool matchURI s = (uriToAuthorityString s == dom) && (uriPath s `isPrefixOf` pth) | @getAuthorities@ return the current set of @Authority@s known -- to the browser. getAuthorities :: BrowserAction t [Authority] getAuthorities = gets bsAuthorities @setAuthorities as@ replaces the Browser 's known set of ' Authority 's to @as@. setAuthorities :: [Authority] -> BrowserAction t () setAuthorities as = modify (\b -> b { bsAuthorities=as }) @addAuthority a@ adds ' Authority ' @a@ to the Browser 's -- set of known authorities. addAuthority :: Authority -> BrowserAction t () addAuthority a = modify (\b -> b { bsAuthorities=a:bsAuthorities b }) -- | @getAuthorityGen@ returns the current authority generator getAuthorityGen :: BrowserAction t (URI -> String -> IO (Maybe (String,String))) getAuthorityGen = gets bsAuthorityGen | @setAuthorityGen genAct@ sets the auth generator to @genAct@. setAuthorityGen :: (URI -> String -> IO (Maybe (String,String))) -> BrowserAction t () setAuthorityGen f = modify (\b -> b { bsAuthorityGen=f }) | @setAllowBasicAuth onOff@ enables\/disables HTTP Basic Authentication . setAllowBasicAuth :: Bool -> BrowserAction t () setAllowBasicAuth ba = modify (\b -> b { bsAllowBasicAuth=ba }) getAllowBasicAuth :: BrowserAction t Bool getAllowBasicAuth = gets bsAllowBasicAuth -- | @setMaxAuthAttempts mbMax@ sets the maximum number of authentication attempts -- to do. If @Nothing@, revert to default max. setMaxAuthAttempts :: Maybe Int -> BrowserAction t () setMaxAuthAttempts mb | fromMaybe 0 mb < 0 = return () | otherwise = modify (\ b -> b{bsMaxAuthAttempts=mb}) | @getMaxAuthAttempts@ returns the current auth attempts . If @Nothing@ , -- the browser's default is used. getMaxAuthAttempts :: BrowserAction t (Maybe Int) getMaxAuthAttempts = gets bsMaxAuthAttempts -- | @setMaxErrorRetries mbMax@ sets the maximum number of attempts at -- transmitting a request. If @Nothing@, rever to default max. setMaxErrorRetries :: Maybe Int -> BrowserAction t () setMaxErrorRetries mb | fromMaybe 0 mb < 0 = return () | otherwise = modify (\ b -> b{bsMaxErrorRetries=mb}) -- | @getMaxErrorRetries@ returns the current max number of error retries. getMaxErrorRetries :: BrowserAction t (Maybe Int) getMaxErrorRetries = gets bsMaxErrorRetries -- TO BE CHANGED!!! pickChallenge :: Bool -> [Challenge] -> Maybe Challenge pickChallenge allowBasic [] | allowBasic = Just (ChalBasic "/") -- manufacture a challenge if one missing; more robust. pickChallenge _ ls = listToMaybe ls -- | Retrieve a likely looking authority for a Request. anticipateChallenge :: Request ty -> BrowserAction t (Maybe Authority) anticipateChallenge rq = let uri = rqURI rq in do { authlist <- getAuthFor (uriAuthToString $ reqURIAuth rq) (uriPath uri) ; return (listToMaybe authlist) } -- | Asking the user to respond to a challenge challengeToAuthority :: URI -> Challenge -> BrowserAction t (Maybe Authority) challengeToAuthority uri ch | not (answerable ch) = return Nothing | otherwise = do -- prompt user for authority prompt <- getAuthorityGen userdetails <- liftIO $ prompt uri (chRealm ch) case userdetails of Nothing -> return Nothing Just (u,p) -> return (Just $ buildAuth ch u p) where answerable :: Challenge -> Bool answerable ChalBasic{} = True answerable chall = (chAlgorithm chall) == Just AlgMD5 buildAuth :: Challenge -> String -> String -> Authority buildAuth (ChalBasic r) u p = AuthBasic { auSite=uri , auRealm=r , auUsername=u , auPassword=p } -- note to self: this is a pretty stupid operation -- to perform isn't it? ChalX and AuthX are so very -- similar. buildAuth (ChalDigest r d n o _stale a q) u p = AuthDigest { auRealm=r , auUsername=u , auPassword=p , auDomain=d , auNonce=n , auOpaque=o , auAlgorithm=a , auQop=q } ------------------------------------------------------------------ ---------------- Browser State Actions ------------------------- ------------------------------------------------------------------ -- | @BrowserState@ is the (large) record type tracking the current -- settings of the browser. data BrowserState connection = BS { bsErr, bsOut :: String -> IO () , bsCookies :: [Cookie] , bsCookieFilter :: URI -> Cookie -> IO Bool , bsAuthorityGen :: URI -> String -> IO (Maybe (String,String)) , bsAuthorities :: [Authority] , bsAllowRedirects :: Bool , bsAllowBasicAuth :: Bool , bsMaxRedirects :: Maybe Int , bsMaxErrorRetries :: Maybe Int , bsMaxAuthAttempts :: Maybe Int , bsMaxPoolSize :: Maybe Int , bsConnectionPool :: [connection] , bsCheckProxy :: Bool , bsProxy :: Proxy , bsDebug :: Maybe String , bsEvent :: Maybe (BrowserEvent -> BrowserAction connection ()) , bsRequestID :: RequestID , bsUserAgent :: Maybe String } instance Show (BrowserState t) where show bs = "BrowserState { " ++ shows (bsCookies bs) ("\n" + + show ( bsAuthorities bs ) + + " \n " ++ "AllowRedirects: " ++ shows (bsAllowRedirects bs) "} ") | @BrowserAction@ is the IO monad , but carrying along a ' BrowserState ' . newtype BrowserAction conn a = BA { unBA :: StateT (BrowserState conn) IO a } deriving ( Functor, Applicative, Monad, MonadIO, MonadState (BrowserState conn) #if MIN_VERSION_base(4,9,0) , MonadFail #endif ) runBA :: BrowserState conn -> BrowserAction conn a -> IO a runBA bs = flip evalStateT bs . unBA -- | @browse act@ is the toplevel action to perform a 'BrowserAction'. Example use : @browse ( request ( getRequest yourURL))@. browse :: BrowserAction conn a -> IO a browse = runBA defaultBrowserState -- | The default browser state has the settings defaultBrowserState :: BrowserState t defaultBrowserState = res where res = BS { bsErr = putStrLn , bsOut = putStrLn , bsCookies = [] , bsCookieFilter = defaultCookieFilter , bsAuthorityGen = \ _uri _realm -> do bsErr res "No action for prompting/generating user+password credentials provided (use: setAuthorityGen); returning Nothing" return Nothing , bsAuthorities = [] , bsAllowRedirects = True , bsAllowBasicAuth = False , bsMaxRedirects = Nothing , bsMaxErrorRetries = Nothing , bsMaxAuthAttempts = Nothing , bsMaxPoolSize = Nothing , bsConnectionPool = [] , bsCheckProxy = defaultAutoProxyDetect , bsProxy = noProxy , bsDebug = Nothing , bsEvent = Nothing , bsRequestID = 0 , bsUserAgent = Nothing } {-# DEPRECATED getBrowserState "Use Control.Monad.State.get instead." #-} | @getBrowserState@ returns the current browser config . Useful for restoring state across ' BrowserAction 's . getBrowserState :: BrowserAction t (BrowserState t) getBrowserState = get | @withBrowserAction st act@ performs @act@ with ' BrowserState ' @st@. withBrowserState :: BrowserState t -> BrowserAction t a -> BrowserAction t a withBrowserState bs = BA . withStateT (const bs) . unBA | @nextRequest act@ performs the browser action @act@ as -- the next request, i.e., setting up a new request context -- before doing so. nextRequest :: BrowserAction t a -> BrowserAction t a nextRequest act = do let updReqID st = let rid = succ (bsRequestID st) in rid `seq` st{bsRequestID=rid} modify updReqID act -- | Lifts an IO action into the 'BrowserAction' monad. # DEPRECATED ioAction " Use Control . . Trans.liftIO instead . " # ioAction :: IO a -> BrowserAction t a ioAction = liftIO | @setErrHandler@ sets the IO action to call when -- the browser reports running errors. To disable any -- such, set it to @const (return ())@. setErrHandler :: (String -> IO ()) -> BrowserAction t () setErrHandler h = modify (\b -> b { bsErr=h }) | @setOutHandler@ sets the IO action to call when -- the browser chatters info on its running. To disable any -- such, set it to @const (return ())@. setOutHandler :: (String -> IO ()) -> BrowserAction t () setOutHandler h = modify (\b -> b { bsOut=h }) out, err :: String -> BrowserAction t () out s = do { f <- gets bsOut ; liftIO $ f s } err s = do { f <- gets bsErr ; liftIO $ f s } -- | @setAllowRedirects onOff@ toggles the willingness to follow redirects ( HTTP responses with 3xx status codes ) . setAllowRedirects :: Bool -> BrowserAction t () setAllowRedirects bl = modify (\b -> b {bsAllowRedirects=bl}) -- | @getAllowRedirects@ returns current setting of the do-chase-redirects flag. getAllowRedirects :: BrowserAction t Bool getAllowRedirects = gets bsAllowRedirects -- | @setMaxRedirects maxCount@ sets the maximum number of forwarding hops we are willing to jump through . A no - op if the count is negative ; if zero , the is set to whatever default applies . Notice that setting the redirects count does /not/ enable following of redirects itself ; use -- 'setAllowRedirects' to do so. setMaxRedirects :: Maybe Int -> BrowserAction t () setMaxRedirects c | fromMaybe 0 c < 0 = return () | otherwise = modify (\b -> b{bsMaxRedirects=c}) | @getMaxRedirects@ returns the current setting for the - redirect count . If @Nothing@ , the " Network . Browser " 's default is used . getMaxRedirects :: BrowserAction t (Maybe Int) getMaxRedirects = gets bsMaxRedirects | @setMaxPoolSize maxCount@ sets the maximum size of the connection pool -- that is used to cache connections between requests setMaxPoolSize :: Maybe Int -> BrowserAction t () setMaxPoolSize c = modify (\b -> b{bsMaxPoolSize=c}) -- | @getMaxPoolSize@ gets the maximum size of the connection pool -- that is used to cache connections between requests. If @Nothing@ , the " Network . Browser " 's default is used . getMaxPoolSize :: BrowserAction t (Maybe Int) getMaxPoolSize = gets bsMaxPoolSize -- | @setProxy p@ will disable proxy usage if @p@ is @NoProxy@. If @p@ is @Proxy proxyURL mbAuth@ , then @proxyURL@ is interpreted -- as the URL of the proxy to use, possibly authenticating via ' Authority ' information in @mbAuth@. setProxy :: Proxy -> BrowserAction t () setProxy p = -- Note: if user _explicitly_ sets the proxy, we turn -- off any auto-detection of proxies. modify (\b -> b {bsProxy = p, bsCheckProxy=False}) -- | @getProxy@ returns the current proxy settings. If the auto - proxy flag is set to @True@ , will -- perform the necessary getProxy :: BrowserAction t Proxy getProxy = do p <- gets bsProxy case p of -- Note: if there is a proxy, no need to perform any auto-detect. -- Presumably this is the user's explicit and preferred proxy server. Proxy{} -> return p NoProxy{} -> do flg <- gets bsCheckProxy if not flg then return p else do np <- liftIO $ fetchProxy True{-issue warning on stderr if ill-formed...-} note : this resets the check - proxy flag ; a one - off affair . setProxy np return np | @setCheckForProxy flg@ sets the one - time check for proxy flag to @flg@. If @True@ , the session will try to determine -- the proxy server is locally configured. See 'Network.HTTP.Proxy.fetchProxy' -- for details of how this done. setCheckForProxy :: Bool -> BrowserAction t () setCheckForProxy flg = modify (\ b -> b{bsCheckProxy=flg}) -- | @getCheckForProxy@ returns the current check-proxy setting. Notice that this may not be equal to @True@ if the session has -- set it to that via 'setCheckForProxy' and subsequently performed -- some HTTP protocol interactions. i.e., the flag return represents -- whether a proxy will be checked for again before any future protocol -- interactions. getCheckForProxy :: BrowserAction t Bool getCheckForProxy = gets bsCheckProxy | @setDebugLog mbFile@ turns off debug logging iff @mbFile@ is @Nothing@. If set to @Just fStem@ , logs of browser activity -- is appended to files of the form @fStem-url-authority@, i.e., @fStem@ is just the prefix for a set of log files , one per host / authority . setDebugLog :: Maybe String -> BrowserAction t () setDebugLog v = modify (\b -> b {bsDebug=v}) sets the current @User - Agent:@ string to @ua@. It -- will be used if no explicit user agent header is found in subsequent requests. -- -- A common form of user agent string is @\"name\/version (details)\"@. For example @\"cabal - install/0.10.2 ( HTTP 4000.1.2)\"@. Including the version -- of this HTTP package can be helpful if you ever need to track down HTTP -- compatibility quirks. This version is available via 'httpPackageVersion'. -- For more info see <>. -- setUserAgent :: String -> BrowserAction t () setUserAgent ua = modify (\b -> b{bsUserAgent=Just ua}) | @getUserAgent@ returns the current @User - Agent:@ default string . getUserAgent :: BrowserAction t String getUserAgent = do n <- gets bsUserAgent return (maybe defaultUserAgent id n) -- | @RequestState@ is an internal tallying type keeping track of various -- per-connection counters, like the number of authorization attempts and -- forwards we've gone through. data RequestState = RequestState ^ number of 401 responses so far , reqRedirects :: Int -- ^ number of redirects so far , reqRetries :: Int -- ^ number of retries so far ^ whether to pre - empt 401 response } type RequestID = Int -- yeah, it will wrap around. nullRequestState :: RequestState nullRequestState = RequestState { reqDenies = 0 , reqRedirects = 0 , reqRetries = 0 , reqStopOnDeny = True } | @BrowserEvent@ is the event record type that a user - defined handler , set -- via 'setEventHandler', will be passed. It indicates various state changes -- encountered in the processing of a given 'RequestID', along with timestamps -- at which they occurred. data BrowserEvent = BrowserEvent { browserTimestamp :: UTCTime , browserRequestID :: RequestID , browserRequestURI :: {-URI-}String , browserEventType :: BrowserEventType } | ' ' is the enumerated list of events that the browser -- internals will report to a user-defined event handler. data BrowserEventType = OpenConnection | ReuseConnection | RequestSent | ResponseEnd ResponseData | ResponseFinish {- not yet, you will have to determine these via the ResponseEnd event. | Redirect | AuthChallenge | AuthResponse -} -- | @setEventHandler onBrowserEvent@ configures event handling. If is @Nothing@ , event handling is turned off ; setting it to @Just onEv@ causes the @onEv@ IO action to be -- notified of browser events during the processing of a request -- by the Browser pipeline. setEventHandler :: Maybe (BrowserEvent -> BrowserAction ty ()) -> BrowserAction ty () setEventHandler mbH = modify (\b -> b { bsEvent=mbH}) buildBrowserEvent :: BrowserEventType -> {-URI-}String -> RequestID -> IO BrowserEvent buildBrowserEvent bt uri reqID = do ct <- getCurrentTime return BrowserEvent { browserTimestamp = ct , browserRequestID = reqID , browserRequestURI = uri , browserEventType = bt } reportEvent :: BrowserEventType -> {-URI-}String -> BrowserAction t () reportEvent bt uri = do st <- get case bsEvent st of Nothing -> return () Just evH -> do evt <- liftIO $ buildBrowserEvent bt uri (bsRequestID st) evH evt -- if it fails, we fail. -- | The default number of hops we are willing not to go beyond for -- request forwardings. defaultMaxRetries :: Int defaultMaxRetries = 4 -- | The default number of error retries we are willing to perform. defaultMaxErrorRetries :: Int defaultMaxErrorRetries = 4 -- | The default maximum HTTP Authentication attempts we will make for -- a single request. defaultMaxAuthAttempts :: Int defaultMaxAuthAttempts = 2 -- | The default setting for auto-proxy detection. -- You may change this within a session via 'setAutoProxyDetect'. To avoid initial backwards compatibility issues , leave this as defaultAutoProxyDetect :: Bool defaultAutoProxyDetect = False -- | @request httpRequest@ tries to submit the 'Request' @httpRequest@ to some HTTP server ( possibly going via a /proxy/ , see ' ' . ) -- Upon successful delivery, the URL where the response was fetched from -- is returned along with the 'Response' itself. request :: HStream ty => Request ty -> BrowserAction (HandleStream ty) (URI,Response ty) request req = nextRequest $ do res <- request' nullVal initialState req reportEvent ResponseFinish (show (rqURI req)) case res of Right r -> return r Left e -> do let errStr = ("Network.Browser.request: Error raised " ++ show e) err errStr Prelude.fail errStr where initialState = nullRequestState nullVal = buf_empty bufferOps -- | Internal helper function, explicitly carrying along per-request -- counts. request' :: HStream ty => ty -> RequestState -> Request ty -> BrowserAction (HandleStream ty) (Result (URI,Response ty)) request' nullVal rqState rq = do let uri = rqURI rq failHTTPS uri let uria = reqURIAuth rq -- add cookies to request cookies <- getCookiesFor (uriAuthToString uria) (uriPath uri) Not for now : ( case of " " - > i d xs - > case chopAtDelim ' : ' xs of ( _ , [ ] ) - > i d ( usr , pwd ) - > withAuth AuthBasic { auUserName = usr , auPassword = pwd , auRealm = " / " , auSite = uri } ) $ do (case uriUserInfo uria of "" -> id xs -> case chopAtDelim ':' xs of (_,[]) -> id (usr,pwd) -> withAuth AuthBasic{ auUserName = usr , auPassword = pwd , auRealm = "/" , auSite = uri }) $ do -} when (not $ null cookies) (out $ "Adding cookies to request. Cookie names: " ++ unwords (map ckName cookies)) -- add credentials to request rq' <- if not (reqStopOnDeny rqState) then return rq else do auth <- anticipateChallenge rq case auth of Nothing -> return rq Just x -> return (insertHeader HdrAuthorization (withAuthority x rq) rq) let rq'' = if not $ null cookies then insertHeaders [cookiesToHeader cookies] rq' else rq' p <- getProxy def_ua <- gets bsUserAgent let defaultOpts = case p of NoProxy -> defaultNormalizeRequestOptions{normUserAgent=def_ua} Proxy _ ath -> defaultNormalizeRequestOptions { normForProxy = True , normUserAgent = def_ua , normCustoms = maybe [] (\ authS -> [\ _ r -> insertHeader HdrProxyAuthorization (withAuthority authS r) r]) ath } let final_req = normalizeRequest defaultOpts rq'' out ("Sending:\n" ++ show final_req) e_rsp <- case p of NoProxy -> dorequest (reqURIAuth rq'') final_req Proxy str _ath -> do let notURI | null pt || null hst = URIAuth{ uriUserInfo = "" , uriRegName = str , uriPort = "" } | otherwise = URIAuth{ uriUserInfo = "" , uriRegName = hst , uriPort = pt } If the ' : ' is dropped from port below , dorequest will assume port 80 . Leave it ! where (hst, pt) = span (':'/=) str Proxy can take multiple forms - look for : port first , -- then host:port. Fall back to just the string given (probably a host name). let proxyURIAuth = maybe notURI (\parsed -> maybe notURI id (uriAuthority parsed)) (parseURI str) out $ "proxy uri host: " ++ uriRegName proxyURIAuth ++ ", port: " ++ uriPort proxyURIAuth dorequest proxyURIAuth final_req mbMx <- getMaxErrorRetries case e_rsp of Left v | (reqRetries rqState < fromMaybe defaultMaxErrorRetries mbMx) && (v == ErrorReset || v == ErrorClosed) -> do --empty connnection pool in case connection has become invalid modify (\b -> b { bsConnectionPool=[] }) request' nullVal rqState{reqRetries=succ (reqRetries rqState)} rq | otherwise -> return (Left v) Right rsp -> do out ("Received:\n" ++ show rsp) -- add new cookies to browser state handleCookies uri (uriAuthToString $ reqURIAuth rq) (retrieveHeaders HdrSetCookie rsp) -- Deal with "Connection: close" in response. handleConnectionClose (reqURIAuth rq) (retrieveHeaders HdrConnection rsp) mbMxAuths <- getMaxAuthAttempts case rspCode rsp of (4,0,1) -- Credentials not sent or refused. | reqDenies rqState > fromMaybe defaultMaxAuthAttempts mbMxAuths -> do out "401 - credentials again refused; exceeded retry count (2)" return (Right (uri,rsp)) | otherwise -> do out "401 - credentials not supplied or refused; retrying.." let hdrs = retrieveHeaders HdrWWWAuthenticate rsp flg <- getAllowBasicAuth case pickChallenge flg (catMaybes $ map (headerToChallenge uri) hdrs) of Nothing -> do out "no challenge" return (Right (uri,rsp)) {- do nothing -} Just x -> do au <- challengeToAuthority uri x case au of Nothing -> do out "no auth" return (Right (uri,rsp)) {- do nothing -} Just au' -> do out "Retrying request with new credentials" request' nullVal rqState{ reqDenies = succ(reqDenies rqState) , reqStopOnDeny = False } (insertHeader HdrAuthorization (withAuthority au' rq) rq) (4,0,7) -- Proxy Authentication required | reqDenies rqState > fromMaybe defaultMaxAuthAttempts mbMxAuths -> do out "407 - proxy authentication required; max deny count exceeeded (2)" return (Right (uri,rsp)) | otherwise -> do out "407 - proxy authentication required" let hdrs = retrieveHeaders HdrProxyAuthenticate rsp flg <- getAllowBasicAuth case pickChallenge flg (catMaybes $ map (headerToChallenge uri) hdrs) of Nothing -> return (Right (uri,rsp)) {- do nothing -} Just x -> do au <- challengeToAuthority uri x case au of Nothing -> return (Right (uri,rsp)) {- do nothing -} Just au' -> do pxy <- gets bsProxy case pxy of NoProxy -> do err "Proxy authentication required without proxy!" return (Right (uri,rsp)) Proxy px _ -> do out "Retrying with proxy authentication" setProxy (Proxy px (Just au')) request' nullVal rqState{ reqDenies = succ(reqDenies rqState) , reqStopOnDeny = False } rq (3,0,x) | x `elem` [2,3,1,7] -> do out ("30" ++ show x ++ " - redirect") allow_redirs <- allowRedirect rqState case allow_redirs of False -> return (Right (uri,rsp)) _ -> do case retrieveHeaders HdrLocation rsp of [] -> do err "No Location: header in redirect response" return (Right (uri,rsp)) (Header _ u:_) -> case parseURIReference u of Nothing -> do err ("Parse of Location: header in a redirect response failed: " ++ u) return (Right (uri,rsp)) Just newURI | {-uriScheme newURI_abs /= uriScheme uri && -}(not (supportedScheme newURI_abs)) -> do err ("Unable to handle redirect, unsupported scheme: " ++ show newURI_abs) return (Right (uri, rsp)) | otherwise -> do out ("Redirecting to " ++ show newURI_abs ++ " ...") -- Redirect using GET request method, depending on -- response code. let toGet = x `elem` [2,3] method = if toGet then GET else rqMethod rq rq1 = rq { rqMethod=method, rqURI=newURI_abs } rq2 = if toGet then (replaceHeader HdrContentLength "0") (rq1 {rqBody = nullVal}) else rq1 request' nullVal rqState{ reqDenies = 0 , reqRedirects = succ(reqRedirects rqState) , reqStopOnDeny = True } rq2 where newURI_abs = uriDefaultTo newURI uri (3,0,5) -> case retrieveHeaders HdrLocation rsp of [] -> do err "No Location header in proxy redirect response." return (Right (uri,rsp)) (Header _ u:_) -> case parseURIReference u of Nothing -> do err ("Parse of Location header in a proxy redirect response failed: " ++ u) return (Right (uri,rsp)) Just newuri -> do out ("Retrying with proxy " ++ show newuri ++ "...") setProxy (Proxy (uriToAuthorityString newuri) Nothing) request' nullVal rqState{ reqDenies = 0 , reqRedirects = 0 , reqRetries = succ (reqRetries rqState) , reqStopOnDeny = True } rq _ -> return (Right (uri,rsp)) -- | The internal request handling state machine. dorequest :: (HStream ty) => URIAuth -> Request ty -> BrowserAction (HandleStream ty) (Result (Response ty)) dorequest hst rqst = do pool <- gets bsConnectionPool let uPort = uriAuthPort Nothing{-ToDo: feed in complete URL-} hst conn <- liftIO $ filterM (\c -> c `isTCPConnectedTo` EndPoint (uriRegName hst) uPort) pool rsp <- case conn of [] -> do out ("Creating new connection to " ++ uriAuthToString hst) reportEvent OpenConnection (show (rqURI rqst)) c <- liftIO $ openStream (uriRegName hst) uPort updateConnectionPool c dorequest2 c rqst (c:_) -> do out ("Recovering connection to " ++ uriAuthToString hst) reportEvent ReuseConnection (show (rqURI rqst)) dorequest2 c rqst case rsp of Right (Response a b c _) -> reportEvent (ResponseEnd (a,b,c)) (show (rqURI rqst)) ; _ -> return () return rsp where dorequest2 c r = do dbg <- gets bsDebug st <- get let onSendComplete = maybe (return ()) (\evh -> do x <- buildBrowserEvent RequestSent (show (rqURI r)) (bsRequestID st) runBA st (evh x) return ()) (bsEvent st) liftIO $ maybe (sendHTTP_notify c r onSendComplete) (\ f -> do c' <- debugByteStream (f++'-': uriAuthToString hst) c sendHTTP_notify c' r onSendComplete) dbg updateConnectionPool :: HStream hTy => HandleStream hTy -> BrowserAction (HandleStream hTy) () updateConnectionPool c = do pool <- gets bsConnectionPool let len_pool = length pool maxPoolSize <- fromMaybe defaultMaxPoolSize <$> gets bsMaxPoolSize when (len_pool > maxPoolSize) (liftIO $ close (last pool)) let pool' | len_pool > maxPoolSize = init pool | otherwise = pool when (maxPoolSize > 0) $ modify (\b -> b { bsConnectionPool=c:pool' }) return () -- | Default maximum number of open connections we are willing to have active. defaultMaxPoolSize :: Int defaultMaxPoolSize = 5 cleanConnectionPool :: HStream hTy => URIAuth -> BrowserAction (HandleStream hTy) () cleanConnectionPool uri = do let ep = EndPoint (uriRegName uri) (uriAuthPort Nothing uri) pool <- gets bsConnectionPool bad <- liftIO $ mapM (\c -> c `isTCPConnectedTo` ep) pool let tmp = zip bad pool newpool = map snd $ filter (not . fst) tmp toclose = map snd $ filter fst tmp liftIO $ forM_ toclose close modify (\b -> b { bsConnectionPool = newpool }) handleCookies :: URI -> String -> [Header] -> BrowserAction t () handleCookies _ _ [] = return () -- cut short the silliness. handleCookies uri dom cookieHeaders = do when (not $ null errs) (err $ unlines ("Errors parsing these cookie values: ":errs)) when (not $ null newCookies) (out $ foldl (\x y -> x ++ "\n " ++ show y) "Cookies received:" newCookies) filterfn <- getCookieFilter newCookies' <- liftIO (filterM (filterfn uri) newCookies) when (not $ null newCookies') (out $ "Accepting cookies with names: " ++ unwords (map ckName newCookies')) mapM_ addCookie newCookies' where (errs, newCookies) = processCookieHeaders dom cookieHeaders handleConnectionClose :: HStream hTy => URIAuth -> [Header] -> BrowserAction (HandleStream hTy) () handleConnectionClose _ [] = return () handleConnectionClose uri headers = do let doClose = any (== "close") $ map headerToConnType headers when doClose $ cleanConnectionPool uri where headerToConnType (Header _ t) = map toLower t ------------------------------------------------------------------ ----------------------- Miscellaneous ---------------------------- ------------------------------------------------------------------ allowRedirect :: RequestState -> BrowserAction t Bool allowRedirect rqState = do rd <- getAllowRedirects mbMxRetries <- getMaxRedirects return (rd && (reqRedirects rqState <= fromMaybe defaultMaxRetries mbMxRetries)) -- | Return @True@ iff the package is able to handle requests and responses -- over it. supportedScheme :: URI -> Bool supportedScheme u = uriScheme u == "http:" | @uriDefaultTo a b@ returns a URI that is consistent with the first argument URI @a@ when read in the context of the second URI @b@. If the second argument is not sufficient context for determining -- a full URI then anarchy reins. uriDefaultTo :: URI -> URI -> URI #if MIN_VERSION_network(2,4,0) uriDefaultTo a b = a `relativeTo` b #else uriDefaultTo a b = maybe a id (a `relativeTo` b) #endif -- This form junk is completely untested... type FormVar = (String,String) data Form = Form RequestMethod URI [FormVar] formToRequest :: Form -> Request_String formToRequest (Form m u vs) = let enc = urlEncodeVars vs in case m of GET -> Request { rqMethod=GET , rqHeaders=[ Header HdrContentLength "0" ] , rqBody="" , rqURI=u { uriQuery= '?' : enc } -- What about old query? } POST -> Request { rqMethod=POST , rqHeaders=[ Header HdrContentType "application/x-www-form-urlencoded", Header HdrContentLength (show $ length enc) ] , rqBody=enc , rqURI=u } _ -> error ("unexpected request: " ++ show m)
null
https://raw.githubusercontent.com/haskell/HTTP/0de8def1146967efbbc0bdb4ea8853c6534f6120/Network/Browser.hs
haskell
handle HTTP redirects handle HTTP redirects browser monad, effectively a state monad. :: Request -> BrowserAction Response :: BrowserState t -> BrowserAction t a -> BrowserAction t a :: Int -> BrowserAction t () :: BrowserAction t (Maybe Int) :: Maybe Int -> BrowserAction t () :: BrowserAction t (Maybe Int) :: Int -> BrowserAction t () :: BrowserAction t (Maybe Int) :: Maybe Int -> BrowserAction t () :: BrowserAction t (Maybe Int) :: (URI -> Cookie -> IO Bool) -> BrowserAction t () :: BrowserAction t (URI -> Cookie -> IO Bool) :: URI -> Cookie -> IO Bool :: URI -> Cookie -> IO Bool :: [Cookie] -> BrowserAction t () :: Cookie -> BrowserAction t () :: (String -> IO ()) -> BrowserAction t () :: (String -> IO ()) -> BrowserAction t () :: (BrowserEvent -> BrowserAction t ()) -> BrowserAction t () :: Proxy -> BrowserAction t () :: BrowserAction t Proxy :: Maybe String -> BrowserAction t () :: BrowserAction t String :: String -> BrowserAction t () :: String -> BrowserAction t () :: String -> BrowserAction t () :: IO a -> BrowserAction a ---------------------------------------------------------------- --------------------- Cookie Stuff ----------------------------- ---------------------------------------------------------------- | @defaultCookieFilter@ is the initial cookie acceptance filter. | @userCookieFilter@ is a handy acceptance filter, asking the user if he/she is willing to accept an incoming cookie before adding it to the store. | @setCookies cookies@ replaces the set of cookies known to the browser to @cookies@. Useful when wanting to restore cookies used across 'browse' invocations. the browser. ...get domain specific cookies... ... this needs changing for consistency with rfc2109... ... currently too broad. | @setCookieFilter fn@ sets the cookie acceptance filter to @fn@. | @getCookieFilter@ returns the current cookie acceptance filter. ---------------------------------------------------------------- --------------------- Authorisation Stuff ---------------------- ---------------------------------------------------------------- | Return authorities for a given domain and path. Assumes "dom" is lower case to the browser. set of known authorities. | @getAuthorityGen@ returns the current authority generator | @setMaxAuthAttempts mbMax@ sets the maximum number of authentication attempts to do. If @Nothing@, revert to default max. the browser's default is used. | @setMaxErrorRetries mbMax@ sets the maximum number of attempts at transmitting a request. If @Nothing@, rever to default max. | @getMaxErrorRetries@ returns the current max number of error retries. TO BE CHANGED!!! manufacture a challenge if one missing; more robust. | Retrieve a likely looking authority for a Request. | Asking the user to respond to a challenge prompt user for authority note to self: this is a pretty stupid operation to perform isn't it? ChalX and AuthX are so very similar. ---------------------------------------------------------------- -------------- Browser State Actions ------------------------- ---------------------------------------------------------------- | @BrowserState@ is the (large) record type tracking the current settings of the browser. | @browse act@ is the toplevel action to perform a 'BrowserAction'. | The default browser state has the settings # DEPRECATED getBrowserState "Use Control.Monad.State.get instead." # the next request, i.e., setting up a new request context before doing so. | Lifts an IO action into the 'BrowserAction' monad. the browser reports running errors. To disable any such, set it to @const (return ())@. the browser chatters info on its running. To disable any such, set it to @const (return ())@. | @setAllowRedirects onOff@ toggles the willingness to | @getAllowRedirects@ returns current setting of the do-chase-redirects flag. | @setMaxRedirects maxCount@ sets the maximum number of forwarding hops 'setAllowRedirects' to do so. that is used to cache connections between requests | @getMaxPoolSize@ gets the maximum size of the connection pool that is used to cache connections between requests. | @setProxy p@ will disable proxy usage if @p@ is @NoProxy@. as the URL of the proxy to use, possibly authenticating via Note: if user _explicitly_ sets the proxy, we turn off any auto-detection of proxies. | @getProxy@ returns the current proxy settings. If perform the necessary Note: if there is a proxy, no need to perform any auto-detect. Presumably this is the user's explicit and preferred proxy server. issue warning on stderr if ill-formed... the proxy server is locally configured. See 'Network.HTTP.Proxy.fetchProxy' for details of how this done. | @getCheckForProxy@ returns the current check-proxy setting. set it to that via 'setCheckForProxy' and subsequently performed some HTTP protocol interactions. i.e., the flag return represents whether a proxy will be checked for again before any future protocol interactions. is appended to files of the form @fStem-url-authority@, i.e., will be used if no explicit user agent header is found in subsequent requests. A common form of user agent string is @\"name\/version (details)\"@. For of this HTTP package can be helpful if you ever need to track down HTTP compatibility quirks. This version is available via 'httpPackageVersion'. For more info see <>. | @RequestState@ is an internal tallying type keeping track of various per-connection counters, like the number of authorization attempts and forwards we've gone through. ^ number of redirects so far ^ number of retries so far yeah, it will wrap around. via 'setEventHandler', will be passed. It indicates various state changes encountered in the processing of a given 'RequestID', along with timestamps at which they occurred. URI internals will report to a user-defined event handler. not yet, you will have to determine these via the ResponseEnd event. | Redirect | AuthChallenge | AuthResponse | @setEventHandler onBrowserEvent@ configures event handling. notified of browser events during the processing of a request by the Browser pipeline. URI URI if it fails, we fail. | The default number of hops we are willing not to go beyond for request forwardings. | The default number of error retries we are willing to perform. | The default maximum HTTP Authentication attempts we will make for a single request. | The default setting for auto-proxy detection. You may change this within a session via 'setAutoProxyDetect'. | @request httpRequest@ tries to submit the 'Request' @httpRequest@ Upon successful delivery, the URL where the response was fetched from is returned along with the 'Response' itself. | Internal helper function, explicitly carrying along per-request counts. add cookies to request add credentials to request then host:port. Fall back to just the string given (probably a host name). empty connnection pool in case connection has become invalid add new cookies to browser state Deal with "Connection: close" in response. Credentials not sent or refused. do nothing do nothing Proxy Authentication required do nothing do nothing uriScheme newURI_abs /= uriScheme uri && Redirect using GET request method, depending on response code. | The internal request handling state machine. ToDo: feed in complete URL | Default maximum number of open connections we are willing to have active. cut short the silliness. ---------------------------------------------------------------- --------------------- Miscellaneous ---------------------------- ---------------------------------------------------------------- | Return @True@ iff the package is able to handle requests and responses over it. a full URI then anarchy reins. This form junk is completely untested... What about old query?
# LANGUAGE MultiParamTypeClasses , GeneralizedNewtypeDeriving , CPP , FlexibleContexts # | Module : Network . Browser Copyright : See LICENSE file License : BSD Maintainer : Ganesh Sittampalam < > Stability : experimental Portability : non - portable ( not tested ) Session - level interactions over HTTP . The " Network . Browser " goes beyond the basic " Network . HTTP " functionality in providing support for more involved , and real , request / response interactions over HTTP . Additional features supported are : * HTTP Authentication handling * Transparent handling of redirects * Cookie stores + transmission . * Transaction logging * Proxy - mediated connections . Example use : > do > ( _ , ) > < - Network.Browser.browse $ do > request " / " > return ( take 100 ( rspBody rsp ) ) Module : Network.Browser Copyright : See LICENSE file License : BSD Maintainer : Ganesh Sittampalam <> Stability : experimental Portability : non-portable (not tested) Session-level interactions over HTTP. The "Network.Browser" goes beyond the basic "Network.HTTP" functionality in providing support for more involved, and real, request/response interactions over HTTP. Additional features supported are: * HTTP Authentication handling * Transparent handling of redirects * Cookie stores + transmission. * Transaction logging * Proxy-mediated connections. Example use: > do > (_, rsp) > <- Network.Browser.browse $ do > request $ getRequest "/" > return (take 100 (rspBody rsp)) -} module Network.Browser ( BrowserState , Proxy(..) : : BrowserAction a - > IO a : : BrowserAction t ( BrowserState t ) : : BrowserAction t ( ) : : BrowserAction t , Authority(..) , getAuthorities , setAuthorities , addAuthority , Challenge(..) , Qop(..) , Algorithm(..) , getAuthorityGen , setAuthorityGen , setAllowBasicAuth , getAllowBasicAuth , Cookie(..) : : BrowserAction t [ Cookie ] , BrowserEvent(..) , BrowserEventType(..) , RequestID : : BrowserAction t ( ) : : BrowserAction t , defaultGETRequest , defaultGETRequest_ , formToRequest , uriDefaultTo old and half - baked ; do n't use : , Form(..) , FormVar ) where import Network.URI ( URI(..) , URIAuth(..) , parseURI, parseURIReference, relativeTo ) import Network.StreamDebugger (debugByteStream) import Network.HTTP hiding ( sendHTTP_notify ) import Network.HTTP.HandleStream ( sendHTTP_notify ) import Network.HTTP.Auth import Network.HTTP.Cookie import Network.HTTP.Proxy import Network.Stream ( ConnError(..), Result ) import Network.BufferType #if (MIN_VERSION_base(4,9,0)) && !(MIN_VERSION_base(4,13,0)) import Control.Monad.Fail #endif import Data.Char (toLower) import Data.List (isPrefixOf) import Data.Maybe (fromMaybe, listToMaybe, catMaybes ) #if !MIN_VERSION_base(4,8,0) import Control.Applicative (Applicative (..), (<$>)) #endif import Control.Monad (filterM, forM_, when) import Control.Monad.IO.Class ( MonadIO (..) ) import Control.Monad.State ( MonadState(..), gets, modify, StateT (..), evalStateT, withStateT ) import qualified System.IO ( hSetBuffering, hPutStr, stdout, stdin, hGetChar , BufferMode(NoBuffering, LineBuffering) ) import Data.Time.Clock ( UTCTime, getCurrentTime ) It welcomes them all into the store @:-)@ defaultCookieFilter :: URI -> Cookie -> IO Bool defaultCookieFilter _url _cky = return True userCookieFilter :: URI -> Cookie -> IO Bool userCookieFilter url cky = do do putStrLn ("Set-Cookie received when requesting: " ++ show url) case ckComment cky of Nothing -> return () Just x -> putStrLn ("Cookie Comment:\n" ++ x) let pth = maybe "" ('/':) (ckPath cky) putStrLn ("Domain/Path: " ++ ckDomain cky ++ pth) putStrLn (ckName cky ++ '=' : ckValue cky) System.IO.hSetBuffering System.IO.stdout System.IO.NoBuffering System.IO.hSetBuffering System.IO.stdin System.IO.NoBuffering System.IO.hPutStr System.IO.stdout "Accept [y/n]? " x <- System.IO.hGetChar System.IO.stdin System.IO.hSetBuffering System.IO.stdin System.IO.LineBuffering System.IO.hSetBuffering System.IO.stdout System.IO.LineBuffering return (toLower x == 'y') | c@ adds a cookie to the browser state , removing duplicates . addCookie :: Cookie -> BrowserAction t () addCookie c = modify (\b -> b{bsCookies = c : filter (/=c) (bsCookies b) }) setCookies :: [Cookie] -> BrowserAction t () setCookies cs = modify (\b -> b { bsCookies=cs }) | @getCookies@ returns the current set of cookies known to getCookies :: BrowserAction t [Cookie] getCookies = gets bsCookies getCookiesFor :: String -> String -> BrowserAction t [Cookie] getCookiesFor dom path = do cks <- getCookies return (filter cookiematch cks) where cookiematch :: Cookie -> Bool cookiematch = cookieMatch (dom,path) setCookieFilter :: (URI -> Cookie -> IO Bool) -> BrowserAction t () setCookieFilter f = modify (\b -> b { bsCookieFilter=f }) getCookieFilter :: BrowserAction t (URI -> Cookie -> IO Bool) getCookieFilter = gets bsCookieFilter The browser handles 401 responses in the following manner : 1 ) extract all WWW - Authenticate headers from a 401 response 2 ) rewrite each as a Challenge object , using " headerToChallenge " 3 ) pick a challenge to respond to , usually the strongest challenge understood by the client , using " pickChallenge " 4 ) generate a username / password combination using the browsers " bsAuthorityGen " function ( the default behaviour is to ask the user ) 5 ) build an Authority object based upon the challenge and user data , store this new Authority in the browser state 6 ) convert the Authority to a request header and add this to a request using " withAuthority " 7 ) send the amended request Note that by default requests are annotated with authority headers before the first sending , based upon previously generated Authority objects ( which contain domain information ) . Once a specific authority is added to a rejected request this predictive annotation is suppressed . 407 responses are handled in a similar manner , except a ) Authorities are not collected , only a single proxy authority is kept by the browser b ) If the proxy used by the browser ( type Proxy ) is NoProxy , then a 407 response will generate output on the " err " stream and the response will be returned . Notes : - digest authentication so far ignores qop , so fails to authenticate properly with qop = auth - int challenges - calculates a1 more than necessary - does n't reverse authenticate - does n't properly receive AuthenticationInfo headers , so fails to use next - nonce etc The browser handles 401 responses in the following manner: 1) extract all WWW-Authenticate headers from a 401 response 2) rewrite each as a Challenge object, using "headerToChallenge" 3) pick a challenge to respond to, usually the strongest challenge understood by the client, using "pickChallenge" 4) generate a username/password combination using the browsers "bsAuthorityGen" function (the default behaviour is to ask the user) 5) build an Authority object based upon the challenge and user data, store this new Authority in the browser state 6) convert the Authority to a request header and add this to a request using "withAuthority" 7) send the amended request Note that by default requests are annotated with authority headers before the first sending, based upon previously generated Authority objects (which contain domain information). Once a specific authority is added to a rejected request this predictive annotation is suppressed. 407 responses are handled in a similar manner, except a) Authorities are not collected, only a single proxy authority is kept by the browser b) If the proxy used by the browser (type Proxy) is NoProxy, then a 407 response will generate output on the "err" stream and the response will be returned. Notes: - digest authentication so far ignores qop, so fails to authenticate properly with qop=auth-int challenges - calculates a1 more than necessary - doesn't reverse authenticate - doesn't properly receive AuthenticationInfo headers, so fails to use next-nonce etc -} getAuthFor :: String -> String -> BrowserAction t [Authority] getAuthFor dom pth = getAuthorities >>= return . (filter match) where match :: Authority -> Bool match au@AuthBasic{} = matchURI (auSite au) match au@AuthDigest{} = or (map matchURI (auDomain au)) matchURI :: URI -> Bool matchURI s = (uriToAuthorityString s == dom) && (uriPath s `isPrefixOf` pth) | @getAuthorities@ return the current set of @Authority@s known getAuthorities :: BrowserAction t [Authority] getAuthorities = gets bsAuthorities @setAuthorities as@ replaces the Browser 's known set of ' Authority 's to @as@. setAuthorities :: [Authority] -> BrowserAction t () setAuthorities as = modify (\b -> b { bsAuthorities=as }) @addAuthority a@ adds ' Authority ' @a@ to the Browser 's addAuthority :: Authority -> BrowserAction t () addAuthority a = modify (\b -> b { bsAuthorities=a:bsAuthorities b }) getAuthorityGen :: BrowserAction t (URI -> String -> IO (Maybe (String,String))) getAuthorityGen = gets bsAuthorityGen | @setAuthorityGen genAct@ sets the auth generator to @genAct@. setAuthorityGen :: (URI -> String -> IO (Maybe (String,String))) -> BrowserAction t () setAuthorityGen f = modify (\b -> b { bsAuthorityGen=f }) | @setAllowBasicAuth onOff@ enables\/disables HTTP Basic Authentication . setAllowBasicAuth :: Bool -> BrowserAction t () setAllowBasicAuth ba = modify (\b -> b { bsAllowBasicAuth=ba }) getAllowBasicAuth :: BrowserAction t Bool getAllowBasicAuth = gets bsAllowBasicAuth setMaxAuthAttempts :: Maybe Int -> BrowserAction t () setMaxAuthAttempts mb | fromMaybe 0 mb < 0 = return () | otherwise = modify (\ b -> b{bsMaxAuthAttempts=mb}) | @getMaxAuthAttempts@ returns the current auth attempts . If @Nothing@ , getMaxAuthAttempts :: BrowserAction t (Maybe Int) getMaxAuthAttempts = gets bsMaxAuthAttempts setMaxErrorRetries :: Maybe Int -> BrowserAction t () setMaxErrorRetries mb | fromMaybe 0 mb < 0 = return () | otherwise = modify (\ b -> b{bsMaxErrorRetries=mb}) getMaxErrorRetries :: BrowserAction t (Maybe Int) getMaxErrorRetries = gets bsMaxErrorRetries pickChallenge :: Bool -> [Challenge] -> Maybe Challenge pickChallenge allowBasic [] pickChallenge _ ls = listToMaybe ls anticipateChallenge :: Request ty -> BrowserAction t (Maybe Authority) anticipateChallenge rq = let uri = rqURI rq in do { authlist <- getAuthFor (uriAuthToString $ reqURIAuth rq) (uriPath uri) ; return (listToMaybe authlist) } challengeToAuthority :: URI -> Challenge -> BrowserAction t (Maybe Authority) challengeToAuthority uri ch | not (answerable ch) = return Nothing | otherwise = do prompt <- getAuthorityGen userdetails <- liftIO $ prompt uri (chRealm ch) case userdetails of Nothing -> return Nothing Just (u,p) -> return (Just $ buildAuth ch u p) where answerable :: Challenge -> Bool answerable ChalBasic{} = True answerable chall = (chAlgorithm chall) == Just AlgMD5 buildAuth :: Challenge -> String -> String -> Authority buildAuth (ChalBasic r) u p = AuthBasic { auSite=uri , auRealm=r , auUsername=u , auPassword=p } buildAuth (ChalDigest r d n o _stale a q) u p = AuthDigest { auRealm=r , auUsername=u , auPassword=p , auDomain=d , auNonce=n , auOpaque=o , auAlgorithm=a , auQop=q } data BrowserState connection = BS { bsErr, bsOut :: String -> IO () , bsCookies :: [Cookie] , bsCookieFilter :: URI -> Cookie -> IO Bool , bsAuthorityGen :: URI -> String -> IO (Maybe (String,String)) , bsAuthorities :: [Authority] , bsAllowRedirects :: Bool , bsAllowBasicAuth :: Bool , bsMaxRedirects :: Maybe Int , bsMaxErrorRetries :: Maybe Int , bsMaxAuthAttempts :: Maybe Int , bsMaxPoolSize :: Maybe Int , bsConnectionPool :: [connection] , bsCheckProxy :: Bool , bsProxy :: Proxy , bsDebug :: Maybe String , bsEvent :: Maybe (BrowserEvent -> BrowserAction connection ()) , bsRequestID :: RequestID , bsUserAgent :: Maybe String } instance Show (BrowserState t) where show bs = "BrowserState { " ++ shows (bsCookies bs) ("\n" + + show ( bsAuthorities bs ) + + " \n " ++ "AllowRedirects: " ++ shows (bsAllowRedirects bs) "} ") | @BrowserAction@ is the IO monad , but carrying along a ' BrowserState ' . newtype BrowserAction conn a = BA { unBA :: StateT (BrowserState conn) IO a } deriving ( Functor, Applicative, Monad, MonadIO, MonadState (BrowserState conn) #if MIN_VERSION_base(4,9,0) , MonadFail #endif ) runBA :: BrowserState conn -> BrowserAction conn a -> IO a runBA bs = flip evalStateT bs . unBA Example use : @browse ( request ( getRequest yourURL))@. browse :: BrowserAction conn a -> IO a browse = runBA defaultBrowserState defaultBrowserState :: BrowserState t defaultBrowserState = res where res = BS { bsErr = putStrLn , bsOut = putStrLn , bsCookies = [] , bsCookieFilter = defaultCookieFilter , bsAuthorityGen = \ _uri _realm -> do bsErr res "No action for prompting/generating user+password credentials provided (use: setAuthorityGen); returning Nothing" return Nothing , bsAuthorities = [] , bsAllowRedirects = True , bsAllowBasicAuth = False , bsMaxRedirects = Nothing , bsMaxErrorRetries = Nothing , bsMaxAuthAttempts = Nothing , bsMaxPoolSize = Nothing , bsConnectionPool = [] , bsCheckProxy = defaultAutoProxyDetect , bsProxy = noProxy , bsDebug = Nothing , bsEvent = Nothing , bsRequestID = 0 , bsUserAgent = Nothing } | @getBrowserState@ returns the current browser config . Useful for restoring state across ' BrowserAction 's . getBrowserState :: BrowserAction t (BrowserState t) getBrowserState = get | @withBrowserAction st act@ performs @act@ with ' BrowserState ' @st@. withBrowserState :: BrowserState t -> BrowserAction t a -> BrowserAction t a withBrowserState bs = BA . withStateT (const bs) . unBA | @nextRequest act@ performs the browser action @act@ as nextRequest :: BrowserAction t a -> BrowserAction t a nextRequest act = do let updReqID st = let rid = succ (bsRequestID st) in rid `seq` st{bsRequestID=rid} modify updReqID act # DEPRECATED ioAction " Use Control . . Trans.liftIO instead . " # ioAction :: IO a -> BrowserAction t a ioAction = liftIO | @setErrHandler@ sets the IO action to call when setErrHandler :: (String -> IO ()) -> BrowserAction t () setErrHandler h = modify (\b -> b { bsErr=h }) | @setOutHandler@ sets the IO action to call when setOutHandler :: (String -> IO ()) -> BrowserAction t () setOutHandler h = modify (\b -> b { bsOut=h }) out, err :: String -> BrowserAction t () out s = do { f <- gets bsOut ; liftIO $ f s } err s = do { f <- gets bsErr ; liftIO $ f s } follow redirects ( HTTP responses with 3xx status codes ) . setAllowRedirects :: Bool -> BrowserAction t () setAllowRedirects bl = modify (\b -> b {bsAllowRedirects=bl}) getAllowRedirects :: BrowserAction t Bool getAllowRedirects = gets bsAllowRedirects we are willing to jump through . A no - op if the count is negative ; if zero , the is set to whatever default applies . Notice that setting the redirects count does /not/ enable following of redirects itself ; use setMaxRedirects :: Maybe Int -> BrowserAction t () setMaxRedirects c | fromMaybe 0 c < 0 = return () | otherwise = modify (\b -> b{bsMaxRedirects=c}) | @getMaxRedirects@ returns the current setting for the - redirect count . If @Nothing@ , the " Network . Browser " 's default is used . getMaxRedirects :: BrowserAction t (Maybe Int) getMaxRedirects = gets bsMaxRedirects | @setMaxPoolSize maxCount@ sets the maximum size of the connection pool setMaxPoolSize :: Maybe Int -> BrowserAction t () setMaxPoolSize c = modify (\b -> b{bsMaxPoolSize=c}) If @Nothing@ , the " Network . Browser " 's default is used . getMaxPoolSize :: BrowserAction t (Maybe Int) getMaxPoolSize = gets bsMaxPoolSize If @p@ is @Proxy proxyURL mbAuth@ , then @proxyURL@ is interpreted ' Authority ' information in @mbAuth@. setProxy :: Proxy -> BrowserAction t () setProxy p = modify (\b -> b {bsProxy = p, bsCheckProxy=False}) the auto - proxy flag is set to @True@ , will getProxy :: BrowserAction t Proxy getProxy = do p <- gets bsProxy case p of Proxy{} -> return p NoProxy{} -> do flg <- gets bsCheckProxy if not flg then return p else do note : this resets the check - proxy flag ; a one - off affair . setProxy np return np | @setCheckForProxy flg@ sets the one - time check for proxy flag to @flg@. If @True@ , the session will try to determine setCheckForProxy :: Bool -> BrowserAction t () setCheckForProxy flg = modify (\ b -> b{bsCheckProxy=flg}) Notice that this may not be equal to @True@ if the session has getCheckForProxy :: BrowserAction t Bool getCheckForProxy = gets bsCheckProxy | @setDebugLog mbFile@ turns off debug logging iff @mbFile@ is @Nothing@. If set to @Just fStem@ , logs of browser activity @fStem@ is just the prefix for a set of log files , one per host / authority . setDebugLog :: Maybe String -> BrowserAction t () setDebugLog v = modify (\b -> b {bsDebug=v}) sets the current @User - Agent:@ string to @ua@. It example @\"cabal - install/0.10.2 ( HTTP 4000.1.2)\"@. Including the version setUserAgent :: String -> BrowserAction t () setUserAgent ua = modify (\b -> b{bsUserAgent=Just ua}) | @getUserAgent@ returns the current @User - Agent:@ default string . getUserAgent :: BrowserAction t String getUserAgent = do n <- gets bsUserAgent return (maybe defaultUserAgent id n) data RequestState = RequestState ^ number of 401 responses so far ^ whether to pre - empt 401 response } nullRequestState :: RequestState nullRequestState = RequestState { reqDenies = 0 , reqRedirects = 0 , reqRetries = 0 , reqStopOnDeny = True } | @BrowserEvent@ is the event record type that a user - defined handler , set data BrowserEvent = BrowserEvent { browserTimestamp :: UTCTime , browserRequestID :: RequestID , browserEventType :: BrowserEventType } | ' ' is the enumerated list of events that the browser data BrowserEventType = OpenConnection | ReuseConnection | RequestSent | ResponseEnd ResponseData | ResponseFinish If is @Nothing@ , event handling is turned off ; setting it to @Just onEv@ causes the @onEv@ IO action to be setEventHandler :: Maybe (BrowserEvent -> BrowserAction ty ()) -> BrowserAction ty () setEventHandler mbH = modify (\b -> b { bsEvent=mbH}) buildBrowserEvent bt uri reqID = do ct <- getCurrentTime return BrowserEvent { browserTimestamp = ct , browserRequestID = reqID , browserRequestURI = uri , browserEventType = bt } reportEvent bt uri = do st <- get case bsEvent st of Nothing -> return () Just evH -> do evt <- liftIO $ buildBrowserEvent bt uri (bsRequestID st) defaultMaxRetries :: Int defaultMaxRetries = 4 defaultMaxErrorRetries :: Int defaultMaxErrorRetries = 4 defaultMaxAuthAttempts :: Int defaultMaxAuthAttempts = 2 To avoid initial backwards compatibility issues , leave this as defaultAutoProxyDetect :: Bool defaultAutoProxyDetect = False to some HTTP server ( possibly going via a /proxy/ , see ' ' . ) request :: HStream ty => Request ty -> BrowserAction (HandleStream ty) (URI,Response ty) request req = nextRequest $ do res <- request' nullVal initialState req reportEvent ResponseFinish (show (rqURI req)) case res of Right r -> return r Left e -> do let errStr = ("Network.Browser.request: Error raised " ++ show e) err errStr Prelude.fail errStr where initialState = nullRequestState nullVal = buf_empty bufferOps request' :: HStream ty => ty -> RequestState -> Request ty -> BrowserAction (HandleStream ty) (Result (URI,Response ty)) request' nullVal rqState rq = do let uri = rqURI rq failHTTPS uri let uria = reqURIAuth rq cookies <- getCookiesFor (uriAuthToString uria) (uriPath uri) Not for now : ( case of " " - > i d xs - > case chopAtDelim ' : ' xs of ( _ , [ ] ) - > i d ( usr , pwd ) - > withAuth AuthBasic { auUserName = usr , auPassword = pwd , auRealm = " / " , auSite = uri } ) $ do (case uriUserInfo uria of "" -> id xs -> case chopAtDelim ':' xs of (_,[]) -> id (usr,pwd) -> withAuth AuthBasic{ auUserName = usr , auPassword = pwd , auRealm = "/" , auSite = uri }) $ do -} when (not $ null cookies) (out $ "Adding cookies to request. Cookie names: " ++ unwords (map ckName cookies)) rq' <- if not (reqStopOnDeny rqState) then return rq else do auth <- anticipateChallenge rq case auth of Nothing -> return rq Just x -> return (insertHeader HdrAuthorization (withAuthority x rq) rq) let rq'' = if not $ null cookies then insertHeaders [cookiesToHeader cookies] rq' else rq' p <- getProxy def_ua <- gets bsUserAgent let defaultOpts = case p of NoProxy -> defaultNormalizeRequestOptions{normUserAgent=def_ua} Proxy _ ath -> defaultNormalizeRequestOptions { normForProxy = True , normUserAgent = def_ua , normCustoms = maybe [] (\ authS -> [\ _ r -> insertHeader HdrProxyAuthorization (withAuthority authS r) r]) ath } let final_req = normalizeRequest defaultOpts rq'' out ("Sending:\n" ++ show final_req) e_rsp <- case p of NoProxy -> dorequest (reqURIAuth rq'') final_req Proxy str _ath -> do let notURI | null pt || null hst = URIAuth{ uriUserInfo = "" , uriRegName = str , uriPort = "" } | otherwise = URIAuth{ uriUserInfo = "" , uriRegName = hst , uriPort = pt } If the ' : ' is dropped from port below , dorequest will assume port 80 . Leave it ! where (hst, pt) = span (':'/=) str Proxy can take multiple forms - look for : port first , let proxyURIAuth = maybe notURI (\parsed -> maybe notURI id (uriAuthority parsed)) (parseURI str) out $ "proxy uri host: " ++ uriRegName proxyURIAuth ++ ", port: " ++ uriPort proxyURIAuth dorequest proxyURIAuth final_req mbMx <- getMaxErrorRetries case e_rsp of Left v | (reqRetries rqState < fromMaybe defaultMaxErrorRetries mbMx) && (v == ErrorReset || v == ErrorClosed) -> do modify (\b -> b { bsConnectionPool=[] }) request' nullVal rqState{reqRetries=succ (reqRetries rqState)} rq | otherwise -> return (Left v) Right rsp -> do out ("Received:\n" ++ show rsp) handleCookies uri (uriAuthToString $ reqURIAuth rq) (retrieveHeaders HdrSetCookie rsp) handleConnectionClose (reqURIAuth rq) (retrieveHeaders HdrConnection rsp) mbMxAuths <- getMaxAuthAttempts case rspCode rsp of | reqDenies rqState > fromMaybe defaultMaxAuthAttempts mbMxAuths -> do out "401 - credentials again refused; exceeded retry count (2)" return (Right (uri,rsp)) | otherwise -> do out "401 - credentials not supplied or refused; retrying.." let hdrs = retrieveHeaders HdrWWWAuthenticate rsp flg <- getAllowBasicAuth case pickChallenge flg (catMaybes $ map (headerToChallenge uri) hdrs) of Nothing -> do out "no challenge" Just x -> do au <- challengeToAuthority uri x case au of Nothing -> do out "no auth" Just au' -> do out "Retrying request with new credentials" request' nullVal rqState{ reqDenies = succ(reqDenies rqState) , reqStopOnDeny = False } (insertHeader HdrAuthorization (withAuthority au' rq) rq) | reqDenies rqState > fromMaybe defaultMaxAuthAttempts mbMxAuths -> do out "407 - proxy authentication required; max deny count exceeeded (2)" return (Right (uri,rsp)) | otherwise -> do out "407 - proxy authentication required" let hdrs = retrieveHeaders HdrProxyAuthenticate rsp flg <- getAllowBasicAuth case pickChallenge flg (catMaybes $ map (headerToChallenge uri) hdrs) of Just x -> do au <- challengeToAuthority uri x case au of Just au' -> do pxy <- gets bsProxy case pxy of NoProxy -> do err "Proxy authentication required without proxy!" return (Right (uri,rsp)) Proxy px _ -> do out "Retrying with proxy authentication" setProxy (Proxy px (Just au')) request' nullVal rqState{ reqDenies = succ(reqDenies rqState) , reqStopOnDeny = False } rq (3,0,x) | x `elem` [2,3,1,7] -> do out ("30" ++ show x ++ " - redirect") allow_redirs <- allowRedirect rqState case allow_redirs of False -> return (Right (uri,rsp)) _ -> do case retrieveHeaders HdrLocation rsp of [] -> do err "No Location: header in redirect response" return (Right (uri,rsp)) (Header _ u:_) -> case parseURIReference u of Nothing -> do err ("Parse of Location: header in a redirect response failed: " ++ u) return (Right (uri,rsp)) Just newURI err ("Unable to handle redirect, unsupported scheme: " ++ show newURI_abs) return (Right (uri, rsp)) | otherwise -> do out ("Redirecting to " ++ show newURI_abs ++ " ...") let toGet = x `elem` [2,3] method = if toGet then GET else rqMethod rq rq1 = rq { rqMethod=method, rqURI=newURI_abs } rq2 = if toGet then (replaceHeader HdrContentLength "0") (rq1 {rqBody = nullVal}) else rq1 request' nullVal rqState{ reqDenies = 0 , reqRedirects = succ(reqRedirects rqState) , reqStopOnDeny = True } rq2 where newURI_abs = uriDefaultTo newURI uri (3,0,5) -> case retrieveHeaders HdrLocation rsp of [] -> do err "No Location header in proxy redirect response." return (Right (uri,rsp)) (Header _ u:_) -> case parseURIReference u of Nothing -> do err ("Parse of Location header in a proxy redirect response failed: " ++ u) return (Right (uri,rsp)) Just newuri -> do out ("Retrying with proxy " ++ show newuri ++ "...") setProxy (Proxy (uriToAuthorityString newuri) Nothing) request' nullVal rqState{ reqDenies = 0 , reqRedirects = 0 , reqRetries = succ (reqRetries rqState) , reqStopOnDeny = True } rq _ -> return (Right (uri,rsp)) dorequest :: (HStream ty) => URIAuth -> Request ty -> BrowserAction (HandleStream ty) (Result (Response ty)) dorequest hst rqst = do pool <- gets bsConnectionPool conn <- liftIO $ filterM (\c -> c `isTCPConnectedTo` EndPoint (uriRegName hst) uPort) pool rsp <- case conn of [] -> do out ("Creating new connection to " ++ uriAuthToString hst) reportEvent OpenConnection (show (rqURI rqst)) c <- liftIO $ openStream (uriRegName hst) uPort updateConnectionPool c dorequest2 c rqst (c:_) -> do out ("Recovering connection to " ++ uriAuthToString hst) reportEvent ReuseConnection (show (rqURI rqst)) dorequest2 c rqst case rsp of Right (Response a b c _) -> reportEvent (ResponseEnd (a,b,c)) (show (rqURI rqst)) ; _ -> return () return rsp where dorequest2 c r = do dbg <- gets bsDebug st <- get let onSendComplete = maybe (return ()) (\evh -> do x <- buildBrowserEvent RequestSent (show (rqURI r)) (bsRequestID st) runBA st (evh x) return ()) (bsEvent st) liftIO $ maybe (sendHTTP_notify c r onSendComplete) (\ f -> do c' <- debugByteStream (f++'-': uriAuthToString hst) c sendHTTP_notify c' r onSendComplete) dbg updateConnectionPool :: HStream hTy => HandleStream hTy -> BrowserAction (HandleStream hTy) () updateConnectionPool c = do pool <- gets bsConnectionPool let len_pool = length pool maxPoolSize <- fromMaybe defaultMaxPoolSize <$> gets bsMaxPoolSize when (len_pool > maxPoolSize) (liftIO $ close (last pool)) let pool' | len_pool > maxPoolSize = init pool | otherwise = pool when (maxPoolSize > 0) $ modify (\b -> b { bsConnectionPool=c:pool' }) return () defaultMaxPoolSize :: Int defaultMaxPoolSize = 5 cleanConnectionPool :: HStream hTy => URIAuth -> BrowserAction (HandleStream hTy) () cleanConnectionPool uri = do let ep = EndPoint (uriRegName uri) (uriAuthPort Nothing uri) pool <- gets bsConnectionPool bad <- liftIO $ mapM (\c -> c `isTCPConnectedTo` ep) pool let tmp = zip bad pool newpool = map snd $ filter (not . fst) tmp toclose = map snd $ filter fst tmp liftIO $ forM_ toclose close modify (\b -> b { bsConnectionPool = newpool }) handleCookies :: URI -> String -> [Header] -> BrowserAction t () handleCookies uri dom cookieHeaders = do when (not $ null errs) (err $ unlines ("Errors parsing these cookie values: ":errs)) when (not $ null newCookies) (out $ foldl (\x y -> x ++ "\n " ++ show y) "Cookies received:" newCookies) filterfn <- getCookieFilter newCookies' <- liftIO (filterM (filterfn uri) newCookies) when (not $ null newCookies') (out $ "Accepting cookies with names: " ++ unwords (map ckName newCookies')) mapM_ addCookie newCookies' where (errs, newCookies) = processCookieHeaders dom cookieHeaders handleConnectionClose :: HStream hTy => URIAuth -> [Header] -> BrowserAction (HandleStream hTy) () handleConnectionClose _ [] = return () handleConnectionClose uri headers = do let doClose = any (== "close") $ map headerToConnType headers when doClose $ cleanConnectionPool uri where headerToConnType (Header _ t) = map toLower t allowRedirect :: RequestState -> BrowserAction t Bool allowRedirect rqState = do rd <- getAllowRedirects mbMxRetries <- getMaxRedirects return (rd && (reqRedirects rqState <= fromMaybe defaultMaxRetries mbMxRetries)) supportedScheme :: URI -> Bool supportedScheme u = uriScheme u == "http:" | @uriDefaultTo a b@ returns a URI that is consistent with the first argument URI @a@ when read in the context of the second URI @b@. If the second argument is not sufficient context for determining uriDefaultTo :: URI -> URI -> URI #if MIN_VERSION_network(2,4,0) uriDefaultTo a b = a `relativeTo` b #else uriDefaultTo a b = maybe a id (a `relativeTo` b) #endif type FormVar = (String,String) data Form = Form RequestMethod URI [FormVar] formToRequest :: Form -> Request_String formToRequest (Form m u vs) = let enc = urlEncodeVars vs in case m of GET -> Request { rqMethod=GET , rqHeaders=[ Header HdrContentLength "0" ] , rqBody="" } POST -> Request { rqMethod=POST , rqHeaders=[ Header HdrContentType "application/x-www-form-urlencoded", Header HdrContentLength (show $ length enc) ] , rqBody=enc , rqURI=u } _ -> error ("unexpected request: " ++ show m)
647b1914e72c19defe9fa6db8dcd7a7b67fe6d2a8ba517d3258f13b726cb3c0e
burkaydurdu/muggle
events.cljs
(ns muggle.houses.events (:require [re-frame.core :refer [reg-event-db]])) (reg-event-db :houses-list-change (fn [db [_ new-list-value]] (assoc db :houses-list new-list-value)))
null
https://raw.githubusercontent.com/burkaydurdu/muggle/8c457397305be6ea2848a2537669a700d0147997/src/muggle/houses/events.cljs
clojure
(ns muggle.houses.events (:require [re-frame.core :refer [reg-event-db]])) (reg-event-db :houses-list-change (fn [db [_ new-list-value]] (assoc db :houses-list new-list-value)))
edcafc94b418f9be1f66da6d91a33f49a8fb40b9c407ba2056dab10d600d41bd
Clozure/ccl-tests
ignore-errors.lsp
;-*- Mode: Lisp -*- Author : Created : Sun Mar 2 20:38:25 2003 Contains : Tests of IGNORE - ERRORS (in-package :cl-test) (deftest ignore-errors.1 (ignore-errors) nil) (deftest ignore-errors.2 (ignore-errors 'a) a) (deftest ignore-errors.3 (ignore-errors (values 1 2 3 4 5 6 7 8)) 1 2 3 4 5 6 7 8) (deftest ignore-errors.4 (multiple-value-bind (val cond) (ignore-errors (error "foo")) (and (null val) (typep cond 'simple-error) t)) t) (deftest ignore-errors.5 (handler-case (ignore-errors (signal "foo")) (condition () 'good)) good) (deftest ignore-errors.6 (handler-case (ignore-errors (signal "foo")) (simple-condition () 'good)) good)
null
https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/ignore-errors.lsp
lisp
-*- Mode: Lisp -*-
Author : Created : Sun Mar 2 20:38:25 2003 Contains : Tests of IGNORE - ERRORS (in-package :cl-test) (deftest ignore-errors.1 (ignore-errors) nil) (deftest ignore-errors.2 (ignore-errors 'a) a) (deftest ignore-errors.3 (ignore-errors (values 1 2 3 4 5 6 7 8)) 1 2 3 4 5 6 7 8) (deftest ignore-errors.4 (multiple-value-bind (val cond) (ignore-errors (error "foo")) (and (null val) (typep cond 'simple-error) t)) t) (deftest ignore-errors.5 (handler-case (ignore-errors (signal "foo")) (condition () 'good)) good) (deftest ignore-errors.6 (handler-case (ignore-errors (signal "foo")) (simple-condition () 'good)) good)
a89d8ca8234a8264ddd46e011ddf7eed0e789a12e66ac2a198c5df360d655ba9
babashka/pod-registry
datalevin.clj
#!/usr/bin/env bb (require '[babashka.pods :as pods]) (pods/load-pod 'huahaiy/datalevin "0.8.4") (require '[pod.huahaiy.datalevin :as d]) (def conn (d/get-conn "/tmp/mydb")) (d/transact! conn [{:greeting "Hello world!"}]) (println (d/q '[:find ?g :where [_ :greeting ?g]] (d/db conn))) (d/close conn)
null
https://raw.githubusercontent.com/babashka/pod-registry/90647da5ddc482c138a0a7f6083079fc3dcbf9fa/examples/datalevin.clj
clojure
#!/usr/bin/env bb (require '[babashka.pods :as pods]) (pods/load-pod 'huahaiy/datalevin "0.8.4") (require '[pod.huahaiy.datalevin :as d]) (def conn (d/get-conn "/tmp/mydb")) (d/transact! conn [{:greeting "Hello world!"}]) (println (d/q '[:find ?g :where [_ :greeting ?g]] (d/db conn))) (d/close conn)
8708f49a61dbb95523c154782167776cc7fc77f6360b47039bae9134f3e32126
8c6794b6/guile-tjit
iconv.scm
;;; Encoding and decoding byte representations of strings Copyright ( C ) 2013 Free Software Foundation , Inc. ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 3 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 ;;;; Lesser General Public License for more details. ;;;; You should have received a copy of the GNU Lesser General Public ;;;; License along with this library; if not, write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA ;;; Code: (define-module (ice-9 iconv) #:use-module (rnrs bytevectors) #:use-module (ice-9 binary-ports) #:use-module ((ice-9 rdelim) #:select (read-string)) #:export (string->bytevector bytevector->string call-with-encoded-output-string)) ;; Like call-with-output-string, but actually closes the port. (define (call-with-output-string* proc) (let ((port (open-output-string))) (proc port) (let ((str (get-output-string port))) (close-port port) str))) (define (call-with-output-bytevector* proc) (call-with-values (lambda () (open-bytevector-output-port)) (lambda (port get-bytevector) (proc port) (let ((bv (get-bytevector))) (close-port port) bv)))) (define* (call-with-encoded-output-string encoding proc #:optional (conversion-strategy 'error)) "Call PROC on a fresh port. Encode the resulting string as a bytevector according to ENCODING, and return the bytevector." (if (and (string-ci=? encoding "utf-8") (eq? conversion-strategy 'error)) ;; I don't know why, but this appears to be faster; at least for serving examples / debug - sxml.scm ( 1464 reqs / s versus 850 reqs / s ) . (string->utf8 (call-with-output-string* proc)) (call-with-output-bytevector* (lambda (port) (set-port-encoding! port encoding) (if conversion-strategy (set-port-conversion-strategy! port conversion-strategy)) (proc port))))) ;; TODO: Provide C implementations that call scm_from_stringn and ;; friends? (define* (string->bytevector str encoding #:optional (conversion-strategy 'error)) "Encode STRING according to ENCODING, which should be a string naming a character encoding, like \"utf-8\"." (if (and (string-ci=? encoding "utf-8") (eq? conversion-strategy 'error)) (string->utf8 str) (call-with-encoded-output-string encoding (lambda (port) (display str port)) conversion-strategy))) (define* (bytevector->string bv encoding #:optional (conversion-strategy 'error)) "Decode the string represented by BV. The bytes in the bytevector will be interpreted according to ENCODING, which should be a string naming a character encoding, like \"utf-8\"." (if (and (string-ci=? encoding "utf-8") (eq? conversion-strategy 'error)) (utf8->string bv) (let ((p (open-bytevector-input-port bv))) (set-port-encoding! p encoding) (if conversion-strategy (set-port-conversion-strategy! p conversion-strategy)) (let ((res (read-string p))) (close-port p) (if (eof-object? res) "" res)))))
null
https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/module/ice-9/iconv.scm
scheme
Encoding and decoding byte representations of strings This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public 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 Lesser General Public License for more details. License along with this library; if not, write to the Free Software Code: Like call-with-output-string, but actually closes the port. I don't know why, but this appears to be faster; at least for TODO: Provide C implementations that call scm_from_stringn and friends?
Copyright ( C ) 2013 Free Software Foundation , Inc. version 3 of the License , or ( at your option ) any later version . You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA (define-module (ice-9 iconv) #:use-module (rnrs bytevectors) #:use-module (ice-9 binary-ports) #:use-module ((ice-9 rdelim) #:select (read-string)) #:export (string->bytevector bytevector->string call-with-encoded-output-string)) (define (call-with-output-string* proc) (let ((port (open-output-string))) (proc port) (let ((str (get-output-string port))) (close-port port) str))) (define (call-with-output-bytevector* proc) (call-with-values (lambda () (open-bytevector-output-port)) (lambda (port get-bytevector) (proc port) (let ((bv (get-bytevector))) (close-port port) bv)))) (define* (call-with-encoded-output-string encoding proc #:optional (conversion-strategy 'error)) "Call PROC on a fresh port. Encode the resulting string as a bytevector according to ENCODING, and return the bytevector." (if (and (string-ci=? encoding "utf-8") (eq? conversion-strategy 'error)) serving examples / debug - sxml.scm ( 1464 reqs / s versus 850 reqs / s ) . (string->utf8 (call-with-output-string* proc)) (call-with-output-bytevector* (lambda (port) (set-port-encoding! port encoding) (if conversion-strategy (set-port-conversion-strategy! port conversion-strategy)) (proc port))))) (define* (string->bytevector str encoding #:optional (conversion-strategy 'error)) "Encode STRING according to ENCODING, which should be a string naming a character encoding, like \"utf-8\"." (if (and (string-ci=? encoding "utf-8") (eq? conversion-strategy 'error)) (string->utf8 str) (call-with-encoded-output-string encoding (lambda (port) (display str port)) conversion-strategy))) (define* (bytevector->string bv encoding #:optional (conversion-strategy 'error)) "Decode the string represented by BV. The bytes in the bytevector will be interpreted according to ENCODING, which should be a string naming a character encoding, like \"utf-8\"." (if (and (string-ci=? encoding "utf-8") (eq? conversion-strategy 'error)) (utf8->string bv) (let ((p (open-bytevector-input-port bv))) (set-port-encoding! p encoding) (if conversion-strategy (set-port-conversion-strategy! p conversion-strategy)) (let ((res (read-string p))) (close-port p) (if (eof-object? res) "" res)))))
450f8c266a9592145138f6b2997e14b75f794cacd7634c23015a27df5489d1ee
manuel-serrano/bigloo
make_lib.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / examples / Lib / make_lib.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Sat Dec 19 13:01:37 1998 * / * Last change : Thu Nov 22 17:21:55 2012 ( serrano ) * / ;* ------------------------------------------------------------- */ ;* The file to make the point heap. */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module __make-point-lib (import (point "scm_point.scm")) (eval (export-all)))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/examples/Lib/make_lib.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * The file to make the point heap. */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/
* serrano / prgm / project / bigloo / examples / Lib / make_lib.scm * / * Author : * / * Creation : Sat Dec 19 13:01:37 1998 * / * Last change : Thu Nov 22 17:21:55 2012 ( serrano ) * / (module __make-point-lib (import (point "scm_point.scm")) (eval (export-all)))
956334a1fcfd7cd592fb5860af060ea9bb5129a0f173718357f5246165626574
bluegraybox/examples
fizzbuzz_2.erl
#!/usr/local/bin/escript -mode(compile). main([]) -> fizzbuzz(100, 1); main([MaxStr]) -> {Max, _} = string:to_integer(MaxStr), fizzbuzz(Max, 1). fizzbuzz(Max, X) when X > Max -> ok; fizzbuzz(Max, X) when ((X rem 5) == 0) and ((X rem 3) == 0) -> io:format("fizzbuzz~n"), fizzbuzz(Max, X + 1); fizzbuzz(Max, X) when ((X rem 3) == 0) -> io:format("fizz~n"), fizzbuzz(Max, X + 1); fizzbuzz(Max, X) when ((X rem 5) == 0) -> io:format("buzz~n"), fizzbuzz(Max, X + 1); fizzbuzz(Max, X) -> io:format("~p~n", [X]), fizzbuzz(Max, X + 1).
null
https://raw.githubusercontent.com/bluegraybox/examples/20f238be10e2e987687d7289b2f4897cc7d95abd/fizzbuzz/fizzbuzz_2.erl
erlang
#!/usr/local/bin/escript -mode(compile). main([]) -> fizzbuzz(100, 1); main([MaxStr]) -> {Max, _} = string:to_integer(MaxStr), fizzbuzz(Max, 1). fizzbuzz(Max, X) when X > Max -> ok; fizzbuzz(Max, X) when ((X rem 5) == 0) and ((X rem 3) == 0) -> io:format("fizzbuzz~n"), fizzbuzz(Max, X + 1); fizzbuzz(Max, X) when ((X rem 3) == 0) -> io:format("fizz~n"), fizzbuzz(Max, X + 1); fizzbuzz(Max, X) when ((X rem 5) == 0) -> io:format("buzz~n"), fizzbuzz(Max, X + 1); fizzbuzz(Max, X) -> io:format("~p~n", [X]), fizzbuzz(Max, X + 1).
4e9d0d8f085a75c4983f08f38c7de797c2e195bdb411577bbea93764d176d48a
prg-titech/Kani-CUDA
diffusion2d-h.rkt
#lang rosette (provide (all-defined-out)) (define M-PI 8) (define Lx (* 2 M-PI)) (define Ly (* 2 M-PI)) (define Nx 16) (define Ny 16) (define dx (exact->inexact (/ Lx (- Nx 1)))) (define dy (exact->inexact (/ Ly (- Ny 1)))) (define dt 0.0001) (define endT 1.0) (define Nt (/ endT dt)) (define DIFF 1.0) (define dxdx (* dx dx)) (define dydy (* dy dy)) (define THREADX 8) (define THREADY 8) (define BLOCKX (quotient Nx THREADX)) (define BLOCKY (quotient Ny THREADY)) (define Nbytes (* Nx Ny 12))
null
https://raw.githubusercontent.com/prg-titech/Kani-CUDA/e97c4bede43a5fc4031a7d2cfc32d71b01ac26c4/Emulator/Examples/Diffusion2d/diffusion2d-h.rkt
racket
#lang rosette (provide (all-defined-out)) (define M-PI 8) (define Lx (* 2 M-PI)) (define Ly (* 2 M-PI)) (define Nx 16) (define Ny 16) (define dx (exact->inexact (/ Lx (- Nx 1)))) (define dy (exact->inexact (/ Ly (- Ny 1)))) (define dt 0.0001) (define endT 1.0) (define Nt (/ endT dt)) (define DIFF 1.0) (define dxdx (* dx dx)) (define dydy (* dy dy)) (define THREADX 8) (define THREADY 8) (define BLOCKX (quotient Nx THREADX)) (define BLOCKY (quotient Ny THREADY)) (define Nbytes (* Nx Ny 12))
49a73f05626d9fc0de84be67184808a5afb19140942fbb7021b7f438683a2162
cedlemo/OCaml-GI-ctypes-bindings-generator
Ptr_array.ml
open Ctypes open Foreign type t let t_typ : t structure typ = structure "Ptr_array" let f_pdata = field t_typ "pdata" (ptr void) let f_len = field t_typ "len" (uint32_t) let _ = seal t_typ
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/GLib/Ptr_array.ml
ocaml
open Ctypes open Foreign type t let t_typ : t structure typ = structure "Ptr_array" let f_pdata = field t_typ "pdata" (ptr void) let f_len = field t_typ "len" (uint32_t) let _ = seal t_typ
8cff2ccaad30749fcfa7f0efb4ca2d44dc8b326bce25e95dc5b2d34735288aef
reanimate/reanimate
doc_oScaleIn.hs
#!/usr/bin/env stack -- stack runghc --package reanimate {-# LANGUAGE OverloadedStrings #-} module Main(main) where import Reanimate import Reanimate.Scene import Reanimate.Builtin.Documentation main :: IO () main = reanimate $ docEnv $ scene $ do txt <- oNew $ withStrokeWidth 0 $ withFillOpacity 1 $ center $ scale 3 $ latex "oScaleIn" oShowWith txt $ adjustDuration (*2) . oScaleIn wait 1; oHideWith txt oFadeOut
null
https://raw.githubusercontent.com/reanimate/reanimate/5ea023980ff7f488934d40593cc5069f5fd038b0/examples/doc_oScaleIn.hs
haskell
stack runghc --package reanimate # LANGUAGE OverloadedStrings #
#!/usr/bin/env stack module Main(main) where import Reanimate import Reanimate.Scene import Reanimate.Builtin.Documentation main :: IO () main = reanimate $ docEnv $ scene $ do txt <- oNew $ withStrokeWidth 0 $ withFillOpacity 1 $ center $ scale 3 $ latex "oScaleIn" oShowWith txt $ adjustDuration (*2) . oScaleIn wait 1; oHideWith txt oFadeOut
1f0d1972ca748d267a218e93a55809fe185c5071b27751f246add090028bedb1
jwiegley/notes
Fib.hs
module Main where import Control.Monad import Data.Time.Clock foldl :: Monad m => (a -> Maybe ()) -> (b -> a -> b) -> b -> [a] -> m (Maybe b) foldl _ _ z [] = return (Just z) foldl b f z (x:xs) = fmap join $ forM (b x) $ \() -> Main.foldl b f (f z x) xs foldl2 :: Monad m => (a -> Maybe ()) -> (b -> a -> b) -> b -> [a] -> m (Maybe b) foldl2 _ _ z [] = return (Just z) foldl2 b f z (x:xs) = case b x of Nothing -> return Nothing Just () -> Main.foldl2 b f (f z x) xs main :: IO () main = test Main.foldl >> test Main.foldl2 where test f = do t0 <- getCurrentTime n <- f (\x -> if x<10000000 then Just () else Nothing) (+) (0 :: Int) ([1..100000000] :: [Int]) print n t1 <- getCurrentTime print $ diffUTCTime t1 t0
null
https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/haskell/Fib.hs
haskell
module Main where import Control.Monad import Data.Time.Clock foldl :: Monad m => (a -> Maybe ()) -> (b -> a -> b) -> b -> [a] -> m (Maybe b) foldl _ _ z [] = return (Just z) foldl b f z (x:xs) = fmap join $ forM (b x) $ \() -> Main.foldl b f (f z x) xs foldl2 :: Monad m => (a -> Maybe ()) -> (b -> a -> b) -> b -> [a] -> m (Maybe b) foldl2 _ _ z [] = return (Just z) foldl2 b f z (x:xs) = case b x of Nothing -> return Nothing Just () -> Main.foldl2 b f (f z x) xs main :: IO () main = test Main.foldl >> test Main.foldl2 where test f = do t0 <- getCurrentTime n <- f (\x -> if x<10000000 then Just () else Nothing) (+) (0 :: Int) ([1..100000000] :: [Int]) print n t1 <- getCurrentTime print $ diffUTCTime t1 t0
386ae5c16395a337deff5d9e79fbddcc732a8aa7779e1c64f5f24a2e2e09b379
disconcision/fructure
navigate.rkt
#lang racket (require "../../shared/containment-patterns/containment-patterns/main.rkt" "../../shared/slash-patterns/slash-patterns.rkt" "../common.rkt" "legacy.rkt" "transform.rkt") ; for insert-menu; refactor todo (provide mode:navigate mode:navigate-ctrl mode:navigate-shift capture-at-cursor) (define (mode:navigate pr key state) ; navigation major mode (define-from state stx mode transforms messages layout-settings) (define update (updater state key)) (if (equal? pr 'release) state (match key ["control" (update 'mode 'nav-ctrl)] ["shift" (update 'mode 'nav-shift)] [" " (update 'mode 'command 'mode-last 'nav)] ["f2" (println `(BEGIN-STX ,stx)) state] ["up" ; moves the cursor up to the nearest containing handle alternative handle symbol : (update 'stx (match stx [(⋱ c1⋱ (and (/ handle as/ (⋱ c2⋱ (/ bs/ (▹ b)))) (not (/ handle _ (⋱ _ (/ handle _ (⋱ _ (/ _ (▹ _))))))))) (⋱ c1⋱ (/ [handle handle] as/ ; bug? ▹ isn't bound if no pair attributes? (▹ (⋱ c2⋱ (/ bs/ b)))))] [x x]))] ["down" ; moves the cursor to the closet handle beneath it (update 'stx (match stx [(⋱ c⋱ (/ b/ (▹ (⋱ d⋱ (/ handle a/ a))))) (⋱ c⋱ (/ b/ (⋱ d⋱ (/ [handle handle] a/ (▹ a)))))] [x x]))] ["right" ; moves the cursor right in a preorder traversal 1 . if there is a handled fruct under the cursor , select it 2 . otherwise , gather all handled subfructs which do n't contain the cursor , ; as well as the current selection, and therein advance the cursor (define new-stx (match stx [(⋱ c⋱ (/ xs/ (▹ (⋱ d⋱ (/ handle as/ a))))) (⋱ c⋱ (/ xs/ ; bug: requires double handle below? (⋱ d⋱ (/ [handle handle] as/ (▹ a)))))] [(⋱+ c⋱ (capture-when (or (/ _ (▹ _)) (/ [handle _] _ (not (⋱ (/ _ (▹ _))))))) `(,as ... ,(/ b/ (▹ b)) ,(/ c/ c) ,ds ...)) (⋱+ c⋱ `(,@as ,(/ b/ b) ,(/ c/ (▹ c)) ,@ds))] [x x])) (update 'stx new-stx)] ["left" ; moves the cursor left in a preorder traversal 1 . if there is a left - sibling to the cursor which contains - or - is a handle , ; select its rightmost handle not containing another handle 2 . otherwise , find the most immediate containing handle ; ; that is, a containing handle not containing a handle containing ▹ (define new-stx (match stx [(⋱ c1⋱ `(,as ... ,(⋱+ c2⋱ (capture-when (/ [handle _] _ (not (⋱ _ (/ [handle _] _ _))))) `(,bs ... ,(/ c/ c))) ,ds ... ,(/ e/ (▹ e)) ,fs ...)) (⋱ c1⋱ `(,@as ,(⋱+ c2⋱ `(,@bs ,(/ c/ (▹ c)))) ,@ds ,(/ e/ e) ,@fs))] [(⋱ c1⋱ (and (/ [handle h] a/ (⋱ c2⋱ (/ b/ (▹ b)))) (not (/ [handle _] _ (⋱ _ (/ [handle _] _ (⋱ _ (/ _ (▹ _))))))))) (⋱ c1⋱ (/ [handle h] a/ (▹ (⋱ c2⋱ (/ b/ b)))))] [x x])) (update 'stx new-stx)] ["\r" ; ENTER: insert a menu and switch to transform mode ; todo: if possible, factor out insert-menu-at for encapsulation (define (setup-transform-mode stx) (match stx [(⋱ c⋱ (/ as/ (▹ a))) (⋱ c⋱ (/ [transform ; todo: fix hardcoded init buffer here: (insert-menu-at-cursor (/ as/ (▹ a)) stx '(▹ ""))] as/ a))])) (define hole-under-cursor? (match-lambda? (⋱ c⋱ (/ _/ (▹ (or '⊙ '⊙+)))))) (update 'mode 'menu 'transform-undo-stack `(,(setup-transform-mode stx)) 'transform-redo-stack '() 'stx ((compose setup-transform-mode (λ (x) x ; TODO: add prop UNCOMMENT TO AUTOCAPTURE SOURCE SYNTAX IN A TRANSFORM ( if ( ( - under - cursor ? has - captures ? ) x ) x (capture-at-cursor x)))) stx))] ["\t" ; paint selection as metavariable if there are metavariables under the selection , erase them first ; metavariables sibling/cousin to cursor may be renamed (update 'stx (capture-at-cursor stx))] ["escape" ; release all extant metavariables (update 'stx (erase-captures stx))] #;["," ; COMMA: undo (BUG: currently completely broken) ; at minimum, would need to include do-seq and initial-state (match transforms ['() (update 'messages `("no undo states" ,messages))] [_ (update 'messages `("reverting to previous state" ,@messages) 'stx (do-seq (hash-ref initial-state 'stx) (reverse (rest transforms))) 'transforms (rest transforms))])] [_ (println "warning: nav: unhandled keypress") state ; commented off legacy mode ; fallthrough: legacy transformation mode #;(println "warning: legacy fallthrough binding") #;(mode:legacy key state)]))) (define (mode:navigate-ctrl pr key state) ; navigation control mode (define-from state stx mode layout-settings) (define update (updater state key)) (if (equal? pr 'release) (match key ["control" (update 'mode 'nav)] [_ state]) (match key ["left" (define current-size (hash-ref layout-settings 'text-size)) (define new-size (if (>= 10 current-size) current-size (- current-size 10))) (update 'layout-settings (hash-set* layout-settings 'text-size new-size))] ["right" (define current-size (hash-ref layout-settings 'text-size)) (define new-size (if (>= current-size 240) current-size (+ current-size 10))) (update 'layout-settings (hash-set* layout-settings 'text-size new-size))] [(and save-number (or "f9" "f10" "f11" "f12")) (save! stx save-number) state] [ " f9 " (define out (open-output-file "fructure-sav-f9.fruct" #:exists 'replace)) (write stx out) (close-output-port out) state] [_ state]))) (define (mode:navigate-shift pr key state) ; navigation settings shifter ; primitive scrobber ; control scheme: ; - use search buffer to filter menu of prop-names ; - up/down moves props ; - left/right cycles props ; supported properties: ; for each property, we must provide an inc and dec ; - numeric: calculate from [operation inverse delta max min] ; - boolean: inc = dec = not - enum : integer inc / dec index of ( index , [ vector of values ] ) #;(; numeric 'text-size 'line-spacing 'char-padding-vertical 'max-menu-length 'max-menu-length-chars 'length-conditional-cutoff ; boolean 'force-horizontal-layout? 'display-keypresses? ;enum 'typeface) (define property 'length-conditional-cutoff) (define prop-inc-decs (hash 'length-conditional-cutoff (numeric-inc-dec * div 1.5 3 100))) ; ACTUAL fn BEGINS ------------------- (define-from state stx mode layout-settings) (define update (updater state key)) (match-define (list inc dec) (hash-ref prop-inc-decs property (list identity identity))) (if (equal? pr 'release) (match key ["shift" (update 'mode 'nav)] [_ state]) (match key ["left" (update 'layout-settings (hash-update layout-settings property dec))] ["right" (update 'layout-settings (hash-update layout-settings property inc))] [(and save-number (or "f9" "f10" "f11" "f12")) (update 'stx (load! save-number))] [_ state]))) (define (load! save-number) (println `(loading ,save-number)) (define in (open-input-file (string-append "saves/fructure-sav-" save-number ".fruct"))) (define saved-state (read in)) (close-input-port in) saved-state) (define (save! stx save-number) (println `(saving ,save-number)) (define out (open-output-file (string-append "saves/fructure-sav-" save-number ".fruct") #:exists 'replace)) (write stx out) (close-output-port out)) (define (numeric-inc-dec prop-operation prop-inverse prop-delta prop-min prop-max) (define (apply-if p f x) (define fx (f x)) (if (p fx) fx x)) (define (in-range prop) (< prop-min prop prop-max)) (define inc (curry apply-if in-range (curryr prop-operation prop-delta))) (define dec (curry apply-if in-range (curryr prop-inverse prop-delta))) (list inc dec)) ; idea for changed properties to unfixed point ; need a different level of abstraction #;(define ((adaptive f) prop) (let loop ([prop-cur prop] [iters 10] [fp (f prop)]) (println `(iters ,iters)) (when (zero? iters) (println "WARNING: ADAPTIVE PROP CHANGER TIMED OUT")) (if (or (not (equal? fp f)) (zero? iters)) fp (loop fp (sub1 iters))))) ; below is old work on search from layout.rkt; usable? (define (my-matches? prefix-string form-name) (regexp-match (regexp (string-append "^" prefix-string ".*")) (symbol->string form-name))) (define (add-hooks prefix-string fruct) (define AH (curry add-hooks prefix-string)) (match fruct [(/ a/ `(,(? (conjoin symbol? (curry my-matches? prefix-string)) form-name) ,xs ...)) (/ [hook prefix-string] a/ (map AH `(,form-name ,@xs)))] [(/ a/ (? list? as)) (/ a/ (map AH as))] [(/ a/ (? symbol? thing)) (if (my-matches? prefix-string thing) (/ [hook prefix-string] a/ thing) (/ a/ thing))] [_ fruct])) #;(add-hooks "x" (stx->fruct '(lambda (x) (and x (▹ (and true false))) x)))
null
https://raw.githubusercontent.com/disconcision/fructure/d434086052eab3c450f631b7b14dcbf9358f45b7/src/mode/navigate.rkt
racket
for insert-menu; refactor todo navigation major mode moves the cursor up to the nearest containing handle bug? ▹ isn't bound if no pair attributes? moves the cursor to the closet handle beneath it moves the cursor right in a preorder traversal as well as the current selection, and therein advance the cursor bug: requires double handle below? moves the cursor left in a preorder traversal select its rightmost handle not containing another handle that is, a containing handle not containing a handle containing ▹ ENTER: insert a menu and switch to transform mode todo: if possible, factor out insert-menu-at for encapsulation todo: fix hardcoded init buffer here: TODO: add prop paint selection as metavariable metavariables sibling/cousin to cursor may be renamed release all extant metavariables ["," COMMA: undo (BUG: currently completely broken) at minimum, would need to include do-seq and initial-state commented off legacy mode fallthrough: legacy transformation mode (println "warning: legacy fallthrough binding") (mode:legacy key state)]))) navigation control mode navigation settings shifter primitive scrobber control scheme: - use search buffer to filter menu of prop-names - up/down moves props - left/right cycles props supported properties: for each property, we must provide an inc and dec - numeric: calculate from [operation inverse delta max min] - boolean: inc = dec = not (; numeric boolean enum ACTUAL fn BEGINS ------------------- idea for changed properties to unfixed point need a different level of abstraction (define ((adaptive f) prop) below is old work on search from layout.rkt; usable? (add-hooks "x" (stx->fruct
#lang racket (require "../../shared/containment-patterns/containment-patterns/main.rkt" "../../shared/slash-patterns/slash-patterns.rkt" "../common.rkt" "legacy.rkt" (provide mode:navigate mode:navigate-ctrl mode:navigate-shift capture-at-cursor) (define (mode:navigate pr key state) (define-from state stx mode transforms messages layout-settings) (define update (updater state key)) (if (equal? pr 'release) state (match key ["control" (update 'mode 'nav-ctrl)] ["shift" (update 'mode 'nav-shift)] [" " (update 'mode 'command 'mode-last 'nav)] ["f2" (println `(BEGIN-STX ,stx)) state] ["up" alternative handle symbol : (update 'stx (match stx [(⋱ c1⋱ (and (/ handle as/ (⋱ c2⋱ (/ bs/ (▹ b)))) (not (/ handle _ (⋱ _ (/ handle _ (⋱ _ (/ _ (▹ _))))))))) (⋱ c1⋱ (/ [handle handle] as/ (▹ (⋱ c2⋱ (/ bs/ b)))))] [x x]))] ["down" (update 'stx (match stx [(⋱ c⋱ (/ b/ (▹ (⋱ d⋱ (/ handle a/ a))))) (⋱ c⋱ (/ b/ (⋱ d⋱ (/ [handle handle] a/ (▹ a)))))] [x x]))] ["right" 1 . if there is a handled fruct under the cursor , select it 2 . otherwise , gather all handled subfructs which do n't contain the cursor , (define new-stx (match stx [(⋱ c⋱ (/ xs/ (▹ (⋱ d⋱ (/ handle as/ a))))) (⋱ d⋱ (/ [handle handle] as/ (▹ a)))))] [(⋱+ c⋱ (capture-when (or (/ _ (▹ _)) (/ [handle _] _ (not (⋱ (/ _ (▹ _))))))) `(,as ... ,(/ b/ (▹ b)) ,(/ c/ c) ,ds ...)) (⋱+ c⋱ `(,@as ,(/ b/ b) ,(/ c/ (▹ c)) ,@ds))] [x x])) (update 'stx new-stx)] ["left" 1 . if there is a left - sibling to the cursor which contains - or - is a handle , (define new-stx (match stx [(⋱ c1⋱ `(,as ... ,(⋱+ c2⋱ (capture-when (/ [handle _] _ (not (⋱ _ (/ [handle _] _ _))))) `(,bs ... ,(/ c/ c))) ,ds ... ,(/ e/ (▹ e)) ,fs ...)) (⋱ c1⋱ `(,@as ,(⋱+ c2⋱ `(,@bs ,(/ c/ (▹ c)))) ,@ds ,(/ e/ e) ,@fs))] [(⋱ c1⋱ (and (/ [handle h] a/ (⋱ c2⋱ (/ b/ (▹ b)))) (not (/ [handle _] _ (⋱ _ (/ [handle _] _ (⋱ _ (/ _ (▹ _))))))))) (⋱ c1⋱ (/ [handle h] a/ (▹ (⋱ c2⋱ (/ b/ b)))))] [x x])) (update 'stx new-stx)] ["\r" (define (setup-transform-mode stx) (match stx [(⋱ c⋱ (/ as/ (▹ a))) (⋱ c⋱ (/ [transform (insert-menu-at-cursor (/ as/ (▹ a)) stx '(▹ ""))] as/ a))])) (define hole-under-cursor? (match-lambda? (⋱ c⋱ (/ _/ (▹ (or '⊙ '⊙+)))))) (update 'mode 'menu 'transform-undo-stack `(,(setup-transform-mode stx)) 'transform-redo-stack '() 'stx ((compose setup-transform-mode (λ (x) x UNCOMMENT TO AUTOCAPTURE SOURCE SYNTAX IN A TRANSFORM ( if ( ( - under - cursor ? has - captures ? ) x ) x (capture-at-cursor x)))) stx))] ["\t" if there are metavariables under the selection , erase them first (update 'stx (capture-at-cursor stx))] ["escape" (update 'stx (erase-captures stx))] (match transforms ['() (update 'messages `("no undo states" ,messages))] [_ (update 'messages `("reverting to previous state" ,@messages) 'stx (do-seq (hash-ref initial-state 'stx) (reverse (rest transforms))) 'transforms (rest transforms))])] [_ (println "warning: nav: unhandled keypress") state (define (mode:navigate-ctrl pr key state) (define-from state stx mode layout-settings) (define update (updater state key)) (if (equal? pr 'release) (match key ["control" (update 'mode 'nav)] [_ state]) (match key ["left" (define current-size (hash-ref layout-settings 'text-size)) (define new-size (if (>= 10 current-size) current-size (- current-size 10))) (update 'layout-settings (hash-set* layout-settings 'text-size new-size))] ["right" (define current-size (hash-ref layout-settings 'text-size)) (define new-size (if (>= current-size 240) current-size (+ current-size 10))) (update 'layout-settings (hash-set* layout-settings 'text-size new-size))] [(and save-number (or "f9" "f10" "f11" "f12")) (save! stx save-number) state] [ " f9 " (define out (open-output-file "fructure-sav-f9.fruct" #:exists 'replace)) (write stx out) (close-output-port out) state] [_ state]))) (define (mode:navigate-shift pr key state) - enum : integer inc / dec index of ( index , [ vector of values ] ) 'text-size 'line-spacing 'char-padding-vertical 'max-menu-length 'max-menu-length-chars 'length-conditional-cutoff 'force-horizontal-layout? 'display-keypresses? 'typeface) (define property 'length-conditional-cutoff) (define prop-inc-decs (hash 'length-conditional-cutoff (numeric-inc-dec * div 1.5 3 100))) (define-from state stx mode layout-settings) (define update (updater state key)) (match-define (list inc dec) (hash-ref prop-inc-decs property (list identity identity))) (if (equal? pr 'release) (match key ["shift" (update 'mode 'nav)] [_ state]) (match key ["left" (update 'layout-settings (hash-update layout-settings property dec))] ["right" (update 'layout-settings (hash-update layout-settings property inc))] [(and save-number (or "f9" "f10" "f11" "f12")) (update 'stx (load! save-number))] [_ state]))) (define (load! save-number) (println `(loading ,save-number)) (define in (open-input-file (string-append "saves/fructure-sav-" save-number ".fruct"))) (define saved-state (read in)) (close-input-port in) saved-state) (define (save! stx save-number) (println `(saving ,save-number)) (define out (open-output-file (string-append "saves/fructure-sav-" save-number ".fruct") #:exists 'replace)) (write stx out) (close-output-port out)) (define (numeric-inc-dec prop-operation prop-inverse prop-delta prop-min prop-max) (define (apply-if p f x) (define fx (f x)) (if (p fx) fx x)) (define (in-range prop) (< prop-min prop prop-max)) (define inc (curry apply-if in-range (curryr prop-operation prop-delta))) (define dec (curry apply-if in-range (curryr prop-inverse prop-delta))) (list inc dec)) (let loop ([prop-cur prop] [iters 10] [fp (f prop)]) (println `(iters ,iters)) (when (zero? iters) (println "WARNING: ADAPTIVE PROP CHANGER TIMED OUT")) (if (or (not (equal? fp f)) (zero? iters)) fp (loop fp (sub1 iters))))) (define (my-matches? prefix-string form-name) (regexp-match (regexp (string-append "^" prefix-string ".*")) (symbol->string form-name))) (define (add-hooks prefix-string fruct) (define AH (curry add-hooks prefix-string)) (match fruct [(/ a/ `(,(? (conjoin symbol? (curry my-matches? prefix-string)) form-name) ,xs ...)) (/ [hook prefix-string] a/ (map AH `(,form-name ,@xs)))] [(/ a/ (? list? as)) (/ a/ (map AH as))] [(/ a/ (? symbol? thing)) (if (my-matches? prefix-string thing) (/ [hook prefix-string] a/ thing) (/ a/ thing))] [_ fruct])) '(lambda (x) (and x (▹ (and true false))) x)))
bf496aa78f410130eb0143f8a12c4511b05e8a55c8c498949ba352435579158e
yrashk/erlang
snmpa_local_db.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1996 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% -module(snmpa_local_db). -include_lib("kernel/include/file.hrl"). -include("snmpa_internal.hrl"). -include("snmp_types.hrl"). -include("STANDARD-MIB.hrl"). %% -define(VMODULE, "LDB"). -include("snmp_verbosity.hrl"). %% External exports -export([start_link/3, start_link/4, stop/0, info/0, verbosity/1]). -export([dump/0, backup/1, register_notify_client/2, unregister_notify_client/1]). -export([table_func/2, table_func/4, variable_get/1, variable_set/2, variable_delete/1, variable_inc/2, table_create/1, table_exists/1, table_delete/1, table_create_row/3, table_create_row/4, table_construct_row/4, table_delete_row/2, table_get_row/2, table_get_element/3, table_get_elements/4, table_set_elements/3, table_set_status/7, table_next/2, table_max_col/2]). -export([get_elements/2]). -export([match/2]). %% Debug exports -export([print/0, print/1, print/2]). %% Internal exports -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(BACKUP_TAB, snmpa_local_backup). -define(DETS_TAB, snmpa_local_db1). -define(ETS_TAB, snmpa_local_db2). -define(SERVER, ?MODULE). -record(state, {dets, ets, notify_clients = [], backup}). -record(dets, {tab, shadow}). %% -define(snmp_debug,true). -include("snmp_debug.hrl"). -ifdef(snmp_debug). -define(GS_START_LINK(Prio, Dir, DbInitError, Opts), gen_server:start_link({local, ?SERVER}, ?MODULE, [Prio, Dir, DbInitError, Opts], [{debug,[trace]}])). -else. -define(GS_START_LINK(Prio, Dir, DbInitError, Opts), gen_server:start_link({local, ?SERVER}, ?MODULE, [Prio, Dir, DbInitError, Opts], [])). -endif. %%%----------------------------------------------------------------- %%% Implements a general database in which its possible %%% to store variables and tables. Provide functions for %%% tableaccess by row or by element, and for next. %%% %%% Opts = [Opt] Opt = { auto_repair , false | true | true_verbose } | %%% {verbosity,silence | log | debug} %%%----------------------------------------------------------------- start_link(Prio, DbDir, Opts) when list(Opts) -> start_link(Prio, DbDir, terminate, Opts). start_link(Prio, DbDir, DbInitError, Opts) when list(Opts) -> ?d("start_link -> entry with" "~n Prio: ~p" "~n DbDir: ~p" "~n DbInitError: ~p" "~n Opts: ~p", [Prio, DbDir, DbInitError, Opts]), ?GS_START_LINK(Prio, DbDir, DbInitError, Opts). stop() -> call(stop). register_notify_client(Client,Module) -> call({register_notify_client,Client,Module}). unregister_notify_client(Client) -> call({unregister_notify_client,Client}). backup(BackupDir) -> call({backup, BackupDir}). dump() -> call(dump). info() -> call(info). verbosity(Verbosity) -> cast({verbosity,Verbosity}). %%%----------------------------------------------------------------- init([Prio, DbDir, DbInitError, Opts]) -> ?d("init -> entry with" "~n Prio: ~p" "~n DbDir: ~p" "~n DbInitError: ~p" "~n Opts: ~p", [Prio, DbDir, DbInitError, Opts]), case (catch do_init(Prio, DbDir, DbInitError, Opts)) of {ok, State} -> ?vdebug("started",[]), {ok, State}; {error, Reason} -> config_err("failed starting local-db: ~n~p", [Reason]), {stop, {error, Reason}}; Error -> config_err("failed starting local-db: ~n~p", [Error]), {stop, {error, Error}} end. do_init(Prio, DbDir, DbInitError, Opts) -> process_flag(priority, Prio), process_flag(trap_exit, true), put(sname,ldb), put(verbosity,get_opt(verbosity, Opts, ?default_verbosity)), ?vlog("starting",[]), Dets = dets_open(DbDir, DbInitError, Opts), Ets = ets:new(?ETS_TAB, [set, protected]), ?vdebug("started",[]), {ok, #state{dets = Dets, ets = Ets}}. dets_open(DbDir, DbInitError, Opts) -> Name = ?DETS_TAB, Filename = dets_filename(Name, DbDir), case file:read_file_info(Filename) of {ok, _} -> %% File exists case do_dets_open(Name, Filename, Opts) of {ok, Dets} -> ?vdebug("dets open done",[]), Shadow = ets:new(snmp_local_db1_shadow, [set, protected]), dets:to_ets(Dets, Shadow), ?vtrace("shadow table created and populated",[]), #dets{tab = Dets, shadow = Shadow}; {error, Reason1} -> user_err("Corrupt local database: ~p", [Filename]), case DbInitError of terminate -> throw({error, {failed_open_dets, Reason1}}); _ -> Saved = Filename ++ ".saved", file:rename(Filename, Saved), case do_dets_open(Name, Filename, Opts) of {ok, Dets} -> Shadow = ets:new(snmp_local_db1_shadow, [set, protected]), #dets{tab = Dets, shadow = Shadow}; {error, Reason2} -> user_err("Could not create local " "database: ~p" "~n ~p" "~n ~p", [Filename, Reason1, Reason2]), throw({error, {failed_open_dets, Reason2}}) end end end; _ -> case do_dets_open(Name, Filename, Opts) of {ok, Dets} -> ?vdebug("dets open done",[]), Shadow = ets:new(snmp_local_db1_shadow, [set, protected]), ?vtrace("shadow table created",[]), #dets{tab = Dets, shadow = Shadow}; {error, Reason} -> user_err("Could not create local database ~p" "~n ~p", [Filename, Reason]), throw({error, {failed_open_dets, Reason}}) end end. do_dets_open(Name, Filename, Opts) -> Repair = get_opt(repair, Opts, true), AutoSave = get_opt(auto_save, Opts, 5000), Args = [{auto_save, AutoSave}, {file, Filename}, {repair, Repair}], dets:open_file(Name, Args). dets_filename(Name, Dir) when is_atom(Name) -> dets_filename(atom_to_list(Name), Dir); dets_filename(Name, Dir) -> filename:join(dets_filename1(Dir), Name). dets_filename1([]) -> "."; dets_filename1(Dir) -> Dir. %%----------------------------------------------------------------- Interface functions . %%----------------------------------------------------------------- %%----------------------------------------------------------------- %% Functions for debugging. %%----------------------------------------------------------------- print() -> call(print). print(Table) -> call({print,Table,volatile}). print(Table, Db) -> call({print,Table,Db}). variable_get({Name, Db}) -> call({variable_get, Name, Db}); variable_get(Name) -> call({variable_get, Name, volatile}). variable_set({Name, Db}, Val) -> call({variable_set, Name, Db, Val}); variable_set(Name, Val) -> call({variable_set, Name, volatile, Val}). variable_inc({Name, Db}, N) -> cast({variable_inc, Name, Db, N}); variable_inc(Name, N) -> cast({variable_inc, Name, volatile, N}). variable_delete({Name, Db}) -> call({variable_delete, Name, Db}); variable_delete(Name) -> call({variable_delete, Name, volatile}). table_create({Name, Db}) -> call({table_create, Name, Db}); table_create(Name) -> call({table_create, Name, volatile}). table_exists({Name, Db}) -> call({table_exists, Name, Db}); table_exists(Name) -> call({table_exists, Name, volatile}). table_delete({Name, Db}) -> call({table_delete, Name, Db}); table_delete(Name) -> call({table_delete, Name, volatile}). table_delete_row({Name, Db}, RowIndex) -> call({table_delete_row, Name, Db, RowIndex}); table_delete_row(Name, RowIndex) -> call({table_delete_row, Name, volatile, RowIndex}). table_get_row({Name, Db}, RowIndex) -> call({table_get_row, Name, Db, RowIndex}); table_get_row(Name, RowIndex) -> call({table_get_row, Name, volatile, RowIndex}). table_get_element({Name, Db}, RowIndex, Col) -> call({table_get_element, Name, Db, RowIndex, Col}); table_get_element(Name, RowIndex, Col) -> call({table_get_element, Name, volatile, RowIndex, Col}). table_set_elements({Name, Db}, RowIndex, Cols) -> call({table_set_elements, Name, Db, RowIndex, Cols}); table_set_elements(Name, RowIndex, Cols) -> call({table_set_elements, Name, volatile, RowIndex, Cols}). table_next({Name, Db}, RestOid) -> call({table_next, Name, Db, RestOid}); table_next(Name, RestOid) -> call({table_next, Name, volatile, RestOid}). table_max_col({Name, Db}, Col) -> call({table_max_col, Name, Db, Col}); table_max_col(Name, Col) -> call({table_max_col, Name, volatile, Col}). table_create_row({Name, Db}, RowIndex, Row) -> call({table_create_row, Name, Db,RowIndex, Row}); table_create_row(Name, RowIndex, Row) -> call({table_create_row, Name, volatile, RowIndex, Row}). table_create_row(NameDb, RowIndex, Status, Cols) -> Row = table_construct_row(NameDb, RowIndex, Status, Cols), table_create_row(NameDb, RowIndex, Row). match({Name, Db}, Pattern) -> call({match, Name, Db, Pattern}); match(Name, Pattern) -> call({match, Name, volatile, Pattern}). %%----------------------------------------------------------------- %% Implements the variable functions. %%----------------------------------------------------------------- handle_call({variable_get, Name, Db}, _From, State) -> ?vlog("variable get: ~p [~p]",[Name, Db]), {reply, lookup(Db, Name, State), State}; handle_call({variable_set, Name, Db, Val}, _From, State) -> ?vlog("variable ~p set [~p]: " "~n Val: ~p",[Name, Db, Val]), {reply, insert(Db, Name, Val, State), State}; handle_call({variable_delete, Name, Db}, _From, State) -> ?vlog("variable delete: ~p [~p]",[Name, Db]), {reply, delete(Db, Name, State), State}; %%----------------------------------------------------------------- %% Implements the table functions. %%----------------------------------------------------------------- %% Entry in ets for a tablerow: %% Key = {<tableName>, <(flat) list of indexes>} %% Val = {{Row}, <Prev>, <Next>} %% Where Prev and Next = <list of indexes>; "pointer to prev/next" %% Each table is a double linked list, with a head-element, with %% direct access to each individual element. Head - el : Key = { < tableName > , first } %% Operations: %% table_create_row(<tableName>, <list of indexes>, <row>) O(n) > , < list of indexes > ) O(1 ) %% get(<tableName>, <list of indexes>, Col) O(1) set(<tableName > , < list of indexes > , Col , ) O(1 ) > , < list of indexes > ) if Row exist O(1 ) , else O(n ) %%----------------------------------------------------------------- handle_call({table_create, Name, Db}, _From, State) -> ?vlog("table create: ~p [~p]",[Name, Db]), catch handle_delete(Db, Name, State), {reply, insert(Db, {Name, first}, {undef, first, first}, State), State}; handle_call({table_exists, Name, Db}, _From, State) -> ?vlog("table exist: ~p [~p]",[Name, Db]), Res = case lookup(Db, {Name, first}, State) of {value, _} -> true; undefined -> false end, ?vdebug("table exist result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_delete, Name, Db}, _From, State) -> ?vlog("table delete: ~p [~p]",[Name, Db]), catch handle_delete(Db, Name, State), {reply, true, State}; handle_call({table_create_row, Name, Db, Indexes, Row}, _From, State) -> ?vlog("table create row [~p]: " "~n Name: ~p" "~n Indexes: ~p" "~n Row: ~p",[Db, Name, Indexes, Row]), Res = case catch handle_create_row(Db, Name, Indexes, Row, State) of {'EXIT', _} -> false; _ -> true end, ?vdebug("table create row result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_delete_row, Name, Db, Indexes}, _From, State) -> ?vlog("table delete row [~p]: " "~n Name: ~p" "~n Indexes: ~p", [Db, Name, Indexes]), Res = case catch handle_delete_row(Db, Name, Indexes, State) of {'EXIT', _} -> false; _ -> true end, ?vdebug("table delete row result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_get_row, Name, Db, Indexes}, _From, State) -> ?vlog("table get row [~p]: " "~n Name: ~p" "~n Indexes: ~p",[Db, Name, Indexes]), Res = case lookup(Db, {Name, Indexes}, State) of undefined -> undefined; {value, {Row, _Prev, _Next}} -> Row end, ?vdebug("table get row result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_get_element, Name, Db, Indexes, Col}, _From, State) -> ?vlog("table ~p get element [~p]: " "~n Indexes: ~p" "~n Col: ~p", [Name, Db, Indexes, Col]), Res = case lookup(Db, {Name, Indexes}, State) of undefined -> undefined; {value, {Row, _Prev, _Next}} -> {value, element(Col, Row)} end, ?vdebug("table get element result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_set_elements, Name, Db, Indexes, Cols}, _From, State) -> ?vlog("table ~p set element [~p]: " "~n Indexes: ~p" "~n Cols: ~p", [Name, Db, Indexes, Cols]), Res = case catch handle_set_elements(Db, Name, Indexes, Cols, State) of {'EXIT', _} -> false; _ -> true end, ?vdebug("table set element result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_next, Name, Db, []}, From, State) -> ?vlog("table next: ~p [~p]",[Name, Db]), handle_call({table_next, Name, Db, first}, From, State); handle_call({table_next, Name, Db, Indexes}, _From, State) -> ?vlog("table ~p next [~p]: " "~n Indexes: ~p",[Name, Db, Indexes]), Res = case lookup(Db, {Name, Indexes}, State) of {value, {_Row, _Prev, Next}} -> if Next == first -> endOfTable; true -> Next end; undefined -> table_search_next(Db, Name, Indexes, State) end, ?vdebug("table next result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_max_col, Name, Db, Col}, _From, State) -> ?vlog("table ~p max col [~p]: " "~n Col: ~p",[Name, Db, Col]), Res = table_max_col(Db, Name, Col, 0, first, State), ?vdebug("table max col result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({match, Name, Db, Pattern}, _From, State) -> ?vlog("match ~p [~p]:" "~n Pat: ~p", [Name, Db, Pattern]), L1 = match(Db, Name, Pattern, State), {reply, lists:delete([undef], L1), State}; handle_call({backup, BackupDir}, From, #state{dets = Dets} = State) -> ?vlog("backup: ~p",[BackupDir]), Pid = self(), V = get(verbosity), case file:read_file_info(BackupDir) of {ok, #file_info{type = directory}} -> BackupServer = erlang:spawn_link( fun() -> put(sname, albs), put(verbosity, V), Dir = filename:join([BackupDir]), #dets{tab = Tab} = Dets, Reply = handle_backup(Tab, Dir), Pid ! {backup_done, Reply}, unlink(Pid) end), ?vtrace("backup server: ~p", [BackupServer]), {noreply, State#state{backup = {BackupServer, From}}}; {ok, _} -> {reply, {error, not_a_directory}, State}; Error -> {reply, Error, State} end; handle_call(dump, _From, #state{dets = Dets} = State) -> ?vlog("dump",[]), dets_sync(Dets), {reply, ok, State}; handle_call(info, _From, #state{dets = Dets, ets = Ets} = State) -> ?vlog("info",[]), Info = get_info(Dets, Ets), {reply, Info, State}; handle_call(print, _From, #state{dets = Dets, ets = Ets} = State) -> ?vlog("print",[]), L1 = ets:tab2list(Ets), L2 = dets_match_object(Dets, '_'), {reply, {{ets, L1}, {dets, L2}}, State}; handle_call({print, Table, Db}, _From, State) -> ?vlog("print: ~p [~p]", [Table, Db]), L = match(Db, Table, '$1', State), {reply, lists:delete([undef], L), State}; handle_call({register_notify_client, Client, Module}, _From, State) -> ?vlog("register_notify_client: " "~n Client: ~p" "~n Module: ~p", [Client, Module]), Nc = State#state.notify_clients, case lists:keysearch(Client,1,Nc) of {value,{Client,Mod}} -> ?vlog("register_notify_client: already registered to: ~p", [Module]), {reply, {error,{already_registered,Mod}}, State}; false -> {reply, ok, State#state{notify_clients = [{Client,Module}|Nc]}} end; handle_call({unregister_notify_client, Client}, _From, State) -> ?vlog("unregister_notify_client: ~p",[Client]), Nc = State#state.notify_clients, case lists:keysearch(Client,1,Nc) of {value,{Client,_Module}} -> Nc1 = lists:keydelete(Client,1,Nc), {reply, ok, State#state{notify_clients = Nc1}}; false -> ?vlog("unregister_notify_client: not registered",[]), {reply, {error,not_registered}, State} end; handle_call(stop, _From, State) -> ?vlog("stop",[]), {stop, normal, stopped, State}; handle_call(Req, _From, State) -> warning_msg("received unknown request: ~n~p", [Req]), Reply = {error, {unknown, Req}}, {reply, Reply, State}. handle_cast({variable_inc, Name, Db, N}, State) -> ?vlog("variable ~p inc" "~n N: ~p", [Name, N]), M = case lookup(Db, Name, State) of {value, Val} -> Val; _ -> 0 end, insert(Db, Name, M+N rem 4294967296, State), {noreply, State}; handle_cast({verbosity,Verbosity}, State) -> ?vlog("verbosity: ~p -> ~p",[get(verbosity),Verbosity]), put(verbosity,?vvalidate(Verbosity)), {noreply, State}; handle_cast(Msg, State) -> warning_msg("received unknown message: ~n~p", [Msg]), {noreply, State}. handle_info({'EXIT', Pid, Reason}, #state{backup = {Pid, From}} = S) -> ?vlog("backup server (~p) exited for reason ~n~p", [Pid, Reason]), gen_server:reply(From, {error, Reason}), {noreply, S#state{backup = undefined}}; handle_info({'EXIT', Pid, Reason}, S) -> %% The only other processes we should be linked to are %% either the master agent or our supervisor, so die... {stop, {received_exit, Pid, Reason}, S}; handle_info({backup_done, Reply}, #state{backup = {_, From}} = S) -> ?vlog("backup done:" "~n Reply: ~p", [Reply]), gen_server:reply(From, Reply), {noreply, S#state{backup = undefined}}; handle_info(Info, State) -> warning_msg("received unknown info: ~n~p", [Info]), {noreply, State}. terminate(Reason, State) -> ?vlog("terminate: ~p",[Reason]), close(State). %%---------------------------------------------------------- %% Code change %%---------------------------------------------------------- %% downgrade %% code_change({down, _Vsn}, S1, downgrade_to_pre_4_11) -> #state{dets = D} = S1, #dets{tab = Dets, shadow = Shadow} = D, ets:delete(Shadow), S2 = S1#state{dets = Dets}, {ok, S2}; %% upgrade %% code_change(_Vsn, S1, upgrade_from_pre_4_11) -> #state{dets = D} = S1, Shadow = ets:new(snmp_local_db1_shadow, [set, protected]), dets:to_ets(D, Shadow), Dets = #dets{tab = D, shadow = Shadow}, S2 = S1#state{dets = Dets}, {ok, S2}; code_change(_Vsn, State, _Extra) -> {ok, State}. %%---------------------------------------------------------- %% Backup %%---------------------------------------------------------- handle_backup(D, BackupDir) -> First check that we do not wrote to the corrent db - dir ... ?vtrace("handle_backup -> entry with" "~n D: ~p" "~n BackupDir: ~p", [D, BackupDir]), case dets:info(D, filename) of undefined -> ?vinfo("handle_backup -> no file to backup", []), {error, no_file}; Filename -> ?vinfo("handle_backup -> file to backup: ~n ~p", [Filename]), case filename:dirname(Filename) of BackupDir -> ?vinfo("handle_backup -> backup dir and db dir the same", []), {error, db_dir}; _ -> case file:read_file_info(BackupDir) of {ok, #file_info{type = directory}} -> ?vdebug("handle_backup -> backup dir ok", []), %% All well so far... Type = dets:info(D, type), KP = dets:info(D, keypos), dets_backup(D, filename:basename(Filename), BackupDir, Type, KP); {ok, _} -> ?vinfo("handle_backup -> backup dir not a dir", []), {error, not_a_directory}; Error -> ?vinfo("handle_backup -> Error: ~p", [Error]), Error end end end. dets_backup(D, Filename, BackupDir, Type, KP) -> ?vtrace("dets_backup -> entry with" "~n D: ~p" "~n Filename: ~p" "~n BackupDir: ~p", [D, Filename, BackupDir]), BackupFile = filename:join(BackupDir, Filename), ?vtrace("dets_backup -> " "~n BackupFile: ~p", [BackupFile]), Opts = [{file, BackupFile}, {type, Type}, {keypos, KP}], case dets:open_file(?BACKUP_TAB, Opts) of {ok, B} -> F = fun(Arg) -> dets_backup(Arg, start, D, B) end, ?vtrace("dets_backup -> fix table", []), dets:safe_fixtable(D, true), ?vtrace("dets_backup -> copy table", []), Res = dets:init_table(?BACKUP_TAB, F, [{format, bchunk}]), ?vtrace("dets_backup -> unfix table", []), dets:safe_fixtable(D, false), ?vtrace("dets_backup -> Res: ~p", [Res]), Res; Error -> ?vinfo("dets_backup -> open_file failed: " "~n ~p", [Error]), Error end. dets_backup(close, _Cont, _D, B) -> dets:close(B), ok; dets_backup(read, Cont1, D, B) -> case dets:bchunk(D, Cont1) of {Cont2, Data} -> F = fun(Arg) -> dets_backup(Arg, Cont2, D, B) end, {Data, F}; '$end_of_table' -> dets:close(B), end_of_input; Error -> Error end. %%----------------------------------------------------------------- %% All handle_ functions exists so we can catch the call to %% them, because we don't want to crash the server if a user %% forgets to call e.g. table_create. %%----------------------------------------------------------------- %% Find larger element and insert before. handle_create_row(Db, Name, Indexes, Row, State) -> case table_find_first_after_maybe_same(Db, Name, Indexes, State) of {{Name, Next}, {NRow, NPrev, NNext}} -> {value, {PRow, PPrev, _PNext}} = lookup(Db, {Name, NPrev}, State), if Next == NPrev -> Insert before first insert(Db, {Name, NPrev}, {PRow, Indexes, Indexes}, State); true -> insert(Db, {Name, NPrev}, {PRow, PPrev, Indexes}, State), insert(Db, {Name, Next}, {NRow, Indexes, NNext}, State) end, insert(Db, {Name, Indexes}, {Row, NPrev, Next}, State); {same_row, {Prev, Next}} -> insert(Db, {Name, Indexes}, {Row, Prev, Next}, State) end. handle_delete_row(Db, Name, Indexes, State) -> {value, {_, Prev, Next}} = lookup(Db, {Name, Indexes}, State), {value, {PRow, PPrev, Indexes}} = lookup(Db, {Name, Prev}, State), insert(Db, {Name, Prev}, {PRow, PPrev, Next}, State), {value, {NRow, Indexes, NNext}} = lookup(Db, {Name, Next}, State), insert(Db, {Name, Next}, {NRow, Prev, NNext}, State), delete(Db, {Name, Indexes}, State). handle_set_elements(Db, Name, Indexes, Cols, State) -> {value, {Row, Prev, Next}} = lookup(Db, {Name, Indexes}, State), NewRow = set_new_row(Cols, Row), insert(Db, {Name, Indexes}, {NewRow, Prev, Next}, State). set_new_row([{Col, Val} | Cols], Row) -> set_new_row(Cols, setelement(Col, Row, Val)); set_new_row([], Row) -> Row. handle_delete(Db, Name, State) -> {value, {_, _, Next}} = lookup(Db, {Name, first}, State), delete(Db, {Name, first}, State), handle_delete(Db, Name, Next, State). handle_delete(_Db, _Name, first, _State) -> true; handle_delete(Db, Name, Indexes, State) -> {value, {_, _, Next}} = lookup(Db, {Name, Indexes}, State), delete(Db, {Name, Indexes}, State), handle_delete(Db, Name, Next, State). %%----------------------------------------------------------------- %% Implementation of next. %%----------------------------------------------------------------- table_search_next(Db, Name, Indexes, State) -> case catch table_find_first_after(Db, Name, Indexes, State) of {{Name, Key}, {_, _, _Next}} -> case Key of first -> endOfTable; _ -> Key end; {'EXIT', _} -> endOfTable end. table_find_first_after(Db, Name, Indexes, State) -> {value, {_Row, _Prev, Next}} = lookup(Db, {Name, first}, State), table_loop(Db, Name, Indexes, Next, State). table_loop(Db, Name, _Indexes, first, State) -> {value, FirstVal} = lookup(Db, {Name, first}, State), {{Name, first}, FirstVal}; table_loop(Db, Name, Indexes, Cur, State) -> {value, {Row, Prev, Next}} = lookup(Db, {Name, Cur}, State), if Cur > Indexes -> {{Name, Cur}, {Row, Prev, Next}}; true -> table_loop(Db, Name, Indexes, Next, State) end. table_find_first_after_maybe_same(Db, Name, Indexes, State) -> {value, {_Row, _Prev, Next}} = lookup(Db, {Name, first}, State), table_loop2(Db, Name, Indexes, Next, State). table_loop2(Db, Name, _Indexes, first, State) -> {value, FirstVal} = lookup(Db, {Name, first}, State), {{Name, first}, FirstVal}; table_loop2(Db, Name, Indexes, Cur, State) -> {value, {Row, Prev, Next}} = lookup(Db, {Name, Cur}, State), if Cur > Indexes -> {{Name, Cur}, {Row, Prev, Next}}; Cur == Indexes -> {same_row, {Prev, Next}}; true -> table_loop2(Db, Name, Indexes, Next, State) end. %%----------------------------------------------------------------- %% Implementation of max. %% The value in a column could be noinit or undefined, %% so we must check only those with an integer. %%----------------------------------------------------------------- table_max_col(Db, Name, Col, Max, Indexes, State) -> case lookup(Db, {Name, Indexes}, State) of {value, {Row, _Prev, Next}} -> if Next == first -> if integer(element(Col, Row)), element(Col, Row) > Max -> element(Col, Row); true -> Max end; integer(element(Col, Row)), element(Col, Row) > Max -> table_max_col(Db,Name, Col,element(Col, Row),Next, State); true -> table_max_col(Db, Name, Col, Max, Next, State) end; undefined -> table_search_next(Db, Name, Indexes, State) end. %%----------------------------------------------------------------- Interface to Pets . %%----------------------------------------------------------------- insert(volatile, Key, Val, #state{ets = Ets}) -> ?vtrace("insert(volatile) -> entry with" "~n Key: ~p" "~n Val: ~p", [Key,Val]), ets:insert(Ets, {Key, Val}), true; insert(persistent, Key, Val, #state{dets = Dets, notify_clients = NC}) -> ?vtrace("insert(persistent) -> entry with" "~n Key: ~p" "~n Val: ~p", [Key,Val]), case dets_insert(Dets, {Key, Val}) of ok -> notify_clients(insert,NC), true; {error, Reason} -> error_msg("DETS (persistent) insert failed for {~w,~w}: ~n~w", [Key, Val, Reason]), false end; insert(permanent, Key, Val, #state{dets = Dets, notify_clients = NC}) -> ?vtrace("insert(permanent) -> entry with" "~n Key: ~p" "~n Val: ~p", [Key,Val]), case dets_insert(Dets, {Key, Val}) of ok -> notify_clients(insert,NC), true; {error, Reason} -> error_msg("DETS (permanent) insert failed for {~w,~w}: ~n~w", [Key, Val, Reason]), false end; insert(UnknownDb, Key, Val, _) -> error_msg("Tried to insert ~w = ~w into unknown db ~w", [Key, Val, UnknownDb]), false. delete(volatile, Key, State) -> ets:delete(State#state.ets, Key), true; delete(persistent, Key, #state{dets = Dets, notify_clients = NC}) -> case dets_delete(Dets, Key) of ok -> notify_clients(delete,NC), true; {error, Reason} -> error_msg("DETS (persistent) delete failed for ~w: ~n~w", [Key, Reason]), false end; delete(permanent, Key, #state{dets = Dets, notify_clients = NC}) -> case dets_delete(Dets, Key) of ok -> notify_clients(delete,NC), true; {error, Reason} -> error_msg("DETS (permanent) delete failed for ~w: ~n~w", [Key, Reason]), false end; delete(UnknownDb, Key, _) -> error_msg("Tried to delete ~w from unknown db ~w", [Key, UnknownDb]), false. match(volatile, Name, Pattern, #state{ets = Ets}) -> ets:match(Ets, {{Name,'_'},{Pattern,'_','_'}}); match(persistent, Name, Pattern, #state{dets = Dets}) -> dets_match(Dets, {{Name,'_'},{Pattern,'_','_'}}); match(permanent, Name, Pattern, #state{dets = Dets}) -> dets_match(Dets, {{Name,'_'},{Pattern,'_','_'}}); match(UnknownDb, Name, Pattern, _) -> error_msg("Tried to match [~p,~p] from unknown db ~w", [Name, Pattern, UnknownDb]), []. lookup(volatile, Key, #state{ets = Ets}) -> case ets:lookup(Ets, Key) of [{_, Val}] -> {value, Val}; [] -> undefined end; lookup(persistent, Key, #state{dets = Dets}) -> case dets_lookup(Dets, Key) of [{_, Val}] -> {value, Val}; [] -> undefined end; lookup(permanent, Key, #state{dets = Dets}) -> case dets_lookup(Dets, Key) of [{_, Val}] -> {value, Val}; [] -> undefined end; lookup(UnknownDb, Key, _) -> error_msg("Tried to lookup ~w in unknown db ~w", [Key, UnknownDb]), false. close(#state{dets = Dets, ets = Ets}) -> ets:delete(Ets), dets_close(Dets). %%----------------------------------------------------------------- %% Notify clients interface %%----------------------------------------------------------------- notify_clients(Event, Clients) -> F = fun(Client) -> notify_client(Client, Event) end, lists:foreach(F, Clients). notify_client({Client,Module}, Event) -> (catch Module:notify(Client,Event)). %%------------------------------------------------------------------ Constructs a row with first elements the own part of RowIndex , and last element RowStatus . All values are stored " as is " , i.e. dynamic key values are stored without length first . RowIndex is a list of the first elements . RowStatus is needed , because the %% provided value may not be stored, e.g. createAndGo %% should be active. %% Returns a tuple of values for the row. If a value %% isn't specified in the Col list, then the %% corresponding value will be noinit. %%------------------------------------------------------------------ table_construct_row(Name, RowIndex, Status, Cols) -> #table_info{nbr_of_cols = LastCol, index_types = Indexes, defvals = Defs, status_col = StatusCol, first_own_index = FirstOwnIndex, not_accessible = NoAccs} = snmp_generic:table_info(Name), Keys = snmp_generic:split_index_to_keys(Indexes, RowIndex), OwnKeys = snmp_generic:get_own_indexes(FirstOwnIndex, Keys), Row = OwnKeys ++ snmp_generic:table_create_rest(length(OwnKeys) + 1, LastCol, StatusCol, Status, Cols, NoAccs), L = snmp_generic:init_defaults(Defs, Row), list_to_tuple(L). table_get_elements(NameDb, RowIndex, Cols, _FirstOwnIndex) -> get_elements(Cols, table_get_row(NameDb, RowIndex)). get_elements(_Cols, undefined) -> undefined; get_elements([Col | Cols], Row) when is_tuple(Row) and (size(Row) >= Col) -> [element(Col, Row) | get_elements(Cols, Row)]; get_elements([], _Row) -> []; get_elements(Cols, Row) -> erlang:error({bad_arguments, Cols, Row}). %%---------------------------------------------------------------------- This should / could be a generic function , but since implements its own and this version still is local_db dependent , it 's not generic yet . %%---------------------------------------------------------------------- %% createAndGo table_set_status(NameDb, RowIndex, ?'RowStatus_createAndGo', StatusCol, Cols, ChangedStatusFunc, _ConsFunc) -> case table_create_row(NameDb, RowIndex, ?'RowStatus_active', Cols) of true -> snmp_generic:try_apply(ChangedStatusFunc, [NameDb, ?'RowStatus_createAndGo', RowIndex, Cols]); _ -> {commitFailed, StatusCol} end; %%------------------------------------------------------------------ createAndWait - set status to notReady , and try to %% make row consistent. %%------------------------------------------------------------------ table_set_status(NameDb, RowIndex, ?'RowStatus_createAndWait', StatusCol, Cols, ChangedStatusFunc, ConsFunc) -> case table_create_row(NameDb, RowIndex, ?'RowStatus_notReady', Cols) of true -> case snmp_generic:try_apply(ConsFunc, [NameDb, RowIndex, Cols]) of {noError, 0} -> snmp_generic:try_apply(ChangedStatusFunc, [NameDb, ?'RowStatus_createAndWait', RowIndex, Cols]); Error -> Error end; _ -> {commitFailed, StatusCol} end; %% destroy table_set_status(NameDb, RowIndex, ?'RowStatus_destroy', _StatusCol, Cols, ChangedStatusFunc, _ConsFunc) -> case snmp_generic:try_apply(ChangedStatusFunc, [NameDb, ?'RowStatus_destroy', RowIndex, Cols]) of {noError, 0} -> table_delete_row(NameDb, RowIndex), {noError, 0}; Error -> Error end; %% Otherwise, active or notInService table_set_status(NameDb, RowIndex, Val, _StatusCol, Cols, ChangedStatusFunc, ConsFunc) -> snmp_generic:table_set_cols(NameDb, RowIndex, Cols, ConsFunc), snmp_generic:try_apply(ChangedStatusFunc, [NameDb, Val, RowIndex, Cols]). table_func(new, NameDb) -> case table_exists(NameDb) of true -> ok; _ -> table_create(NameDb) end; table_func(delete, _NameDb) -> ok. table_func(get, RowIndex, Cols, NameDb) -> TableInfo = snmp_generic:table_info(NameDb), snmp_generic:handle_table_get(NameDb, RowIndex, Cols, TableInfo#table_info.first_own_index); %%------------------------------------------------------------------ Returns : List of endOfTable | { NextOid , Value } . %% Implements the next operation, with the function %% handle_table_next. Next should return the next accessible %% instance, which cannot be a key. %%------------------------------------------------------------------ table_func(get_next, RowIndex, Cols, NameDb) -> #table_info{first_accessible = FirstCol, first_own_index = FOI, nbr_of_cols = LastCol} = snmp_generic:table_info(NameDb), snmp_generic:handle_table_next(NameDb, RowIndex, Cols, FirstCol, FOI, LastCol); %%----------------------------------------------------------------- This function must only be used by tables with a RowStatus col ! %% Other tables must check if row exist themselves. %%----------------------------------------------------------------- table_func(is_set_ok, RowIndex, Cols, NameDb) -> snmp_generic:table_try_row(NameDb, nofunc, RowIndex, Cols); %%------------------------------------------------------------------ is here a list of { ColumnNumber , NewValue } This function must only be used by tables with a RowStatus col ! %% Other tables should use table_set_cols/3,4. %%------------------------------------------------------------------ table_func(set, RowIndex, Cols, NameDb) -> snmp_generic:table_set_row(NameDb, nofunc, {snmp_generic, table_try_make_consistent}, RowIndex, Cols); table_func(undo, _RowIndex, _Cols, _NameDb) -> {noError, 0}. %%------------------------------------------------------------------ %% This functions retrieves option values from the Options list. %%------------------------------------------------------------------ get_opt(Key, Opts, Def) -> snmp_misc:get_option(Key, Opts, Def). %%------------------------------------------------------------------ get_info(Dets, Ets) -> ProcSize = proc_mem(self()), DetsSz = dets_size(Dets), EtsSz = ets_size(Ets), [{process_memory, ProcSize}, {db_memory, [{persistent, DetsSz}, {volatile, EtsSz}]}]. proc_mem(P) when is_pid(P) -> case (catch erlang:process_info(P, memory)) of {memory, Sz} -> Sz; _ -> undefined end. %% proc_mem(_) -> %% undefined. dets_size(#dets{tab = Tab, shadow = Shadow}) -> TabSz = case (catch dets:info(Tab, file_size)) of Sz when is_integer(Sz) -> Sz; _ -> undefined end, ShadowSz = ets_size(Shadow), [{tab, TabSz}, {shadow, ShadowSz}]. ets_size(T) -> case (catch ets:info(T, memory)) of Sz when is_integer(Sz) -> Sz; _ -> undefined end. %%------------------------------------------------------------------ %% info_msg(F, A) -> %% ?snmpa_info("Local DB server: " ++ F, A). warning_msg(F, A) -> ?snmpa_warning("Local DB server: " ++ F, A). error_msg(F, A) -> ?snmpa_error("Local DB server: " ++ F, A). %% --- user_err(F, A) -> snmpa_error:user_err(F, A). config_err(F, A) -> snmpa_error:config_err(F, A). %% ---------------------------------------------------------------- call(Req) -> gen_server:call(?SERVER, Req, infinity). cast(Msg) -> gen_server:cast(?SERVER, Msg). %% ---------------------------------------------------------------- %% DETS wrapper functions %% The purpose of these fuctions is basically to hide the shadow %% table. %% Changes are made both in dets and in the shadow table. %% Reads are made from the shadow table. %% ---------------------------------------------------------------- dets_sync(#dets{tab = Dets}) -> dets:sync(Dets). dets_insert(#dets{tab = Tab, shadow = Shadow}, Data) -> ets:insert(Shadow, Data), dets:insert(Tab, Data). dets_delete(#dets{tab = Tab, shadow = Shadow}, Key) -> ets:delete(Shadow, Key), dets:delete(Tab, Key). dets_match(#dets{shadow = Shadow}, Pat) -> ets:match(Shadow, Pat). dets_match_object(#dets{shadow = Shadow}, Pat) -> ets:match_object(Shadow, Pat). dets_lookup(#dets{shadow = Shadow}, Key) -> ets:lookup(Shadow, Key). dets_close(#dets{tab = Tab, shadow = Shadow}) -> ets:delete(Shadow), dets:close(Tab).
null
https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/snmp/src/agent/snmpa_local_db.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% -define(VMODULE, "LDB"). External exports Debug exports Internal exports -define(snmp_debug,true). ----------------------------------------------------------------- Implements a general database in which its possible to store variables and tables. Provide functions for tableaccess by row or by element, and for next. Opts = [Opt] {verbosity,silence | log | debug} ----------------------------------------------------------------- ----------------------------------------------------------------- File exists ----------------------------------------------------------------- ----------------------------------------------------------------- ----------------------------------------------------------------- Functions for debugging. ----------------------------------------------------------------- ----------------------------------------------------------------- Implements the variable functions. ----------------------------------------------------------------- ----------------------------------------------------------------- Implements the table functions. ----------------------------------------------------------------- Entry in ets for a tablerow: Key = {<tableName>, <(flat) list of indexes>} Val = {{Row}, <Prev>, <Next>} Where Prev and Next = <list of indexes>; "pointer to prev/next" Each table is a double linked list, with a head-element, with direct access to each individual element. Operations: table_create_row(<tableName>, <list of indexes>, <row>) O(n) get(<tableName>, <list of indexes>, Col) O(1) ----------------------------------------------------------------- The only other processes we should be linked to are either the master agent or our supervisor, so die... ---------------------------------------------------------- Code change ---------------------------------------------------------- downgrade upgrade ---------------------------------------------------------- Backup ---------------------------------------------------------- All well so far... ----------------------------------------------------------------- All handle_ functions exists so we can catch the call to them, because we don't want to crash the server if a user forgets to call e.g. table_create. ----------------------------------------------------------------- Find larger element and insert before. ----------------------------------------------------------------- Implementation of next. ----------------------------------------------------------------- ----------------------------------------------------------------- Implementation of max. The value in a column could be noinit or undefined, so we must check only those with an integer. ----------------------------------------------------------------- ----------------------------------------------------------------- ----------------------------------------------------------------- ----------------------------------------------------------------- Notify clients interface ----------------------------------------------------------------- ------------------------------------------------------------------ provided value may not be stored, e.g. createAndGo should be active. Returns a tuple of values for the row. If a value isn't specified in the Col list, then the corresponding value will be noinit. ------------------------------------------------------------------ ---------------------------------------------------------------------- ---------------------------------------------------------------------- createAndGo ------------------------------------------------------------------ make row consistent. ------------------------------------------------------------------ destroy Otherwise, active or notInService ------------------------------------------------------------------ Implements the next operation, with the function handle_table_next. Next should return the next accessible instance, which cannot be a key. ------------------------------------------------------------------ ----------------------------------------------------------------- Other tables must check if row exist themselves. ----------------------------------------------------------------- ------------------------------------------------------------------ Other tables should use table_set_cols/3,4. ------------------------------------------------------------------ ------------------------------------------------------------------ This functions retrieves option values from the Options list. ------------------------------------------------------------------ ------------------------------------------------------------------ proc_mem(_) -> undefined. ------------------------------------------------------------------ info_msg(F, A) -> ?snmpa_info("Local DB server: " ++ F, A). --- ---------------------------------------------------------------- ---------------------------------------------------------------- DETS wrapper functions The purpose of these fuctions is basically to hide the shadow table. Changes are made both in dets and in the shadow table. Reads are made from the shadow table. ----------------------------------------------------------------
Copyright Ericsson AB 1996 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(snmpa_local_db). -include_lib("kernel/include/file.hrl"). -include("snmpa_internal.hrl"). -include("snmp_types.hrl"). -include("STANDARD-MIB.hrl"). -include("snmp_verbosity.hrl"). -export([start_link/3, start_link/4, stop/0, info/0, verbosity/1]). -export([dump/0, backup/1, register_notify_client/2, unregister_notify_client/1]). -export([table_func/2, table_func/4, variable_get/1, variable_set/2, variable_delete/1, variable_inc/2, table_create/1, table_exists/1, table_delete/1, table_create_row/3, table_create_row/4, table_construct_row/4, table_delete_row/2, table_get_row/2, table_get_element/3, table_get_elements/4, table_set_elements/3, table_set_status/7, table_next/2, table_max_col/2]). -export([get_elements/2]). -export([match/2]). -export([print/0, print/1, print/2]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(BACKUP_TAB, snmpa_local_backup). -define(DETS_TAB, snmpa_local_db1). -define(ETS_TAB, snmpa_local_db2). -define(SERVER, ?MODULE). -record(state, {dets, ets, notify_clients = [], backup}). -record(dets, {tab, shadow}). -include("snmp_debug.hrl"). -ifdef(snmp_debug). -define(GS_START_LINK(Prio, Dir, DbInitError, Opts), gen_server:start_link({local, ?SERVER}, ?MODULE, [Prio, Dir, DbInitError, Opts], [{debug,[trace]}])). -else. -define(GS_START_LINK(Prio, Dir, DbInitError, Opts), gen_server:start_link({local, ?SERVER}, ?MODULE, [Prio, Dir, DbInitError, Opts], [])). -endif. Opt = { auto_repair , false | true | true_verbose } | start_link(Prio, DbDir, Opts) when list(Opts) -> start_link(Prio, DbDir, terminate, Opts). start_link(Prio, DbDir, DbInitError, Opts) when list(Opts) -> ?d("start_link -> entry with" "~n Prio: ~p" "~n DbDir: ~p" "~n DbInitError: ~p" "~n Opts: ~p", [Prio, DbDir, DbInitError, Opts]), ?GS_START_LINK(Prio, DbDir, DbInitError, Opts). stop() -> call(stop). register_notify_client(Client,Module) -> call({register_notify_client,Client,Module}). unregister_notify_client(Client) -> call({unregister_notify_client,Client}). backup(BackupDir) -> call({backup, BackupDir}). dump() -> call(dump). info() -> call(info). verbosity(Verbosity) -> cast({verbosity,Verbosity}). init([Prio, DbDir, DbInitError, Opts]) -> ?d("init -> entry with" "~n Prio: ~p" "~n DbDir: ~p" "~n DbInitError: ~p" "~n Opts: ~p", [Prio, DbDir, DbInitError, Opts]), case (catch do_init(Prio, DbDir, DbInitError, Opts)) of {ok, State} -> ?vdebug("started",[]), {ok, State}; {error, Reason} -> config_err("failed starting local-db: ~n~p", [Reason]), {stop, {error, Reason}}; Error -> config_err("failed starting local-db: ~n~p", [Error]), {stop, {error, Error}} end. do_init(Prio, DbDir, DbInitError, Opts) -> process_flag(priority, Prio), process_flag(trap_exit, true), put(sname,ldb), put(verbosity,get_opt(verbosity, Opts, ?default_verbosity)), ?vlog("starting",[]), Dets = dets_open(DbDir, DbInitError, Opts), Ets = ets:new(?ETS_TAB, [set, protected]), ?vdebug("started",[]), {ok, #state{dets = Dets, ets = Ets}}. dets_open(DbDir, DbInitError, Opts) -> Name = ?DETS_TAB, Filename = dets_filename(Name, DbDir), case file:read_file_info(Filename) of {ok, _} -> case do_dets_open(Name, Filename, Opts) of {ok, Dets} -> ?vdebug("dets open done",[]), Shadow = ets:new(snmp_local_db1_shadow, [set, protected]), dets:to_ets(Dets, Shadow), ?vtrace("shadow table created and populated",[]), #dets{tab = Dets, shadow = Shadow}; {error, Reason1} -> user_err("Corrupt local database: ~p", [Filename]), case DbInitError of terminate -> throw({error, {failed_open_dets, Reason1}}); _ -> Saved = Filename ++ ".saved", file:rename(Filename, Saved), case do_dets_open(Name, Filename, Opts) of {ok, Dets} -> Shadow = ets:new(snmp_local_db1_shadow, [set, protected]), #dets{tab = Dets, shadow = Shadow}; {error, Reason2} -> user_err("Could not create local " "database: ~p" "~n ~p" "~n ~p", [Filename, Reason1, Reason2]), throw({error, {failed_open_dets, Reason2}}) end end end; _ -> case do_dets_open(Name, Filename, Opts) of {ok, Dets} -> ?vdebug("dets open done",[]), Shadow = ets:new(snmp_local_db1_shadow, [set, protected]), ?vtrace("shadow table created",[]), #dets{tab = Dets, shadow = Shadow}; {error, Reason} -> user_err("Could not create local database ~p" "~n ~p", [Filename, Reason]), throw({error, {failed_open_dets, Reason}}) end end. do_dets_open(Name, Filename, Opts) -> Repair = get_opt(repair, Opts, true), AutoSave = get_opt(auto_save, Opts, 5000), Args = [{auto_save, AutoSave}, {file, Filename}, {repair, Repair}], dets:open_file(Name, Args). dets_filename(Name, Dir) when is_atom(Name) -> dets_filename(atom_to_list(Name), Dir); dets_filename(Name, Dir) -> filename:join(dets_filename1(Dir), Name). dets_filename1([]) -> "."; dets_filename1(Dir) -> Dir. Interface functions . print() -> call(print). print(Table) -> call({print,Table,volatile}). print(Table, Db) -> call({print,Table,Db}). variable_get({Name, Db}) -> call({variable_get, Name, Db}); variable_get(Name) -> call({variable_get, Name, volatile}). variable_set({Name, Db}, Val) -> call({variable_set, Name, Db, Val}); variable_set(Name, Val) -> call({variable_set, Name, volatile, Val}). variable_inc({Name, Db}, N) -> cast({variable_inc, Name, Db, N}); variable_inc(Name, N) -> cast({variable_inc, Name, volatile, N}). variable_delete({Name, Db}) -> call({variable_delete, Name, Db}); variable_delete(Name) -> call({variable_delete, Name, volatile}). table_create({Name, Db}) -> call({table_create, Name, Db}); table_create(Name) -> call({table_create, Name, volatile}). table_exists({Name, Db}) -> call({table_exists, Name, Db}); table_exists(Name) -> call({table_exists, Name, volatile}). table_delete({Name, Db}) -> call({table_delete, Name, Db}); table_delete(Name) -> call({table_delete, Name, volatile}). table_delete_row({Name, Db}, RowIndex) -> call({table_delete_row, Name, Db, RowIndex}); table_delete_row(Name, RowIndex) -> call({table_delete_row, Name, volatile, RowIndex}). table_get_row({Name, Db}, RowIndex) -> call({table_get_row, Name, Db, RowIndex}); table_get_row(Name, RowIndex) -> call({table_get_row, Name, volatile, RowIndex}). table_get_element({Name, Db}, RowIndex, Col) -> call({table_get_element, Name, Db, RowIndex, Col}); table_get_element(Name, RowIndex, Col) -> call({table_get_element, Name, volatile, RowIndex, Col}). table_set_elements({Name, Db}, RowIndex, Cols) -> call({table_set_elements, Name, Db, RowIndex, Cols}); table_set_elements(Name, RowIndex, Cols) -> call({table_set_elements, Name, volatile, RowIndex, Cols}). table_next({Name, Db}, RestOid) -> call({table_next, Name, Db, RestOid}); table_next(Name, RestOid) -> call({table_next, Name, volatile, RestOid}). table_max_col({Name, Db}, Col) -> call({table_max_col, Name, Db, Col}); table_max_col(Name, Col) -> call({table_max_col, Name, volatile, Col}). table_create_row({Name, Db}, RowIndex, Row) -> call({table_create_row, Name, Db,RowIndex, Row}); table_create_row(Name, RowIndex, Row) -> call({table_create_row, Name, volatile, RowIndex, Row}). table_create_row(NameDb, RowIndex, Status, Cols) -> Row = table_construct_row(NameDb, RowIndex, Status, Cols), table_create_row(NameDb, RowIndex, Row). match({Name, Db}, Pattern) -> call({match, Name, Db, Pattern}); match(Name, Pattern) -> call({match, Name, volatile, Pattern}). handle_call({variable_get, Name, Db}, _From, State) -> ?vlog("variable get: ~p [~p]",[Name, Db]), {reply, lookup(Db, Name, State), State}; handle_call({variable_set, Name, Db, Val}, _From, State) -> ?vlog("variable ~p set [~p]: " "~n Val: ~p",[Name, Db, Val]), {reply, insert(Db, Name, Val, State), State}; handle_call({variable_delete, Name, Db}, _From, State) -> ?vlog("variable delete: ~p [~p]",[Name, Db]), {reply, delete(Db, Name, State), State}; Head - el : Key = { < tableName > , first } > , < list of indexes > ) O(1 ) set(<tableName > , < list of indexes > , Col , ) O(1 ) > , < list of indexes > ) if Row exist O(1 ) , else O(n ) handle_call({table_create, Name, Db}, _From, State) -> ?vlog("table create: ~p [~p]",[Name, Db]), catch handle_delete(Db, Name, State), {reply, insert(Db, {Name, first}, {undef, first, first}, State), State}; handle_call({table_exists, Name, Db}, _From, State) -> ?vlog("table exist: ~p [~p]",[Name, Db]), Res = case lookup(Db, {Name, first}, State) of {value, _} -> true; undefined -> false end, ?vdebug("table exist result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_delete, Name, Db}, _From, State) -> ?vlog("table delete: ~p [~p]",[Name, Db]), catch handle_delete(Db, Name, State), {reply, true, State}; handle_call({table_create_row, Name, Db, Indexes, Row}, _From, State) -> ?vlog("table create row [~p]: " "~n Name: ~p" "~n Indexes: ~p" "~n Row: ~p",[Db, Name, Indexes, Row]), Res = case catch handle_create_row(Db, Name, Indexes, Row, State) of {'EXIT', _} -> false; _ -> true end, ?vdebug("table create row result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_delete_row, Name, Db, Indexes}, _From, State) -> ?vlog("table delete row [~p]: " "~n Name: ~p" "~n Indexes: ~p", [Db, Name, Indexes]), Res = case catch handle_delete_row(Db, Name, Indexes, State) of {'EXIT', _} -> false; _ -> true end, ?vdebug("table delete row result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_get_row, Name, Db, Indexes}, _From, State) -> ?vlog("table get row [~p]: " "~n Name: ~p" "~n Indexes: ~p",[Db, Name, Indexes]), Res = case lookup(Db, {Name, Indexes}, State) of undefined -> undefined; {value, {Row, _Prev, _Next}} -> Row end, ?vdebug("table get row result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_get_element, Name, Db, Indexes, Col}, _From, State) -> ?vlog("table ~p get element [~p]: " "~n Indexes: ~p" "~n Col: ~p", [Name, Db, Indexes, Col]), Res = case lookup(Db, {Name, Indexes}, State) of undefined -> undefined; {value, {Row, _Prev, _Next}} -> {value, element(Col, Row)} end, ?vdebug("table get element result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_set_elements, Name, Db, Indexes, Cols}, _From, State) -> ?vlog("table ~p set element [~p]: " "~n Indexes: ~p" "~n Cols: ~p", [Name, Db, Indexes, Cols]), Res = case catch handle_set_elements(Db, Name, Indexes, Cols, State) of {'EXIT', _} -> false; _ -> true end, ?vdebug("table set element result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_next, Name, Db, []}, From, State) -> ?vlog("table next: ~p [~p]",[Name, Db]), handle_call({table_next, Name, Db, first}, From, State); handle_call({table_next, Name, Db, Indexes}, _From, State) -> ?vlog("table ~p next [~p]: " "~n Indexes: ~p",[Name, Db, Indexes]), Res = case lookup(Db, {Name, Indexes}, State) of {value, {_Row, _Prev, Next}} -> if Next == first -> endOfTable; true -> Next end; undefined -> table_search_next(Db, Name, Indexes, State) end, ?vdebug("table next result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({table_max_col, Name, Db, Col}, _From, State) -> ?vlog("table ~p max col [~p]: " "~n Col: ~p",[Name, Db, Col]), Res = table_max_col(Db, Name, Col, 0, first, State), ?vdebug("table max col result: " "~n ~p",[Res]), {reply, Res, State}; handle_call({match, Name, Db, Pattern}, _From, State) -> ?vlog("match ~p [~p]:" "~n Pat: ~p", [Name, Db, Pattern]), L1 = match(Db, Name, Pattern, State), {reply, lists:delete([undef], L1), State}; handle_call({backup, BackupDir}, From, #state{dets = Dets} = State) -> ?vlog("backup: ~p",[BackupDir]), Pid = self(), V = get(verbosity), case file:read_file_info(BackupDir) of {ok, #file_info{type = directory}} -> BackupServer = erlang:spawn_link( fun() -> put(sname, albs), put(verbosity, V), Dir = filename:join([BackupDir]), #dets{tab = Tab} = Dets, Reply = handle_backup(Tab, Dir), Pid ! {backup_done, Reply}, unlink(Pid) end), ?vtrace("backup server: ~p", [BackupServer]), {noreply, State#state{backup = {BackupServer, From}}}; {ok, _} -> {reply, {error, not_a_directory}, State}; Error -> {reply, Error, State} end; handle_call(dump, _From, #state{dets = Dets} = State) -> ?vlog("dump",[]), dets_sync(Dets), {reply, ok, State}; handle_call(info, _From, #state{dets = Dets, ets = Ets} = State) -> ?vlog("info",[]), Info = get_info(Dets, Ets), {reply, Info, State}; handle_call(print, _From, #state{dets = Dets, ets = Ets} = State) -> ?vlog("print",[]), L1 = ets:tab2list(Ets), L2 = dets_match_object(Dets, '_'), {reply, {{ets, L1}, {dets, L2}}, State}; handle_call({print, Table, Db}, _From, State) -> ?vlog("print: ~p [~p]", [Table, Db]), L = match(Db, Table, '$1', State), {reply, lists:delete([undef], L), State}; handle_call({register_notify_client, Client, Module}, _From, State) -> ?vlog("register_notify_client: " "~n Client: ~p" "~n Module: ~p", [Client, Module]), Nc = State#state.notify_clients, case lists:keysearch(Client,1,Nc) of {value,{Client,Mod}} -> ?vlog("register_notify_client: already registered to: ~p", [Module]), {reply, {error,{already_registered,Mod}}, State}; false -> {reply, ok, State#state{notify_clients = [{Client,Module}|Nc]}} end; handle_call({unregister_notify_client, Client}, _From, State) -> ?vlog("unregister_notify_client: ~p",[Client]), Nc = State#state.notify_clients, case lists:keysearch(Client,1,Nc) of {value,{Client,_Module}} -> Nc1 = lists:keydelete(Client,1,Nc), {reply, ok, State#state{notify_clients = Nc1}}; false -> ?vlog("unregister_notify_client: not registered",[]), {reply, {error,not_registered}, State} end; handle_call(stop, _From, State) -> ?vlog("stop",[]), {stop, normal, stopped, State}; handle_call(Req, _From, State) -> warning_msg("received unknown request: ~n~p", [Req]), Reply = {error, {unknown, Req}}, {reply, Reply, State}. handle_cast({variable_inc, Name, Db, N}, State) -> ?vlog("variable ~p inc" "~n N: ~p", [Name, N]), M = case lookup(Db, Name, State) of {value, Val} -> Val; _ -> 0 end, insert(Db, Name, M+N rem 4294967296, State), {noreply, State}; handle_cast({verbosity,Verbosity}, State) -> ?vlog("verbosity: ~p -> ~p",[get(verbosity),Verbosity]), put(verbosity,?vvalidate(Verbosity)), {noreply, State}; handle_cast(Msg, State) -> warning_msg("received unknown message: ~n~p", [Msg]), {noreply, State}. handle_info({'EXIT', Pid, Reason}, #state{backup = {Pid, From}} = S) -> ?vlog("backup server (~p) exited for reason ~n~p", [Pid, Reason]), gen_server:reply(From, {error, Reason}), {noreply, S#state{backup = undefined}}; handle_info({'EXIT', Pid, Reason}, S) -> {stop, {received_exit, Pid, Reason}, S}; handle_info({backup_done, Reply}, #state{backup = {_, From}} = S) -> ?vlog("backup done:" "~n Reply: ~p", [Reply]), gen_server:reply(From, Reply), {noreply, S#state{backup = undefined}}; handle_info(Info, State) -> warning_msg("received unknown info: ~n~p", [Info]), {noreply, State}. terminate(Reason, State) -> ?vlog("terminate: ~p",[Reason]), close(State). code_change({down, _Vsn}, S1, downgrade_to_pre_4_11) -> #state{dets = D} = S1, #dets{tab = Dets, shadow = Shadow} = D, ets:delete(Shadow), S2 = S1#state{dets = Dets}, {ok, S2}; code_change(_Vsn, S1, upgrade_from_pre_4_11) -> #state{dets = D} = S1, Shadow = ets:new(snmp_local_db1_shadow, [set, protected]), dets:to_ets(D, Shadow), Dets = #dets{tab = D, shadow = Shadow}, S2 = S1#state{dets = Dets}, {ok, S2}; code_change(_Vsn, State, _Extra) -> {ok, State}. handle_backup(D, BackupDir) -> First check that we do not wrote to the corrent db - dir ... ?vtrace("handle_backup -> entry with" "~n D: ~p" "~n BackupDir: ~p", [D, BackupDir]), case dets:info(D, filename) of undefined -> ?vinfo("handle_backup -> no file to backup", []), {error, no_file}; Filename -> ?vinfo("handle_backup -> file to backup: ~n ~p", [Filename]), case filename:dirname(Filename) of BackupDir -> ?vinfo("handle_backup -> backup dir and db dir the same", []), {error, db_dir}; _ -> case file:read_file_info(BackupDir) of {ok, #file_info{type = directory}} -> ?vdebug("handle_backup -> backup dir ok", []), Type = dets:info(D, type), KP = dets:info(D, keypos), dets_backup(D, filename:basename(Filename), BackupDir, Type, KP); {ok, _} -> ?vinfo("handle_backup -> backup dir not a dir", []), {error, not_a_directory}; Error -> ?vinfo("handle_backup -> Error: ~p", [Error]), Error end end end. dets_backup(D, Filename, BackupDir, Type, KP) -> ?vtrace("dets_backup -> entry with" "~n D: ~p" "~n Filename: ~p" "~n BackupDir: ~p", [D, Filename, BackupDir]), BackupFile = filename:join(BackupDir, Filename), ?vtrace("dets_backup -> " "~n BackupFile: ~p", [BackupFile]), Opts = [{file, BackupFile}, {type, Type}, {keypos, KP}], case dets:open_file(?BACKUP_TAB, Opts) of {ok, B} -> F = fun(Arg) -> dets_backup(Arg, start, D, B) end, ?vtrace("dets_backup -> fix table", []), dets:safe_fixtable(D, true), ?vtrace("dets_backup -> copy table", []), Res = dets:init_table(?BACKUP_TAB, F, [{format, bchunk}]), ?vtrace("dets_backup -> unfix table", []), dets:safe_fixtable(D, false), ?vtrace("dets_backup -> Res: ~p", [Res]), Res; Error -> ?vinfo("dets_backup -> open_file failed: " "~n ~p", [Error]), Error end. dets_backup(close, _Cont, _D, B) -> dets:close(B), ok; dets_backup(read, Cont1, D, B) -> case dets:bchunk(D, Cont1) of {Cont2, Data} -> F = fun(Arg) -> dets_backup(Arg, Cont2, D, B) end, {Data, F}; '$end_of_table' -> dets:close(B), end_of_input; Error -> Error end. handle_create_row(Db, Name, Indexes, Row, State) -> case table_find_first_after_maybe_same(Db, Name, Indexes, State) of {{Name, Next}, {NRow, NPrev, NNext}} -> {value, {PRow, PPrev, _PNext}} = lookup(Db, {Name, NPrev}, State), if Next == NPrev -> Insert before first insert(Db, {Name, NPrev}, {PRow, Indexes, Indexes}, State); true -> insert(Db, {Name, NPrev}, {PRow, PPrev, Indexes}, State), insert(Db, {Name, Next}, {NRow, Indexes, NNext}, State) end, insert(Db, {Name, Indexes}, {Row, NPrev, Next}, State); {same_row, {Prev, Next}} -> insert(Db, {Name, Indexes}, {Row, Prev, Next}, State) end. handle_delete_row(Db, Name, Indexes, State) -> {value, {_, Prev, Next}} = lookup(Db, {Name, Indexes}, State), {value, {PRow, PPrev, Indexes}} = lookup(Db, {Name, Prev}, State), insert(Db, {Name, Prev}, {PRow, PPrev, Next}, State), {value, {NRow, Indexes, NNext}} = lookup(Db, {Name, Next}, State), insert(Db, {Name, Next}, {NRow, Prev, NNext}, State), delete(Db, {Name, Indexes}, State). handle_set_elements(Db, Name, Indexes, Cols, State) -> {value, {Row, Prev, Next}} = lookup(Db, {Name, Indexes}, State), NewRow = set_new_row(Cols, Row), insert(Db, {Name, Indexes}, {NewRow, Prev, Next}, State). set_new_row([{Col, Val} | Cols], Row) -> set_new_row(Cols, setelement(Col, Row, Val)); set_new_row([], Row) -> Row. handle_delete(Db, Name, State) -> {value, {_, _, Next}} = lookup(Db, {Name, first}, State), delete(Db, {Name, first}, State), handle_delete(Db, Name, Next, State). handle_delete(_Db, _Name, first, _State) -> true; handle_delete(Db, Name, Indexes, State) -> {value, {_, _, Next}} = lookup(Db, {Name, Indexes}, State), delete(Db, {Name, Indexes}, State), handle_delete(Db, Name, Next, State). table_search_next(Db, Name, Indexes, State) -> case catch table_find_first_after(Db, Name, Indexes, State) of {{Name, Key}, {_, _, _Next}} -> case Key of first -> endOfTable; _ -> Key end; {'EXIT', _} -> endOfTable end. table_find_first_after(Db, Name, Indexes, State) -> {value, {_Row, _Prev, Next}} = lookup(Db, {Name, first}, State), table_loop(Db, Name, Indexes, Next, State). table_loop(Db, Name, _Indexes, first, State) -> {value, FirstVal} = lookup(Db, {Name, first}, State), {{Name, first}, FirstVal}; table_loop(Db, Name, Indexes, Cur, State) -> {value, {Row, Prev, Next}} = lookup(Db, {Name, Cur}, State), if Cur > Indexes -> {{Name, Cur}, {Row, Prev, Next}}; true -> table_loop(Db, Name, Indexes, Next, State) end. table_find_first_after_maybe_same(Db, Name, Indexes, State) -> {value, {_Row, _Prev, Next}} = lookup(Db, {Name, first}, State), table_loop2(Db, Name, Indexes, Next, State). table_loop2(Db, Name, _Indexes, first, State) -> {value, FirstVal} = lookup(Db, {Name, first}, State), {{Name, first}, FirstVal}; table_loop2(Db, Name, Indexes, Cur, State) -> {value, {Row, Prev, Next}} = lookup(Db, {Name, Cur}, State), if Cur > Indexes -> {{Name, Cur}, {Row, Prev, Next}}; Cur == Indexes -> {same_row, {Prev, Next}}; true -> table_loop2(Db, Name, Indexes, Next, State) end. table_max_col(Db, Name, Col, Max, Indexes, State) -> case lookup(Db, {Name, Indexes}, State) of {value, {Row, _Prev, Next}} -> if Next == first -> if integer(element(Col, Row)), element(Col, Row) > Max -> element(Col, Row); true -> Max end; integer(element(Col, Row)), element(Col, Row) > Max -> table_max_col(Db,Name, Col,element(Col, Row),Next, State); true -> table_max_col(Db, Name, Col, Max, Next, State) end; undefined -> table_search_next(Db, Name, Indexes, State) end. Interface to Pets . insert(volatile, Key, Val, #state{ets = Ets}) -> ?vtrace("insert(volatile) -> entry with" "~n Key: ~p" "~n Val: ~p", [Key,Val]), ets:insert(Ets, {Key, Val}), true; insert(persistent, Key, Val, #state{dets = Dets, notify_clients = NC}) -> ?vtrace("insert(persistent) -> entry with" "~n Key: ~p" "~n Val: ~p", [Key,Val]), case dets_insert(Dets, {Key, Val}) of ok -> notify_clients(insert,NC), true; {error, Reason} -> error_msg("DETS (persistent) insert failed for {~w,~w}: ~n~w", [Key, Val, Reason]), false end; insert(permanent, Key, Val, #state{dets = Dets, notify_clients = NC}) -> ?vtrace("insert(permanent) -> entry with" "~n Key: ~p" "~n Val: ~p", [Key,Val]), case dets_insert(Dets, {Key, Val}) of ok -> notify_clients(insert,NC), true; {error, Reason} -> error_msg("DETS (permanent) insert failed for {~w,~w}: ~n~w", [Key, Val, Reason]), false end; insert(UnknownDb, Key, Val, _) -> error_msg("Tried to insert ~w = ~w into unknown db ~w", [Key, Val, UnknownDb]), false. delete(volatile, Key, State) -> ets:delete(State#state.ets, Key), true; delete(persistent, Key, #state{dets = Dets, notify_clients = NC}) -> case dets_delete(Dets, Key) of ok -> notify_clients(delete,NC), true; {error, Reason} -> error_msg("DETS (persistent) delete failed for ~w: ~n~w", [Key, Reason]), false end; delete(permanent, Key, #state{dets = Dets, notify_clients = NC}) -> case dets_delete(Dets, Key) of ok -> notify_clients(delete,NC), true; {error, Reason} -> error_msg("DETS (permanent) delete failed for ~w: ~n~w", [Key, Reason]), false end; delete(UnknownDb, Key, _) -> error_msg("Tried to delete ~w from unknown db ~w", [Key, UnknownDb]), false. match(volatile, Name, Pattern, #state{ets = Ets}) -> ets:match(Ets, {{Name,'_'},{Pattern,'_','_'}}); match(persistent, Name, Pattern, #state{dets = Dets}) -> dets_match(Dets, {{Name,'_'},{Pattern,'_','_'}}); match(permanent, Name, Pattern, #state{dets = Dets}) -> dets_match(Dets, {{Name,'_'},{Pattern,'_','_'}}); match(UnknownDb, Name, Pattern, _) -> error_msg("Tried to match [~p,~p] from unknown db ~w", [Name, Pattern, UnknownDb]), []. lookup(volatile, Key, #state{ets = Ets}) -> case ets:lookup(Ets, Key) of [{_, Val}] -> {value, Val}; [] -> undefined end; lookup(persistent, Key, #state{dets = Dets}) -> case dets_lookup(Dets, Key) of [{_, Val}] -> {value, Val}; [] -> undefined end; lookup(permanent, Key, #state{dets = Dets}) -> case dets_lookup(Dets, Key) of [{_, Val}] -> {value, Val}; [] -> undefined end; lookup(UnknownDb, Key, _) -> error_msg("Tried to lookup ~w in unknown db ~w", [Key, UnknownDb]), false. close(#state{dets = Dets, ets = Ets}) -> ets:delete(Ets), dets_close(Dets). notify_clients(Event, Clients) -> F = fun(Client) -> notify_client(Client, Event) end, lists:foreach(F, Clients). notify_client({Client,Module}, Event) -> (catch Module:notify(Client,Event)). Constructs a row with first elements the own part of RowIndex , and last element RowStatus . All values are stored " as is " , i.e. dynamic key values are stored without length first . RowIndex is a list of the first elements . RowStatus is needed , because the table_construct_row(Name, RowIndex, Status, Cols) -> #table_info{nbr_of_cols = LastCol, index_types = Indexes, defvals = Defs, status_col = StatusCol, first_own_index = FirstOwnIndex, not_accessible = NoAccs} = snmp_generic:table_info(Name), Keys = snmp_generic:split_index_to_keys(Indexes, RowIndex), OwnKeys = snmp_generic:get_own_indexes(FirstOwnIndex, Keys), Row = OwnKeys ++ snmp_generic:table_create_rest(length(OwnKeys) + 1, LastCol, StatusCol, Status, Cols, NoAccs), L = snmp_generic:init_defaults(Defs, Row), list_to_tuple(L). table_get_elements(NameDb, RowIndex, Cols, _FirstOwnIndex) -> get_elements(Cols, table_get_row(NameDb, RowIndex)). get_elements(_Cols, undefined) -> undefined; get_elements([Col | Cols], Row) when is_tuple(Row) and (size(Row) >= Col) -> [element(Col, Row) | get_elements(Cols, Row)]; get_elements([], _Row) -> []; get_elements(Cols, Row) -> erlang:error({bad_arguments, Cols, Row}). This should / could be a generic function , but since implements its own and this version still is local_db dependent , it 's not generic yet . table_set_status(NameDb, RowIndex, ?'RowStatus_createAndGo', StatusCol, Cols, ChangedStatusFunc, _ConsFunc) -> case table_create_row(NameDb, RowIndex, ?'RowStatus_active', Cols) of true -> snmp_generic:try_apply(ChangedStatusFunc, [NameDb, ?'RowStatus_createAndGo', RowIndex, Cols]); _ -> {commitFailed, StatusCol} end; createAndWait - set status to notReady , and try to table_set_status(NameDb, RowIndex, ?'RowStatus_createAndWait', StatusCol, Cols, ChangedStatusFunc, ConsFunc) -> case table_create_row(NameDb, RowIndex, ?'RowStatus_notReady', Cols) of true -> case snmp_generic:try_apply(ConsFunc, [NameDb, RowIndex, Cols]) of {noError, 0} -> snmp_generic:try_apply(ChangedStatusFunc, [NameDb, ?'RowStatus_createAndWait', RowIndex, Cols]); Error -> Error end; _ -> {commitFailed, StatusCol} end; table_set_status(NameDb, RowIndex, ?'RowStatus_destroy', _StatusCol, Cols, ChangedStatusFunc, _ConsFunc) -> case snmp_generic:try_apply(ChangedStatusFunc, [NameDb, ?'RowStatus_destroy', RowIndex, Cols]) of {noError, 0} -> table_delete_row(NameDb, RowIndex), {noError, 0}; Error -> Error end; table_set_status(NameDb, RowIndex, Val, _StatusCol, Cols, ChangedStatusFunc, ConsFunc) -> snmp_generic:table_set_cols(NameDb, RowIndex, Cols, ConsFunc), snmp_generic:try_apply(ChangedStatusFunc, [NameDb, Val, RowIndex, Cols]). table_func(new, NameDb) -> case table_exists(NameDb) of true -> ok; _ -> table_create(NameDb) end; table_func(delete, _NameDb) -> ok. table_func(get, RowIndex, Cols, NameDb) -> TableInfo = snmp_generic:table_info(NameDb), snmp_generic:handle_table_get(NameDb, RowIndex, Cols, TableInfo#table_info.first_own_index); Returns : List of endOfTable | { NextOid , Value } . table_func(get_next, RowIndex, Cols, NameDb) -> #table_info{first_accessible = FirstCol, first_own_index = FOI, nbr_of_cols = LastCol} = snmp_generic:table_info(NameDb), snmp_generic:handle_table_next(NameDb, RowIndex, Cols, FirstCol, FOI, LastCol); This function must only be used by tables with a RowStatus col ! table_func(is_set_ok, RowIndex, Cols, NameDb) -> snmp_generic:table_try_row(NameDb, nofunc, RowIndex, Cols); is here a list of { ColumnNumber , NewValue } This function must only be used by tables with a RowStatus col ! table_func(set, RowIndex, Cols, NameDb) -> snmp_generic:table_set_row(NameDb, nofunc, {snmp_generic, table_try_make_consistent}, RowIndex, Cols); table_func(undo, _RowIndex, _Cols, _NameDb) -> {noError, 0}. get_opt(Key, Opts, Def) -> snmp_misc:get_option(Key, Opts, Def). get_info(Dets, Ets) -> ProcSize = proc_mem(self()), DetsSz = dets_size(Dets), EtsSz = ets_size(Ets), [{process_memory, ProcSize}, {db_memory, [{persistent, DetsSz}, {volatile, EtsSz}]}]. proc_mem(P) when is_pid(P) -> case (catch erlang:process_info(P, memory)) of {memory, Sz} -> Sz; _ -> undefined end. dets_size(#dets{tab = Tab, shadow = Shadow}) -> TabSz = case (catch dets:info(Tab, file_size)) of Sz when is_integer(Sz) -> Sz; _ -> undefined end, ShadowSz = ets_size(Shadow), [{tab, TabSz}, {shadow, ShadowSz}]. ets_size(T) -> case (catch ets:info(T, memory)) of Sz when is_integer(Sz) -> Sz; _ -> undefined end. warning_msg(F, A) -> ?snmpa_warning("Local DB server: " ++ F, A). error_msg(F, A) -> ?snmpa_error("Local DB server: " ++ F, A). user_err(F, A) -> snmpa_error:user_err(F, A). config_err(F, A) -> snmpa_error:config_err(F, A). call(Req) -> gen_server:call(?SERVER, Req, infinity). cast(Msg) -> gen_server:cast(?SERVER, Msg). dets_sync(#dets{tab = Dets}) -> dets:sync(Dets). dets_insert(#dets{tab = Tab, shadow = Shadow}, Data) -> ets:insert(Shadow, Data), dets:insert(Tab, Data). dets_delete(#dets{tab = Tab, shadow = Shadow}, Key) -> ets:delete(Shadow, Key), dets:delete(Tab, Key). dets_match(#dets{shadow = Shadow}, Pat) -> ets:match(Shadow, Pat). dets_match_object(#dets{shadow = Shadow}, Pat) -> ets:match_object(Shadow, Pat). dets_lookup(#dets{shadow = Shadow}, Key) -> ets:lookup(Shadow, Key). dets_close(#dets{tab = Tab, shadow = Shadow}) -> ets:delete(Shadow), dets:close(Tab).
bd0a5183b7d8fc0de42bb08cdaf81be1271b1c3e26742d07ed56ebb9c9827d33
reach-sh/reach-lang
ALGO_SourceMap.hs
# OPTIONS_GHC -Wno - missing - export - lists # module Reach.Connector.ALGO_SourceMap where import Control.Monad.Extra import Data.Aeson ((.:)) import qualified Data.Aeson as AS import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Internal as BI import qualified Data.ByteString.Lazy as BSL import Data.IORef import qualified Data.Map.Strict as M import qualified Data.Text as T import qualified Reach.VLQ as VLQ data SourceMapV3 = SourceMapV3 { sm_mappings :: T.Text } instance AS.FromJSON SourceMapV3 where parseJSON = AS.withObject "SourceMapV3" $ \o -> do sm_mappings <- o .: "mapping" return $ SourceMapV3 {..} type SourceMap = M.Map Integer Integer type CodeAndMap = (BS.ByteString, SourceMap) interpSourceMap :: SourceMapV3 -> IO SourceMap interpSourceMap (SourceMapV3 {..}) = do let ms = BSL.fromStrict $ B.pack $ T.unpack sm_mappings lr <- newIORef 2 mr <- newIORef mempty forM_ (zip [0..] $ BSL.split (BI.c2w ';') ms) $ \(i, group) -> do let segs = BSL.split (BI.c2w ',') group seg1' <- case segs of [] -> return 0 seg1_b64 : _ -> do let seg1_bs = BSL.toStrict seg1_b64 seg1 <- VLQ.decode' $ BSL.fromStrict seg1_bs return $ fromIntegral seg1 modifyIORef lr $ (+) seg1' l <- readIORef lr modifyIORef mr $ M.insert i l readIORef mr readSourceMapFile :: FilePath -> IO (Either BS.ByteString SourceMap) readSourceMapFile fp = do AS.eitherDecodeFileStrict fp >>= \case Left m -> return $ Left $ B.pack $ "could not decode source map: " <> m Right sm -> Right <$> interpSourceMap sm
null
https://raw.githubusercontent.com/reach-sh/reach-lang/f79282c49705c66fc10489045d502d17621d60c5/hs/src/Reach/Connector/ALGO_SourceMap.hs
haskell
# OPTIONS_GHC -Wno - missing - export - lists # module Reach.Connector.ALGO_SourceMap where import Control.Monad.Extra import Data.Aeson ((.:)) import qualified Data.Aeson as AS import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Internal as BI import qualified Data.ByteString.Lazy as BSL import Data.IORef import qualified Data.Map.Strict as M import qualified Data.Text as T import qualified Reach.VLQ as VLQ data SourceMapV3 = SourceMapV3 { sm_mappings :: T.Text } instance AS.FromJSON SourceMapV3 where parseJSON = AS.withObject "SourceMapV3" $ \o -> do sm_mappings <- o .: "mapping" return $ SourceMapV3 {..} type SourceMap = M.Map Integer Integer type CodeAndMap = (BS.ByteString, SourceMap) interpSourceMap :: SourceMapV3 -> IO SourceMap interpSourceMap (SourceMapV3 {..}) = do let ms = BSL.fromStrict $ B.pack $ T.unpack sm_mappings lr <- newIORef 2 mr <- newIORef mempty forM_ (zip [0..] $ BSL.split (BI.c2w ';') ms) $ \(i, group) -> do let segs = BSL.split (BI.c2w ',') group seg1' <- case segs of [] -> return 0 seg1_b64 : _ -> do let seg1_bs = BSL.toStrict seg1_b64 seg1 <- VLQ.decode' $ BSL.fromStrict seg1_bs return $ fromIntegral seg1 modifyIORef lr $ (+) seg1' l <- readIORef lr modifyIORef mr $ M.insert i l readIORef mr readSourceMapFile :: FilePath -> IO (Either BS.ByteString SourceMap) readSourceMapFile fp = do AS.eitherDecodeFileStrict fp >>= \case Left m -> return $ Left $ B.pack $ "could not decode source map: " <> m Right sm -> Right <$> interpSourceMap sm
3020f5807670bf1a6d3187db656ceb9385493b80e2b239437feb58631ac9bdca
zen-lang/zen
schema_test.clj
(ns zen.schema-test (:require [zen.schema :as sut] [matcho.core :as matcho] [clojure.test :as t] [clojure.string :as str] [zen.core])) (sut/register-compile-key-interpreter! [:keys ::ts] (fn [_ ztx ks] (fn [vtx data opts] (if-let [s (or (when-let [nm (:zen/name data)] (str "type " (name nm) " = {")) (when-let [tp (:type data)] (str (name (last (:path vtx))) ": " (get {'zen/string "string"} tp) ";")))] (update vtx ::ts conj s) vtx)))) (sut/register-compile-key-interpreter! [:every ::ts] (fn [_ ztx every] (fn [vtx data opts] (update vtx ::ts conj "Array < ")))) (sut/register-compile-key-interpreter! [:type ::ts] (fn [_ ztx ks] (fn [vtx data opts] (-> vtx #_(update ::ts conj [:type (:schema vtx) (:path vtx) data]))))) (sut/register-schema-pre-process-hook! ::ts (fn [ztx schema] (fn [vtx data opts] (-> vtx #_(update ::ts conj [:pre (:schema vtx) (:path vtx) data]))))) (sut/register-schema-post-process-hook! ::ts (fn [ztx schema] (fn [vtx data opts] (if-let [nm (:zen/name data)] (update vtx ::ts conj "}") vtx)))) (t/deftest ^:kaocha/pending custom-interpreter-test (t/testing "typescript type generation" (def ztx (zen.core/new-context {})) (def my-structs-ns '{:ns my-sturcts User {:zen/tags #{zen/schema} :type zen/map :keys {:id {:type zen/string} :email {:type zen/string #_#_:regex "@"} :name {:type zen/vector :every {:type zen/map :keys {:given {:type zen/vector :every {:type zen/string}} :family {:type zen/string}}}}}}}) (zen.core/load-ns ztx my-structs-ns) (def ts-typedef-assert (str "type User = {" "id: string;" "email: string;" "name: Array < {" "given: Array < string >;" "family: string;" "}>}")) (def r (sut/apply-schema ztx {::ts []} (zen.core/get-symbol ztx 'zen/schema) (zen.core/get-symbol ztx 'my-sturcts/User) {:interpreters [::ts]})) (t/is (= ts-typedef-assert (str/join "" (distinct (::ts r))))))) (defmethod sut/compile-key :my/defaults [_ _ _] {:priority -1}) (sut/register-compile-key-interpreter! [:my/defaults ::default] (fn [_ ztx defaults] (fn [vtx data opts] (update-in vtx (cons ::with-defaults (:path vtx)) #(merge defaults %))))) (t/deftest default-value-test (t/testing "set default value" (def ztx (zen.core/new-context {})) (zen.core/get-tag ztx 'zen/type) (def my-ns '{:ns my defaults {:zen/tags #{zen/schema zen/is-key} :zen/desc "only primitive default values are supported currently" :for #{zen/map} :priority 100 :type zen/map :key {:type zen/keyword} :values {:type zen/case :case [{:when {:type zen/boolean}} {:when {:type zen/date}} {:when {:type zen/datetime}} {:when {:type zen/integer}} {:when {:type zen/keyword}} {:when {:type zen/number}} {:when {:type zen/qsymbol}} {:when {:type zen/regex}} {:when {:type zen/string}} {:when {:type zen/symbol}}]}} HumanName {:zen/tags #{zen/schema} :type zen/map :require #{:family :given} :keys {:given {:type zen/vector :minItems 1 :every {:type zen/string}} :family {:type zen/string}}} DefaultHumanName {:zen/tags #{zen/schema} :type zen/map :my/defaults {:family "None"}} User {:zen/tags #{zen/schema} :type zen/map :my/defaults {:active true} :keys {:id {:type zen/string} :name {:type zen/vector :every {:confirms #{HumanName DefaultHumanName}}} :active {:type zen/boolean} :email {:type zen/string}}}}) (zen.core/load-ns ztx my-ns) #_(matcho/match (zen.core/errors ztx) #_"NOTE: FIXME: keys that use get-cached during compile time won't be recompiled when these schemas used in get-cached updated. E.g. adding new is-key for zen/schema won't cause zen/schema recompile and the key won't be recognized by zen/schema validation" empty?) (def data {:id "foo" :email "bar@baz" :name [{:given ["foo"]}]}) (def r (sut/apply-schema ztx {::with-defaults data} (zen.core/get-symbol ztx 'my/User) data {:interpreters [::default]})) (matcho/match (::with-defaults r) {:id "foo" :email "bar@baz" :active true :name [{:family "None" :given ["foo"]}]})))
null
https://raw.githubusercontent.com/zen-lang/zen/dcc55ee80aad6d1689d2d30d638e4ba56542d645/test/zen/schema_test.clj
clojure
(ns zen.schema-test (:require [zen.schema :as sut] [matcho.core :as matcho] [clojure.test :as t] [clojure.string :as str] [zen.core])) (sut/register-compile-key-interpreter! [:keys ::ts] (fn [_ ztx ks] (fn [vtx data opts] (if-let [s (or (when-let [nm (:zen/name data)] (str "type " (name nm) " = {")) (when-let [tp (:type data)] (str (name (last (:path vtx))) ": " (get {'zen/string "string"} tp) ";")))] (update vtx ::ts conj s) vtx)))) (sut/register-compile-key-interpreter! [:every ::ts] (fn [_ ztx every] (fn [vtx data opts] (update vtx ::ts conj "Array < ")))) (sut/register-compile-key-interpreter! [:type ::ts] (fn [_ ztx ks] (fn [vtx data opts] (-> vtx #_(update ::ts conj [:type (:schema vtx) (:path vtx) data]))))) (sut/register-schema-pre-process-hook! ::ts (fn [ztx schema] (fn [vtx data opts] (-> vtx #_(update ::ts conj [:pre (:schema vtx) (:path vtx) data]))))) (sut/register-schema-post-process-hook! ::ts (fn [ztx schema] (fn [vtx data opts] (if-let [nm (:zen/name data)] (update vtx ::ts conj "}") vtx)))) (t/deftest ^:kaocha/pending custom-interpreter-test (t/testing "typescript type generation" (def ztx (zen.core/new-context {})) (def my-structs-ns '{:ns my-sturcts User {:zen/tags #{zen/schema} :type zen/map :keys {:id {:type zen/string} :email {:type zen/string #_#_:regex "@"} :name {:type zen/vector :every {:type zen/map :keys {:given {:type zen/vector :every {:type zen/string}} :family {:type zen/string}}}}}}}) (zen.core/load-ns ztx my-structs-ns) (def ts-typedef-assert (str "type User = {" "id: string;" "email: string;" "name: Array < {" "given: Array < string >;" "family: string;" "}>}")) (def r (sut/apply-schema ztx {::ts []} (zen.core/get-symbol ztx 'zen/schema) (zen.core/get-symbol ztx 'my-sturcts/User) {:interpreters [::ts]})) (t/is (= ts-typedef-assert (str/join "" (distinct (::ts r))))))) (defmethod sut/compile-key :my/defaults [_ _ _] {:priority -1}) (sut/register-compile-key-interpreter! [:my/defaults ::default] (fn [_ ztx defaults] (fn [vtx data opts] (update-in vtx (cons ::with-defaults (:path vtx)) #(merge defaults %))))) (t/deftest default-value-test (t/testing "set default value" (def ztx (zen.core/new-context {})) (zen.core/get-tag ztx 'zen/type) (def my-ns '{:ns my defaults {:zen/tags #{zen/schema zen/is-key} :zen/desc "only primitive default values are supported currently" :for #{zen/map} :priority 100 :type zen/map :key {:type zen/keyword} :values {:type zen/case :case [{:when {:type zen/boolean}} {:when {:type zen/date}} {:when {:type zen/datetime}} {:when {:type zen/integer}} {:when {:type zen/keyword}} {:when {:type zen/number}} {:when {:type zen/qsymbol}} {:when {:type zen/regex}} {:when {:type zen/string}} {:when {:type zen/symbol}}]}} HumanName {:zen/tags #{zen/schema} :type zen/map :require #{:family :given} :keys {:given {:type zen/vector :minItems 1 :every {:type zen/string}} :family {:type zen/string}}} DefaultHumanName {:zen/tags #{zen/schema} :type zen/map :my/defaults {:family "None"}} User {:zen/tags #{zen/schema} :type zen/map :my/defaults {:active true} :keys {:id {:type zen/string} :name {:type zen/vector :every {:confirms #{HumanName DefaultHumanName}}} :active {:type zen/boolean} :email {:type zen/string}}}}) (zen.core/load-ns ztx my-ns) #_(matcho/match (zen.core/errors ztx) #_"NOTE: FIXME: keys that use get-cached during compile time won't be recompiled when these schemas used in get-cached updated. E.g. adding new is-key for zen/schema won't cause zen/schema recompile and the key won't be recognized by zen/schema validation" empty?) (def data {:id "foo" :email "bar@baz" :name [{:given ["foo"]}]}) (def r (sut/apply-schema ztx {::with-defaults data} (zen.core/get-symbol ztx 'my/User) data {:interpreters [::default]})) (matcho/match (::with-defaults r) {:id "foo" :email "bar@baz" :active true :name [{:family "None" :given ["foo"]}]})))
765c251d45c7b16c7e3facede52d042a1041bea1fe06f508b26ca249961c3989
kudu-dynamics/blaze
General.hs
module Blaze.Cfg.Solver.General where import Blaze.Prelude hiding (Type, sym, bitSize, Constraint) import qualified Blaze.Types.Pil as Pil import qualified Data.HashSet as HSet import Blaze.Types.Pil.Checker (DeepSymType, SymTypedStmt) import Blaze.Types.Cfg (Cfg, CfNode, BranchType(TrueBranch, FalseBranch), CfEdge (CfEdge), PilCfg, PilNode) import qualified Blaze.Cfg as Cfg import qualified Blaze.Types.Graph as G import Blaze.Types.Pil.Analysis ( DataDependenceGraph ) import qualified Blaze.Cfg.Analysis as CfgA import qualified Blaze.Pil.Solver as PilSolver import Blaze.Pil.Solver (makeSymVarOfType, warn) import Blaze.Types.Pil.Solver import qualified Blaze.Types.Pil.Checker as Ch import Blaze.Cfg.Checker (checkCfg) import Data.SBV.Dynamic (SVal, svNot) import qualified Data.SBV.Trans.Control as Q import qualified Data.SBV.Trans as SBV import qualified Data.HashMap.Strict as HashMap data DecidedBranchCond = DecidedBranchCond { conditionStatementIndex :: Int , condition :: Ch.InfoExpression (Ch.SymInfo, Maybe DeepSymType) , decidedBranch :: Bool } deriving (Eq, Ord, Show, Generic) -- | Accumulation of branch conditions that should be rechecked during -- the next iteration ('condsToRecheck') and the edges which were found to be -- unsat and should be removed ('edgesToRemove'). data BranchCheckAccum = BranchCheckAccum { condsToRecheck :: [(UndecidedBranchCond (CfNode [(Int, SymTypedStmt)]), SVal)] , edgesToRemove :: [CfEdge (CfNode [(Int, SymTypedStmt)])] } deriving (Eq, Show) | If the node contains a conditional branch , and one of the conditional edges -- has been removed, this returns information about which conditional edge remains -- and the branching condition. getDecidedBranchCondNode :: CfNode [(Int, SymTypedStmt)] -> Cfg (CfNode [(Int, SymTypedStmt)]) -> Maybe DecidedBranchCond getDecidedBranchCondNode n cfg = case outBranchTypes of [] -> Nothing [TrueBranch] -> mcond ?? True [FalseBranch] -> mcond ?? False [TrueBranch, FalseBranch] -> Nothing [FalseBranch, TrueBranch] -> Nothing _ -> Nothing where mcond = lastMay (Cfg.getNodeData n) >>= \case (i, Pil.BranchCond (Pil.BranchCondOp x)) -> Just $ DecidedBranchCond i x _ -> Nothing outBranchTypes :: [BranchType] outBranchTypes = fmap (view #branchType) . HSet.toList $ Cfg.succEdges n cfg | Adds overly general constraints for a CFG . If conditions are ignored . Phi vars are Or'd together . TODO memory generalCfgFormula :: DataDependenceGraph -> Cfg (CfNode [(Int, SymTypedStmt)]) -> Solver () generalCfgFormula ddg cfg = do mapM_ addDecidedBranchConstraint decidedBranchConditions mapM_ setIndexAndSolveStmt $ Cfg.gatherCfgData cfg where setIndexAndSolveStmt :: (Int, SymTypedStmt) -> Solver () setIndexAndSolveStmt (i, stmt) = do #currentStmtIndex .= i solveStmt ddg stmt addDecidedBranchConstraint (DecidedBranchCond i x b) = do #currentStmtIndex .= i r <- bool svNot identity b <$> solveExpr ddg x PilSolver.guardBool r PilSolver.constrain r decidedBranchConditions = mapMaybe (`getDecidedBranchCondNode` cfg) . HSet.toList . G.nodes $ cfg solveStmt :: DataDependenceGraph -> SymTypedStmt -> Solver () solveStmt ddg stmt = case stmt of -- this is handled elsewhere (only used if there is single outgoing branch edge) Pil.BranchCond _ -> return () TODO : convert stores / loads into immutable SSA vars Pil.Store _ -> return () Pil.DefPhi (Pil.DefPhiOp dest vars) -> do unless (or $ isDependentOn <$> vars) pilSolveStmt where destDescendants = G.getDescendants dest ddg isDependentOn = flip HSet.member destDescendants _ -> pilSolveStmt where pilSolveStmt = PilSolver.solveStmt_ (solveExpr ddg) stmt solveExpr :: DataDependenceGraph -> DSTExpression -> Solver SVal solveExpr ddg expr@(Ch.InfoExpression (Ch.SymInfo _sz xsym, mdst) op) = catchFallbackAndWarn $ case op of TOOD : turn mem into immutable vars Pil.LOAD _ -> fallbackAsFreeVar _ -> PilSolver.solveExpr_ (solveExpr ddg) expr where fallbackAsFreeVar :: Solver SVal fallbackAsFreeVar = case mdst of Nothing -> throwError . ExprError xsym . ErrorMessage $ "missing DeepSymType" Just dst -> catchError (makeSymVarOfType Nothing dst) $ \e -> throwError $ ExprError xsym e catchFallbackAndWarn :: Solver SVal -> Solver SVal catchFallbackAndWarn m = catchError m $ \e -> do si <- use #currentStmtIndex warn $ StmtError si e fallbackAsFreeVar ---------------------------- data UndecidedBranchCond n = UndecidedBranchCond { conditionStatementIndex :: Int , condition :: Ch.InfoExpression (Ch.SymInfo, Maybe DeepSymType) , trueEdge :: CfEdge n , falseEdge :: CfEdge n } deriving (Eq, Ord, Show, Generic) -- | If the node contains a conditional branch, and neither of the conditional edgesToRemove -- have been removed, this returns an 'UndecidedBranchCond'. Otherwise, 'Nothing' is returned. getUndecidedBranchCondNode :: CfNode [(Int, SymTypedStmt)] -> Cfg (CfNode [(Int, SymTypedStmt)]) -> Maybe (UndecidedBranchCond (CfNode [(Int, SymTypedStmt)])) getUndecidedBranchCondNode n cfg = case outBranches of [(TrueBranch, tnode), (FalseBranch, fnode)] -> mcond <*> pure tnode <*> pure fnode [(FalseBranch, fnode), (TrueBranch, tnode)] -> mcond <*> pure tnode <*> pure fnode _ -> Nothing where mcond = lastMay (Cfg.getNodeData n) >>= \case (i, Pil.BranchCond (Pil.BranchCondOp x)) -> Just $ UndecidedBranchCond i x _ -> Nothing outBranches :: [(BranchType, CfEdge (CfNode [(Int, SymTypedStmt)]))] outBranches = fmap (\e -> (e ^. #branchType, e)) . HSet.toList $ Cfg.succEdges n cfg -- | Checks individual true and false branches to find impossible constraints. Starts at root node and finds nodes with conditional branches in breadth - first order . -- Returns a list of inconsistent branch edges. unsatBranches :: DataDependenceGraph -> Cfg (CfNode [(Int, SymTypedStmt)]) -> Solver [CfEdge (CfNode [(Int, SymTypedStmt)])] unsatBranches ddg typedCfg = case undecidedBranchCondNodes of [] -> return [] ubranches -> do generalCfgFormula ddg typedCfg ubranchesWithSvals <- traverse getBranchCondSVal ubranches er <- liftSymbolicT . Q.query $ Q.checkSat >>= \case Q.DSat _ -> Right <$> findRemoveableUnsats ubranchesWithSvals Q.Sat -> Right <$> findRemoveableUnsats ubranchesWithSvals r -> Left <$> toSolverResult r case er of Left sr -> do putText $ "General constraints are not sat: " <> show sr return [] Right xs -> return xs where getBranchCondSVal :: UndecidedBranchCond (CfNode [(Int, SymTypedStmt)]) -> Solver (UndecidedBranchCond (CfNode [(Int, SymTypedStmt)]), SVal) getBranchCondSVal u = do #currentStmtIndex .= u ^. #conditionStatementIndex c <- solveExpr ddg $ u ^. #condition PilSolver.guardBool c return (u, c) isSat :: Query Bool isSat = Q.checkSat >>= \case Q.DSat _ -> return True Q.Sat -> return True _ -> return False -- | Returns either generic non-sat result, or list of edges that can be removed. -- -- The general algorithm for `findRemovableUnsats` can be described in imperative -- terms: -- findRemoveableUnsats(xs) = -- for each undecided branch: -- if either side is UNSAT: -- collect the other side in the general constraints -- remove the correct edge -- else: -- remember to revisit this branch on the next recursive call -- if there were any edges removed: -- recur into findRemoveableUnsats(branches to revisit) -- append that result onto edges to be removed -- return edges that should be removed findRemoveableUnsats :: [(UndecidedBranchCond (CfNode [(Int, SymTypedStmt)]), SVal)] -> Query [CfEdge (CfNode [(Int, SymTypedStmt)])] findRemoveableUnsats xs = do (BranchCheckAccum condsToRecheck edgesToRemove) <- foldM checkBranchCond (BranchCheckAccum [] []) xs if null edgesToRemove then return [] else do edgesToRemove' <- findRemoveableUnsats condsToRecheck return $ edgesToRemove <> edgesToRemove' where -- | Check an individual branch condition. If a conditional edge is unsat, -- that edge is added to `edgesToRemove` and the constraint implied by the -- remaining edge is added to the assertion stack. -- If both conditional edges for a branch condition are sat, then the branch -- condition is added to the `condsToRecheck` for rechecking later. checkBranchCond :: BranchCheckAccum -> (UndecidedBranchCond (CfNode [(Int, SymTypedStmt)]), SVal) -> Query BranchCheckAccum checkBranchCond (BranchCheckAccum condsToRecheck edgesToRemove) (u, c) = do tryConstraint c >>= \case -- True branch is unsat False -> do -- Add false branch consraint to general formula addConstraint $ PilSolver.svBoolNot c -- Add true-branch edge to removal list return $ BranchCheckAccum condsToRecheck (u ^. #trueEdge : edgesToRemove) True -> tryConstraint (PilSolver.svBoolNot c) >>= \case -- False branch is unsat False -> do -- Add true-branch constraint to general formula addConstraint c -- Add false-branch edge to removal list return $ BranchCheckAccum condsToRecheck (u ^. #falseEdge : edgesToRemove) True -> -- Both true and false branch are Sat return $ BranchCheckAccum ((u, c) : condsToRecheck) edgesToRemove addConstraint :: SVal -> Query () addConstraint c = do SBV.constrain $ PilSolver.toSBool' c Q.push 1 tryConstraint :: SVal -> Query Bool tryConstraint c = Q.inNewAssertionStack $ SBV.constrain (PilSolver.toSBool' c) >> isSat undecidedBranchCondNodes = mapMaybe (`getUndecidedBranchCondNode` typedCfg) . concat . G.bfs [Cfg.getRootNode typedCfg] $ typedCfg data GeneralSolveError = TypeCheckerError Ch.ConstraintGenError | SolverError Ch.TypeReport PilSolver.SolverError deriving (Eq, Ord, Show, Generic) getUnsatBranches :: PilCfg -> IO (Either GeneralSolveError [CfEdge PilNode]) getUnsatBranches cfg = case checkCfg cfg of Left err -> return . Left . TypeCheckerError $ err Right (_, cfg', tr) -> do let ddg = CfgA.getDataDependenceGraph cfg er <- flip (PilSolver.runSolverWith SBV.z3) ( PilSolver.emptyState , SolverCtx (tr ^. #varSymTypeMap) HashMap.empty False SkipStatementsWithErrors ) $ PilSolver.declarePilVars >> unsatBranches ddg cfg' case er of Left err -> return . Left $ SolverError tr err Right (unsatEdges, _) -> return . Right $ fmap getOrigEdge unsatEdges where getOrigEdge :: CfEdge (CfNode [(Int, SymTypedStmt)]) -> CfEdge PilNode getOrigEdge (CfEdge src dst label) = let src' = fromJust $ Cfg.getNode cfg (G.getNodeId src) dst' = fromJust $ Cfg.getNode cfg (G.getNodeId dst) in CfEdge src' dst' label simplify_ :: Bool -> Int -> PilCfg -> IO (Either GeneralSolveError PilCfg) simplify_ isRecursiveCall numItersLeft cfg | numItersLeft <= 0 = return . Right $ cfg | otherwise = do let cfg' = CfgA.simplify cfg if cfg' == cfg && isRecursiveCall then return . Right $ cfg' else getUnsatBranches cfg' >>= \case Left err -> return $ Left err Right [] -> return . Right $ cfg' Right es -> simplify_ True (numItersLeft - 1) $ foldr Cfg.removeEdge cfg' es simplify :: PilCfg -> IO (Either GeneralSolveError PilCfg) simplify stmts = do simplify_ False 10 stmts
null
https://raw.githubusercontent.com/kudu-dynamics/blaze/f08a5d6dd76420828afc056010bf14a262955ba4/src/Blaze/Cfg/Solver/General.hs
haskell
| Accumulation of branch conditions that should be rechecked during the next iteration ('condsToRecheck') and the edges which were found to be unsat and should be removed ('edgesToRemove'). has been removed, this returns information about which conditional edge remains and the branching condition. this is handled elsewhere (only used if there is single outgoing branch edge) -------------------------- | If the node contains a conditional branch, and neither of the conditional edgesToRemove have been removed, this returns an 'UndecidedBranchCond'. Otherwise, 'Nothing' is returned. | Checks individual true and false branches to find impossible constraints. Returns a list of inconsistent branch edges. | Returns either generic non-sat result, or list of edges that can be removed. The general algorithm for `findRemovableUnsats` can be described in imperative terms: findRemoveableUnsats(xs) = for each undecided branch: if either side is UNSAT: collect the other side in the general constraints remove the correct edge else: remember to revisit this branch on the next recursive call if there were any edges removed: recur into findRemoveableUnsats(branches to revisit) append that result onto edges to be removed return edges that should be removed | Check an individual branch condition. If a conditional edge is unsat, that edge is added to `edgesToRemove` and the constraint implied by the remaining edge is added to the assertion stack. If both conditional edges for a branch condition are sat, then the branch condition is added to the `condsToRecheck` for rechecking later. True branch is unsat Add false branch consraint to general formula Add true-branch edge to removal list False branch is unsat Add true-branch constraint to general formula Add false-branch edge to removal list Both true and false branch are Sat
module Blaze.Cfg.Solver.General where import Blaze.Prelude hiding (Type, sym, bitSize, Constraint) import qualified Blaze.Types.Pil as Pil import qualified Data.HashSet as HSet import Blaze.Types.Pil.Checker (DeepSymType, SymTypedStmt) import Blaze.Types.Cfg (Cfg, CfNode, BranchType(TrueBranch, FalseBranch), CfEdge (CfEdge), PilCfg, PilNode) import qualified Blaze.Cfg as Cfg import qualified Blaze.Types.Graph as G import Blaze.Types.Pil.Analysis ( DataDependenceGraph ) import qualified Blaze.Cfg.Analysis as CfgA import qualified Blaze.Pil.Solver as PilSolver import Blaze.Pil.Solver (makeSymVarOfType, warn) import Blaze.Types.Pil.Solver import qualified Blaze.Types.Pil.Checker as Ch import Blaze.Cfg.Checker (checkCfg) import Data.SBV.Dynamic (SVal, svNot) import qualified Data.SBV.Trans.Control as Q import qualified Data.SBV.Trans as SBV import qualified Data.HashMap.Strict as HashMap data DecidedBranchCond = DecidedBranchCond { conditionStatementIndex :: Int , condition :: Ch.InfoExpression (Ch.SymInfo, Maybe DeepSymType) , decidedBranch :: Bool } deriving (Eq, Ord, Show, Generic) data BranchCheckAccum = BranchCheckAccum { condsToRecheck :: [(UndecidedBranchCond (CfNode [(Int, SymTypedStmt)]), SVal)] , edgesToRemove :: [CfEdge (CfNode [(Int, SymTypedStmt)])] } deriving (Eq, Show) | If the node contains a conditional branch , and one of the conditional edges getDecidedBranchCondNode :: CfNode [(Int, SymTypedStmt)] -> Cfg (CfNode [(Int, SymTypedStmt)]) -> Maybe DecidedBranchCond getDecidedBranchCondNode n cfg = case outBranchTypes of [] -> Nothing [TrueBranch] -> mcond ?? True [FalseBranch] -> mcond ?? False [TrueBranch, FalseBranch] -> Nothing [FalseBranch, TrueBranch] -> Nothing _ -> Nothing where mcond = lastMay (Cfg.getNodeData n) >>= \case (i, Pil.BranchCond (Pil.BranchCondOp x)) -> Just $ DecidedBranchCond i x _ -> Nothing outBranchTypes :: [BranchType] outBranchTypes = fmap (view #branchType) . HSet.toList $ Cfg.succEdges n cfg | Adds overly general constraints for a CFG . If conditions are ignored . Phi vars are Or'd together . TODO memory generalCfgFormula :: DataDependenceGraph -> Cfg (CfNode [(Int, SymTypedStmt)]) -> Solver () generalCfgFormula ddg cfg = do mapM_ addDecidedBranchConstraint decidedBranchConditions mapM_ setIndexAndSolveStmt $ Cfg.gatherCfgData cfg where setIndexAndSolveStmt :: (Int, SymTypedStmt) -> Solver () setIndexAndSolveStmt (i, stmt) = do #currentStmtIndex .= i solveStmt ddg stmt addDecidedBranchConstraint (DecidedBranchCond i x b) = do #currentStmtIndex .= i r <- bool svNot identity b <$> solveExpr ddg x PilSolver.guardBool r PilSolver.constrain r decidedBranchConditions = mapMaybe (`getDecidedBranchCondNode` cfg) . HSet.toList . G.nodes $ cfg solveStmt :: DataDependenceGraph -> SymTypedStmt -> Solver () solveStmt ddg stmt = case stmt of Pil.BranchCond _ -> return () TODO : convert stores / loads into immutable SSA vars Pil.Store _ -> return () Pil.DefPhi (Pil.DefPhiOp dest vars) -> do unless (or $ isDependentOn <$> vars) pilSolveStmt where destDescendants = G.getDescendants dest ddg isDependentOn = flip HSet.member destDescendants _ -> pilSolveStmt where pilSolveStmt = PilSolver.solveStmt_ (solveExpr ddg) stmt solveExpr :: DataDependenceGraph -> DSTExpression -> Solver SVal solveExpr ddg expr@(Ch.InfoExpression (Ch.SymInfo _sz xsym, mdst) op) = catchFallbackAndWarn $ case op of TOOD : turn mem into immutable vars Pil.LOAD _ -> fallbackAsFreeVar _ -> PilSolver.solveExpr_ (solveExpr ddg) expr where fallbackAsFreeVar :: Solver SVal fallbackAsFreeVar = case mdst of Nothing -> throwError . ExprError xsym . ErrorMessage $ "missing DeepSymType" Just dst -> catchError (makeSymVarOfType Nothing dst) $ \e -> throwError $ ExprError xsym e catchFallbackAndWarn :: Solver SVal -> Solver SVal catchFallbackAndWarn m = catchError m $ \e -> do si <- use #currentStmtIndex warn $ StmtError si e fallbackAsFreeVar data UndecidedBranchCond n = UndecidedBranchCond { conditionStatementIndex :: Int , condition :: Ch.InfoExpression (Ch.SymInfo, Maybe DeepSymType) , trueEdge :: CfEdge n , falseEdge :: CfEdge n } deriving (Eq, Ord, Show, Generic) getUndecidedBranchCondNode :: CfNode [(Int, SymTypedStmt)] -> Cfg (CfNode [(Int, SymTypedStmt)]) -> Maybe (UndecidedBranchCond (CfNode [(Int, SymTypedStmt)])) getUndecidedBranchCondNode n cfg = case outBranches of [(TrueBranch, tnode), (FalseBranch, fnode)] -> mcond <*> pure tnode <*> pure fnode [(FalseBranch, fnode), (TrueBranch, tnode)] -> mcond <*> pure tnode <*> pure fnode _ -> Nothing where mcond = lastMay (Cfg.getNodeData n) >>= \case (i, Pil.BranchCond (Pil.BranchCondOp x)) -> Just $ UndecidedBranchCond i x _ -> Nothing outBranches :: [(BranchType, CfEdge (CfNode [(Int, SymTypedStmt)]))] outBranches = fmap (\e -> (e ^. #branchType, e)) . HSet.toList $ Cfg.succEdges n cfg Starts at root node and finds nodes with conditional branches in breadth - first order . unsatBranches :: DataDependenceGraph -> Cfg (CfNode [(Int, SymTypedStmt)]) -> Solver [CfEdge (CfNode [(Int, SymTypedStmt)])] unsatBranches ddg typedCfg = case undecidedBranchCondNodes of [] -> return [] ubranches -> do generalCfgFormula ddg typedCfg ubranchesWithSvals <- traverse getBranchCondSVal ubranches er <- liftSymbolicT . Q.query $ Q.checkSat >>= \case Q.DSat _ -> Right <$> findRemoveableUnsats ubranchesWithSvals Q.Sat -> Right <$> findRemoveableUnsats ubranchesWithSvals r -> Left <$> toSolverResult r case er of Left sr -> do putText $ "General constraints are not sat: " <> show sr return [] Right xs -> return xs where getBranchCondSVal :: UndecidedBranchCond (CfNode [(Int, SymTypedStmt)]) -> Solver (UndecidedBranchCond (CfNode [(Int, SymTypedStmt)]), SVal) getBranchCondSVal u = do #currentStmtIndex .= u ^. #conditionStatementIndex c <- solveExpr ddg $ u ^. #condition PilSolver.guardBool c return (u, c) isSat :: Query Bool isSat = Q.checkSat >>= \case Q.DSat _ -> return True Q.Sat -> return True _ -> return False findRemoveableUnsats :: [(UndecidedBranchCond (CfNode [(Int, SymTypedStmt)]), SVal)] -> Query [CfEdge (CfNode [(Int, SymTypedStmt)])] findRemoveableUnsats xs = do (BranchCheckAccum condsToRecheck edgesToRemove) <- foldM checkBranchCond (BranchCheckAccum [] []) xs if null edgesToRemove then return [] else do edgesToRemove' <- findRemoveableUnsats condsToRecheck return $ edgesToRemove <> edgesToRemove' where checkBranchCond :: BranchCheckAccum -> (UndecidedBranchCond (CfNode [(Int, SymTypedStmt)]), SVal) -> Query BranchCheckAccum checkBranchCond (BranchCheckAccum condsToRecheck edgesToRemove) (u, c) = do tryConstraint c >>= \case False -> do addConstraint $ PilSolver.svBoolNot c return $ BranchCheckAccum condsToRecheck (u ^. #trueEdge : edgesToRemove) True -> tryConstraint (PilSolver.svBoolNot c) >>= \case False -> do addConstraint c return $ BranchCheckAccum condsToRecheck (u ^. #falseEdge : edgesToRemove) return $ BranchCheckAccum ((u, c) : condsToRecheck) edgesToRemove addConstraint :: SVal -> Query () addConstraint c = do SBV.constrain $ PilSolver.toSBool' c Q.push 1 tryConstraint :: SVal -> Query Bool tryConstraint c = Q.inNewAssertionStack $ SBV.constrain (PilSolver.toSBool' c) >> isSat undecidedBranchCondNodes = mapMaybe (`getUndecidedBranchCondNode` typedCfg) . concat . G.bfs [Cfg.getRootNode typedCfg] $ typedCfg data GeneralSolveError = TypeCheckerError Ch.ConstraintGenError | SolverError Ch.TypeReport PilSolver.SolverError deriving (Eq, Ord, Show, Generic) getUnsatBranches :: PilCfg -> IO (Either GeneralSolveError [CfEdge PilNode]) getUnsatBranches cfg = case checkCfg cfg of Left err -> return . Left . TypeCheckerError $ err Right (_, cfg', tr) -> do let ddg = CfgA.getDataDependenceGraph cfg er <- flip (PilSolver.runSolverWith SBV.z3) ( PilSolver.emptyState , SolverCtx (tr ^. #varSymTypeMap) HashMap.empty False SkipStatementsWithErrors ) $ PilSolver.declarePilVars >> unsatBranches ddg cfg' case er of Left err -> return . Left $ SolverError tr err Right (unsatEdges, _) -> return . Right $ fmap getOrigEdge unsatEdges where getOrigEdge :: CfEdge (CfNode [(Int, SymTypedStmt)]) -> CfEdge PilNode getOrigEdge (CfEdge src dst label) = let src' = fromJust $ Cfg.getNode cfg (G.getNodeId src) dst' = fromJust $ Cfg.getNode cfg (G.getNodeId dst) in CfEdge src' dst' label simplify_ :: Bool -> Int -> PilCfg -> IO (Either GeneralSolveError PilCfg) simplify_ isRecursiveCall numItersLeft cfg | numItersLeft <= 0 = return . Right $ cfg | otherwise = do let cfg' = CfgA.simplify cfg if cfg' == cfg && isRecursiveCall then return . Right $ cfg' else getUnsatBranches cfg' >>= \case Left err -> return $ Left err Right [] -> return . Right $ cfg' Right es -> simplify_ True (numItersLeft - 1) $ foldr Cfg.removeEdge cfg' es simplify :: PilCfg -> IO (Either GeneralSolveError PilCfg) simplify stmts = do simplify_ False 10 stmts
40a3b99935cc27388993a2a403dba7a86e7a95529c99279028b211b511fa5ab9
skynet-gh/skylobby
host_battle.clj
(ns skylobby.fx.host-battle (:require [cljfx.api :as fx] clojure.set skylobby.fx [skylobby.fx.engines :refer [engines-view]] [skylobby.fx.maps :refer [maps-view]] [skylobby.fx.mods :refer [mods-view]] [skylobby.fx.sub :as sub] [skylobby.util :as u] [taoensso.tufte :as tufte])) (set! *warn-on-reflection* true) (def host-battle-window-width 700) (def host-battle-window-height 400) (def host-battle-window-keys [:battle-password :battle-port :battle-title :by-server :by-spring-root :css :engine-filter :engine-version :map-input-prefix :map-name :mod-filter :mod-name :selected-server-tab :servers :show-host-battle-window :spring-isolation-dir]) (defn nat-cell [nat-type] {:text (str nat-type ": " (case (int nat-type) 0 "none" 1 "Hole punching" 2 "Fixed source ports" nil))}) (defn host-battle-window-impl [{:fx/keys [context] :keys [screen-bounds]}] (let [ server-key (fx/sub-ctx context skylobby.fx/selected-tab-server-key-sub) client-data (fx/sub-val context get-in [:by-server server-key :client-data]) show-host-battle-window (fx/sub-val context :show-host-battle-window)] {:fx/type :stage :showing (boolean (and client-data show-host-battle-window)) :title (str u/app-name " Host Battle") :icons skylobby.fx/icons :on-close-request {:event/type :spring-lobby/dissoc :key :show-host-battle-window} :x (skylobby.fx/fitx screen-bounds) :y (skylobby.fx/fity screen-bounds) :width (skylobby.fx/fitwidth screen-bounds host-battle-window-width) :height (skylobby.fx/fitheight screen-bounds host-battle-window-height) :scene {:fx/type :scene :stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub) :root (if show-host-battle-window (let [ battle-password (fx/sub-val context :battle-password) battle-port (fx/sub-val context :battle-port) battle-nat-type (or (fx/sub-val context :battle-nat-type) 0) battle-title (fx/sub-val context :battle-title) engine-filter (fx/sub-val context :engine-filter) map-input-prefix (fx/sub-val context :map-input-prefix) mod-filter (fx/sub-val context :mod-filter) server-key (fx/sub-ctx context skylobby.fx/selected-tab-server-key-sub) client-data (fx/sub-val context get-in [:by-server server-key :client-data]) scripttags (fx/sub-val context get-in [:by-server server-key :scripttags]) spring-root (fx/sub-ctx context sub/spring-root server-key) {:keys [engine-version map-name maps mod-name mods]} (fx/sub-ctx context sub/spring-resources spring-root) host-battle-action {:event/type :spring-lobby/host-battle :host-battle-state {:host-port battle-port :title battle-title :nat-type battle-nat-type :battle-password battle-password :engine-version engine-version :map-name map-name :mod-name mod-name :mod-hash -1 :map-hash -1} :client-data client-data :scripttags scripttags :use-git-mod-version (fx/sub-val context :use-git-mod-version)}] {:fx/type :v-box :style {:-fx-font-size 16} :children [ {:fx/type :label :text (str " Spring root for this server: " spring-root)} {:fx/type :h-box :children [ {:fx/type :label :text " Battle Name: "} {:fx/type :text-field :text (str battle-title) :prompt-text "Battle Title" :on-action host-battle-action :on-text-changed {:event/type :spring-lobby/assoc :key :battle-title}}]} {:fx/type :h-box :children [ {:fx/type :label :text " Battle Password: "} {:fx/type :text-field :text (str battle-password) :prompt-text "Battle Password" :on-action host-battle-action :on-text-changed {:event/type :spring-lobby/assoc :key :battle-password}}]} {:fx/type :h-box :alignment :center-left :children [ {:fx/type :label :text " Port: "} {:fx/type :text-field :text (str battle-port) :prompt-text "8452" :on-text-changed {:event/type :spring-lobby/assoc :key :battle-port} :text-formatter {:fx/type :text-formatter :value-converter :integer :value (int (or (u/to-number battle-port) 8452))}}]} {:fx/type :h-box :alignment :center-left :children [ {:fx/type :label :text " You will need to have this port reachable from other players, see"} (let [url "/"] {:fx/type :hyperlink :text url :on-action {:event/type :spring-lobby/desktop-browse-url :url url}})]} {:fx/type :h-box :alignment :center-left :children [ {:fx/type :label :text " NAT Type: "} {:fx/type :combo-box :value battle-nat-type :items [0 1 2] :on-value-changed {:event/type :spring-lobby/assoc :key :battle-nat-type} :button-cell nat-cell :cell-factory {:fx/cell-type :list-cell :describe nat-cell}}]} {:fx/type engines-view :engine-filter engine-filter :engine-version engine-version :flow false :spring-isolation-dir spring-root} {:fx/type mods-view :flow false :mod-filter mod-filter :mod-name mod-name :mods mods :spring-isolation-dir spring-root} {:fx/type maps-view :flow false :map-name map-name :maps maps :map-input-prefix map-input-prefix :spring-isolation-dir spring-root} {:fx/type :pane :v-box/vgrow :always} {:fx/type :button :text "Host Battle" :on-action host-battle-action}]}) {:fx/type :pane})}})) (defn host-battle-window [state] (tufte/profile {:dynamic? true :id :skylobby/ui} (tufte/p :host-battle-window (host-battle-window-impl state))))
null
https://raw.githubusercontent.com/skynet-gh/skylobby/e25c88d149c298326ec8a32306a86485c2324fd8/src/clj/skylobby/fx/host_battle.clj
clojure
(ns skylobby.fx.host-battle (:require [cljfx.api :as fx] clojure.set skylobby.fx [skylobby.fx.engines :refer [engines-view]] [skylobby.fx.maps :refer [maps-view]] [skylobby.fx.mods :refer [mods-view]] [skylobby.fx.sub :as sub] [skylobby.util :as u] [taoensso.tufte :as tufte])) (set! *warn-on-reflection* true) (def host-battle-window-width 700) (def host-battle-window-height 400) (def host-battle-window-keys [:battle-password :battle-port :battle-title :by-server :by-spring-root :css :engine-filter :engine-version :map-input-prefix :map-name :mod-filter :mod-name :selected-server-tab :servers :show-host-battle-window :spring-isolation-dir]) (defn nat-cell [nat-type] {:text (str nat-type ": " (case (int nat-type) 0 "none" 1 "Hole punching" 2 "Fixed source ports" nil))}) (defn host-battle-window-impl [{:fx/keys [context] :keys [screen-bounds]}] (let [ server-key (fx/sub-ctx context skylobby.fx/selected-tab-server-key-sub) client-data (fx/sub-val context get-in [:by-server server-key :client-data]) show-host-battle-window (fx/sub-val context :show-host-battle-window)] {:fx/type :stage :showing (boolean (and client-data show-host-battle-window)) :title (str u/app-name " Host Battle") :icons skylobby.fx/icons :on-close-request {:event/type :spring-lobby/dissoc :key :show-host-battle-window} :x (skylobby.fx/fitx screen-bounds) :y (skylobby.fx/fity screen-bounds) :width (skylobby.fx/fitwidth screen-bounds host-battle-window-width) :height (skylobby.fx/fitheight screen-bounds host-battle-window-height) :scene {:fx/type :scene :stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub) :root (if show-host-battle-window (let [ battle-password (fx/sub-val context :battle-password) battle-port (fx/sub-val context :battle-port) battle-nat-type (or (fx/sub-val context :battle-nat-type) 0) battle-title (fx/sub-val context :battle-title) engine-filter (fx/sub-val context :engine-filter) map-input-prefix (fx/sub-val context :map-input-prefix) mod-filter (fx/sub-val context :mod-filter) server-key (fx/sub-ctx context skylobby.fx/selected-tab-server-key-sub) client-data (fx/sub-val context get-in [:by-server server-key :client-data]) scripttags (fx/sub-val context get-in [:by-server server-key :scripttags]) spring-root (fx/sub-ctx context sub/spring-root server-key) {:keys [engine-version map-name maps mod-name mods]} (fx/sub-ctx context sub/spring-resources spring-root) host-battle-action {:event/type :spring-lobby/host-battle :host-battle-state {:host-port battle-port :title battle-title :nat-type battle-nat-type :battle-password battle-password :engine-version engine-version :map-name map-name :mod-name mod-name :mod-hash -1 :map-hash -1} :client-data client-data :scripttags scripttags :use-git-mod-version (fx/sub-val context :use-git-mod-version)}] {:fx/type :v-box :style {:-fx-font-size 16} :children [ {:fx/type :label :text (str " Spring root for this server: " spring-root)} {:fx/type :h-box :children [ {:fx/type :label :text " Battle Name: "} {:fx/type :text-field :text (str battle-title) :prompt-text "Battle Title" :on-action host-battle-action :on-text-changed {:event/type :spring-lobby/assoc :key :battle-title}}]} {:fx/type :h-box :children [ {:fx/type :label :text " Battle Password: "} {:fx/type :text-field :text (str battle-password) :prompt-text "Battle Password" :on-action host-battle-action :on-text-changed {:event/type :spring-lobby/assoc :key :battle-password}}]} {:fx/type :h-box :alignment :center-left :children [ {:fx/type :label :text " Port: "} {:fx/type :text-field :text (str battle-port) :prompt-text "8452" :on-text-changed {:event/type :spring-lobby/assoc :key :battle-port} :text-formatter {:fx/type :text-formatter :value-converter :integer :value (int (or (u/to-number battle-port) 8452))}}]} {:fx/type :h-box :alignment :center-left :children [ {:fx/type :label :text " You will need to have this port reachable from other players, see"} (let [url "/"] {:fx/type :hyperlink :text url :on-action {:event/type :spring-lobby/desktop-browse-url :url url}})]} {:fx/type :h-box :alignment :center-left :children [ {:fx/type :label :text " NAT Type: "} {:fx/type :combo-box :value battle-nat-type :items [0 1 2] :on-value-changed {:event/type :spring-lobby/assoc :key :battle-nat-type} :button-cell nat-cell :cell-factory {:fx/cell-type :list-cell :describe nat-cell}}]} {:fx/type engines-view :engine-filter engine-filter :engine-version engine-version :flow false :spring-isolation-dir spring-root} {:fx/type mods-view :flow false :mod-filter mod-filter :mod-name mod-name :mods mods :spring-isolation-dir spring-root} {:fx/type maps-view :flow false :map-name map-name :maps maps :map-input-prefix map-input-prefix :spring-isolation-dir spring-root} {:fx/type :pane :v-box/vgrow :always} {:fx/type :button :text "Host Battle" :on-action host-battle-action}]}) {:fx/type :pane})}})) (defn host-battle-window [state] (tufte/profile {:dynamic? true :id :skylobby/ui} (tufte/p :host-battle-window (host-battle-window-impl state))))
394d7a28af4551bd5d21dbe2115200a3fc17e540f2bdaf1d483e9b7195b682ee
crategus/cl-cffi-gtk
rtest-gtk-action.lisp
(def-suite gtk-action :in gtk-suite) (in-suite gtk-action) (defvar *verbose-gtk-action* nil) ;;; GtkAction (test gtk-action-class ;; Type check (is (g-type-is-object "GtkAction")) ;; Check the registered name (is (eq 'gtk-action (registered-object-type-by-name "GtkAction"))) ;; Check the parent (is (eq (gtype "GObject") (g-type-parent "GtkAction"))) ;; Check the children (is (equal '("GtkToggleAction" "GtkRecentAction") (mapcar #'g-type-name (g-type-children "GtkAction")))) ;; Check the interfaces (is (equal '("GtkBuildable") (mapcar #'g-type-name (g-type-interfaces "GtkAction")))) ;; Check the class properties (is (equal '("action-group" "always-show-image" "gicon" "hide-if-empty" "icon-name" "is-important" "label" "name" "sensitive" "short-label" "stock-id" "tooltip" "visible" "visible-horizontal" "visible-overflown" "visible-vertical") (sort (mapcar #'g-param-spec-name (g-object-class-list-properties "GtkAction")) #'string-lessp))) ;; Check the class definition (is (equal '(DEFINE-G-OBJECT-CLASS "GtkAction" GTK-ACTION (:SUPERCLASS G-OBJECT :EXPORT T :INTERFACES ("GtkBuildable") :TYPE-INITIALIZER "gtk_action_get_type") ((ACTION-GROUP GTK-ACTION-ACTION-GROUP "action-group" "GtkActionGroup" T T) (ALWAYS-SHOW-IMAGE GTK-ACTION-ALWAYS-SHOW-IMAGE "always-show-image" "gboolean" T T) (GICON GTK-ACTION-GICON "gicon" "GIcon" T T) (HIDE-IF-EMPTY GTK-ACTION-HIDE-IF-EMPTY "hide-if-empty" "gboolean" T T) (ICON-NAME GTK-ACTION-ICON-NAME "icon-name" "gchararray" T T) (IS-IMPORTANT GTK-ACTION-IS-IMPORTANT "is-important" "gboolean" T T) (LABEL GTK-ACTION-LABEL "label" "gchararray" T T) (NAME GTK-ACTION-NAME "name" "gchararray" T NIL) (SENSITIVE GTK-ACTION-SENSITIVE "sensitive" "gboolean" T T) (SHORT-LABEL GTK-ACTION-SHORT-LABEL "short-label" "gchararray" T T) (STOCK-ID GTK-ACTION-STOCK-ID "stock-id" "gchararray" T T) (TOOLTIP GTK-ACTION-TOOLTIP "tooltip" "gchararray" T T) (VISIBLE GTK-ACTION-VISIBLE "visible" "gboolean" T T) (VISIBLE-HORIZONTAL GTK-ACTION-VISIBLE-HORIZONTAL "visible-horizontal" "gboolean" T T) (VISIBLE-OVERFLOWN GTK-ACTION-VISIBLE-OVERFLOWN "visible-overflown" "gboolean" T T) (VISIBLE-VERTICAL GTK-ACTION-VISIBLE-VERTICAL "visible-vertical" "gboolean" T T))) (get-g-type-definition "GtkAction")))) gtk_action_new (test gtk-action-new.1 (let ((action (gtk-action-new "action"))) (is (string= "action" (gtk-action-name action))) (is-false (gtk-action-label action)) (is-false (gtk-action-tooltip action)) (is-false (gtk-action-stock-id action)))) (test gtk-action-new.2 (let ((action (gtk-action-new "action" "label" "tooltip" "stock-id"))) (is (string= "action" (gtk-action-name action))) (is (string= "label" (gtk-action-label action))) (is (string= "tooltip" (gtk-action-tooltip action))) (is (string= "stock-id" (gtk-action-stock-id action))))) ;;; gtk-action-name (test gtk-action-name (let ((action (gtk-action-new "action"))) (is (string= "action" (gtk-action-name action))))) ;;; gtk-action-is-sensitive ;;; gtk-action-sensitive (test gtk-action-sensitive (let ((action (gtk-action-new "action"))) (is-true (gtk-action-sensitive action)) (is-true (gtk-action-is-sensitive action)) (setf (gtk-action-sensitive action) nil) (is-false (gtk-action-sensitive action)) (is-false (gtk-action-is-sensitive action)))) ;;; gtk-action-is-visible ;;; gtk-action-visible (test gtk-action-visible (let ((action (gtk-action-new "action"))) (is-true (gtk-action-visible action)) (is-true (gtk-action-is-visible action)) (setf (gtk-action-visible action) nil) (is-false (gtk-action-visible action)) (is-false (gtk-action-is-visible action)))) ;;; gtk-action-activate #+nil (test gtk-action-activate (let ((message nil)) (within-main-loop (let ((action (gtk-action-new "action"))) (g-signal-connect action "activate" (lambda (action) (setf message "ACTIVATE CALLED") (when *verbose-gtk-action* (format t "~&Signal ACTIVATE for ~A~%" (gtk-action-name action))) (leave-gtk-main))) (gtk-action-activate action))) (join-gtk-main) (is (equal "ACTIVATE CALLED" message)))) ;;; gtk-action-create-icon (test gtk-action-create-icon (let ((action (gtk-action-new "action"))) ;; Check for a stock-id, also check for icon-name and gicon (setf (gtk-action-stock-id action) "gtk-ok") (is (typep (gtk-action-create-icon action :dialog) 'gtk-image)))) ;;; gtk-action-create-menu-item (test gtk-action-create-menu-item (let ((action (gtk-action-new "action"))) (is (typep (gtk-action-create-menu-item action) 'gtk-image-menu-item)))) ;;; gtk-action-create-tool-item (test gtk-action-create-tool-item (let ((action (gtk-action-new "action"))) (is (typep (gtk-action-create-tool-item action) 'gtk-tool-button)))) ;;; gtk-action-create-menu (test gtk-action-create-menu (let ((action (gtk-action-new "action"))) ;; Create an test for an result not nil (is-false (gtk-action-create-menu action)))) ;;; gtk_action_get_proxies (test gtk-action-proxies (let ((action (gtk-action-new "action"))) (is-false (gtk-action-proxies action)) ;; Add a tool item to list of proxies (gtk-action-create-tool-item action) (is (typep (first (gtk-action-proxies action)) 'gtk-tool-button)) ;; Add a menu item to list of proxies (gtk-action-create-menu-item action) (is (typep (first (gtk-action-proxies action)) 'gtk-image-menu-item)))) ;;; gtk-action-connect-accelerator (test gtk-action-connect-accelerator (let ((accel-group (gtk-accel-group-new)) (action (gtk-action-new "action"))) (setf (gtk-action-accel-path action) "<test>/File/Exit") (gtk-action-set-accel-group action accel-group) (gtk-action-connect-accelerator action))) ;;; gtk_action_disconnect_accelerator ;;; gtk_action_block_activate gtk_action_unblock_activate ;;; gtk_action_get_always_show_image ;;; gtk_action_set_always_show_image ;;; gtk_action_get_accel_path ;;; gtk_action_set_accel_path ;;; gtk_action_get_accel_closure ;;; gtk_action_set_accel_group ;;; gtk_action_set_label ;;; gtk_action_get_label ;;; gtk_action_get_short_label ;;; gtk_action_set_tooltip ;;; gtk_action_get_tooltip ;;; gtk_action_set_stock_id ;;; gtk_action_get_stock_id ;;; gtk_action_set_gicon ;;; gtk_action_get_gicon ;;; gtk_action_set_icon_name ;;; gtk_action_get_icon_name ;;; gtk_action_set_visible_horizontal ;;; gtk_action_get_visible_horizontal ;;; gtk_action_set_visible_vertical gtk_action_get_visible_vertical ;;; gtk_action_set_is_important ;;; gtk_action_get_is_important 2021 - 8 - 20
null
https://raw.githubusercontent.com/crategus/cl-cffi-gtk/74a78a6912a96f982644f3ee5ab7b8396cc2235f/test/rtest-gtk-action.lisp
lisp
GtkAction Type check Check the registered name Check the parent Check the children Check the interfaces Check the class properties Check the class definition gtk-action-name gtk-action-is-sensitive gtk-action-sensitive gtk-action-is-visible gtk-action-visible gtk-action-activate gtk-action-create-icon Check for a stock-id, also check for icon-name and gicon gtk-action-create-menu-item gtk-action-create-tool-item gtk-action-create-menu Create an test for an result not nil gtk_action_get_proxies Add a tool item to list of proxies Add a menu item to list of proxies gtk-action-connect-accelerator gtk_action_disconnect_accelerator gtk_action_block_activate gtk_action_get_always_show_image gtk_action_set_always_show_image gtk_action_get_accel_path gtk_action_set_accel_path gtk_action_get_accel_closure gtk_action_set_accel_group gtk_action_set_label gtk_action_get_label gtk_action_get_short_label gtk_action_set_tooltip gtk_action_get_tooltip gtk_action_set_stock_id gtk_action_get_stock_id gtk_action_set_gicon gtk_action_get_gicon gtk_action_set_icon_name gtk_action_get_icon_name gtk_action_set_visible_horizontal gtk_action_get_visible_horizontal gtk_action_set_visible_vertical gtk_action_set_is_important gtk_action_get_is_important
(def-suite gtk-action :in gtk-suite) (in-suite gtk-action) (defvar *verbose-gtk-action* nil) (test gtk-action-class (is (g-type-is-object "GtkAction")) (is (eq 'gtk-action (registered-object-type-by-name "GtkAction"))) (is (eq (gtype "GObject") (g-type-parent "GtkAction"))) (is (equal '("GtkToggleAction" "GtkRecentAction") (mapcar #'g-type-name (g-type-children "GtkAction")))) (is (equal '("GtkBuildable") (mapcar #'g-type-name (g-type-interfaces "GtkAction")))) (is (equal '("action-group" "always-show-image" "gicon" "hide-if-empty" "icon-name" "is-important" "label" "name" "sensitive" "short-label" "stock-id" "tooltip" "visible" "visible-horizontal" "visible-overflown" "visible-vertical") (sort (mapcar #'g-param-spec-name (g-object-class-list-properties "GtkAction")) #'string-lessp))) (is (equal '(DEFINE-G-OBJECT-CLASS "GtkAction" GTK-ACTION (:SUPERCLASS G-OBJECT :EXPORT T :INTERFACES ("GtkBuildable") :TYPE-INITIALIZER "gtk_action_get_type") ((ACTION-GROUP GTK-ACTION-ACTION-GROUP "action-group" "GtkActionGroup" T T) (ALWAYS-SHOW-IMAGE GTK-ACTION-ALWAYS-SHOW-IMAGE "always-show-image" "gboolean" T T) (GICON GTK-ACTION-GICON "gicon" "GIcon" T T) (HIDE-IF-EMPTY GTK-ACTION-HIDE-IF-EMPTY "hide-if-empty" "gboolean" T T) (ICON-NAME GTK-ACTION-ICON-NAME "icon-name" "gchararray" T T) (IS-IMPORTANT GTK-ACTION-IS-IMPORTANT "is-important" "gboolean" T T) (LABEL GTK-ACTION-LABEL "label" "gchararray" T T) (NAME GTK-ACTION-NAME "name" "gchararray" T NIL) (SENSITIVE GTK-ACTION-SENSITIVE "sensitive" "gboolean" T T) (SHORT-LABEL GTK-ACTION-SHORT-LABEL "short-label" "gchararray" T T) (STOCK-ID GTK-ACTION-STOCK-ID "stock-id" "gchararray" T T) (TOOLTIP GTK-ACTION-TOOLTIP "tooltip" "gchararray" T T) (VISIBLE GTK-ACTION-VISIBLE "visible" "gboolean" T T) (VISIBLE-HORIZONTAL GTK-ACTION-VISIBLE-HORIZONTAL "visible-horizontal" "gboolean" T T) (VISIBLE-OVERFLOWN GTK-ACTION-VISIBLE-OVERFLOWN "visible-overflown" "gboolean" T T) (VISIBLE-VERTICAL GTK-ACTION-VISIBLE-VERTICAL "visible-vertical" "gboolean" T T))) (get-g-type-definition "GtkAction")))) gtk_action_new (test gtk-action-new.1 (let ((action (gtk-action-new "action"))) (is (string= "action" (gtk-action-name action))) (is-false (gtk-action-label action)) (is-false (gtk-action-tooltip action)) (is-false (gtk-action-stock-id action)))) (test gtk-action-new.2 (let ((action (gtk-action-new "action" "label" "tooltip" "stock-id"))) (is (string= "action" (gtk-action-name action))) (is (string= "label" (gtk-action-label action))) (is (string= "tooltip" (gtk-action-tooltip action))) (is (string= "stock-id" (gtk-action-stock-id action))))) (test gtk-action-name (let ((action (gtk-action-new "action"))) (is (string= "action" (gtk-action-name action))))) (test gtk-action-sensitive (let ((action (gtk-action-new "action"))) (is-true (gtk-action-sensitive action)) (is-true (gtk-action-is-sensitive action)) (setf (gtk-action-sensitive action) nil) (is-false (gtk-action-sensitive action)) (is-false (gtk-action-is-sensitive action)))) (test gtk-action-visible (let ((action (gtk-action-new "action"))) (is-true (gtk-action-visible action)) (is-true (gtk-action-is-visible action)) (setf (gtk-action-visible action) nil) (is-false (gtk-action-visible action)) (is-false (gtk-action-is-visible action)))) #+nil (test gtk-action-activate (let ((message nil)) (within-main-loop (let ((action (gtk-action-new "action"))) (g-signal-connect action "activate" (lambda (action) (setf message "ACTIVATE CALLED") (when *verbose-gtk-action* (format t "~&Signal ACTIVATE for ~A~%" (gtk-action-name action))) (leave-gtk-main))) (gtk-action-activate action))) (join-gtk-main) (is (equal "ACTIVATE CALLED" message)))) (test gtk-action-create-icon (let ((action (gtk-action-new "action"))) (setf (gtk-action-stock-id action) "gtk-ok") (is (typep (gtk-action-create-icon action :dialog) 'gtk-image)))) (test gtk-action-create-menu-item (let ((action (gtk-action-new "action"))) (is (typep (gtk-action-create-menu-item action) 'gtk-image-menu-item)))) (test gtk-action-create-tool-item (let ((action (gtk-action-new "action"))) (is (typep (gtk-action-create-tool-item action) 'gtk-tool-button)))) (test gtk-action-create-menu (let ((action (gtk-action-new "action"))) (is-false (gtk-action-create-menu action)))) (test gtk-action-proxies (let ((action (gtk-action-new "action"))) (is-false (gtk-action-proxies action)) (gtk-action-create-tool-item action) (is (typep (first (gtk-action-proxies action)) 'gtk-tool-button)) (gtk-action-create-menu-item action) (is (typep (first (gtk-action-proxies action)) 'gtk-image-menu-item)))) (test gtk-action-connect-accelerator (let ((accel-group (gtk-accel-group-new)) (action (gtk-action-new "action"))) (setf (gtk-action-accel-path action) "<test>/File/Exit") (gtk-action-set-accel-group action accel-group) (gtk-action-connect-accelerator action))) gtk_action_unblock_activate gtk_action_get_visible_vertical 2021 - 8 - 20
571464084da0d92d73f8f48ee6d984d3ca4db936b6b91e59e41c589cedd6a30e
NetComposer/nksip
refer_test_client3.erl
%% ------------------------------------------------------------------- %% %% refer_test: REFER Test %% Copyright ( c ) 2013 . All Rights Reserved . %% This file is provided to you 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. %% %% ------------------------------------------------------------------- -module(refer_test_client3). -include_lib("nkserver/include/nkserver_module.hrl"). -export([sip_refer/3, sip_refer_update/3, sip_invite/2]). sip_refer(_ReferTo, _Req, _Call) -> true. sip_refer_update(SubsHandle, Status, Call) -> {ok, DialogId} = nksip_dialog:get_handle(SubsHandle), PkgId = nksip_call:srv_id(Call), Dialogs = nkserver:get(PkgId, dialogs, []), case lists:keyfind(DialogId, 1, Dialogs) of {DialogId, Ref, Pid}=_D -> Pid ! {Ref, {PkgId, SubsHandle, Status}}; false -> ok end. sip_invite(Req, _Call) -> {ok, ReqId} = nksip_request:get_handle(Req), spawn( fun() -> nksip_request:reply(180, ReqId), timer:sleep(1000), nksip_request:reply(ok, ReqId) end), noreply.
null
https://raw.githubusercontent.com/NetComposer/nksip/7fbcc66806635dc8ecc5d11c30322e4d1df36f0a/test/callbacks/refer_test_client3.erl
erlang
------------------------------------------------------------------- refer_test: REFER Test Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------
Copyright ( c ) 2013 . All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(refer_test_client3). -include_lib("nkserver/include/nkserver_module.hrl"). -export([sip_refer/3, sip_refer_update/3, sip_invite/2]). sip_refer(_ReferTo, _Req, _Call) -> true. sip_refer_update(SubsHandle, Status, Call) -> {ok, DialogId} = nksip_dialog:get_handle(SubsHandle), PkgId = nksip_call:srv_id(Call), Dialogs = nkserver:get(PkgId, dialogs, []), case lists:keyfind(DialogId, 1, Dialogs) of {DialogId, Ref, Pid}=_D -> Pid ! {Ref, {PkgId, SubsHandle, Status}}; false -> ok end. sip_invite(Req, _Call) -> {ok, ReqId} = nksip_request:get_handle(Req), spawn( fun() -> nksip_request:reply(180, ReqId), timer:sleep(1000), nksip_request:reply(ok, ReqId) end), noreply.
a5314351eeadd31f9aa07b13484fe3d273aaf305a8697cb1b0642e16c17f375f
erlyaws/yaws
yaws_jsonrpc.erl
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED %%% WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED %%% Use module yaws_rpc.erl instead %%% %%% This module is deprecated. %%% %%% Do not report problems with this module, as they will not be fixed. You %%% should instead convert your code to use the yaws_rpc module. %%% %%% WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED %%% WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright ( C ) 2003 < > . %% All rights reserved. %% Copyright ( C ) 2006 < > < > %% All rights reserved. %% %% %% Redistribution and use in source and binary forms, with or without %% modification, are permitted provided that the following conditions %% are met: %% 1 . Redistributions of source code must retain the above copyright %% notice, this list of conditions and the following disclaimer. 2 . Redistributions in binary form must reproduce the above %% copyright notice, this list of conditions and the following %% disclaimer in the documentation and/or other materials provided %% with the distribution. %% THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` 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 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. -module(yaws_jsonrpc). -author("Gaspar Chilingarov <>, Gurgen Tumanyan <>"). -export([handler/2]). -export([handler_session/2, handler_session/3]). -define(debug , 1 ) . -include("yaws_debug.hrl"). -include("../include/yaws_api.hrl"). # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # %%% public interface %%% %%% use jsonrpc handler which can automagically start sessions if we need %%% handler_session(Args, Handler) -> handler_session(Args, Handler, 'SID'). %%% %%% allow overriding session Cookie name %%% handler_session(Args, Handler, SID_NAME) when is_atom(SID_NAME) -> handler_session(Args, Handler, atom_to_list(SID_NAME)); handler_session(Args, Handler, SID_NAME) -> handler(Args, Handler, {session, SID_NAME}). % go to generic handler %%% %%% xmlrpc:handler compatible call %%% no session support will be available handler(Args, Handler) -> handler(Args, Handler, simple). # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # %%% private functions %%% %%% we should be called from yaws page or module handler(Args, Handler, Type) when is_record(Args, arg) -> case parse_request(Args) of ok -> handle_payload(Args, Handler, Type); {status, StatusCode} -> % cannot parse request send(Args, StatusCode) end. -define(ERROR_LOG(Reason), error_logger:error_report({?MODULE, ?LINE, Reason})). %%% %%% check that request come in reasonable protocol version and reasonable method %%% parse_request(Args) -> case {(Args#arg.req)#http_request.method, (Args#arg.req)#http_request.version} of {'POST', {1,0}} -> ?Debug("HTTP Version 1.0~n", []), ok; {'POST', {1,1}} -> ?Debug("HTTP Version 1.1~n", []), ok; {'POST', _HTTPVersion} -> {status, 505}; {_Method, {1,1}} -> {status, 501}; _ -> {status, 400} end. handle_payload(Args, Handler, Type) -> Payload = binary_to_list(Args#arg.clidata), ?Debug("jsonrpc plaintext call ~p ~n", [Payload]), case decode_handler_payload(Payload) of {ok, DecodedPayload, ID} -> ?Debug("json2erl decoded call ~p ~n", [DecodedPayload]), eval_payload(Args, Handler, DecodedPayload, Type, ID); {error, Reason} -> ?ERROR_LOG({html, json2erl, Payload, Reason}), send(Args, 400) end. %%% %%% call handler/3 and provide session support eval_payload(Args, {M, F}, Payload, {session, CookieName},ID) -> {SessionValue, Cookie} = case yaws_api:find_cookie_val(CookieName, (Args#arg.headers)#headers.cookie) of [] -> % have no session started, just call handler {undefined, undefined}; Cookie2 -> % get old session data case yaws_api:cookieval_to_opaque(Cookie2) of {ok, OP} -> yaws_api:cookieval_to_opaque(Cookie2), {OP, Cookie2}; {error, _ErrMsg} -> % cannot get corresponding session {undefined, undefined} end end, case catch M:F(Args#arg.state, Payload, SessionValue) of {'EXIT', Reason} -> ?ERROR_LOG({M, F, {'EXIT', Reason}}), send(Args, 500); {error, Reason} -> ?ERROR_LOG({M, F, Reason}), send(Args, 500); {false, ResponsePayload} -> %% do not have updates in session data encode_send(Args, 200, ResponsePayload, [], ID); {true, _NewTimeout, NewSessionValue, ResponsePayload} -> %% be compatible with xmlrpc module CO = case NewSessionValue of undefined when Cookie == undefined -> []; % nothing to do undefined -> % rpc handler requested session delete yaws_api:delete_cookie_session(Cookie), []; %% XXX: may be return set-cookie with empty val? _ -> %% any other value will stored in session case SessionValue of undefined -> %% got session data and should start %% new session now Cookie1 = yaws_api:new_cookie_session( NewSessionValue), yaws_api:setcookie(CookieName, Cookie1, "/"); _ -> yaws_api:replace_cookie_session( Cookie, NewSessionValue), [] % nothing to add to yaws data end end, encode_send(Args, 200, ResponsePayload, CO, ID) end; %%% %%% call handler/2 without session support %%% eval_payload(Args, {M, F}, Payload, simple, ID) -> case catch M:F(Args#arg.state, Payload) of {'EXIT', Reason} -> ?ERROR_LOG({M, F, {'EXIT', Reason}}), send(Args, 500); {error, Reason} -> ?ERROR_LOG({M, F, Reason}), send(Args, 500); {false, ResponsePayload} -> encode_send(Args, 200, ResponsePayload, [],ID); {true, _NewTimeout, _NewState, ResponsePayload} -> encode_send(Args, 200, ResponsePayload, [],ID) end. XXX compatibility with XMLRPC handlers %%% XXX - potential bug here? encode_send(Args, StatusCode, [Payload], AddOn, ID) -> encode_send(Args, StatusCode, Payload, AddOn, ID); encode_send(Args, StatusCode, Payload, AddOn, ID) -> {ok, EncodedPayload} = encode_handler_payload(Payload, ID), send(Args, StatusCode, EncodedPayload, AddOn). send(Args, StatusCode) -> send(Args, StatusCode, "", []). send(Args, StatusCode, Payload, AddOnData) when not is_list(AddOnData) -> send(Args, StatusCode, Payload, [AddOnData]); send(_Args, StatusCode, Payload, AddOnData) -> A = [ {status, StatusCode}, {content, "text/xml", Payload}, {header, {content_length, lists:flatlength(Payload) }} ] ++ AddOnData, A. encode_handler_payload({response, [ErlStruct]},ID) -> encode_handler_payload({response, ErlStruct}, ID); encode_handler_payload({response, ErlStruct},ID) -> StructStr = json2:encode({struct, [{result, ErlStruct}, {id, ID}]}), {ok, StructStr}. decode_handler_payload(JSonStr) -> try {ok, JSON} = json2:decode_string(JSonStr), Method = list_to_atom(jsonrpc:s(JSON, method)), {array, Args} = jsonrpc:s(JSON, params), ID = jsonrpc:s(JSON, id), {ok, {call, Method, Args}, ID} catch error:Err -> {error, Err} end.
null
https://raw.githubusercontent.com/erlyaws/yaws/bbd0a2224f03fe60db6c986da4e4b2f0c9227402/src/yaws_jsonrpc.erl
erlang
WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED This module is deprecated. Do not report problems with this module, as they will not be fixed. You should instead convert your code to use the yaws_rpc module. WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED WARNING DEPRECATED All rights reserved. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. public interface allow overriding session Cookie name go to generic handler xmlrpc:handler compatible call no session support will be available private functions we should be called from yaws page or module cannot parse request check that request come in reasonable protocol version and reasonable method call handler/3 and provide session support have no session started, just call handler get old session data cannot get corresponding session do not have updates in session data be compatible with xmlrpc module nothing to do rpc handler requested session delete XXX: may be return set-cookie with empty val? any other value will stored in session got session data and should start new session now nothing to add to yaws data call handler/2 without session support XXX - potential bug here?
Use module yaws_rpc.erl instead Copyright ( C ) 2003 < > . Copyright ( C ) 2006 < > < > 1 . Redistributions of source code must retain the above copyright 2 . Redistributions in binary form must reproduce the above THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , -module(yaws_jsonrpc). -author("Gaspar Chilingarov <>, Gurgen Tumanyan <>"). -export([handler/2]). -export([handler_session/2, handler_session/3]). -define(debug , 1 ) . -include("yaws_debug.hrl"). -include("../include/yaws_api.hrl"). # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # use jsonrpc handler which can automagically start sessions if we need handler_session(Args, Handler) -> handler_session(Args, Handler, 'SID'). handler_session(Args, Handler, SID_NAME) when is_atom(SID_NAME) -> handler_session(Args, Handler, atom_to_list(SID_NAME)); handler_session(Args, Handler, SID_NAME) -> handler(Args, Handler) -> handler(Args, Handler, simple). # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # handler(Args, Handler, Type) when is_record(Args, arg) -> case parse_request(Args) of ok -> handle_payload(Args, Handler, Type); send(Args, StatusCode) end. -define(ERROR_LOG(Reason), error_logger:error_report({?MODULE, ?LINE, Reason})). parse_request(Args) -> case {(Args#arg.req)#http_request.method, (Args#arg.req)#http_request.version} of {'POST', {1,0}} -> ?Debug("HTTP Version 1.0~n", []), ok; {'POST', {1,1}} -> ?Debug("HTTP Version 1.1~n", []), ok; {'POST', _HTTPVersion} -> {status, 505}; {_Method, {1,1}} -> {status, 501}; _ -> {status, 400} end. handle_payload(Args, Handler, Type) -> Payload = binary_to_list(Args#arg.clidata), ?Debug("jsonrpc plaintext call ~p ~n", [Payload]), case decode_handler_payload(Payload) of {ok, DecodedPayload, ID} -> ?Debug("json2erl decoded call ~p ~n", [DecodedPayload]), eval_payload(Args, Handler, DecodedPayload, Type, ID); {error, Reason} -> ?ERROR_LOG({html, json2erl, Payload, Reason}), send(Args, 400) end. eval_payload(Args, {M, F}, Payload, {session, CookieName},ID) -> {SessionValue, Cookie} = case yaws_api:find_cookie_val(CookieName, (Args#arg.headers)#headers.cookie) of {undefined, undefined}; case yaws_api:cookieval_to_opaque(Cookie2) of {ok, OP} -> yaws_api:cookieval_to_opaque(Cookie2), {OP, Cookie2}; {undefined, undefined} end end, case catch M:F(Args#arg.state, Payload, SessionValue) of {'EXIT', Reason} -> ?ERROR_LOG({M, F, {'EXIT', Reason}}), send(Args, 500); {error, Reason} -> ?ERROR_LOG({M, F, Reason}), send(Args, 500); {false, ResponsePayload} -> encode_send(Args, 200, ResponsePayload, [], ID); {true, _NewTimeout, NewSessionValue, ResponsePayload} -> CO = case NewSessionValue of yaws_api:delete_cookie_session(Cookie), []; _ -> case SessionValue of undefined -> Cookie1 = yaws_api:new_cookie_session( NewSessionValue), yaws_api:setcookie(CookieName, Cookie1, "/"); _ -> yaws_api:replace_cookie_session( Cookie, NewSessionValue), end end, encode_send(Args, 200, ResponsePayload, CO, ID) end; eval_payload(Args, {M, F}, Payload, simple, ID) -> case catch M:F(Args#arg.state, Payload) of {'EXIT', Reason} -> ?ERROR_LOG({M, F, {'EXIT', Reason}}), send(Args, 500); {error, Reason} -> ?ERROR_LOG({M, F, Reason}), send(Args, 500); {false, ResponsePayload} -> encode_send(Args, 200, ResponsePayload, [],ID); {true, _NewTimeout, _NewState, ResponsePayload} -> encode_send(Args, 200, ResponsePayload, [],ID) end. XXX compatibility with XMLRPC handlers encode_send(Args, StatusCode, [Payload], AddOn, ID) -> encode_send(Args, StatusCode, Payload, AddOn, ID); encode_send(Args, StatusCode, Payload, AddOn, ID) -> {ok, EncodedPayload} = encode_handler_payload(Payload, ID), send(Args, StatusCode, EncodedPayload, AddOn). send(Args, StatusCode) -> send(Args, StatusCode, "", []). send(Args, StatusCode, Payload, AddOnData) when not is_list(AddOnData) -> send(Args, StatusCode, Payload, [AddOnData]); send(_Args, StatusCode, Payload, AddOnData) -> A = [ {status, StatusCode}, {content, "text/xml", Payload}, {header, {content_length, lists:flatlength(Payload) }} ] ++ AddOnData, A. encode_handler_payload({response, [ErlStruct]},ID) -> encode_handler_payload({response, ErlStruct}, ID); encode_handler_payload({response, ErlStruct},ID) -> StructStr = json2:encode({struct, [{result, ErlStruct}, {id, ID}]}), {ok, StructStr}. decode_handler_payload(JSonStr) -> try {ok, JSON} = json2:decode_string(JSonStr), Method = list_to_atom(jsonrpc:s(JSON, method)), {array, Args} = jsonrpc:s(JSON, params), ID = jsonrpc:s(JSON, id), {ok, {call, Method, Args}, ID} catch error:Err -> {error, Err} end.
c227fb7d2615da80617b2deb528649a027027ccf34632d586e87f30a2b7ec7e9
ar-nelson/schemepunk
function.test.scm
(import (scheme base) (schemepunk syntax) (schemepunk function) (schemepunk test)) (test-group "Function Combinators" (test-equal 'foo (identity 'foo)) (test-equal 'foo ((const 'foo) 'bar)) (test-equal '(y . x) ((flip cons) 'x 'y)) (test-equal "-2" ((compose number->string - length) '(1 2))) (test-equal "-3" ((bind length - number->string) '(1 2 3))) (test-equal #f ((complement <) 1 2)))
null
https://raw.githubusercontent.com/ar-nelson/schemepunk/e2840d3c445933528aaf0a36ec72b053ec5016ce/tests/function.test.scm
scheme
(import (scheme base) (schemepunk syntax) (schemepunk function) (schemepunk test)) (test-group "Function Combinators" (test-equal 'foo (identity 'foo)) (test-equal 'foo ((const 'foo) 'bar)) (test-equal '(y . x) ((flip cons) 'x 'y)) (test-equal "-2" ((compose number->string - length) '(1 2))) (test-equal "-3" ((bind length - number->string) '(1 2 3))) (test-equal #f ((complement <) 1 2)))
88eb7932b54e31f44a4df9cb27739456e99f2be4e3fb52492e75f7cb79e970b7
idubrov/siperl
sip_uri.erl
%%%---------------------------------------------------------------- @author < > %%% @doc URI parse utilities %%% Implementation of parsing for supported URI schemes ( ` sip ' , ` sips ' , ` tel ' ) . %%% @end @reference See < a href=" / html / rfc3261#section-19">RFC 3261</a > for details . 2011 - 2012 . See LICENSE file . %%%---------------------------------------------------------------- -module(sip_uri). %% Exports %% API -export([parse/1, format/1]). -export([is_loose_router/1, is_strict_router/1, is_sips/1]). %% Include files -include("../sip_common.hrl"). -include("sip.hrl"). %%----------------------------------------------------------------- %% API functions %%----------------------------------------------------------------- @doc Parses all supported URI formats %% If URI could not be parsed because scheme is not supported , %% a binary is returned as is. %% @end -spec parse(URI :: binary()) -> #sip_uri{} | binary(). parse(<<"sip:", Rest/binary>>) -> parse_sip(sip, Rest); parse(<<"sips:", Rest/binary>>) -> parse_sip(sips, Rest); parse(Bin) when is_binary(Bin) -> Bin. @doc Check if SIP URI is loose router URI %% @end -spec is_loose_router(#sip_uri{}) -> boolean(). is_loose_router(#sip_uri{params = Params}) -> proplists:get_bool(lr, Params). @doc Check if SIP URI is strict router URI %% @end -spec is_strict_router(#sip_uri{}) -> boolean(). is_strict_router(URI) -> not is_loose_router(URI). -spec is_sips(sip_uri()) -> boolean(). @doc Check if URI is SIPS URI . %% @end is_sips(#sip_uri{scheme = sips}) -> true; is_sips(_Other) -> false. %% @doc Parse SIP URI BNF notation : %% ``` %% SIP-URI = "sip:" [ userinfo ] hostport %% uri-parameters [ headers ] %% SIPS-URI = "sips:" [ userinfo ] hostport %% uri-parameters [ headers ] %% userinfo = ( user / telephone-subscriber ) [ ":" password ] "@" user = 1 * ( unreserved / escaped / user - unreserved ) hostport = host [ " : " port ] %% uri-parameters = *( ";" uri-parameter) %% uri-parameter = transport-param / user-param / method-param / - param / maddr - param / lr - param / other - param %% headers = "?" header *( "&" header ) %% header = hname "=" hvalue %% ''' %% @end parse_sip(Scheme, Bin) -> case binary:split(Bin, <<$@>>) of [UserInfo, Rest] -> case binary:split(UserInfo, <<$:>>) of [User, Password] -> ok; [User] -> Password = <<>> end; [Rest] -> User = <<>>, Password = <<>> end, {Host, Port, ParamsBin} = sip_syntax:parse_host_port(Rest), {Params, HeadersBin} = parse_params(ParamsBin, []), Headers = parse_headers(HeadersBin), #sip_uri{scheme = Scheme, user = User, password = Password, host = Host, port = Port, headers = Headers, params = Params}. %% @doc Parse SIP URI parameters lists BNF notation : %% ``` %% uri-parameters = *( ";" uri-parameter) %% uri-parameter = transport-param / user-param / method-param / - param / maddr - param / lr - param / other - param %% transport-param = "transport=" %% ( "udp" / "tcp" / "sctp" / "tls" %% / other-transport) %% other-transport = token %% user-param = "user=" ( "phone" / "ip" / other-user) %% other-user = token %% method-param = "method=" Method ttl - param = " ttl= " %% maddr-param = "maddr=" host %% lr-param = "lr" %% other-param = pname [ "=" pvalue ] pname = 1*paramchar pvalue = 1*paramchar %% paramchar = param-unreserved / unreserved / escaped %% param-unreserved = "[" / "]" / "/" / ":" / "&" / "+" / "$" %% ''' %% @end parse_params(<<$;, Bin/binary>>, List) -> Pred = fun ($;) -> true; % next parameter ($?) -> true; % headers ($=) -> true; % value (_) -> false end, {Param, Rest} = case sip_binary:parse_until(Bin, Pred) of {Name, <<$=, Bin2/binary>>} -> % parse value {Value, R} = sip_binary:parse_until(Bin2, Pred), {{sip_syntax:parse_name(Name), Value}, R}; {Name, Bin2} -> % no value {sip_syntax:parse_name(Name), Bin2} end, parse_params(Rest, [Param|List]); parse_params(Bin, List) -> {lists:reverse(List), Bin}. %% @doc Parse SIP URI headers BNF notation : %% ``` %% headers = "?" header *( "&" header ) %% header = hname "=" hvalue hname = 1 * ( hnv - unreserved / unreserved / escaped ) hvalue = * ( hnv - unreserved / unreserved / escaped ) hnv - unreserved = " [ " / " ] " / " / " / " ? " / " : " / " + " / " $ " %% unreserved = alphanum / mark %% mark = "-" / "_" / "." / "!" / "~" / "*" / "'" %% / "(" / ")" %% escaped = "%" HEXDIG HEXDIG %% ''' %% @end parse_headers(<<>>) -> []; parse_headers(<<$?, Bin/binary>>) -> Headers = [binary:split(Header, <<$=>>) || Header <- binary:split(Bin, <<$&>>)], [{sip_syntax:parse_name(Name), Value} || [Name, Value] <- Headers]. %% @doc Format URI to binary string %% %% @end -spec format(#sip_uri{} | binary()) -> binary(). format(URI) when is_binary(URI) -> URI; format(#sip_uri{scheme = sip} = URI) -> append_userinfo(URI, <<"sip:">>); format(#sip_uri{scheme = sips} = URI) -> append_userinfo(URI, <<"sips:">>). append_userinfo(#sip_uri{user = <<>>} = URI, Bin) -> append_hostport(URI, Bin); append_userinfo(#sip_uri{user = User} = URI, Bin) -> append_password(URI, <<Bin/binary, User/binary>>). append_password(#sip_uri{password = <<>>} = URI, Bin) -> append_hostport(URI, <<Bin/binary, $@>>); append_password(#sip_uri{password = Password} = URI, Bin) -> append_hostport(URI, <<Bin/binary, $:, Password/binary, $@>>). append_hostport(URI, Bin) -> Host = sip_syntax:format_addr(URI#sip_uri.host), append_port(URI, <<Bin/binary, Host/binary>>). append_port(#sip_uri{port = undefined} = URI, Bin) -> append_params(URI, URI#sip_uri.params, Bin); append_port(#sip_uri{port = Port} = URI, Bin) -> append_params(URI, URI#sip_uri.params, <<Bin/binary, $:, (sip_binary:integer_to_binary(Port))/binary>>). append_params(URI, [{Name, Value} | Tail], Bin) -> NameBin = sip_syntax:format_name(Name), Bin2 = <<Bin/binary, $;, NameBin/binary, $=, Value/binary>>, append_params(URI, Tail, Bin2); append_params(URI, [Name | Tail], Bin) -> NameBin = sip_syntax:format_name(Name), Bin2 = <<Bin/binary, $;, NameBin/binary>>, append_params(URI, Tail, Bin2); append_params(URI, [], Bin) -> append_headers(URI#sip_uri.headers, $?, Bin). append_headers([], _Sep, Bin) -> Bin; append_headers([{Name, Value} | Tail], Sep, Bin) -> NameBin = sip_syntax:format_name(Name), Bin2 = <<Bin/binary, Sep, NameBin/binary, $=, Value/binary>>, append_headers(Tail, $&, Bin2). %%----------------------------------------------------------------- %% Tests %%----------------------------------------------------------------- -ifdef(TEST). -spec parse_test_() -> list(). parse_test_() -> [ % samples from RFC ?_assertEqual(#sip_uri{scheme = sip, user = <<"alice">>, host = "atlanta.com"}, parse(<<"sip:">>)), ?_assertEqual(#sip_uri{scheme = sip, user = <<"alice">>, password = <<"secretword">>, host = "atlanta.com", params = [{transport, <<"tcp">>}]}, parse(<<"sip:alice:;transport=tcp">>)), ?_assertEqual(#sip_uri{scheme = sips, user = <<"alice">>, host = "atlanta.com", headers = [{subject, <<"project%20x">>}, {priority, <<"urgent">>}]}, parse(<<"sips:?subject=project%20x&priority=urgent">>)), ?_assertEqual(#sip_uri{scheme = sip, user = <<"+1-212-555-1212">>, password = <<"1234">>, host = "gateway.com", params = [{user, <<"phone">>}]}, parse(<<"sip:+1-212-555-1212:;user=phone">>)), ?_assertEqual(#sip_uri{scheme = sips, user = <<"1212">>, host = "gateway.com"}, parse(<<"sips:">>)), ?_assertEqual(#sip_uri{scheme = sip, user = <<"alice">>, host = {192, 0, 2, 4}}, parse(<<"sip:alice@192.0.2.4">>)), ?_assertEqual(#sip_uri{scheme = sip, host = "atlanta.com", params = [{method, <<"REGISTER">>}], headers = [{to, <<"alice%40atlanta.com">>}]}, parse(<<"sip:atlanta.com;method=REGISTER?to=alice%40atlanta.com">>)), ?_assertEqual(#sip_uri{scheme = sip, user = <<"alice;day=tuesday">>, host = "atlanta.com"}, parse(<<"sip:alice;day=">>)), % extra test cases ?_assertEqual(#sip_uri{scheme = sips, user = <<"alice">>, host = "atlanta.com", params = [{maddr, <<"239.255.255.1">>}, {ttl, <<"15">>}]}, parse(<<"sips:;maddr=239.255.255.1;ttl=15">>)), ?_assertEqual(#sip_uri{scheme = sip, user = <<"j%40s0n">>, host = "atlanta.com"}, parse(<<"sip:j%">>)), ?_assertEqual(#sip_uri{scheme = sip, user = <<"alice">>, host = {8193,3512,0,0,0,0,44577,44306}, port = 5060}, parse(<<"sip:alice@[2001:0db8:0000:0000:0000:0000:ae21:ad12]:5060">>)) ]. -spec format_test_() -> list(). format_test_() -> [ % samples from RFC ?_assertEqual(<<"sip:">>, format(#sip_uri{scheme = sip, user = <<"alice">>, host = "atlanta.com"})), ?_assertEqual(<<"sip:alice:;transport=tcp">>, format(#sip_uri{scheme = sip, user = <<"alice">>, password = <<"secretword">>, host = "atlanta.com", params = [{transport, <<"tcp">>}]})), ?_assertEqual(<<"sips:?subject=project%20x&priority=urgent">>, format(#sip_uri{scheme = sips, user = <<"alice">>, host = "atlanta.com", headers = [{subject, <<"project%20x">>}, {priority, <<"urgent">>}]})), ?_assertEqual(<<"sip:+1-212-555-1212:;user=phone">>, format(#sip_uri{scheme = sip, user = <<"+1-212-555-1212">>, password = <<"1234">>, host = "gateway.com", params = [{user, <<"phone">>}]})), ?_assertEqual(<<"sips:">>, format(#sip_uri{scheme = sips, user = <<"1212">>, host = "gateway.com"})), ?_assertEqual(<<"sip:alice@192.0.2.4">>, format(#sip_uri{scheme = sip, user = <<"alice">>, host = {192, 0, 2, 4}})), ?_assertEqual(<<"sip:atlanta.com;method=REGISTER?to=alice%40atlanta.com">>, format(#sip_uri{scheme = sip, host = "atlanta.com", params = [{method, <<"REGISTER">>}], headers = [{to, <<"alice%40atlanta.com">>}]})), ?_assertEqual(<<"sip:alice;day=">>, format(#sip_uri{scheme = sip, user = <<"alice;day=tuesday">>, host = "atlanta.com"})), % extra test cases ?_assertEqual(<<"sips:;maddr=239.255.255.1;ttl=15">>, format(#sip_uri{scheme = sips, user = <<"alice">>, host = "atlanta.com", params = [{maddr, <<"239.255.255.1">>}, {ttl, <<"15">>}]})), ?_assertEqual(<<"sip:j%">>, format(#sip_uri{scheme = sip, user = <<"j%40s0n">>, host = "atlanta.com"})), ?_assertEqual(<<"sip:alice@[2001:0db8:0000:0000:0000:0000:ae21:ad12]:5060">>, format(#sip_uri{scheme = sip, user = <<"alice">>, host = {8193,3512,0,0,0,0,44577,44306}, port = 5060})) ]. -spec is_strict_router_test_() -> list(). is_strict_router_test_() -> [?_assertEqual(true, is_strict_router(sip_uri:parse(<<"sip:p3.middle.com">>))), ?_assertEqual(false, is_strict_router(sip_uri:parse(<<"sip:p2.example.com;lr">>))) ]. -endif.
null
https://raw.githubusercontent.com/idubrov/siperl/251daf3a0d7c7442f56f42cfd6c92764a4f475a7/apps/sip/src/syntax/sip_uri.erl
erlang
---------------------------------------------------------------- @doc URI parse utilities @end ---------------------------------------------------------------- Exports API Include files ----------------------------------------------------------------- API functions ----------------------------------------------------------------- a binary is returned as is. @end @end @end @end @doc Parse SIP URI ``` SIP-URI = "sip:" [ userinfo ] hostport uri-parameters [ headers ] SIPS-URI = "sips:" [ userinfo ] hostport uri-parameters [ headers ] userinfo = ( user / telephone-subscriber ) [ ":" password ] "@" uri-parameters = *( ";" uri-parameter) uri-parameter = transport-param / user-param / method-param headers = "?" header *( "&" header ) header = hname "=" hvalue ''' @end @doc Parse SIP URI parameters lists ``` uri-parameters = *( ";" uri-parameter) uri-parameter = transport-param / user-param / method-param transport-param = "transport=" ( "udp" / "tcp" / "sctp" / "tls" / other-transport) other-transport = token user-param = "user=" ( "phone" / "ip" / other-user) other-user = token method-param = "method=" Method maddr-param = "maddr=" host lr-param = "lr" other-param = pname [ "=" pvalue ] paramchar = param-unreserved / unreserved / escaped param-unreserved = "[" / "]" / "/" / ":" / "&" / "+" / "$" ''' @end next parameter headers value parse value no value @doc Parse SIP URI headers ``` headers = "?" header *( "&" header ) header = hname "=" hvalue unreserved = alphanum / mark mark = "-" / "_" / "." / "!" / "~" / "*" / "'" / "(" / ")" escaped = "%" HEXDIG HEXDIG ''' @end @doc Format URI to binary string @end ----------------------------------------------------------------- Tests ----------------------------------------------------------------- samples from RFC extra test cases samples from RFC extra test cases
@author < > Implementation of parsing for supported URI schemes ( ` sip ' , ` sips ' , ` tel ' ) . @reference See < a href=" / html / rfc3261#section-19">RFC 3261</a > for details . 2011 - 2012 . See LICENSE file . -module(sip_uri). -export([parse/1, format/1]). -export([is_loose_router/1, is_strict_router/1, is_sips/1]). -include("../sip_common.hrl"). -include("sip.hrl"). @doc Parses all supported URI formats If URI could not be parsed because scheme is not supported , -spec parse(URI :: binary()) -> #sip_uri{} | binary(). parse(<<"sip:", Rest/binary>>) -> parse_sip(sip, Rest); parse(<<"sips:", Rest/binary>>) -> parse_sip(sips, Rest); parse(Bin) when is_binary(Bin) -> Bin. @doc Check if SIP URI is loose router URI -spec is_loose_router(#sip_uri{}) -> boolean(). is_loose_router(#sip_uri{params = Params}) -> proplists:get_bool(lr, Params). @doc Check if SIP URI is strict router URI -spec is_strict_router(#sip_uri{}) -> boolean(). is_strict_router(URI) -> not is_loose_router(URI). -spec is_sips(sip_uri()) -> boolean(). @doc Check if URI is SIPS URI . is_sips(#sip_uri{scheme = sips}) -> true; is_sips(_Other) -> false. BNF notation : user = 1 * ( unreserved / escaped / user - unreserved ) hostport = host [ " : " port ] / - param / maddr - param / lr - param / other - param parse_sip(Scheme, Bin) -> case binary:split(Bin, <<$@>>) of [UserInfo, Rest] -> case binary:split(UserInfo, <<$:>>) of [User, Password] -> ok; [User] -> Password = <<>> end; [Rest] -> User = <<>>, Password = <<>> end, {Host, Port, ParamsBin} = sip_syntax:parse_host_port(Rest), {Params, HeadersBin} = parse_params(ParamsBin, []), Headers = parse_headers(HeadersBin), #sip_uri{scheme = Scheme, user = User, password = Password, host = Host, port = Port, headers = Headers, params = Params}. BNF notation : / - param / maddr - param / lr - param / other - param ttl - param = " ttl= " pname = 1*paramchar pvalue = 1*paramchar parse_params(<<$;, Bin/binary>>, List) -> (_) -> false end, {Param, Rest} = case sip_binary:parse_until(Bin, Pred) of {Name, <<$=, Bin2/binary>>} -> {Value, R} = sip_binary:parse_until(Bin2, Pred), {{sip_syntax:parse_name(Name), Value}, R}; {Name, Bin2} -> {sip_syntax:parse_name(Name), Bin2} end, parse_params(Rest, [Param|List]); parse_params(Bin, List) -> {lists:reverse(List), Bin}. BNF notation : hname = 1 * ( hnv - unreserved / unreserved / escaped ) hvalue = * ( hnv - unreserved / unreserved / escaped ) hnv - unreserved = " [ " / " ] " / " / " / " ? " / " : " / " + " / " $ " parse_headers(<<>>) -> []; parse_headers(<<$?, Bin/binary>>) -> Headers = [binary:split(Header, <<$=>>) || Header <- binary:split(Bin, <<$&>>)], [{sip_syntax:parse_name(Name), Value} || [Name, Value] <- Headers]. -spec format(#sip_uri{} | binary()) -> binary(). format(URI) when is_binary(URI) -> URI; format(#sip_uri{scheme = sip} = URI) -> append_userinfo(URI, <<"sip:">>); format(#sip_uri{scheme = sips} = URI) -> append_userinfo(URI, <<"sips:">>). append_userinfo(#sip_uri{user = <<>>} = URI, Bin) -> append_hostport(URI, Bin); append_userinfo(#sip_uri{user = User} = URI, Bin) -> append_password(URI, <<Bin/binary, User/binary>>). append_password(#sip_uri{password = <<>>} = URI, Bin) -> append_hostport(URI, <<Bin/binary, $@>>); append_password(#sip_uri{password = Password} = URI, Bin) -> append_hostport(URI, <<Bin/binary, $:, Password/binary, $@>>). append_hostport(URI, Bin) -> Host = sip_syntax:format_addr(URI#sip_uri.host), append_port(URI, <<Bin/binary, Host/binary>>). append_port(#sip_uri{port = undefined} = URI, Bin) -> append_params(URI, URI#sip_uri.params, Bin); append_port(#sip_uri{port = Port} = URI, Bin) -> append_params(URI, URI#sip_uri.params, <<Bin/binary, $:, (sip_binary:integer_to_binary(Port))/binary>>). append_params(URI, [{Name, Value} | Tail], Bin) -> NameBin = sip_syntax:format_name(Name), Bin2 = <<Bin/binary, $;, NameBin/binary, $=, Value/binary>>, append_params(URI, Tail, Bin2); append_params(URI, [Name | Tail], Bin) -> NameBin = sip_syntax:format_name(Name), Bin2 = <<Bin/binary, $;, NameBin/binary>>, append_params(URI, Tail, Bin2); append_params(URI, [], Bin) -> append_headers(URI#sip_uri.headers, $?, Bin). append_headers([], _Sep, Bin) -> Bin; append_headers([{Name, Value} | Tail], Sep, Bin) -> NameBin = sip_syntax:format_name(Name), Bin2 = <<Bin/binary, Sep, NameBin/binary, $=, Value/binary>>, append_headers(Tail, $&, Bin2). -ifdef(TEST). -spec parse_test_() -> list(). parse_test_() -> [ ?_assertEqual(#sip_uri{scheme = sip, user = <<"alice">>, host = "atlanta.com"}, parse(<<"sip:">>)), ?_assertEqual(#sip_uri{scheme = sip, user = <<"alice">>, password = <<"secretword">>, host = "atlanta.com", params = [{transport, <<"tcp">>}]}, parse(<<"sip:alice:;transport=tcp">>)), ?_assertEqual(#sip_uri{scheme = sips, user = <<"alice">>, host = "atlanta.com", headers = [{subject, <<"project%20x">>}, {priority, <<"urgent">>}]}, parse(<<"sips:?subject=project%20x&priority=urgent">>)), ?_assertEqual(#sip_uri{scheme = sip, user = <<"+1-212-555-1212">>, password = <<"1234">>, host = "gateway.com", params = [{user, <<"phone">>}]}, parse(<<"sip:+1-212-555-1212:;user=phone">>)), ?_assertEqual(#sip_uri{scheme = sips, user = <<"1212">>, host = "gateway.com"}, parse(<<"sips:">>)), ?_assertEqual(#sip_uri{scheme = sip, user = <<"alice">>, host = {192, 0, 2, 4}}, parse(<<"sip:alice@192.0.2.4">>)), ?_assertEqual(#sip_uri{scheme = sip, host = "atlanta.com", params = [{method, <<"REGISTER">>}], headers = [{to, <<"alice%40atlanta.com">>}]}, parse(<<"sip:atlanta.com;method=REGISTER?to=alice%40atlanta.com">>)), ?_assertEqual(#sip_uri{scheme = sip, user = <<"alice;day=tuesday">>, host = "atlanta.com"}, parse(<<"sip:alice;day=">>)), ?_assertEqual(#sip_uri{scheme = sips, user = <<"alice">>, host = "atlanta.com", params = [{maddr, <<"239.255.255.1">>}, {ttl, <<"15">>}]}, parse(<<"sips:;maddr=239.255.255.1;ttl=15">>)), ?_assertEqual(#sip_uri{scheme = sip, user = <<"j%40s0n">>, host = "atlanta.com"}, parse(<<"sip:j%">>)), ?_assertEqual(#sip_uri{scheme = sip, user = <<"alice">>, host = {8193,3512,0,0,0,0,44577,44306}, port = 5060}, parse(<<"sip:alice@[2001:0db8:0000:0000:0000:0000:ae21:ad12]:5060">>)) ]. -spec format_test_() -> list(). format_test_() -> [ ?_assertEqual(<<"sip:">>, format(#sip_uri{scheme = sip, user = <<"alice">>, host = "atlanta.com"})), ?_assertEqual(<<"sip:alice:;transport=tcp">>, format(#sip_uri{scheme = sip, user = <<"alice">>, password = <<"secretword">>, host = "atlanta.com", params = [{transport, <<"tcp">>}]})), ?_assertEqual(<<"sips:?subject=project%20x&priority=urgent">>, format(#sip_uri{scheme = sips, user = <<"alice">>, host = "atlanta.com", headers = [{subject, <<"project%20x">>}, {priority, <<"urgent">>}]})), ?_assertEqual(<<"sip:+1-212-555-1212:;user=phone">>, format(#sip_uri{scheme = sip, user = <<"+1-212-555-1212">>, password = <<"1234">>, host = "gateway.com", params = [{user, <<"phone">>}]})), ?_assertEqual(<<"sips:">>, format(#sip_uri{scheme = sips, user = <<"1212">>, host = "gateway.com"})), ?_assertEqual(<<"sip:alice@192.0.2.4">>, format(#sip_uri{scheme = sip, user = <<"alice">>, host = {192, 0, 2, 4}})), ?_assertEqual(<<"sip:atlanta.com;method=REGISTER?to=alice%40atlanta.com">>, format(#sip_uri{scheme = sip, host = "atlanta.com", params = [{method, <<"REGISTER">>}], headers = [{to, <<"alice%40atlanta.com">>}]})), ?_assertEqual(<<"sip:alice;day=">>, format(#sip_uri{scheme = sip, user = <<"alice;day=tuesday">>, host = "atlanta.com"})), ?_assertEqual(<<"sips:;maddr=239.255.255.1;ttl=15">>, format(#sip_uri{scheme = sips, user = <<"alice">>, host = "atlanta.com", params = [{maddr, <<"239.255.255.1">>}, {ttl, <<"15">>}]})), ?_assertEqual(<<"sip:j%">>, format(#sip_uri{scheme = sip, user = <<"j%40s0n">>, host = "atlanta.com"})), ?_assertEqual(<<"sip:alice@[2001:0db8:0000:0000:0000:0000:ae21:ad12]:5060">>, format(#sip_uri{scheme = sip, user = <<"alice">>, host = {8193,3512,0,0,0,0,44577,44306}, port = 5060})) ]. -spec is_strict_router_test_() -> list(). is_strict_router_test_() -> [?_assertEqual(true, is_strict_router(sip_uri:parse(<<"sip:p3.middle.com">>))), ?_assertEqual(false, is_strict_router(sip_uri:parse(<<"sip:p2.example.com;lr">>))) ]. -endif.
332e1a260496def1e71c2f23324f95d5dc81b65ab5807642cf319e587135b649
ghcjs/jsaddle-dom
JSDOM.hs
# LANGUAGE CPP , OverloadedStrings , PatternSynonyms # #ifndef ghcjs_HOST_OS # LANGUAGE RecursiveDo # #endif module JSDOM ( globalThis , globalThisUnchecked , currentWindow , currentWindowUnchecked , currentDocument , currentDocumentUnchecked , syncPoint , syncAfter , waitForAnimationFrame , nextAnimationFrame , AnimationFrameHandle , inAnimationFrame , inAnimationFrame' , catch , bracket ) where #ifdef ghcjs_HOST_OS import JSDOM.Types (FromJSVal(..), MonadDOM, liftDOM, GlobalThis(..), Document(..), Window(..), JSM) import Language.Javascript.JSaddle.Object (jsg) import JavaScript.Web.AnimationFrame (AnimationFrameHandle, inAnimationFrame) #else import Control.Monad (void, forM_, when) import Control.Monad.IO.Class (MonadIO(..)) import Control.Concurrent.MVar (putMVar, takeMVar) import Language.Javascript.JSaddle.Types (JSContextRef(..)) import Language.Javascript.JSaddle.Object (freeFunction, jsg) import Language.Javascript.JSaddle.Monad (askJSM) import JSDOM.Types (Callback(..), RequestAnimationFrameCallback(..), FromJSVal(..), MonadDOM, liftDOM, GlobalThis(..), Document(..), Window(..), JSM, JSContextRef(..)) import JSDOM.Generated.RequestAnimationFrameCallback (newRequestAnimationFrameCallbackSync) import JSDOM.Generated.Window (requestAnimationFrame) #endif import GHCJS.Concurrent (OnBlocked(..)) import Language.Javascript.JSaddle (syncPoint, syncAfter, waitForAnimationFrame, nextAnimationFrame, catch, bracket) globalThis :: MonadDOM m => m (Maybe GlobalThis) globalThis = liftDOM $ jsg ("globalThis" :: String) >>= fromJSVal globalThisUnchecked :: MonadDOM m => m GlobalThis globalThisUnchecked = liftDOM $ jsg ("globalThis" :: String) >>= fromJSValUnchecked currentWindow :: MonadDOM m => m (Maybe Window) currentWindow = liftDOM $ jsg ("window" :: String) >>= fromJSVal currentWindowUnchecked :: MonadDOM m => m Window currentWindowUnchecked = liftDOM $ jsg ("window" :: String) >>= fromJSValUnchecked currentDocument :: MonadDOM m => m (Maybe Document) currentDocument = liftDOM $ jsg ("document" :: String) >>= fromJSVal currentDocumentUnchecked :: MonadDOM m => m Document currentDocumentUnchecked = liftDOM $ jsg ("document" :: String) >>= fromJSValUnchecked #ifndef ghcjs_HOST_OS data AnimationFrameHandle = AnimationFrameHandle {- | Run the action in an animationframe callback. The action runs in a synchronous thread, and is passed the high-performance clock time stamp for that frame. -} inAnimationFrame :: OnBlocked -- ^ what to do when encountering a blocking call -> (Double -> JSM ()) -- ^ the action to run -> JSM AnimationFrameHandle inAnimationFrame _ f = do handlersMVar <- animationFrameHandlers <$> askJSM -- Take the list of pending animation fram handlers handlers <- liftIO $ takeMVar handlersMVar -- Add this handler to the list to be run by the callback liftIO $ putMVar handlersMVar (f : handlers) If this was the first handler added set up a callback -- to run the handlers in the next animation frame. when (null handlers) $ do win <- currentWindowUnchecked rec cb@(RequestAnimationFrameCallback (Callback fCb)) <- newRequestAnimationFrameCallbackSync $ \t -> do -- This is a one off handler so free it when it runs freeFunction fCb -- Take the list of handers and empty it handlersToRun <- liftIO $ takeMVar handlersMVar liftIO $ putMVar handlersMVar [] Exectute handlers in the order forM_ (reverse handlersToRun) (\handler -> handler t) -- Add the callback function void $ requestAnimationFrame win cb return AnimationFrameHandle #endif | Run the action in an animationframe callback . The action runs in a synchronous thread , and is passed the high - performance clock time stamp for that frame . On GHCJS this version will continue asynchronously if it is not possible to complete the callback synchronously . Run the action in an animationframe callback. The action runs in a synchronous thread, and is passed the high-performance clock time stamp for that frame. On GHCJS this version will continue asynchronously if it is not possible to complete the callback synchronously. -} inAnimationFrame' :: (Double -> JSM ()) -- ^ the action to run -> JSM AnimationFrameHandle inAnimationFrame' = inAnimationFrame ContinueAsync
null
https://raw.githubusercontent.com/ghcjs/jsaddle-dom/fa40dd223c3128e7f2560e4f49486ca1673b78f6/src/JSDOM.hs
haskell
| Run the action in an animationframe callback. The action runs in a synchronous thread, and is passed the high-performance clock time stamp for that frame. ^ what to do when encountering a blocking call ^ the action to run Take the list of pending animation fram handlers Add this handler to the list to be run by the callback to run the handlers in the next animation frame. This is a one off handler so free it when it runs Take the list of handers and empty it Add the callback function ^ the action to run
# LANGUAGE CPP , OverloadedStrings , PatternSynonyms # #ifndef ghcjs_HOST_OS # LANGUAGE RecursiveDo # #endif module JSDOM ( globalThis , globalThisUnchecked , currentWindow , currentWindowUnchecked , currentDocument , currentDocumentUnchecked , syncPoint , syncAfter , waitForAnimationFrame , nextAnimationFrame , AnimationFrameHandle , inAnimationFrame , inAnimationFrame' , catch , bracket ) where #ifdef ghcjs_HOST_OS import JSDOM.Types (FromJSVal(..), MonadDOM, liftDOM, GlobalThis(..), Document(..), Window(..), JSM) import Language.Javascript.JSaddle.Object (jsg) import JavaScript.Web.AnimationFrame (AnimationFrameHandle, inAnimationFrame) #else import Control.Monad (void, forM_, when) import Control.Monad.IO.Class (MonadIO(..)) import Control.Concurrent.MVar (putMVar, takeMVar) import Language.Javascript.JSaddle.Types (JSContextRef(..)) import Language.Javascript.JSaddle.Object (freeFunction, jsg) import Language.Javascript.JSaddle.Monad (askJSM) import JSDOM.Types (Callback(..), RequestAnimationFrameCallback(..), FromJSVal(..), MonadDOM, liftDOM, GlobalThis(..), Document(..), Window(..), JSM, JSContextRef(..)) import JSDOM.Generated.RequestAnimationFrameCallback (newRequestAnimationFrameCallbackSync) import JSDOM.Generated.Window (requestAnimationFrame) #endif import GHCJS.Concurrent (OnBlocked(..)) import Language.Javascript.JSaddle (syncPoint, syncAfter, waitForAnimationFrame, nextAnimationFrame, catch, bracket) globalThis :: MonadDOM m => m (Maybe GlobalThis) globalThis = liftDOM $ jsg ("globalThis" :: String) >>= fromJSVal globalThisUnchecked :: MonadDOM m => m GlobalThis globalThisUnchecked = liftDOM $ jsg ("globalThis" :: String) >>= fromJSValUnchecked currentWindow :: MonadDOM m => m (Maybe Window) currentWindow = liftDOM $ jsg ("window" :: String) >>= fromJSVal currentWindowUnchecked :: MonadDOM m => m Window currentWindowUnchecked = liftDOM $ jsg ("window" :: String) >>= fromJSValUnchecked currentDocument :: MonadDOM m => m (Maybe Document) currentDocument = liftDOM $ jsg ("document" :: String) >>= fromJSVal currentDocumentUnchecked :: MonadDOM m => m Document currentDocumentUnchecked = liftDOM $ jsg ("document" :: String) >>= fromJSValUnchecked #ifndef ghcjs_HOST_OS data AnimationFrameHandle = AnimationFrameHandle -> JSM AnimationFrameHandle inAnimationFrame _ f = do handlersMVar <- animationFrameHandlers <$> askJSM handlers <- liftIO $ takeMVar handlersMVar liftIO $ putMVar handlersMVar (f : handlers) If this was the first handler added set up a callback when (null handlers) $ do win <- currentWindowUnchecked rec cb@(RequestAnimationFrameCallback (Callback fCb)) <- newRequestAnimationFrameCallbackSync $ \t -> do freeFunction fCb handlersToRun <- liftIO $ takeMVar handlersMVar liftIO $ putMVar handlersMVar [] Exectute handlers in the order forM_ (reverse handlersToRun) (\handler -> handler t) void $ requestAnimationFrame win cb return AnimationFrameHandle #endif | Run the action in an animationframe callback . The action runs in a synchronous thread , and is passed the high - performance clock time stamp for that frame . On GHCJS this version will continue asynchronously if it is not possible to complete the callback synchronously . Run the action in an animationframe callback. The action runs in a synchronous thread, and is passed the high-performance clock time stamp for that frame. On GHCJS this version will continue asynchronously if it is not possible to complete the callback synchronously. -} -> JSM AnimationFrameHandle inAnimationFrame' = inAnimationFrame ContinueAsync
f7fad70ee4b36df8707dee03931b3568c44e332306e00d94cf89d268af272a7d
NorfairKing/smos
ProjectsSpec.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeApplications # module Smos.Report.ProjectsSpec where import Data.Tree import Smos.Data import Smos.Report.Archive.Gen () import Smos.Report.Filter.Gen () import Smos.Report.Projects import Smos.Report.Projects.Gen () import Test.Syd import Test.Syd.Validity import Test.Syd.Validity.Aeson spec :: Spec spec = do genValidSpec @ProjectsReport jsonSpec @ProjectsReport genValidSpec @ProjectEntry jsonSpec @ProjectEntry describe "getCurrentEntry" $ do it "produces valid entries" $ producesValid getCurrentEntry it "finds nothing in an empty file" $ getCurrentEntry emptySmosFile `shouldBe` Nothing it "finds a STARTING action" $ forAllValid $ \h -> forAllValid $ \time -> do let startedEntry = entryWithState h time "STARTED" getCurrentEntry (makeSmosFile [Node startedEntry []]) `shouldBe` Just startedEntry it "finds the first of two NEXT entries" $ forAllValid $ \header1 -> forAllValid $ \header2 -> forAllValid $ \time1 -> forAllValid $ \time2 -> do let startedEntry = entryWithState header1 time1 "STARTED" nextEntry = entryWithState header2 time2 "NEXT" getCurrentEntry ( makeSmosFile [ Node startedEntry [], Node nextEntry [] ] ) `shouldBe` Just startedEntry it "ignores a TODO entry if there is a NEXT entry" $ forAllValid $ \header1 -> forAllValid $ \header2 -> forAllValid $ \time1 -> forAllValid $ \time2 -> do let todoEntry = entryWithState header1 time1 "TODO" nextEntry = entryWithState header2 time2 "NEXT" getCurrentEntry ( makeSmosFile [ Node todoEntry [], Node nextEntry [] ] ) `shouldBe` Just nextEntry it "ignores DONE, CANCELLED, and FAILED entries if there is a NEXT entry" $ forAllValid $ \header1 -> forAllValid $ \header2 -> forAllValid $ \header3 -> forAllValid $ \header4 -> forAllValid $ \time1 -> forAllValid $ \time2 -> forAllValid $ \time3 -> forAllValid $ \time4 -> do let doneEntry = entryWithState header1 time1 "DONE" cancelledEntry = entryWithState header2 time2 "CANCELLED" failedEntry = entryWithState header3 time3 "FAILED" nextEntry = entryWithState header4 time4 "NEXT" getCurrentEntry ( makeSmosFile [ Node doneEntry [], Node cancelledEntry [], Node failedEntry [], Node nextEntry [] ] ) `shouldBe` Just nextEntry it "finds a NEXT action even under an entry without a state" $ forAllValid $ \h -> forAllValid $ \time -> do let nextEntry = entryWithState h time "NEXT" getCurrentEntry (makeSmosFile [Node (newEntry "foo") [Node nextEntry []]]) `shouldBe` Just nextEntry describe "makeProjectsReport" $ it "produces valid reports" $ producesValid makeProjectsReport pending "produceProjectsreport, which doesn't exist yet, produces valid reports for interesting stores." modifyMaxSuccess ( ` div ` 10 ) $ -- describe "makeProjectsReport" $ -- it "produces valid reports for interesting stores" $ -- forAllValid $ -- \mFilter -> forAllValid $ \ha - > withInterestingStore $ \dc - > do wr < - produceWaitingReport mFilter ha DontPrint dc -- shouldBeValid wr
null
https://raw.githubusercontent.com/NorfairKing/smos/3bb953f467d83aacec1ce1dd59b687c87258559e/smos-report-gen/test/Smos/Report/ProjectsSpec.hs
haskell
# LANGUAGE OverloadedStrings # describe "makeProjectsReport" $ it "produces valid reports for interesting stores" $ forAllValid $ \mFilter -> shouldBeValid wr
# LANGUAGE TypeApplications # module Smos.Report.ProjectsSpec where import Data.Tree import Smos.Data import Smos.Report.Archive.Gen () import Smos.Report.Filter.Gen () import Smos.Report.Projects import Smos.Report.Projects.Gen () import Test.Syd import Test.Syd.Validity import Test.Syd.Validity.Aeson spec :: Spec spec = do genValidSpec @ProjectsReport jsonSpec @ProjectsReport genValidSpec @ProjectEntry jsonSpec @ProjectEntry describe "getCurrentEntry" $ do it "produces valid entries" $ producesValid getCurrentEntry it "finds nothing in an empty file" $ getCurrentEntry emptySmosFile `shouldBe` Nothing it "finds a STARTING action" $ forAllValid $ \h -> forAllValid $ \time -> do let startedEntry = entryWithState h time "STARTED" getCurrentEntry (makeSmosFile [Node startedEntry []]) `shouldBe` Just startedEntry it "finds the first of two NEXT entries" $ forAllValid $ \header1 -> forAllValid $ \header2 -> forAllValid $ \time1 -> forAllValid $ \time2 -> do let startedEntry = entryWithState header1 time1 "STARTED" nextEntry = entryWithState header2 time2 "NEXT" getCurrentEntry ( makeSmosFile [ Node startedEntry [], Node nextEntry [] ] ) `shouldBe` Just startedEntry it "ignores a TODO entry if there is a NEXT entry" $ forAllValid $ \header1 -> forAllValid $ \header2 -> forAllValid $ \time1 -> forAllValid $ \time2 -> do let todoEntry = entryWithState header1 time1 "TODO" nextEntry = entryWithState header2 time2 "NEXT" getCurrentEntry ( makeSmosFile [ Node todoEntry [], Node nextEntry [] ] ) `shouldBe` Just nextEntry it "ignores DONE, CANCELLED, and FAILED entries if there is a NEXT entry" $ forAllValid $ \header1 -> forAllValid $ \header2 -> forAllValid $ \header3 -> forAllValid $ \header4 -> forAllValid $ \time1 -> forAllValid $ \time2 -> forAllValid $ \time3 -> forAllValid $ \time4 -> do let doneEntry = entryWithState header1 time1 "DONE" cancelledEntry = entryWithState header2 time2 "CANCELLED" failedEntry = entryWithState header3 time3 "FAILED" nextEntry = entryWithState header4 time4 "NEXT" getCurrentEntry ( makeSmosFile [ Node doneEntry [], Node cancelledEntry [], Node failedEntry [], Node nextEntry [] ] ) `shouldBe` Just nextEntry it "finds a NEXT action even under an entry without a state" $ forAllValid $ \h -> forAllValid $ \time -> do let nextEntry = entryWithState h time "NEXT" getCurrentEntry (makeSmosFile [Node (newEntry "foo") [Node nextEntry []]]) `shouldBe` Just nextEntry describe "makeProjectsReport" $ it "produces valid reports" $ producesValid makeProjectsReport pending "produceProjectsreport, which doesn't exist yet, produces valid reports for interesting stores." modifyMaxSuccess ( ` div ` 10 ) $ forAllValid $ \ha - > withInterestingStore $ \dc - > do wr < - produceWaitingReport mFilter ha DontPrint dc
c40e1f2dfbee174b656fc2210209bfd93505a6f0e866bfbc3701155b480cbdb9
acowley/GLUtil
Linear.hs
# LANGUAGE CPP , DefaultSignatures , FlexibleInstances , FlexibleContexts , ScopedTypeVariables # ScopedTypeVariables #-} |Support for writing " Linear " types to uniform locations in -- shader programs. module Graphics.GLUtil.Linear (AsUniform(..)) where import Foreign.Marshal.Array (withArray) import Foreign.Marshal.Utils (with) import Foreign.Ptr (Ptr, castPtr) import Graphics.Rendering.OpenGL import Graphics.GL.Core31 import Linear import Unsafe.Coerce (unsafeCoerce) -- | A type class for things we can write to uniform locations in -- shader programs. We can provide instances of this class for types from " Linear " without introducing orphan instances . class AsUniform t where asUniform :: t -> UniformLocation -> IO () default asUniform :: Uniform t => t -> UniformLocation -> IO () asUniform x loc = uniform loc $= x getUL :: UniformLocation -> GLint getUL = unsafeCoerce castVecComponent :: Ptr (t a) -> Ptr a castVecComponent = castPtr castMatComponent :: Ptr (t (f a)) -> Ptr a castMatComponent = castPtr instance AsUniform GLint where x `asUniform` loc = with x $ glUniform1iv (getUL loc) 1 instance AsUniform GLuint where x `asUniform` loc = with x $ glUniform1uiv (getUL loc) 1 instance AsUniform GLfloat where x `asUniform` loc = with x $ glUniform1fv (getUL loc) 1 instance AsUniform TextureUnit where instance UniformComponent a => AsUniform (Index1 a) where instance UniformComponent a => AsUniform (Color4 a) where instance UniformComponent a => AsUniform (Color3 a) where instance UniformComponent a => AsUniform (FogCoord1 a) where instance UniformComponent a => AsUniform (Normal3 a) where instance UniformComponent a => AsUniform (TexCoord4 a) where instance UniformComponent a => AsUniform (TexCoord3 a) where instance UniformComponent a => AsUniform (TexCoord2 a) where instance UniformComponent a => AsUniform (TexCoord1 a) where instance UniformComponent a => AsUniform (Vertex4 a) where instance UniformComponent a => AsUniform (Vertex3 a) where instance UniformComponent a => AsUniform (Vertex2 a) where #define UNIFORMVEC_T(d,ht,glt) instance AsUniform (V ## d ht) where {v `asUniform` loc = with v $ glUniform##d##glt##v (getUL loc) 1 . castVecComponent} #define UNIFORMVEC(d) UNIFORMVEC_T(d,GLint,i); UNIFORMVEC_T(d,GLuint,ui); UNIFORMVEC_T(d,GLfloat,f) UNIFORMVEC(1) UNIFORMVEC(2) UNIFORMVEC(3) UNIFORMVEC(4) instance AsUniform (M22 GLfloat) where m `asUniform` loc = with m $ glUniformMatrix2fv (getUL loc) 1 1 . castMatComponent instance AsUniform (M33 GLfloat) where m `asUniform` loc = with m $ glUniformMatrix3fv (getUL loc) 1 1 . castMatComponent instance AsUniform (M44 GLfloat) where m `asUniform` loc = with m $ glUniformMatrix4fv (getUL loc) 1 1 . castMatComponent -- Support lists of vectors as uniform arrays of vectors. #define UNIFORMARRAY_T(d,ht,glt) instance AsUniform [V##d ht] where {l `asUniform` loc = withArray l $ glUniform##d##glt##v (getUL loc) (fromIntegral $ length l) . castVecComponent} #define UNIFORMARRAY(d) UNIFORMARRAY_T(d,GLint,i); UNIFORMARRAY_T(d,GLuint,ui); UNIFORMARRAY_T(d,GLfloat,f) UNIFORMARRAY(1) UNIFORMARRAY(2) UNIFORMARRAY(3) UNIFORMARRAY(4)
null
https://raw.githubusercontent.com/acowley/GLUtil/09faac00072b08c72ab12bcc57d4ab2a02ff1c88/src/Graphics/GLUtil/Linear.hs
haskell
shader programs. | A type class for things we can write to uniform locations in shader programs. We can provide instances of this class for types Support lists of vectors as uniform arrays of vectors.
# LANGUAGE CPP , DefaultSignatures , FlexibleInstances , FlexibleContexts , ScopedTypeVariables # ScopedTypeVariables #-} |Support for writing " Linear " types to uniform locations in module Graphics.GLUtil.Linear (AsUniform(..)) where import Foreign.Marshal.Array (withArray) import Foreign.Marshal.Utils (with) import Foreign.Ptr (Ptr, castPtr) import Graphics.Rendering.OpenGL import Graphics.GL.Core31 import Linear import Unsafe.Coerce (unsafeCoerce) from " Linear " without introducing orphan instances . class AsUniform t where asUniform :: t -> UniformLocation -> IO () default asUniform :: Uniform t => t -> UniformLocation -> IO () asUniform x loc = uniform loc $= x getUL :: UniformLocation -> GLint getUL = unsafeCoerce castVecComponent :: Ptr (t a) -> Ptr a castVecComponent = castPtr castMatComponent :: Ptr (t (f a)) -> Ptr a castMatComponent = castPtr instance AsUniform GLint where x `asUniform` loc = with x $ glUniform1iv (getUL loc) 1 instance AsUniform GLuint where x `asUniform` loc = with x $ glUniform1uiv (getUL loc) 1 instance AsUniform GLfloat where x `asUniform` loc = with x $ glUniform1fv (getUL loc) 1 instance AsUniform TextureUnit where instance UniformComponent a => AsUniform (Index1 a) where instance UniformComponent a => AsUniform (Color4 a) where instance UniformComponent a => AsUniform (Color3 a) where instance UniformComponent a => AsUniform (FogCoord1 a) where instance UniformComponent a => AsUniform (Normal3 a) where instance UniformComponent a => AsUniform (TexCoord4 a) where instance UniformComponent a => AsUniform (TexCoord3 a) where instance UniformComponent a => AsUniform (TexCoord2 a) where instance UniformComponent a => AsUniform (TexCoord1 a) where instance UniformComponent a => AsUniform (Vertex4 a) where instance UniformComponent a => AsUniform (Vertex3 a) where instance UniformComponent a => AsUniform (Vertex2 a) where #define UNIFORMVEC_T(d,ht,glt) instance AsUniform (V ## d ht) where {v `asUniform` loc = with v $ glUniform##d##glt##v (getUL loc) 1 . castVecComponent} #define UNIFORMVEC(d) UNIFORMVEC_T(d,GLint,i); UNIFORMVEC_T(d,GLuint,ui); UNIFORMVEC_T(d,GLfloat,f) UNIFORMVEC(1) UNIFORMVEC(2) UNIFORMVEC(3) UNIFORMVEC(4) instance AsUniform (M22 GLfloat) where m `asUniform` loc = with m $ glUniformMatrix2fv (getUL loc) 1 1 . castMatComponent instance AsUniform (M33 GLfloat) where m `asUniform` loc = with m $ glUniformMatrix3fv (getUL loc) 1 1 . castMatComponent instance AsUniform (M44 GLfloat) where m `asUniform` loc = with m $ glUniformMatrix4fv (getUL loc) 1 1 . castMatComponent #define UNIFORMARRAY_T(d,ht,glt) instance AsUniform [V##d ht] where {l `asUniform` loc = withArray l $ glUniform##d##glt##v (getUL loc) (fromIntegral $ length l) . castVecComponent} #define UNIFORMARRAY(d) UNIFORMARRAY_T(d,GLint,i); UNIFORMARRAY_T(d,GLuint,ui); UNIFORMARRAY_T(d,GLfloat,f) UNIFORMARRAY(1) UNIFORMARRAY(2) UNIFORMARRAY(3) UNIFORMARRAY(4)
bbb179b157cefaf3e0f9b47a9ca6b6b2dc38676ef72f25f9e3267a792452d1b8
heechul/crest-z3
rmtmps.ml
* * Copyright ( c ) 2001 - 2002 , * < > * < > * < > * < > * All rights reserved . * * Redistribution and use in source and binary forms , with or without * modification , are permitted provided that the following conditions are * met : * * 1 . Redistributions of source code must retain the above copyright * notice , this list of conditions and the following disclaimer . * * 2 . Redistributions in binary form must reproduce the above copyright * notice , this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution . * * 3 . The names of the contributors may not 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 OWNER * OR 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 . * * * Copyright (c) 2001-2002, * George C. Necula <> * Scott McPeak <> * Wes Weimer <> * Ben Liblit <> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The names of the contributors may not 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 OWNER * 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. * *) (* rmtmps.ml *) (* implementation for rmtmps.mli *) open Pretty open Cil module H = Hashtbl module E = Errormsg module U = Util (* Set on the command-line: *) let keepUnused = ref false let rmUnusedInlines = ref false let trace = Trace.trace "rmtmps" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Clearing of " referenced " bits * * * Clearing of "referenced" bits * *) let clearReferencedBits file = let considerGlobal global = match global with | GType (info, _) -> trace (dprintf "clearing mark: %a\n" d_shortglobal global); info.treferenced <- false | GEnumTag (info, _) | GEnumTagDecl (info, _) -> trace (dprintf "clearing mark: %a\n" d_shortglobal global); info.ereferenced <- false | GCompTag (info, _) | GCompTagDecl (info, _) -> trace (dprintf "clearing mark: %a\n" d_shortglobal global); info.creferenced <- false | GVar ({vname = name} as info, _, _) | GVarDecl ({vname = name} as info, _) -> trace (dprintf "clearing mark: %a\n" d_shortglobal global); info.vreferenced <- false | GFun ({svar = info} as func, _) -> trace (dprintf "clearing mark: %a\n" d_shortglobal global); info.vreferenced <- false; let clearMark local = trace (dprintf "clearing mark: local %s\n" local.vname); local.vreferenced <- false in List.iter clearMark func.slocals | _ -> () in iterGlobals file considerGlobal (*********************************************************************** * * Scanning and categorization of pragmas * *) (* collections of names of things to keep *) type collection = (string, unit) H.t type keepers = { typedefs : collection; enums : collection; structs : collection; unions : collection; defines : collection; } (* rapid transfer of control when we find a malformed pragma *) exception Bad_pragma let ccureddeepcopystring = "ccureddeepcopy" (* Save this length so we don't recompute it each time. *) let ccureddeepcopystring_length = String.length ccureddeepcopystring (* CIL and CCured define several pragmas which prevent removal of * various global symbols. Here we scan for those pragmas and build * up collections of the corresponding symbols' names. *) let categorizePragmas file = (* names of things which should be retained *) let keepers = { typedefs = H.create 0; enums = H.create 0; structs = H.create 0; unions = H.create 0; defines = H.create 1 } in (* populate these name collections in light of each pragma *) let considerPragma = let badPragma location pragma = ignore (warnLoc location "Invalid argument to pragma %s" pragma) in function | GPragma (Attr ("cilnoremove" as directive, args), location) -> (* a very flexible pragma: can retain typedefs, enums, * structs, unions, or globals (functions or variables) *) begin let processArg arg = try match arg with | AStr specifier -> isolate and categorize one symbol name let collection, name = Two words denotes a typedef , enum , struct , or * union , as in " type foo " or " enum bar " . A * single word denotes a global function or * variable . * union, as in "type foo" or "enum bar". A * single word denotes a global function or * variable. *) let whitespace = Str.regexp "[ \t]+" in let words = Str.split whitespace specifier in match words with | ["type"; name] -> keepers.typedefs, name | ["enum"; name] -> keepers.enums, name | ["struct"; name] -> keepers.structs, name | ["union"; name] -> keepers.unions, name | [name] -> keepers.defines, name | _ -> raise Bad_pragma in H.add collection name () | _ -> raise Bad_pragma with Bad_pragma -> badPragma location directive in List.iter processArg args end | GVarDecl (v, _) -> begin (* Look for alias attributes, e.g. Linux modules *) match filterAttributes "alias" v.vattr with [] -> () (* ordinary prototype. *) | [Attr("alias", [AStr othername])] -> H.add keepers.defines othername () | _ -> E.s (error "Bad alias attribute at %a" d_loc !currentLoc) end (*** Begin CCured-specific checks: ***) these pragmas indirectly require that we keep the function named in -- the first arguments of boxmodelof and ccuredwrapperof , and -- the third argument of ccureddeepcopy * . -- the first arguments of boxmodelof and ccuredwrapperof, and -- the third argument of ccureddeepcopy*. *) | GPragma (Attr("ccuredwrapper" as directive, attribute :: _), location) -> begin match attribute with | AStr name -> H.add keepers.defines name () | _ -> badPragma location directive end | GPragma (Attr("ccuredvararg", funcname :: (ASizeOf t) :: _), location) -> begin match t with | TComp(c,_) when c.cstruct -> (* struct *) H.add keepers.structs c.cname () | TComp(c,_) -> (* union *) H.add keepers.unions c.cname () | TNamed(ti,_) -> H.add keepers.typedefs ti.tname () | TEnum(ei, _) -> H.add keepers.enums ei.ename () | _ -> () end | GPragma (Attr(directive, _ :: _ :: attribute :: _), location) when String.length directive > ccureddeepcopystring_length && (Str.first_chars directive ccureddeepcopystring_length) = ccureddeepcopystring -> begin match attribute with | AStr name -> H.add keepers.defines name () | _ -> badPragma location directive end (** end CCured-specific stuff **) | _ -> () in iterGlobals file considerPragma; keepers (*********************************************************************** * * Function body elimination from pragmas * *) When performing global slicing , any functions not explicitly marked * as pragma roots are reduced to mere declarations . This leaves one * with a reduced source file that still compiles to object code , but * which contains the bodies of only explicitly retained functions . * as pragma roots are reduced to mere declarations. This leaves one * with a reduced source file that still compiles to object code, but * which contains the bodies of only explicitly retained functions. *) let amputateFunctionBodies keptGlobals file = let considerGlobal = function | GFun ({svar = {vname = name} as info}, location) when not (H.mem keptGlobals name) -> trace (dprintf "slicing: reducing to prototype: function %s\n" name); GVarDecl (info, location) | other -> other in mapGlobals file considerGlobal (*********************************************************************** * * Root collection from pragmas * *) let isPragmaRoot keepers = function | GType ({tname = name}, _) -> H.mem keepers.typedefs name | GEnumTag ({ename = name}, _) | GEnumTagDecl ({ename = name}, _) -> H.mem keepers.enums name | GCompTag ({cname = name; cstruct = structure}, _) | GCompTagDecl ({cname = name; cstruct = structure}, _) -> let collection = if structure then keepers.structs else keepers.unions in H.mem collection name | GVar ({vname = name; vattr = attrs}, _, _) | GVarDecl ({vname = name; vattr = attrs}, _) | GFun ({svar = {vname = name; vattr = attrs}}, _) -> H.mem keepers.defines name || hasAttribute "used" attrs | _ -> false (*********************************************************************** * * Common root collecting utilities * *) let traceRoot reason global = trace (dprintf "root (%s): %a@!" reason d_shortglobal global); true let traceNonRoot reason global = trace (dprintf "non-root (%s): %a@!" reason d_shortglobal global); false let hasExportingAttribute funvar = let rec isExportingAttribute = function | Attr ("constructor", []) -> true | Attr ("destructor", []) -> true | _ -> false in List.exists isExportingAttribute funvar.vattr (*********************************************************************** * * Root collection from external linkage * *) Exported roots are those global symbols which are visible to the * linker and dynamic loader . For variables , this consists of * anything that is not " static " . For functions , this consists of : * * - functions bearing a " constructor " or " destructor " attribute * - functions declared extern but not inline * - functions declared neither inline nor static * * gcc incorrectly ( according to C99 ) makes inline functions visible to * the linker . So we can only remove inline functions on MSVC . * linker and dynamic loader. For variables, this consists of * anything that is not "static". For functions, this consists of: * * - functions bearing a "constructor" or "destructor" attribute * - functions declared extern but not inline * - functions declared neither inline nor static * * gcc incorrectly (according to C99) makes inline functions visible to * the linker. So we can only remove inline functions on MSVC. *) let isExportedRoot global = let result, reason = match global with | GVar ({vstorage = Static}, _, _) -> false, "static variable" | GVar _ -> true, "non-static variable" | GFun ({svar = v}, _) -> begin if hasExportingAttribute v then true, "constructor or destructor function" else if v.vstorage = Static then false, "static function" else if v.vinline && v.vstorage != Extern && (!msvcMode || !rmUnusedInlines) then false, "inline function" else true, "other function" end | GVarDecl(v,_) when hasAttribute "alias" v.vattr -> true, "has GCC alias attribute" | _ -> false, "neither function nor variable" in trace (dprintf "isExportedRoot %a -> %b, %s@!" d_shortglobal global result reason); result (*********************************************************************** * * Root collection for complete programs * *) (* Exported roots are "main()" and functions bearing a "constructor" * or "destructor" attribute. These are the only things which must be * retained in a complete program. *) let isCompleteProgramRoot global = let result = match global with | GFun ({svar = {vname = "main"; vstorage = vstorage}}, _) -> vstorage <> Static | GFun (fundec, _) when hasExportingAttribute fundec.svar -> true | _ -> false in trace (dprintf "complete program root -> %b for %a@!" result d_shortglobal global); result (*********************************************************************** * * Transitive reachability closure from roots * *) (* This visitor recursively marks all reachable types and variables as used. *) class markReachableVisitor ((globalMap: (string, Cil.global) H.t), (currentFunc: fundec option ref)) = object (self) inherit nopCilVisitor method vglob = function | GType (typeinfo, _) -> typeinfo.treferenced <- true; DoChildren | GCompTag (compinfo, _) | GCompTagDecl (compinfo, _) -> compinfo.creferenced <- true; DoChildren | GEnumTag (enuminfo, _) | GEnumTagDecl (enuminfo, _) -> enuminfo.ereferenced <- true; DoChildren | GVar (varinfo, _, _) | GVarDecl (varinfo, _) | GFun ({svar = varinfo}, _) -> varinfo.vreferenced <- true; DoChildren | _ -> SkipChildren method vinst = function Asm (_, tmpls, _, _, _, _) when !msvcMode -> If we have inline assembly on MSVC , we can not tell which locals * are referenced . Keep thsem all * are referenced. Keep thsem all *) (match !currentFunc with Some fd -> List.iter (fun v -> let vre = Str.regexp_string (Str.quote v.vname) in if List.exists (fun tmp -> try ignore (Str.search_forward vre tmp 0); true with Not_found -> false) tmpls then v.vreferenced <- true) fd.slocals | _ -> assert false); DoChildren | _ -> DoChildren method vvrbl v = if not v.vreferenced then begin let name = v.vname in if v.vglob then trace (dprintf "marking transitive use: global %s\n" name) else trace (dprintf "marking transitive use: local %s\n" name); (* If this is a global, we need to keep everything used in its * definition and declarations. *) if v.vglob then begin trace (dprintf "descending: global %s\n" name); let descend global = ignore (visitCilGlobal (self :> cilVisitor) global) in let globals = Hashtbl.find_all globalMap name in List.iter descend globals end else v.vreferenced <- true; end; SkipChildren method vexpr (e: exp) = match e with Const (CEnum (_, _, ei)) -> ei.ereferenced <- true; DoChildren | _ -> DoChildren method vtype typ = let old : bool = let visitAttrs attrs = ignore (visitCilAttributes (self :> cilVisitor) attrs) in let visitType typ = ignore (visitCilType (self :> cilVisitor) typ) in match typ with | TEnum(e, attrs) -> let old = e.ereferenced in if not old then begin trace (dprintf "marking transitive use: enum %s\n" e.ename); e.ereferenced <- true; visitAttrs attrs; visitAttrs e.eattr end; old | TComp(c, attrs) -> let old = c.creferenced in if not old then begin trace (dprintf "marking transitive use: compound %s\n" c.cname); c.creferenced <- true; (* to recurse, we must ask explicitly *) let recurse f = visitType f.ftype in List.iter recurse c.cfields; visitAttrs attrs; visitAttrs c.cattr end; old | TNamed(ti, attrs) -> let old = ti.treferenced in if not old then begin trace (dprintf "marking transitive use: typedef %s\n" ti.tname); ti.treferenced <- true; (* recurse deeper into the type referred-to by the typedef *) (* to recurse, we must ask explicitly *) visitType ti.ttype; visitAttrs attrs end; old | _ -> (* for anything else, just look inside it *) false in if old then SkipChildren else DoChildren end let markReachable file isRoot = (* build a mapping from global names back to their definitions & * declarations *) let globalMap = Hashtbl.create 137 in let considerGlobal global = match global with | GFun ({svar = info}, _) | GVar (info, _, _) | GVarDecl (info, _) -> Hashtbl.add globalMap info.vname global | _ -> () in iterGlobals file considerGlobal; let currentFunc = ref None in (* mark everything reachable from the global roots *) let visitor = new markReachableVisitor (globalMap, currentFunc) in let visitIfRoot global = if isRoot global then begin trace (dprintf "traversing root global: %a\n" d_shortglobal global); (match global with GFun(fd, _) -> currentFunc := Some fd | _ -> currentFunc := None); ignore (visitCilGlobal visitor global) end else trace (dprintf "skipping non-root global: %a\n" d_shortglobal global) in iterGlobals file visitIfRoot (********************************************************************** * * Marking and removing of unused labels * **********************************************************************) We keep only one label , preferably one that was not introduced by CIL . * Scan a list of labels and return the data for the label that should be * kept , and the remaining filtered list of labels * Scan a list of labels and return the data for the label that should be * kept, and the remaining filtered list of labels *) let labelsToKeep (ll: label list) : (string * location * bool) * label list = let rec loop (sofar: string * location * bool) = function [] -> sofar, [] | l :: rest -> let newlabel, keepl = match l with | Case _ | Default _ -> sofar, true | Label (ln, lloc, isorig) -> begin match isorig, sofar with | false, ("", _, _) -> (* keep this one only if we have no label so far *) (ln, lloc, isorig), false | false, _ -> sofar, false | true, (_, _, false) -> (* this is an original label; prefer it to temporary or * missing labels *) (ln, lloc, isorig), false | true, _ -> sofar, false end in let newlabel', rest' = loop newlabel rest in newlabel', (if keepl then l :: rest' else rest') in loop ("", locUnknown, false) ll class markUsedLabels (labelMap: (string, unit) H.t) = object inherit nopCilVisitor method vstmt (s: stmt) = match s.skind with Goto (dest, _) -> let (ln, _, _), _ = labelsToKeep !dest.labels in if ln = "" then E.s (E.bug "rmtmps: destination of statement does not have labels"); (* Mark it as used *) H.replace labelMap ln (); DoChildren | _ -> DoChildren (* No need to go into expressions or instructions *) method vexpr _ = SkipChildren method vinst _ = SkipChildren method vtype _ = SkipChildren end class removeUnusedLabels (labelMap: (string, unit) H.t) = object inherit nopCilVisitor method vstmt (s: stmt) = let (ln, lloc, lorig), lrest = labelsToKeep s.labels in s.labels <- (if ln <> "" && H.mem labelMap ln then (* We had labels *) (Label(ln, lloc, lorig) :: lrest) else lrest); DoChildren (* No need to go into expressions or instructions *) method vexpr _ = SkipChildren method vinst _ = SkipChildren method vtype _ = SkipChildren end (*********************************************************************** * * Removal of unused symbols * *) (* regular expression matching names of uninteresting locals *) let uninteresting = let names = [ Cil.makeTempVar "__cil_tmp"; (* sm: I don't know where it comes from but these show up all over. *) (* this doesn't seem to do what I wanted.. *) "iter"; (* various macros in glibc's <bits/string2.h> *) "__result"; "__s"; "__s1"; "__s2"; "__s1_len"; "__s2_len"; "__retval"; "__len"; (* various macros in glibc's <ctype.h> *) "__c"; "__res"; (* We remove the __malloc variables *) ] in (* optional alpha renaming *) let alpha = "\\(___[0-9]+\\)?" in let pattern = "\\(" ^ (String.concat "\\|" names) ^ "\\)" ^ alpha ^ "$" in Str.regexp pattern let removeUnmarked file = let removedLocals = ref [] in let filterGlobal global = match global with (* unused global types, variables, and functions are simply removed *) | GType ({treferenced = false}, _) | GCompTag ({creferenced = false}, _) | GCompTagDecl ({creferenced = false}, _) | GEnumTag ({ereferenced = false}, _) | GEnumTagDecl ({ereferenced = false}, _) | GVar ({vreferenced = false}, _, _) | GVarDecl ({vreferenced = false}, _) | GFun ({svar = {vreferenced = false}}, _) -> trace (dprintf "removing global: %a\n" d_shortglobal global); false (* retained functions may wish to discard some unused locals *) | GFun (func, _) -> let rec filterLocal local = if not local.vreferenced then begin (* along the way, record the interesting locals that were removed *) let name = local.vname in trace (dprintf "removing local: %s\n" name); if not (Str.string_match uninteresting name 0) then removedLocals := (func.svar.vname ^ "::" ^ name) :: !removedLocals; end; local.vreferenced in func.slocals <- List.filter filterLocal func.slocals; (* We also want to remove unused labels. We do it all here, including * marking the used labels *) let usedLabels:(string, unit) H.t = H.create 13 in ignore (visitCilBlock (new markUsedLabels usedLabels) func.sbody); (* And now we scan again and we remove them *) ignore (visitCilBlock (new removeUnusedLabels usedLabels) func.sbody); true (* all other globals are retained *) | _ -> trace (dprintf "keeping global: %a\n" d_shortglobal global); true in file.globals <- List.filter filterGlobal file.globals; !removedLocals (*********************************************************************** * * Exported interface * *) type rootsFilter = global -> bool let isDefaultRoot = isExportedRoot let rec removeUnusedTemps ?(isRoot : rootsFilter = isDefaultRoot) file = if !keepUnused || Trace.traceActive "disableTmpRemoval" then Trace.trace "disableTmpRemoval" (dprintf "temp removal disabled\n") else begin if !E.verboseFlag then ignore (E.log "Removing unused temporaries\n" ); if Trace.traceActive "printCilTree" then dumpFile defaultCilPrinter stdout "stdout" file; (* digest any pragmas that would create additional roots *) let keepers = categorizePragmas file in (* if slicing, remove the bodies of non-kept functions *) if !Cilutil.sliceGlobal then amputateFunctionBodies keepers.defines file; (* build up the root set *) let isRoot global = isPragmaRoot keepers global || isRoot global in (* mark everything reachable from the global roots *) clearReferencedBits file; markReachable file isRoot; (* take out the trash *) let removedLocals = removeUnmarked file in (* print which original source variables were removed *) if false && removedLocals != [] then let count = List.length removedLocals in if count > 2000 then ignore (E.warn "%d unused local variables removed" count) else ignore (E.warn "%d unused local variables removed:@!%a" count (docList ~sep:(chr ',' ++ break) text) removedLocals) end
null
https://raw.githubusercontent.com/heechul/crest-z3/cfcebadddb5e9d69e9956644fc37b46f6c2a21a0/cil/src/rmtmps.ml
ocaml
rmtmps.ml implementation for rmtmps.mli Set on the command-line: ********************************************************************** * * Scanning and categorization of pragmas * collections of names of things to keep rapid transfer of control when we find a malformed pragma Save this length so we don't recompute it each time. CIL and CCured define several pragmas which prevent removal of * various global symbols. Here we scan for those pragmas and build * up collections of the corresponding symbols' names. names of things which should be retained populate these name collections in light of each pragma a very flexible pragma: can retain typedefs, enums, * structs, unions, or globals (functions or variables) Look for alias attributes, e.g. Linux modules ordinary prototype. ** Begin CCured-specific checks: ** struct union * end CCured-specific stuff * ********************************************************************** * * Function body elimination from pragmas * ********************************************************************** * * Root collection from pragmas * ********************************************************************** * * Common root collecting utilities * ********************************************************************** * * Root collection from external linkage * ********************************************************************** * * Root collection for complete programs * Exported roots are "main()" and functions bearing a "constructor" * or "destructor" attribute. These are the only things which must be * retained in a complete program. ********************************************************************** * * Transitive reachability closure from roots * This visitor recursively marks all reachable types and variables as used. If this is a global, we need to keep everything used in its * definition and declarations. to recurse, we must ask explicitly recurse deeper into the type referred-to by the typedef to recurse, we must ask explicitly for anything else, just look inside it build a mapping from global names back to their definitions & * declarations mark everything reachable from the global roots ********************************************************************* * * Marking and removing of unused labels * ********************************************************************* keep this one only if we have no label so far this is an original label; prefer it to temporary or * missing labels Mark it as used No need to go into expressions or instructions We had labels No need to go into expressions or instructions ********************************************************************** * * Removal of unused symbols * regular expression matching names of uninteresting locals sm: I don't know where it comes from but these show up all over. this doesn't seem to do what I wanted.. various macros in glibc's <bits/string2.h> various macros in glibc's <ctype.h> We remove the __malloc variables optional alpha renaming unused global types, variables, and functions are simply removed retained functions may wish to discard some unused locals along the way, record the interesting locals that were removed We also want to remove unused labels. We do it all here, including * marking the used labels And now we scan again and we remove them all other globals are retained ********************************************************************** * * Exported interface * digest any pragmas that would create additional roots if slicing, remove the bodies of non-kept functions build up the root set mark everything reachable from the global roots take out the trash print which original source variables were removed
* * Copyright ( c ) 2001 - 2002 , * < > * < > * < > * < > * All rights reserved . * * Redistribution and use in source and binary forms , with or without * modification , are permitted provided that the following conditions are * met : * * 1 . Redistributions of source code must retain the above copyright * notice , this list of conditions and the following disclaimer . * * 2 . Redistributions in binary form must reproduce the above copyright * notice , this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution . * * 3 . The names of the contributors may not 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 OWNER * OR 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 . * * * Copyright (c) 2001-2002, * George C. Necula <> * Scott McPeak <> * Wes Weimer <> * Ben Liblit <> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The names of the contributors may not 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 OWNER * 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. * *) open Pretty open Cil module H = Hashtbl module E = Errormsg module U = Util let keepUnused = ref false let rmUnusedInlines = ref false let trace = Trace.trace "rmtmps" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Clearing of " referenced " bits * * * Clearing of "referenced" bits * *) let clearReferencedBits file = let considerGlobal global = match global with | GType (info, _) -> trace (dprintf "clearing mark: %a\n" d_shortglobal global); info.treferenced <- false | GEnumTag (info, _) | GEnumTagDecl (info, _) -> trace (dprintf "clearing mark: %a\n" d_shortglobal global); info.ereferenced <- false | GCompTag (info, _) | GCompTagDecl (info, _) -> trace (dprintf "clearing mark: %a\n" d_shortglobal global); info.creferenced <- false | GVar ({vname = name} as info, _, _) | GVarDecl ({vname = name} as info, _) -> trace (dprintf "clearing mark: %a\n" d_shortglobal global); info.vreferenced <- false | GFun ({svar = info} as func, _) -> trace (dprintf "clearing mark: %a\n" d_shortglobal global); info.vreferenced <- false; let clearMark local = trace (dprintf "clearing mark: local %s\n" local.vname); local.vreferenced <- false in List.iter clearMark func.slocals | _ -> () in iterGlobals file considerGlobal type collection = (string, unit) H.t type keepers = { typedefs : collection; enums : collection; structs : collection; unions : collection; defines : collection; } exception Bad_pragma let ccureddeepcopystring = "ccureddeepcopy" let ccureddeepcopystring_length = String.length ccureddeepcopystring let categorizePragmas file = let keepers = { typedefs = H.create 0; enums = H.create 0; structs = H.create 0; unions = H.create 0; defines = H.create 1 } in let considerPragma = let badPragma location pragma = ignore (warnLoc location "Invalid argument to pragma %s" pragma) in function | GPragma (Attr ("cilnoremove" as directive, args), location) -> begin let processArg arg = try match arg with | AStr specifier -> isolate and categorize one symbol name let collection, name = Two words denotes a typedef , enum , struct , or * union , as in " type foo " or " enum bar " . A * single word denotes a global function or * variable . * union, as in "type foo" or "enum bar". A * single word denotes a global function or * variable. *) let whitespace = Str.regexp "[ \t]+" in let words = Str.split whitespace specifier in match words with | ["type"; name] -> keepers.typedefs, name | ["enum"; name] -> keepers.enums, name | ["struct"; name] -> keepers.structs, name | ["union"; name] -> keepers.unions, name | [name] -> keepers.defines, name | _ -> raise Bad_pragma in H.add collection name () | _ -> raise Bad_pragma with Bad_pragma -> badPragma location directive in List.iter processArg args end | GVarDecl (v, _) -> begin match filterAttributes "alias" v.vattr with | [Attr("alias", [AStr othername])] -> H.add keepers.defines othername () | _ -> E.s (error "Bad alias attribute at %a" d_loc !currentLoc) end these pragmas indirectly require that we keep the function named in -- the first arguments of boxmodelof and ccuredwrapperof , and -- the third argument of ccureddeepcopy * . -- the first arguments of boxmodelof and ccuredwrapperof, and -- the third argument of ccureddeepcopy*. *) | GPragma (Attr("ccuredwrapper" as directive, attribute :: _), location) -> begin match attribute with | AStr name -> H.add keepers.defines name () | _ -> badPragma location directive end | GPragma (Attr("ccuredvararg", funcname :: (ASizeOf t) :: _), location) -> begin match t with H.add keepers.structs c.cname () H.add keepers.unions c.cname () | TNamed(ti,_) -> H.add keepers.typedefs ti.tname () | TEnum(ei, _) -> H.add keepers.enums ei.ename () | _ -> () end | GPragma (Attr(directive, _ :: _ :: attribute :: _), location) when String.length directive > ccureddeepcopystring_length && (Str.first_chars directive ccureddeepcopystring_length) = ccureddeepcopystring -> begin match attribute with | AStr name -> H.add keepers.defines name () | _ -> badPragma location directive end | _ -> () in iterGlobals file considerPragma; keepers When performing global slicing , any functions not explicitly marked * as pragma roots are reduced to mere declarations . This leaves one * with a reduced source file that still compiles to object code , but * which contains the bodies of only explicitly retained functions . * as pragma roots are reduced to mere declarations. This leaves one * with a reduced source file that still compiles to object code, but * which contains the bodies of only explicitly retained functions. *) let amputateFunctionBodies keptGlobals file = let considerGlobal = function | GFun ({svar = {vname = name} as info}, location) when not (H.mem keptGlobals name) -> trace (dprintf "slicing: reducing to prototype: function %s\n" name); GVarDecl (info, location) | other -> other in mapGlobals file considerGlobal let isPragmaRoot keepers = function | GType ({tname = name}, _) -> H.mem keepers.typedefs name | GEnumTag ({ename = name}, _) | GEnumTagDecl ({ename = name}, _) -> H.mem keepers.enums name | GCompTag ({cname = name; cstruct = structure}, _) | GCompTagDecl ({cname = name; cstruct = structure}, _) -> let collection = if structure then keepers.structs else keepers.unions in H.mem collection name | GVar ({vname = name; vattr = attrs}, _, _) | GVarDecl ({vname = name; vattr = attrs}, _) | GFun ({svar = {vname = name; vattr = attrs}}, _) -> H.mem keepers.defines name || hasAttribute "used" attrs | _ -> false let traceRoot reason global = trace (dprintf "root (%s): %a@!" reason d_shortglobal global); true let traceNonRoot reason global = trace (dprintf "non-root (%s): %a@!" reason d_shortglobal global); false let hasExportingAttribute funvar = let rec isExportingAttribute = function | Attr ("constructor", []) -> true | Attr ("destructor", []) -> true | _ -> false in List.exists isExportingAttribute funvar.vattr Exported roots are those global symbols which are visible to the * linker and dynamic loader . For variables , this consists of * anything that is not " static " . For functions , this consists of : * * - functions bearing a " constructor " or " destructor " attribute * - functions declared extern but not inline * - functions declared neither inline nor static * * gcc incorrectly ( according to C99 ) makes inline functions visible to * the linker . So we can only remove inline functions on MSVC . * linker and dynamic loader. For variables, this consists of * anything that is not "static". For functions, this consists of: * * - functions bearing a "constructor" or "destructor" attribute * - functions declared extern but not inline * - functions declared neither inline nor static * * gcc incorrectly (according to C99) makes inline functions visible to * the linker. So we can only remove inline functions on MSVC. *) let isExportedRoot global = let result, reason = match global with | GVar ({vstorage = Static}, _, _) -> false, "static variable" | GVar _ -> true, "non-static variable" | GFun ({svar = v}, _) -> begin if hasExportingAttribute v then true, "constructor or destructor function" else if v.vstorage = Static then false, "static function" else if v.vinline && v.vstorage != Extern && (!msvcMode || !rmUnusedInlines) then false, "inline function" else true, "other function" end | GVarDecl(v,_) when hasAttribute "alias" v.vattr -> true, "has GCC alias attribute" | _ -> false, "neither function nor variable" in trace (dprintf "isExportedRoot %a -> %b, %s@!" d_shortglobal global result reason); result let isCompleteProgramRoot global = let result = match global with | GFun ({svar = {vname = "main"; vstorage = vstorage}}, _) -> vstorage <> Static | GFun (fundec, _) when hasExportingAttribute fundec.svar -> true | _ -> false in trace (dprintf "complete program root -> %b for %a@!" result d_shortglobal global); result class markReachableVisitor ((globalMap: (string, Cil.global) H.t), (currentFunc: fundec option ref)) = object (self) inherit nopCilVisitor method vglob = function | GType (typeinfo, _) -> typeinfo.treferenced <- true; DoChildren | GCompTag (compinfo, _) | GCompTagDecl (compinfo, _) -> compinfo.creferenced <- true; DoChildren | GEnumTag (enuminfo, _) | GEnumTagDecl (enuminfo, _) -> enuminfo.ereferenced <- true; DoChildren | GVar (varinfo, _, _) | GVarDecl (varinfo, _) | GFun ({svar = varinfo}, _) -> varinfo.vreferenced <- true; DoChildren | _ -> SkipChildren method vinst = function Asm (_, tmpls, _, _, _, _) when !msvcMode -> If we have inline assembly on MSVC , we can not tell which locals * are referenced . Keep thsem all * are referenced. Keep thsem all *) (match !currentFunc with Some fd -> List.iter (fun v -> let vre = Str.regexp_string (Str.quote v.vname) in if List.exists (fun tmp -> try ignore (Str.search_forward vre tmp 0); true with Not_found -> false) tmpls then v.vreferenced <- true) fd.slocals | _ -> assert false); DoChildren | _ -> DoChildren method vvrbl v = if not v.vreferenced then begin let name = v.vname in if v.vglob then trace (dprintf "marking transitive use: global %s\n" name) else trace (dprintf "marking transitive use: local %s\n" name); if v.vglob then begin trace (dprintf "descending: global %s\n" name); let descend global = ignore (visitCilGlobal (self :> cilVisitor) global) in let globals = Hashtbl.find_all globalMap name in List.iter descend globals end else v.vreferenced <- true; end; SkipChildren method vexpr (e: exp) = match e with Const (CEnum (_, _, ei)) -> ei.ereferenced <- true; DoChildren | _ -> DoChildren method vtype typ = let old : bool = let visitAttrs attrs = ignore (visitCilAttributes (self :> cilVisitor) attrs) in let visitType typ = ignore (visitCilType (self :> cilVisitor) typ) in match typ with | TEnum(e, attrs) -> let old = e.ereferenced in if not old then begin trace (dprintf "marking transitive use: enum %s\n" e.ename); e.ereferenced <- true; visitAttrs attrs; visitAttrs e.eattr end; old | TComp(c, attrs) -> let old = c.creferenced in if not old then begin trace (dprintf "marking transitive use: compound %s\n" c.cname); c.creferenced <- true; let recurse f = visitType f.ftype in List.iter recurse c.cfields; visitAttrs attrs; visitAttrs c.cattr end; old | TNamed(ti, attrs) -> let old = ti.treferenced in if not old then begin trace (dprintf "marking transitive use: typedef %s\n" ti.tname); ti.treferenced <- true; visitType ti.ttype; visitAttrs attrs end; old | _ -> false in if old then SkipChildren else DoChildren end let markReachable file isRoot = let globalMap = Hashtbl.create 137 in let considerGlobal global = match global with | GFun ({svar = info}, _) | GVar (info, _, _) | GVarDecl (info, _) -> Hashtbl.add globalMap info.vname global | _ -> () in iterGlobals file considerGlobal; let currentFunc = ref None in let visitor = new markReachableVisitor (globalMap, currentFunc) in let visitIfRoot global = if isRoot global then begin trace (dprintf "traversing root global: %a\n" d_shortglobal global); (match global with GFun(fd, _) -> currentFunc := Some fd | _ -> currentFunc := None); ignore (visitCilGlobal visitor global) end else trace (dprintf "skipping non-root global: %a\n" d_shortglobal global) in iterGlobals file visitIfRoot We keep only one label , preferably one that was not introduced by CIL . * Scan a list of labels and return the data for the label that should be * kept , and the remaining filtered list of labels * Scan a list of labels and return the data for the label that should be * kept, and the remaining filtered list of labels *) let labelsToKeep (ll: label list) : (string * location * bool) * label list = let rec loop (sofar: string * location * bool) = function [] -> sofar, [] | l :: rest -> let newlabel, keepl = match l with | Case _ | Default _ -> sofar, true | Label (ln, lloc, isorig) -> begin match isorig, sofar with | false, ("", _, _) -> (ln, lloc, isorig), false | false, _ -> sofar, false | true, (_, _, false) -> (ln, lloc, isorig), false | true, _ -> sofar, false end in let newlabel', rest' = loop newlabel rest in newlabel', (if keepl then l :: rest' else rest') in loop ("", locUnknown, false) ll class markUsedLabels (labelMap: (string, unit) H.t) = object inherit nopCilVisitor method vstmt (s: stmt) = match s.skind with Goto (dest, _) -> let (ln, _, _), _ = labelsToKeep !dest.labels in if ln = "" then E.s (E.bug "rmtmps: destination of statement does not have labels"); H.replace labelMap ln (); DoChildren | _ -> DoChildren method vexpr _ = SkipChildren method vinst _ = SkipChildren method vtype _ = SkipChildren end class removeUnusedLabels (labelMap: (string, unit) H.t) = object inherit nopCilVisitor method vstmt (s: stmt) = let (ln, lloc, lorig), lrest = labelsToKeep s.labels in s.labels <- (Label(ln, lloc, lorig) :: lrest) else lrest); DoChildren method vexpr _ = SkipChildren method vinst _ = SkipChildren method vtype _ = SkipChildren end let uninteresting = let names = [ Cil.makeTempVar "__cil_tmp"; "iter"; "__result"; "__s"; "__s1"; "__s2"; "__s1_len"; "__s2_len"; "__retval"; "__len"; "__c"; "__res"; ] in let alpha = "\\(___[0-9]+\\)?" in let pattern = "\\(" ^ (String.concat "\\|" names) ^ "\\)" ^ alpha ^ "$" in Str.regexp pattern let removeUnmarked file = let removedLocals = ref [] in let filterGlobal global = match global with | GType ({treferenced = false}, _) | GCompTag ({creferenced = false}, _) | GCompTagDecl ({creferenced = false}, _) | GEnumTag ({ereferenced = false}, _) | GEnumTagDecl ({ereferenced = false}, _) | GVar ({vreferenced = false}, _, _) | GVarDecl ({vreferenced = false}, _) | GFun ({svar = {vreferenced = false}}, _) -> trace (dprintf "removing global: %a\n" d_shortglobal global); false | GFun (func, _) -> let rec filterLocal local = if not local.vreferenced then begin let name = local.vname in trace (dprintf "removing local: %s\n" name); if not (Str.string_match uninteresting name 0) then removedLocals := (func.svar.vname ^ "::" ^ name) :: !removedLocals; end; local.vreferenced in func.slocals <- List.filter filterLocal func.slocals; let usedLabels:(string, unit) H.t = H.create 13 in ignore (visitCilBlock (new markUsedLabels usedLabels) func.sbody); ignore (visitCilBlock (new removeUnusedLabels usedLabels) func.sbody); true | _ -> trace (dprintf "keeping global: %a\n" d_shortglobal global); true in file.globals <- List.filter filterGlobal file.globals; !removedLocals type rootsFilter = global -> bool let isDefaultRoot = isExportedRoot let rec removeUnusedTemps ?(isRoot : rootsFilter = isDefaultRoot) file = if !keepUnused || Trace.traceActive "disableTmpRemoval" then Trace.trace "disableTmpRemoval" (dprintf "temp removal disabled\n") else begin if !E.verboseFlag then ignore (E.log "Removing unused temporaries\n" ); if Trace.traceActive "printCilTree" then dumpFile defaultCilPrinter stdout "stdout" file; let keepers = categorizePragmas file in if !Cilutil.sliceGlobal then amputateFunctionBodies keepers.defines file; let isRoot global = isPragmaRoot keepers global || isRoot global in clearReferencedBits file; markReachable file isRoot; let removedLocals = removeUnmarked file in if false && removedLocals != [] then let count = List.length removedLocals in if count > 2000 then ignore (E.warn "%d unused local variables removed" count) else ignore (E.warn "%d unused local variables removed:@!%a" count (docList ~sep:(chr ',' ++ break) text) removedLocals) end