_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
b3219feb977df6c6fa2d54e9e338891410e9d81229c34a54639c8b27ddf8f547
craigl64/clim-ccl
instclimxm.lisp
;; -*- mode: common-lisp; package: system -*- ;; ;; ;; See the file LICENSE for the full license governing this code. ;; ;; Load the Motif version of CLIM ;; (in-package :system) (load-application (require :climxm) :devel system::*devel*) #+ics (load-application (require :climwnn) :devel system::*devel*) (format t "~&; Finished loading CLIM XM~%") (force-output)
null
https://raw.githubusercontent.com/craigl64/clim-ccl/301efbd770745b429f2b00b4e8ca6624de9d9ea9/instclimxm.lisp
lisp
-*- mode: common-lisp; package: system -*- See the file LICENSE for the full license governing this code.
Load the Motif version of CLIM (in-package :system) (load-application (require :climxm) :devel system::*devel*) #+ics (load-application (require :climwnn) :devel system::*devel*) (format t "~&; Finished loading CLIM XM~%") (force-output)
682e9327f5185889a5c59c1133f1c4e21a75d1c236ddbc00029467c06d82f71f
adnelson/simple-nix
SpecHelper.hs
# LANGUAGE NoImplicitPrelude # module SpecHelper ( module Test.Hspec , module Nix.Common , module Nix.Expr , module Nix.Parser , shouldBeM, shouldBeR, shouldHaveErr, shouldBeMR, shouldBeJ , shouldBeN ) where import Test.Hspec import Test.Hspec.Expectations.Contrib import Nix.Common hiding (isLeft, isRight) import Nix.Expr import Nix.Parser | Runs ` shouldBe ` on the result of an IO action . shouldBeM :: (Show a, Eq a) => IO a -> a -> IO () shouldBeM action expected = do result <- action result `shouldBe` expected infixr 0 `shouldBeM` | Asserts that the first argument is a ` Just ` value equal to the second -- argument. shouldBeJ :: (Show a, Eq a) => Maybe a -> a -> IO () shouldBeJ x y = do shouldSatisfy x isJust let Just x' = x x' `shouldBe` y -- | Asserts that the argument is `Nothing`. shouldBeN :: (Show a) => Maybe a -> IO () shouldBeN = flip shouldSatisfy isNothing | Asserts that the first argument is a ` Right ` value equal to the second -- argument. shouldBeR :: (Show a, Show b, Eq b) => Either a b -> b -> IO () shouldBeR x y = do shouldSatisfy x isRight let Right x' = x x' `shouldBe` y infixr 0 `shouldBeR` -- | Asserts that the argument is a `Left` value, containing something which -- when `Show`n contains the provided substring. shouldHaveErr :: (Show a, Show b) => Either a b -- ^ Should be a `Left` value. -> String -- ^ Error should contain this. -> IO () shouldHaveErr x msg = do shouldSatisfy x isLeft let Left err = x show err `shouldSatisfy` isInfixOf msg -- | Runs `shouldBeR` on the result of an IO action. shouldBeMR :: (Show a, Show x, Eq a, Eq x) => IO (Either x a) -> a -> IO () shouldBeMR action expected = action >>= flip shouldBeR expected
null
https://raw.githubusercontent.com/adnelson/simple-nix/ea70f94a602637de90d3750314ff767b4540171a/test/SpecHelper.hs
haskell
argument. | Asserts that the argument is `Nothing`. argument. | Asserts that the argument is a `Left` value, containing something which when `Show`n contains the provided substring. ^ Should be a `Left` value. ^ Error should contain this. | Runs `shouldBeR` on the result of an IO action.
# LANGUAGE NoImplicitPrelude # module SpecHelper ( module Test.Hspec , module Nix.Common , module Nix.Expr , module Nix.Parser , shouldBeM, shouldBeR, shouldHaveErr, shouldBeMR, shouldBeJ , shouldBeN ) where import Test.Hspec import Test.Hspec.Expectations.Contrib import Nix.Common hiding (isLeft, isRight) import Nix.Expr import Nix.Parser | Runs ` shouldBe ` on the result of an IO action . shouldBeM :: (Show a, Eq a) => IO a -> a -> IO () shouldBeM action expected = do result <- action result `shouldBe` expected infixr 0 `shouldBeM` | Asserts that the first argument is a ` Just ` value equal to the second shouldBeJ :: (Show a, Eq a) => Maybe a -> a -> IO () shouldBeJ x y = do shouldSatisfy x isJust let Just x' = x x' `shouldBe` y shouldBeN :: (Show a) => Maybe a -> IO () shouldBeN = flip shouldSatisfy isNothing | Asserts that the first argument is a ` Right ` value equal to the second shouldBeR :: (Show a, Show b, Eq b) => Either a b -> b -> IO () shouldBeR x y = do shouldSatisfy x isRight let Right x' = x x' `shouldBe` y infixr 0 `shouldBeR` shouldHaveErr :: (Show a, Show b) -> IO () shouldHaveErr x msg = do shouldSatisfy x isLeft let Left err = x show err `shouldSatisfy` isInfixOf msg shouldBeMR :: (Show a, Show x, Eq a, Eq x) => IO (Either x a) -> a -> IO () shouldBeMR action expected = action >>= flip shouldBeR expected
552661b971b646045857161d841b84982231cb5447750cfa1a8b265509c50561
freizl/dive-into-haskell
Main.hs
module Main where import Control.Monad.IO.Class import GHC.Paths import GHC.IO.Handle.FD import GHC import HscTypes import SimplStg import SimplCore import CorePrep import CoreToStg import DynFlags import TyCon import Pretty import Outputable import System.IO import StgSyn import Name import qualified Data.ByteString.Char8 as C import CodeGen main :: IO () main = do print ("libdir: " ++ libdir) print ("ghc_pkg: " ++ ghc_pkg) print ("docdir: " ++ docdir) print ("ghc: " ++ ghc) runGhc (Just libdir) $ do env <- getSession dflags <- getSessionDynFlags HscInterpreted , HscC -- , ghcLink = LinkInMemory } target <- guessTarget "src/Example.hs" Nothing targetLib <- guessTarget "src/Lib.hs" Nothing setTargets [target, targetLib] load LoadAllTargets depanal [] True modSum <- getModSummary $ mkModuleName "Example" pmod <- parseModule modSum -- ModuleSummary TypecheckedSource dmod <- desugarModule tmod -- DesugaredModule CoreModule let mod = ms_mod modSum let loc = ms_location modSum let core = mg_binds coreMod let tcs = filter isDataTyCon (mg_tcs coreMod) -- see note in source code: cg_tycons includes newtypes , for the benefit of External Core , -- but we don't generate any code for newtypes let dflags' = foldl gopt_set dflags [Opt_StgCSE, Opt_DoEtaReduction, Opt_CallArity, Opt_FunToThunk, Opt_StgStats ] let env' = env {hsc_dflags = dflags'} -- run core2core passes guts' <- liftIO $ core2core env' coreMod let core' = mg_binds guts' (prep, _) <- liftIO $ corePrepPgm env' mod loc core' tcs let (stg,_) = coreToStg dflags' mod prep stg_binds2 <- liftIO $ stg2stg dflags' stg liftIO $ do logFile <- openFile "/tmp/example.hs.stg.txt" WriteMode mapM_ print (map fooCompile stg_binds2) printSDocLn PageMode dflags' logFile (defaultUserStyle dflags') $ ppr stg_binds2 hClose logFile
null
https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/codes/stg-to-js/src/Main.hs
haskell
, ghcLink = LinkInMemory ModuleSummary DesugaredModule see note in source code: but we don't generate any code for newtypes run core2core passes
module Main where import Control.Monad.IO.Class import GHC.Paths import GHC.IO.Handle.FD import GHC import HscTypes import SimplStg import SimplCore import CorePrep import CoreToStg import DynFlags import TyCon import Pretty import Outputable import System.IO import StgSyn import Name import qualified Data.ByteString.Char8 as C import CodeGen main :: IO () main = do print ("libdir: " ++ libdir) print ("ghc_pkg: " ++ ghc_pkg) print ("docdir: " ++ docdir) print ("ghc: " ++ ghc) runGhc (Just libdir) $ do env <- getSession dflags <- getSessionDynFlags HscInterpreted , HscC } target <- guessTarget "src/Example.hs" Nothing targetLib <- guessTarget "src/Lib.hs" Nothing setTargets [target, targetLib] load LoadAllTargets depanal [] True modSum <- getModSummary $ mkModuleName "Example" TypecheckedSource CoreModule let mod = ms_mod modSum let loc = ms_location modSum let core = mg_binds coreMod cg_tycons includes newtypes , for the benefit of External Core , let dflags' = foldl gopt_set dflags [Opt_StgCSE, Opt_DoEtaReduction, Opt_CallArity, Opt_FunToThunk, Opt_StgStats ] let env' = env {hsc_dflags = dflags'} guts' <- liftIO $ core2core env' coreMod let core' = mg_binds guts' (prep, _) <- liftIO $ corePrepPgm env' mod loc core' tcs let (stg,_) = coreToStg dflags' mod prep stg_binds2 <- liftIO $ stg2stg dflags' stg liftIO $ do logFile <- openFile "/tmp/example.hs.stg.txt" WriteMode mapM_ print (map fooCompile stg_binds2) printSDocLn PageMode dflags' logFile (defaultUserStyle dflags') $ ppr stg_binds2 hClose logFile
edc50eca673c59d5d774eb4eedb4ea8817fc2a37105882110cce7fb6d78979ee
shriphani/pegasus
dsl.clj
(ns pegasus.dsl "DSL for easy extractors and stuff" (:require [net.cgrand.enlive-html :as html] [org.bovinegenius.exploding-fish :as uri] [pegasus.process :as process]) (:import [java.io StringReader])) (def default-extractor-options {:when identity :at-selector [:a] :follow :href :with-regex nil}) (defn extract "Constructs extractors." [& options] (fn [obj] (let [url (:url obj) body (:body obj) resource (-> body (StringReader.) html/html-resource) options-map (into {} (map vec (partition 2 options))) merged-options-map (merge default-extractor-options options-map) enlive-sel (:at-selector merged-options-map) follow-sel (:follow merged-options-map) predicate (:when merged-options-map) tags (filter identity (html/select resource enlive-sel)) attrs (filter identity (map (fn [a-tag] (get (:attrs a-tag) follow-sel)) tags)) all-extracted (filter identity (if (predicate obj) (map #(uri/resolve-uri url %) attrs) [])) regex-filtered (if (:with-regex merged-options-map) (filter #(re-find (:with-regex merged-options-map) %) all-extracted) all-extracted)] regex-filtered))) (defn defextractors [& extractors] (reify process/PipelineComponentProtocol (initialize [this config] config) (run [this obj config] (let [extracted (distinct (filter identity (flatten (map (fn [e] (e obj)) extractors))))] (merge obj {:extracted extracted}))) (clean [this config] nil)))
null
https://raw.githubusercontent.com/shriphani/pegasus/0ffbce77e596ae0af8d5ae9ffb85a8f1fa66914b/src/pegasus/dsl.clj
clojure
(ns pegasus.dsl "DSL for easy extractors and stuff" (:require [net.cgrand.enlive-html :as html] [org.bovinegenius.exploding-fish :as uri] [pegasus.process :as process]) (:import [java.io StringReader])) (def default-extractor-options {:when identity :at-selector [:a] :follow :href :with-regex nil}) (defn extract "Constructs extractors." [& options] (fn [obj] (let [url (:url obj) body (:body obj) resource (-> body (StringReader.) html/html-resource) options-map (into {} (map vec (partition 2 options))) merged-options-map (merge default-extractor-options options-map) enlive-sel (:at-selector merged-options-map) follow-sel (:follow merged-options-map) predicate (:when merged-options-map) tags (filter identity (html/select resource enlive-sel)) attrs (filter identity (map (fn [a-tag] (get (:attrs a-tag) follow-sel)) tags)) all-extracted (filter identity (if (predicate obj) (map #(uri/resolve-uri url %) attrs) [])) regex-filtered (if (:with-regex merged-options-map) (filter #(re-find (:with-regex merged-options-map) %) all-extracted) all-extracted)] regex-filtered))) (defn defextractors [& extractors] (reify process/PipelineComponentProtocol (initialize [this config] config) (run [this obj config] (let [extracted (distinct (filter identity (flatten (map (fn [e] (e obj)) extractors))))] (merge obj {:extracted extracted}))) (clean [this config] nil)))
a038ce896b5b2e10cf49999d251c38ae30423fd00b006596be838477af121cb4
konn/type-natural
Natural.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE DataKinds # # LANGUAGE EmptyCase # # LANGUAGE ExplicitNamespaces # # LANGUAGE FlexibleContexts # {-# LANGUAGE GADTs #-} # LANGUAGE InstanceSigs # # LANGUAGE PolyKinds # {-# LANGUAGE RankNTypes #-} # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # # LANGUAGE ViewPatterns # {-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.Presburger #-} | Coercion between Peano Numerals . Type . Natural . Nat'@ and builtin naturals @'GHC.TypeLits . Nat'@ module Data.Type.Natural ( -- * Type-level naturals * * @Nat@ , singletons and KnownNat manipulation , Nat, KnownNat, SNat (Succ, Zero), sNat, sNatP, toNatural, SomeSNat (..), toSomeSNat, withSNat, withKnownNat, natVal, natVal', someNatVal, SomeNat (..), (%~), Equality (..), type (===), -- *** Pattens and Views viewNat, zeroOrSucc, ZeroOrSucc (..), -- ** Promtoed and singletonised operations -- *** Arithmetic Succ, sSucc, S, Pred, sPred, sS, Zero, sZero, One, sOne, type (+), (%+), type (-), (%-), type (*), (%*), Div, sDiv, Mod, sMod, type (^), (%^), type (-.), (%-.), Log2, sLog2, -- *** Ordering type (<=?), type (<=), (%<=?), type (<?), type (<), (%<?), type (>=?), type (>=), (%>=?), type (>?), type (>), (%>?), CmpNat, sCmpNat, sCompare, Min, sMin, Max, sMax, induction, -- * QuasiQuotes snat, -- * Singletons for auxiliary types SBool (..), SOrdering (..), FlipOrdering, sFlipOrdering, ) where import Data.Coerce (coerce) import Data.Proxy (Proxy) import Data.Type.Natural.Core import Data.Type.Natural.Lemma.Arithmetic import Data.Type.Natural.Lemma.Order import Language.Haskell.TH (litT, numTyLit) import Language.Haskell.TH.Quote import Numeric.Natural import Text.Read (readMaybe) for SNatleton types for @'GHC.TypeLits . Nat'@. This can be used for an expression . For example : @[snat|12| ] ' % + ' [ snat| 5 |]@. For example: @[snat|12|] '%+' [snat| 5 |]@. -} snat :: QuasiQuoter snat = QuasiQuoter { quoteExp = \str -> case readMaybe str of Just n -> [|sNat :: SNat $(litT $ numTyLit n)|] Nothing -> error "Must be natural literal" , quotePat = \str -> case readMaybe str of Just n -> [p|((%~ (sNat :: SNat $(litT $ numTyLit n))) -> Equal)|] Nothing -> error "Must be natural literal" , quoteType = \str -> case readMaybe str of Just n -> litT $ numTyLit n Nothing -> error "Must be natural literal" , quoteDec = error "No declaration Quotes for Nat" } toNatural :: SNat n -> Natural toNatural = coerce data SomeSNat where SomeSNat :: KnownNat n => SNat n -> SomeSNat deriving instance Show SomeSNat instance Eq SomeSNat where SomeSNat (SNat n) == SomeSNat (SNat m) = n == m SomeSNat (SNat n) /= SomeSNat (SNat m) = n /= m toSomeSNat :: Natural -> SomeSNat toSomeSNat n = case someNatVal n of SomeNat pn -> withKnownNat sn $ SomeSNat sn where sn = sNatP pn withSNat :: Natural -> (forall n. KnownNat n => SNat n -> r) -> r withSNat n act = case someNatVal n of SomeNat (pn :: Proxy n) -> withKnownNat sn $ act sn where sn = sNatP pn sNatP :: KnownNat n => pxy n -> SNat n sNatP = const sNat
null
https://raw.githubusercontent.com/konn/type-natural/bcdd9ff0bf8d74a7fbecc49ef063c4e440ea417b/src/Data/Type/Natural.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE GADTs # # LANGUAGE RankNTypes # # OPTIONS_GHC -fplugin GHC.TypeLits.Normalise # # OPTIONS_GHC -fplugin GHC.TypeLits.Presburger # * Type-level naturals *** Pattens and Views ** Promtoed and singletonised operations *** Arithmetic *** Ordering * QuasiQuotes * Singletons for auxiliary types
# LANGUAGE DataKinds # # LANGUAGE EmptyCase # # LANGUAGE ExplicitNamespaces # # LANGUAGE FlexibleContexts # # LANGUAGE InstanceSigs # # LANGUAGE PolyKinds # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # # LANGUAGE ViewPatterns # | Coercion between Peano Numerals . Type . Natural . Nat'@ and builtin naturals @'GHC.TypeLits . Nat'@ module Data.Type.Natural * * @Nat@ , singletons and KnownNat manipulation , Nat, KnownNat, SNat (Succ, Zero), sNat, sNatP, toNatural, SomeSNat (..), toSomeSNat, withSNat, withKnownNat, natVal, natVal', someNatVal, SomeNat (..), (%~), Equality (..), type (===), viewNat, zeroOrSucc, ZeroOrSucc (..), Succ, sSucc, S, Pred, sPred, sS, Zero, sZero, One, sOne, type (+), (%+), type (-), (%-), type (*), (%*), Div, sDiv, Mod, sMod, type (^), (%^), type (-.), (%-.), Log2, sLog2, type (<=?), type (<=), (%<=?), type (<?), type (<), (%<?), type (>=?), type (>=), (%>=?), type (>?), type (>), (%>?), CmpNat, sCmpNat, sCompare, Min, sMin, Max, sMax, induction, snat, SBool (..), SOrdering (..), FlipOrdering, sFlipOrdering, ) where import Data.Coerce (coerce) import Data.Proxy (Proxy) import Data.Type.Natural.Core import Data.Type.Natural.Lemma.Arithmetic import Data.Type.Natural.Lemma.Order import Language.Haskell.TH (litT, numTyLit) import Language.Haskell.TH.Quote import Numeric.Natural import Text.Read (readMaybe) for SNatleton types for @'GHC.TypeLits . Nat'@. This can be used for an expression . For example : @[snat|12| ] ' % + ' [ snat| 5 |]@. For example: @[snat|12|] '%+' [snat| 5 |]@. -} snat :: QuasiQuoter snat = QuasiQuoter { quoteExp = \str -> case readMaybe str of Just n -> [|sNat :: SNat $(litT $ numTyLit n)|] Nothing -> error "Must be natural literal" , quotePat = \str -> case readMaybe str of Just n -> [p|((%~ (sNat :: SNat $(litT $ numTyLit n))) -> Equal)|] Nothing -> error "Must be natural literal" , quoteType = \str -> case readMaybe str of Just n -> litT $ numTyLit n Nothing -> error "Must be natural literal" , quoteDec = error "No declaration Quotes for Nat" } toNatural :: SNat n -> Natural toNatural = coerce data SomeSNat where SomeSNat :: KnownNat n => SNat n -> SomeSNat deriving instance Show SomeSNat instance Eq SomeSNat where SomeSNat (SNat n) == SomeSNat (SNat m) = n == m SomeSNat (SNat n) /= SomeSNat (SNat m) = n /= m toSomeSNat :: Natural -> SomeSNat toSomeSNat n = case someNatVal n of SomeNat pn -> withKnownNat sn $ SomeSNat sn where sn = sNatP pn withSNat :: Natural -> (forall n. KnownNat n => SNat n -> r) -> r withSNat n act = case someNatVal n of SomeNat (pn :: Proxy n) -> withKnownNat sn $ act sn where sn = sNatP pn sNatP :: KnownNat n => pxy n -> SNat n sNatP = const sNat
2c29f331d39747e3d234a10734356b71c137d902f3dcd387eb86b9d94de499fe
fission-codes/fission
Class.hs
module Fission.Web.Server.IPFS.Cluster.Class (MonadIPFSCluster (..)) where -- 🧱 import RIO.NonEmpty -- 🌐 import Servant.API import Servant.Client import qualified Servant.Client.Streaming as Stream ⚛ ️ import Fission.Prelude class MonadIO m => MonadIPFSCluster m a where runCluster :: ClientM a -> m (NonEmpty (Async (Either ClientError a))) streamCluster :: Stream.ClientM (SourceIO a) -> m (NonEmpty ((Async (Either ClientError a)), TChan (Either ClientError a)))
null
https://raw.githubusercontent.com/fission-codes/fission/11d14b729ccebfd69499a534445fb072ac3433a3/fission-web-server/library/Fission/Web/Server/IPFS/Cluster/Class.hs
haskell
🧱 🌐
module Fission.Web.Server.IPFS.Cluster.Class (MonadIPFSCluster (..)) where import RIO.NonEmpty import Servant.API import Servant.Client import qualified Servant.Client.Streaming as Stream ⚛ ️ import Fission.Prelude class MonadIO m => MonadIPFSCluster m a where runCluster :: ClientM a -> m (NonEmpty (Async (Either ClientError a))) streamCluster :: Stream.ClientM (SourceIO a) -> m (NonEmpty ((Async (Either ClientError a)), TChan (Either ClientError a)))
799e6b4b1f0d2721772b6dce18fd76713dada8d0c2c8b29baf1402834432c5c1
antono/guix-debian
bison.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2012 , 2013 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU 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. ;;; ;;; GNU Guix 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 GNU . If not , see < / > . (define-module (gnu packages bison) #:use-module (guix licenses) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu) #:use-module (gnu packages m4) #:use-module (gnu packages perl) #:use-module (gnu packages flex) #:use-module (srfi srfi-1) #:export (bison)) (define bison (package (name "bison") (version "3.0.2") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "0g4gjan477lac18m51kv4xzcsp6wjfsfwvd2dxymcl6vid9fihx2")))) (build-system gnu-build-system) (native-inputs `(("perl" ,perl))) (inputs `(("flex" ,flex))) (propagated-inputs `(("m4" ,m4))) (home-page "/") (synopsis "Parser generator") (description "GNU Bison is a general-purpose parser generator. It can build a deterministic or generalized LR parser from an annotated, context-free grammar. It is versatile enough to have many applications, from parsers for simple tools through complex programming languages.") (license gpl3+)))
null
https://raw.githubusercontent.com/antono/guix-debian/85ef443788f0788a62010a942973d4f7714d10b4/gnu/packages/bison.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix 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.
Copyright © 2012 , 2013 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages bison) #:use-module (guix licenses) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu) #:use-module (gnu packages m4) #:use-module (gnu packages perl) #:use-module (gnu packages flex) #:use-module (srfi srfi-1) #:export (bison)) (define bison (package (name "bison") (version "3.0.2") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "0g4gjan477lac18m51kv4xzcsp6wjfsfwvd2dxymcl6vid9fihx2")))) (build-system gnu-build-system) (native-inputs `(("perl" ,perl))) (inputs `(("flex" ,flex))) (propagated-inputs `(("m4" ,m4))) (home-page "/") (synopsis "Parser generator") (description "GNU Bison is a general-purpose parser generator. It can build a deterministic or generalized LR parser from an annotated, context-free grammar. It is versatile enough to have many applications, from parsers for simple tools through complex programming languages.") (license gpl3+)))
1d459f2f13fa2b947c44bdc45088386e5c2db1a5f9f04c90883e1d3877d4b004
semperos/webdriver-logic
templates.clj
(ns webdriver-logic.test.example-app.templates (:use net.cgrand.enlive-html)) (deftemplate page "page.html" [styles scripts cnt] [:div#content] (content cnt)) (defsnippet welcome-page "welcome.html" [:body :> any-node] []) (defsnippet clojure-page "clojure.html" [:body :> any-node] []) (defsnippet example-form "form.html" [:body :> any-node] [])
null
https://raw.githubusercontent.com/semperos/webdriver-logic/d6fa8795ebf9e023d3f6baffbdba27cdf784368f/test/webdriver_logic/test/example_app/templates.clj
clojure
(ns webdriver-logic.test.example-app.templates (:use net.cgrand.enlive-html)) (deftemplate page "page.html" [styles scripts cnt] [:div#content] (content cnt)) (defsnippet welcome-page "welcome.html" [:body :> any-node] []) (defsnippet clojure-page "clojure.html" [:body :> any-node] []) (defsnippet example-form "form.html" [:body :> any-node] [])
8e80ae01dcbad6e43f22271a3f2e38b6463026715bdc7614f035de51d6cfda2b
haskell-tools/haskell-tools
Definitions.hs
{-# LANGUAGE TypeFamilies , ConstraintKinds , RankNTypes #-} module Definitions where type EqRel a b = a ~ b type TrfAB a b = a ~ b => a -> b type family F a :: * where F Int = Integer F Char = String F a = a type HiddenEqRel a b = EqRel a b type ComplexEqRelType a = Eq a => a -> a -> (forall c . HiddenEqRel a c => c -> c -> Bool) -> Bool eqRelName :: EqRel a b => a -> b eqRelName = id nestedEqRelName :: a -> (forall a b . EqRel a b => a -> b) -> a nestedEqRelName x f = f x
null
https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/builtin-refactorings/test/ExtensionOrganizerTest/TypeFamiliesTest/Definitions.hs
haskell
# LANGUAGE TypeFamilies , ConstraintKinds , RankNTypes #
module Definitions where type EqRel a b = a ~ b type TrfAB a b = a ~ b => a -> b type family F a :: * where F Int = Integer F Char = String F a = a type HiddenEqRel a b = EqRel a b type ComplexEqRelType a = Eq a => a -> a -> (forall c . HiddenEqRel a c => c -> c -> Bool) -> Bool eqRelName :: EqRel a b => a -> b eqRelName = id nestedEqRelName :: a -> (forall a b . EqRel a b => a -> b) -> a nestedEqRelName x f = f x
956aca34e68fa3e34e246d716cb0e61b81bf592bda3772864a77a938d2da32af
electric-sql/vaxine
commit_hooks_SUITE.erl
%% ------------------------------------------------------------------- %% Copyright < 2013 - 2018 > < Technische Universität Kaiserslautern , Germany , France Universidade NOVA de Lisboa , Portugal Université catholique de Louvain ( UCL ) , Belgique , Portugal %% > %% 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 expressed or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% List of the contributors to the development of Antidote : see file . %% Description and complete License: see LICENSE file. %% ------------------------------------------------------------------- -module(commit_hooks_SUITE). %% common_test callbacks -export([ init_per_suite/1, end_per_suite/1, init_per_testcase/2, end_per_testcase/2, all/0]). %% tests -export([register_hook_test/1, execute_hook_test/1, execute_post_hook_test/1, execute_prehooks_static_txn_test/1, execute_posthooks_static_txn_test/1]). -include_lib("common_test/include/ct.hrl"). -include_lib("eunit/include/eunit.hrl"). -define(BUCKET, test_utils:bucket(commit_hooks_bucket)). init_per_suite(Config) -> test_utils:init_single_dc(?MODULE, Config). end_per_suite(Config) -> Config. init_per_testcase(_Case, Config) -> Config. end_per_testcase(Name, _) -> ct:print("[ OK ] ~p", [Name]), ok. all() -> [ register_hook_test, execute_hook_test, execute_post_hook_test, execute_prehooks_static_txn_test, execute_posthooks_static_txn_test ]. register_hook_test(Config) -> Node = proplists:get_value(node, Config), Bucket = ?BUCKET, Response = rpc:call(Node, antidote, register_pre_hook, [Bucket, hooks_module, hooks_function]), ?assertMatch({error, _}, Response), ok = rpc:call(Node, antidote_hooks, register_post_hook, [Bucket, antidote_hooks, test_commit_hook]), Result1 = rpc:call(Node, antidote_hooks, get_hooks, [post_commit, Bucket]), ?assertMatch({antidote_hooks, test_commit_hook}, Result1), ok = rpc:call(Node, antidote, unregister_hook, [post_commit, Bucket]), Result2 = rpc:call(Node, antidote_hooks, get_hooks, [post_commit, Bucket]), ?assertMatch(undefined, Result2). %% Test pre-commit hook execute_hook_test(Config) -> Node = proplists:get_value(node, Config), Bucket = ?BUCKET, BoundObject = {hook_key, antidote_crdt_counter_pn, Bucket}, ok = rpc:call(Node, antidote, register_pre_hook, [Bucket, antidote_hooks, test_increment_hook]), {ok, TxId} = rpc:call(Node, antidote, start_transaction, [ignore, []]), ct:log("Txid ~p", [TxId]), ok = rpc:call(Node, antidote, update_objects, [[{BoundObject, increment, 1}], TxId]), {ok, CT} = rpc:call(Node, antidote, commit_transaction, [TxId]), {ok, TxId2} = rpc:call(Node, antidote, start_transaction, [CT, []]), Res = rpc:call(Node, antidote, read_objects, [[BoundObject], TxId2]), rpc:call(Node, antidote, commit_transaction, [TxId2]), ?assertMatch({ok, [2]}, Res). %% Test post-commit hook execute_post_hook_test(Config) -> Node = proplists:get_value(node, Config), Bucket = ?BUCKET, BoundObject = {post_hook_key, antidote_crdt_counter_pn, Bucket}, ok = rpc:call(Node, antidote, register_post_hook, [Bucket, antidote_hooks, test_post_hook]), {ok, TxId} = rpc:call(Node, antidote, start_transaction, [ignore, []]), ok = rpc:call(Node, antidote, update_objects, [[{BoundObject, increment, 1}], TxId]), {ok, CT} = rpc:call(Node, antidote, commit_transaction, [TxId]), CommitCount = {post_hook_key, antidote_crdt_counter_pn, commitcount}, {ok, TxId2} = rpc:call(Node, antidote, start_transaction, [CT, []]), Res = rpc:call(Node, antidote, read_objects, [[CommitCount], TxId2]), rpc:call(Node, antidote, commit_transaction, [TxId2]), ?assertMatch({ok, [1]}, Res). execute_prehooks_static_txn_test(Config) -> Node = proplists:get_value(node, Config), Bucket = ?BUCKET, BoundObject = {prehook_key, antidote_crdt_counter_pn, Bucket}, ok = rpc:call(Node, antidote, register_pre_hook, [Bucket, antidote_hooks, test_increment_hook]), {ok, CT} = rpc:call(Node, antidote, update_objects, [ignore, [], [{BoundObject, increment, 1}]]), {ok, TxId2} = rpc:call(Node, antidote, start_transaction, [CT, []]), Res = rpc:call(Node, antidote, read_objects, [[BoundObject], TxId2]), rpc:call(Node, antidote, commit_transaction, [TxId2]), ?assertMatch({ok, [2]}, Res). execute_posthooks_static_txn_test(Config) -> Node = proplists:get_value(node, Config), Bucket = ?BUCKET, BoundObject = {posthook_static_key, antidote_crdt_counter_pn, Bucket}, ok = rpc:call(Node, antidote, register_post_hook, [Bucket, antidote_hooks, test_post_hook]), {ok, CT} = rpc:call(Node, antidote, update_objects, [ignore, [], [{BoundObject, increment, 1}]]), CommitCount = {posthook_static_key, antidote_crdt_counter_pn, commitcount}, {ok, TxId2} = rpc:call(Node, antidote, start_transaction, [CT, []]), Res = rpc:call(Node, antidote, read_objects, [[CommitCount], TxId2]), rpc:call(Node, antidote, commit_transaction, [TxId2]), ?assertMatch({ok, [1]}, Res).
null
https://raw.githubusercontent.com/electric-sql/vaxine/872a83ea8d4935a52c7b850bb17ab099ee9c346b/apps/antidote/test/singledc/commit_hooks_SUITE.erl
erlang
------------------------------------------------------------------- > 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 expressed or implied. See the License for the specific language governing permissions and limitations under the License. Description and complete License: see LICENSE file. ------------------------------------------------------------------- common_test callbacks tests Test pre-commit hook Test post-commit hook
Copyright < 2013 - 2018 > < Technische Universität Kaiserslautern , Germany , France Universidade NOVA de Lisboa , Portugal Université catholique de Louvain ( UCL ) , Belgique , Portugal 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 List of the contributors to the development of Antidote : see file . -module(commit_hooks_SUITE). -export([ init_per_suite/1, end_per_suite/1, init_per_testcase/2, end_per_testcase/2, all/0]). -export([register_hook_test/1, execute_hook_test/1, execute_post_hook_test/1, execute_prehooks_static_txn_test/1, execute_posthooks_static_txn_test/1]). -include_lib("common_test/include/ct.hrl"). -include_lib("eunit/include/eunit.hrl"). -define(BUCKET, test_utils:bucket(commit_hooks_bucket)). init_per_suite(Config) -> test_utils:init_single_dc(?MODULE, Config). end_per_suite(Config) -> Config. init_per_testcase(_Case, Config) -> Config. end_per_testcase(Name, _) -> ct:print("[ OK ] ~p", [Name]), ok. all() -> [ register_hook_test, execute_hook_test, execute_post_hook_test, execute_prehooks_static_txn_test, execute_posthooks_static_txn_test ]. register_hook_test(Config) -> Node = proplists:get_value(node, Config), Bucket = ?BUCKET, Response = rpc:call(Node, antidote, register_pre_hook, [Bucket, hooks_module, hooks_function]), ?assertMatch({error, _}, Response), ok = rpc:call(Node, antidote_hooks, register_post_hook, [Bucket, antidote_hooks, test_commit_hook]), Result1 = rpc:call(Node, antidote_hooks, get_hooks, [post_commit, Bucket]), ?assertMatch({antidote_hooks, test_commit_hook}, Result1), ok = rpc:call(Node, antidote, unregister_hook, [post_commit, Bucket]), Result2 = rpc:call(Node, antidote_hooks, get_hooks, [post_commit, Bucket]), ?assertMatch(undefined, Result2). execute_hook_test(Config) -> Node = proplists:get_value(node, Config), Bucket = ?BUCKET, BoundObject = {hook_key, antidote_crdt_counter_pn, Bucket}, ok = rpc:call(Node, antidote, register_pre_hook, [Bucket, antidote_hooks, test_increment_hook]), {ok, TxId} = rpc:call(Node, antidote, start_transaction, [ignore, []]), ct:log("Txid ~p", [TxId]), ok = rpc:call(Node, antidote, update_objects, [[{BoundObject, increment, 1}], TxId]), {ok, CT} = rpc:call(Node, antidote, commit_transaction, [TxId]), {ok, TxId2} = rpc:call(Node, antidote, start_transaction, [CT, []]), Res = rpc:call(Node, antidote, read_objects, [[BoundObject], TxId2]), rpc:call(Node, antidote, commit_transaction, [TxId2]), ?assertMatch({ok, [2]}, Res). execute_post_hook_test(Config) -> Node = proplists:get_value(node, Config), Bucket = ?BUCKET, BoundObject = {post_hook_key, antidote_crdt_counter_pn, Bucket}, ok = rpc:call(Node, antidote, register_post_hook, [Bucket, antidote_hooks, test_post_hook]), {ok, TxId} = rpc:call(Node, antidote, start_transaction, [ignore, []]), ok = rpc:call(Node, antidote, update_objects, [[{BoundObject, increment, 1}], TxId]), {ok, CT} = rpc:call(Node, antidote, commit_transaction, [TxId]), CommitCount = {post_hook_key, antidote_crdt_counter_pn, commitcount}, {ok, TxId2} = rpc:call(Node, antidote, start_transaction, [CT, []]), Res = rpc:call(Node, antidote, read_objects, [[CommitCount], TxId2]), rpc:call(Node, antidote, commit_transaction, [TxId2]), ?assertMatch({ok, [1]}, Res). execute_prehooks_static_txn_test(Config) -> Node = proplists:get_value(node, Config), Bucket = ?BUCKET, BoundObject = {prehook_key, antidote_crdt_counter_pn, Bucket}, ok = rpc:call(Node, antidote, register_pre_hook, [Bucket, antidote_hooks, test_increment_hook]), {ok, CT} = rpc:call(Node, antidote, update_objects, [ignore, [], [{BoundObject, increment, 1}]]), {ok, TxId2} = rpc:call(Node, antidote, start_transaction, [CT, []]), Res = rpc:call(Node, antidote, read_objects, [[BoundObject], TxId2]), rpc:call(Node, antidote, commit_transaction, [TxId2]), ?assertMatch({ok, [2]}, Res). execute_posthooks_static_txn_test(Config) -> Node = proplists:get_value(node, Config), Bucket = ?BUCKET, BoundObject = {posthook_static_key, antidote_crdt_counter_pn, Bucket}, ok = rpc:call(Node, antidote, register_post_hook, [Bucket, antidote_hooks, test_post_hook]), {ok, CT} = rpc:call(Node, antidote, update_objects, [ignore, [], [{BoundObject, increment, 1}]]), CommitCount = {posthook_static_key, antidote_crdt_counter_pn, commitcount}, {ok, TxId2} = rpc:call(Node, antidote, start_transaction, [CT, []]), Res = rpc:call(Node, antidote, read_objects, [[CommitCount], TxId2]), rpc:call(Node, antidote, commit_transaction, [TxId2]), ?assertMatch({ok, [1]}, Res).
622ce321f567bce80837e9e7e785cc82a8ae9da29028b14bd0bbbce827c75d2b
piranha/ecomspark
cart.clj
(ns ecomspark.views.cart (:require [hiccup.core :as hi])) (defn HeaderCart [opts] (hi/html (if opts [:a#cart.btn.btn-link {:href "/cart" :ts-swap-push "#cart"} (when (pos? (:count opts)) [:span.chip (:count opts)]) "Cart"] [:a#cart.btn.btn-link {:href "/cart" :ts-req "/cart" :ts-trigger "load"} "Cart"]))) (defn BuyResult [opts] (hi/html [:a.btn.btn-primary {:href "/cart"} "Cart"] (HeaderCart {:count (:count opts)}))) (defn Buy [id] (hi/html [:form {:method "post" :action "/cart/add" :ts-req ""} [:input {:type "hidden" :name "id" :value id}] [:button.btn.btn-primary "Buy"]])) (defn RemoveResult [opts] (hi/html [:button.btn.btn-primary {:disabled true :ts-trigger "load" :ts-action "target 'parent .product', class+ fade, wait transitionend, remove"} "Remove"] (HeaderCart {:count (:count opts)}))) (defn Remove [id] (hi/html [:form {:method "post" :action "/cart/add" :ts-req "" :ts-req-method "delete"} [:input {:type "hidden" :name "_method" :value "delete"}] [:input {:type "hidden" :name "id" :value id}] [:button.btn.btn-primary "Remove"]]))
null
https://raw.githubusercontent.com/piranha/ecomspark/17de72141d9620b25aa9fe2286b503a104a476a3/src/ecomspark/views/cart.clj
clojure
(ns ecomspark.views.cart (:require [hiccup.core :as hi])) (defn HeaderCart [opts] (hi/html (if opts [:a#cart.btn.btn-link {:href "/cart" :ts-swap-push "#cart"} (when (pos? (:count opts)) [:span.chip (:count opts)]) "Cart"] [:a#cart.btn.btn-link {:href "/cart" :ts-req "/cart" :ts-trigger "load"} "Cart"]))) (defn BuyResult [opts] (hi/html [:a.btn.btn-primary {:href "/cart"} "Cart"] (HeaderCart {:count (:count opts)}))) (defn Buy [id] (hi/html [:form {:method "post" :action "/cart/add" :ts-req ""} [:input {:type "hidden" :name "id" :value id}] [:button.btn.btn-primary "Buy"]])) (defn RemoveResult [opts] (hi/html [:button.btn.btn-primary {:disabled true :ts-trigger "load" :ts-action "target 'parent .product', class+ fade, wait transitionend, remove"} "Remove"] (HeaderCart {:count (:count opts)}))) (defn Remove [id] (hi/html [:form {:method "post" :action "/cart/add" :ts-req "" :ts-req-method "delete"} [:input {:type "hidden" :name "_method" :value "delete"}] [:input {:type "hidden" :name "id" :value id}] [:button.btn.btn-primary "Remove"]]))
ea0a04e15d79aaf30d1fee3d82a4015bb6cfd5fddd5cb43fd39723cdfe74c08d
whalliburton/academy
phonetic-alphabet.lisp
(in-package :academy) ;; (defparameter *nato-phonetic-alphabet* '((#\a alfa) (#\b bravo) (#\c charlie) (#\d delta) (#\e echo) (#\f foxtrot) (#\g golf) (#\h hotel) (#\i india) (#\j juliet) (#\k kilo) (#\l lima) (#\m mike) (#\n november) (#\o oscar) (#\p papa) (#\q quebec) (#\r romeo) (#\s sierra) (#\t tango) (#\u uniform) (#\v victor) (#\w whiskey) (#\x xray) (#\y yankee) (#\z zulu) (#\1 one) (#\2 two) (#\3 three) (#\4 four) (#\5 five) (#\6 six) (#\7 seven) (#\8 eight) (#\9 nine) (#\0 zero))) (defun string-to-phonetic-alphabet (string) (loop for char across (string-downcase string) collect (or (second (assoc char *nato-phonetic-alphabet* :test #'char=)) (error "Unknown NATO chararacter ~S." char))))
null
https://raw.githubusercontent.com/whalliburton/academy/87a1a13ffbcd60d8553e42e647c59486c761e8cf/phonetic-alphabet.lisp
lisp
(in-package :academy) (defparameter *nato-phonetic-alphabet* '((#\a alfa) (#\b bravo) (#\c charlie) (#\d delta) (#\e echo) (#\f foxtrot) (#\g golf) (#\h hotel) (#\i india) (#\j juliet) (#\k kilo) (#\l lima) (#\m mike) (#\n november) (#\o oscar) (#\p papa) (#\q quebec) (#\r romeo) (#\s sierra) (#\t tango) (#\u uniform) (#\v victor) (#\w whiskey) (#\x xray) (#\y yankee) (#\z zulu) (#\1 one) (#\2 two) (#\3 three) (#\4 four) (#\5 five) (#\6 six) (#\7 seven) (#\8 eight) (#\9 nine) (#\0 zero))) (defun string-to-phonetic-alphabet (string) (loop for char across (string-downcase string) collect (or (second (assoc char *nato-phonetic-alphabet* :test #'char=)) (error "Unknown NATO chararacter ~S." char))))
59c49d1b1186f3ccc7a7c70d5d0fb1f52e725735b744c35d6400f92c9fa913d8
brendanhay/gogol
Auth.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # -- | Module : . Internal . Auth Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < > -- Stability : provisional Portability : non - portable ( GHC extensions ) -- Internal types and helpers for constructing OAuth credentials . module Gogol.Internal.Auth where import Control.Exception (Exception, SomeException, catch, throwIO) import Control.Exception.Lens (exception) import Control.Lens (Prism', prism) import Control.Monad.IO.Class (MonadIO (..)) import Crypto.PubKey.RSA.Types (PrivateKey) import Data.Aeson import Data.Aeson.Types (Pair) import Data.ByteArray (ByteArray) import Data.ByteArray.Encoding import Data.ByteString.Builder () import qualified Data.ByteString.Lazy as LBS import Data.String (IsString) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Time import Data.X509 (PrivKey (..)) import Data.X509.Memory (readKeyFileFromMemory) import GHC.TypeLits (Symbol) import Gogol.Internal.Logger import Gogol.Prelude import Network.HTTP.Conduit (HttpException, Manager) import qualified Network.HTTP.Conduit as Client import Network.HTTP.Types (Status, hContentType) -- | The supported credential mechanisms. data Credentials (s :: [Symbol]) | Obtain and refresh access tokens from the underlying GCE host metadata -- at @http:\/\/169.254.169.254@. FromMetadata !ServiceId | -- | Obtain and refresh access tokens using the specified client secret -- and authorization code obtained from. -- -- See the < OAuth2 Installed Application> -- documentation for more information. FromClient !OAuthClient !(OAuthCode s) | Use the specified @service_account@ and scopes to sign and request -- an access token. The 'ServiceAccount' will also be used for subsequent -- token refreshes. -- -- A 'ServiceAccount' is typically generated through the Google Developer Console . FromAccount !ServiceAccount | -- | Use the specified @authorized_user@ to obtain and refresh access tokens. -- An ' AuthorizedUser ' is typically created by the init@ command of the Google CloudSDK Tools . FromUser !AuthorizedUser | FromTokenFile !FilePath -- | Service Account credentials which are typically generated/download from the Google Developer console of the following form : -- -- > { -- > \"type\": \"service_account\", -- > \"private_key_id\": \"303ad77e5efdf2ce952DFa\", -- > \"private_key\": \"-----BEGIN PRIVATE KEY-----\n...\n\", > \"client_email\ " : \"\ " , > \"client_id\ " : \"035 - 2 - 310.useraccount.com\ " -- > } -- The private key is used to sign a JSON Web Token ( JWT ) of the grant_type @urn : ietf : params : oauth : grant - type : jwt - bearer@ , which is sent to -- 'accountsURL' to obtain a valid 'OAuthToken'. This process requires explicitly specifying which ' Scope 's the resulting ' OAuthToken ' is authorized to access . -- -- /See:/ <#delegatingauthority Delegating authority to your service account>. data ServiceAccount = ServiceAccount { _serviceId :: !ClientId, _serviceEmail :: !Text, _serviceKeyId :: !Text, _servicePrivateKey :: !PrivateKey, _serviceAccountUser :: !(Maybe Text) } deriving (Eq, Show) instance FromJSON ServiceAccount where parseJSON = withObject "service_account" $ \o -> do bs <- Text.encodeUtf8 <$> o .: "private_key" k <- case listToMaybe (readKeyFileFromMemory bs) of Just (PrivKeyRSA k) -> pure k _ -> fail "Unable to parse key contents from \"private_key\"" ServiceAccount <$> o .: "client_id" <*> o .: "client_email" <*> o .: "private_key_id" <*> pure k <*> pure Nothing | Authorized User credentials which are typically generated by the Cloud SDK Tools such as init@ , of the following form : -- -- > { -- > \"type\": \"authorized_user\", -- > \"client_id\": \"32555940559.apps.googleusercontent.com\", > \"client_secret\ " : \"Zms2qjJy2998hD4CTg2ejr2\ " , -- > \"refresh_token\": \"1/B3gM1x35v.VtqffS1n5w-rSJ\" -- > } -- -- The secret and refresh token are used to obtain a valid 'OAuthToken' from ' accountsURL ' using grant_type @refresh_token@. data AuthorizedUser = AuthorizedUser { _userId :: !ClientId, _userRefresh :: !RefreshToken, _userSecret :: !GSecret } deriving (Eq, Show) instance ToJSON AuthorizedUser where toJSON (AuthorizedUser i r s) = object [ "client_id" .= i, "refresh_token" .= r, "client_secret" .= s ] instance FromJSON AuthorizedUser where parseJSON = withObject "authorized_user" $ \o -> AuthorizedUser <$> o .: "client_id" <*> o .: "refresh_token" <*> o .: "client_secret" -- | A client identifier and accompanying secret used to obtain/refresh a token. data OAuthClient = OAuthClient { _clientId :: !ClientId, _clientSecret :: !GSecret } deriving (Eq, Show) -- | An OAuth bearer type token of the following form: -- -- > { -- > \"token_type\": \"Bearer\", > \"access_token\ " : \"eyJhbGci ... \ " , -- > \"refresh_token\": \"1/B3gq9K...\", > \"expires_in\ " : 3600 , -- > ... -- > } -- -- The '_tokenAccess' field will be inserted verbatim into the -- @Authorization: Bearer ...@ header for all HTTP requests. data OAuthToken (s :: [Symbol]) = OAuthToken { _tokenAccess :: !AccessToken, _tokenRefresh :: !(Maybe RefreshToken), _tokenExpiry :: !UTCTime } deriving (Eq, Show) instance FromJSON (UTCTime -> OAuthToken s) where parseJSON = withObject "bearer" $ \o -> do t <- o .: "access_token" r <- o .:? "refresh_token" e <- o .: "expires_in" <&> fromInteger pure (OAuthToken t r . addUTCTime e) | An OAuth client authorization code . newtype OAuthCode (s :: [Symbol]) = OAuthCode Text deriving (Eq, Ord, Show, Read, IsString, Generic, Typeable, FromJSON, ToJSON) instance ToHttpApiData (OAuthCode s) where toQueryParam (OAuthCode c) = c toHeader (OAuthCode c) = Text.encodeUtf8 c -- | An error thrown when attempting to read/write AuthN/AuthZ information. data AuthError = RetrievalError HttpException | MissingFileError FilePath | InvalidFileError FilePath Text | TokenRefreshError Status Text (Maybe Text) | FileExistError FilePath deriving (Show, Typeable) instance Exception AuthError class AsAuthError a where -- | A general authentication error. _AuthError :: Prism' a AuthError {-# MINIMAL _AuthError #-} -- | An error occured while communicating over HTTP with either then -- local metadata or remote accounts.google.com endpoints. _RetrievalError :: Prism' a HttpException -- | The specified default credentials file could not be found. _MissingFileError :: Prism' a FilePath -- | An error occured parsing the default credentials file. _InvalidFileError :: Prism' a (FilePath, Text) -- | An error occured when attempting to refresh a token. _TokenRefreshError :: Prism' a (Status, Text, Maybe Text) _RetrievalError = _AuthError . _RetrievalError _MissingFileError = _AuthError . _MissingFileError _InvalidFileError = _AuthError . _InvalidFileError _TokenRefreshError = _AuthError . _TokenRefreshError instance AsAuthError SomeException where _AuthError = exception instance AsAuthError AuthError where _AuthError = id _RetrievalError = prism RetrievalError $ \case RetrievalError e -> Right e x -> Left x _MissingFileError = prism MissingFileError $ \case MissingFileError f -> Right f x -> Left x _InvalidFileError = prism (uncurry InvalidFileError) ( \case InvalidFileError f e -> Right (f, e) x -> Left x ) _TokenRefreshError = prism (\(s, e, d) -> TokenRefreshError s e d) ( \case TokenRefreshError s e d -> Right (s, e, d) x -> Left x ) data RefreshError = RefreshError { _error :: !Text, _description :: !(Maybe Text) } instance FromJSON RefreshError where parseJSON = withObject "refresh_error" $ \o -> RefreshError <$> o .: "error" <*> o .:? "error_description" -- | @@. accountsURL :: Text accountsURL = "" accountsRequest :: Client.Request accountsRequest = Client.defaultRequest { Client.host = "accounts.google.com", Client.port = 443, Client.secure = True, Client.method = "POST", Client.path = "/o/oauth2/v2/auth", Client.requestHeaders = [ (hContentType, "application/x-www-form-urlencoded") ] } | @ / / v4 / token@. tokenURL :: Text tokenURL = "" tokenRequest :: Client.Request tokenRequest = Client.defaultRequest { Client.host = "www.googleapis.com", Client.port = 443, Client.secure = True, Client.method = "POST", Client.path = "/oauth2/v4/token", Client.requestHeaders = [ (hContentType, "application/x-www-form-urlencoded") ] } refreshRequest :: MonadIO m => Client.Request -> Logger -> Manager -> m (OAuthToken s) refreshRequest rq l m = do logDebug l rq -- debug:ClientRequest rs <- liftIO (Client.httpLbs rq m `catch` (throwIO . RetrievalError)) let bs = Client.responseBody rs s = Client.responseStatus rs logDebug l rs -- debug:ClientResponse trace : ResponseBody if fromEnum s == 200 then success s bs else failure s bs where success s bs = do f <- parseErr s bs ts <- liftIO getCurrentTime pure (f ts) failure s bs = do let e = "Failure refreshing token from " <> host <> path logError l $ "[Refresh Error] " <> build e case parseLBS bs of Right x -> refreshErr s (_error x) (_description x) Left _ -> refreshErr s e Nothing parseErr s bs = case parseLBS bs of Right !x -> pure x Left e -> do logError l $ "[Parse Error] Failure parsing token refresh " <> build e refreshErr s e Nothing refreshErr :: MonadIO m => Status -> Text -> Maybe Text -> m a refreshErr s e = liftIO . throwIO . TokenRefreshError s e host = Text.decodeUtf8 (Client.host rq) path = Text.decodeUtf8 (Client.path rq) parseLBS :: FromJSON a => LBS.ByteString -> Either Text a parseLBS = either (Left . Text.pack) Right . eitherDecode' base64Encode :: [Pair] -> ByteString base64Encode = base64 . LBS.toStrict . encode . object base64 :: ByteArray a => a -> ByteString base64 = convertToBase Base64URLUnpadded textBody :: Text -> RequestBody textBody = Client.RequestBodyBS . Text.encodeUtf8
null
https://raw.githubusercontent.com/brendanhay/gogol/8cbceeaaba36a3c08712b2e272606161500fbe91/lib/gogol/src/Gogol/Internal/Auth.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE OverloadedStrings # | Stability : provisional | The supported credential mechanisms. at @http:\/\/169.254.169.254@. | Obtain and refresh access tokens using the specified client secret and authorization code obtained from. See the < OAuth2 Installed Application> documentation for more information. an access token. The 'ServiceAccount' will also be used for subsequent token refreshes. A 'ServiceAccount' is typically generated through the | Use the specified @authorized_user@ to obtain and refresh access tokens. | Service Account credentials which are typically generated/download > { > \"type\": \"service_account\", > \"private_key_id\": \"303ad77e5efdf2ce952DFa\", > \"private_key\": \"-----BEGIN PRIVATE KEY-----\n...\n\", > } 'accountsURL' to obtain a valid 'OAuthToken'. This process requires explicitly /See:/ <#delegatingauthority Delegating authority to your service account>. > { > \"type\": \"authorized_user\", > \"client_id\": \"32555940559.apps.googleusercontent.com\", > \"refresh_token\": \"1/B3gM1x35v.VtqffS1n5w-rSJ\" > } The secret and refresh token are used to obtain a valid 'OAuthToken' from | A client identifier and accompanying secret used to obtain/refresh a token. | An OAuth bearer type token of the following form: > { > \"token_type\": \"Bearer\", > \"refresh_token\": \"1/B3gq9K...\", > ... > } The '_tokenAccess' field will be inserted verbatim into the @Authorization: Bearer ...@ header for all HTTP requests. | An error thrown when attempting to read/write AuthN/AuthZ information. | A general authentication error. # MINIMAL _AuthError # | An error occured while communicating over HTTP with either then local metadata or remote accounts.google.com endpoints. | The specified default credentials file could not be found. | An error occured parsing the default credentials file. | An error occured when attempting to refresh a token. | @@. debug:ClientRequest debug:ClientResponse
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # Module : . Internal . Auth Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < > Portability : non - portable ( GHC extensions ) Internal types and helpers for constructing OAuth credentials . module Gogol.Internal.Auth where import Control.Exception (Exception, SomeException, catch, throwIO) import Control.Exception.Lens (exception) import Control.Lens (Prism', prism) import Control.Monad.IO.Class (MonadIO (..)) import Crypto.PubKey.RSA.Types (PrivateKey) import Data.Aeson import Data.Aeson.Types (Pair) import Data.ByteArray (ByteArray) import Data.ByteArray.Encoding import Data.ByteString.Builder () import qualified Data.ByteString.Lazy as LBS import Data.String (IsString) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Time import Data.X509 (PrivKey (..)) import Data.X509.Memory (readKeyFileFromMemory) import GHC.TypeLits (Symbol) import Gogol.Internal.Logger import Gogol.Prelude import Network.HTTP.Conduit (HttpException, Manager) import qualified Network.HTTP.Conduit as Client import Network.HTTP.Types (Status, hContentType) data Credentials (s :: [Symbol]) | Obtain and refresh access tokens from the underlying GCE host metadata FromMetadata !ServiceId FromClient !OAuthClient !(OAuthCode s) | Use the specified @service_account@ and scopes to sign and request Google Developer Console . FromAccount !ServiceAccount An ' AuthorizedUser ' is typically created by the init@ command of the Google CloudSDK Tools . FromUser !AuthorizedUser | FromTokenFile !FilePath from the Google Developer console of the following form : > \"client_email\ " : \"\ " , > \"client_id\ " : \"035 - 2 - 310.useraccount.com\ " The private key is used to sign a JSON Web Token ( JWT ) of the grant_type @urn : ietf : params : oauth : grant - type : jwt - bearer@ , which is sent to specifying which ' Scope 's the resulting ' OAuthToken ' is authorized to access . data ServiceAccount = ServiceAccount { _serviceId :: !ClientId, _serviceEmail :: !Text, _serviceKeyId :: !Text, _servicePrivateKey :: !PrivateKey, _serviceAccountUser :: !(Maybe Text) } deriving (Eq, Show) instance FromJSON ServiceAccount where parseJSON = withObject "service_account" $ \o -> do bs <- Text.encodeUtf8 <$> o .: "private_key" k <- case listToMaybe (readKeyFileFromMemory bs) of Just (PrivKeyRSA k) -> pure k _ -> fail "Unable to parse key contents from \"private_key\"" ServiceAccount <$> o .: "client_id" <*> o .: "client_email" <*> o .: "private_key_id" <*> pure k <*> pure Nothing | Authorized User credentials which are typically generated by the Cloud SDK Tools such as init@ , of the following form : > \"client_secret\ " : \"Zms2qjJy2998hD4CTg2ejr2\ " , ' accountsURL ' using grant_type @refresh_token@. data AuthorizedUser = AuthorizedUser { _userId :: !ClientId, _userRefresh :: !RefreshToken, _userSecret :: !GSecret } deriving (Eq, Show) instance ToJSON AuthorizedUser where toJSON (AuthorizedUser i r s) = object [ "client_id" .= i, "refresh_token" .= r, "client_secret" .= s ] instance FromJSON AuthorizedUser where parseJSON = withObject "authorized_user" $ \o -> AuthorizedUser <$> o .: "client_id" <*> o .: "refresh_token" <*> o .: "client_secret" data OAuthClient = OAuthClient { _clientId :: !ClientId, _clientSecret :: !GSecret } deriving (Eq, Show) > \"access_token\ " : \"eyJhbGci ... \ " , > \"expires_in\ " : 3600 , data OAuthToken (s :: [Symbol]) = OAuthToken { _tokenAccess :: !AccessToken, _tokenRefresh :: !(Maybe RefreshToken), _tokenExpiry :: !UTCTime } deriving (Eq, Show) instance FromJSON (UTCTime -> OAuthToken s) where parseJSON = withObject "bearer" $ \o -> do t <- o .: "access_token" r <- o .:? "refresh_token" e <- o .: "expires_in" <&> fromInteger pure (OAuthToken t r . addUTCTime e) | An OAuth client authorization code . newtype OAuthCode (s :: [Symbol]) = OAuthCode Text deriving (Eq, Ord, Show, Read, IsString, Generic, Typeable, FromJSON, ToJSON) instance ToHttpApiData (OAuthCode s) where toQueryParam (OAuthCode c) = c toHeader (OAuthCode c) = Text.encodeUtf8 c data AuthError = RetrievalError HttpException | MissingFileError FilePath | InvalidFileError FilePath Text | TokenRefreshError Status Text (Maybe Text) | FileExistError FilePath deriving (Show, Typeable) instance Exception AuthError class AsAuthError a where _AuthError :: Prism' a AuthError _RetrievalError :: Prism' a HttpException _MissingFileError :: Prism' a FilePath _InvalidFileError :: Prism' a (FilePath, Text) _TokenRefreshError :: Prism' a (Status, Text, Maybe Text) _RetrievalError = _AuthError . _RetrievalError _MissingFileError = _AuthError . _MissingFileError _InvalidFileError = _AuthError . _InvalidFileError _TokenRefreshError = _AuthError . _TokenRefreshError instance AsAuthError SomeException where _AuthError = exception instance AsAuthError AuthError where _AuthError = id _RetrievalError = prism RetrievalError $ \case RetrievalError e -> Right e x -> Left x _MissingFileError = prism MissingFileError $ \case MissingFileError f -> Right f x -> Left x _InvalidFileError = prism (uncurry InvalidFileError) ( \case InvalidFileError f e -> Right (f, e) x -> Left x ) _TokenRefreshError = prism (\(s, e, d) -> TokenRefreshError s e d) ( \case TokenRefreshError s e d -> Right (s, e, d) x -> Left x ) data RefreshError = RefreshError { _error :: !Text, _description :: !(Maybe Text) } instance FromJSON RefreshError where parseJSON = withObject "refresh_error" $ \o -> RefreshError <$> o .: "error" <*> o .:? "error_description" accountsURL :: Text accountsURL = "" accountsRequest :: Client.Request accountsRequest = Client.defaultRequest { Client.host = "accounts.google.com", Client.port = 443, Client.secure = True, Client.method = "POST", Client.path = "/o/oauth2/v2/auth", Client.requestHeaders = [ (hContentType, "application/x-www-form-urlencoded") ] } | @ / / v4 / token@. tokenURL :: Text tokenURL = "" tokenRequest :: Client.Request tokenRequest = Client.defaultRequest { Client.host = "www.googleapis.com", Client.port = 443, Client.secure = True, Client.method = "POST", Client.path = "/oauth2/v4/token", Client.requestHeaders = [ (hContentType, "application/x-www-form-urlencoded") ] } refreshRequest :: MonadIO m => Client.Request -> Logger -> Manager -> m (OAuthToken s) refreshRequest rq l m = do rs <- liftIO (Client.httpLbs rq m `catch` (throwIO . RetrievalError)) let bs = Client.responseBody rs s = Client.responseStatus rs trace : ResponseBody if fromEnum s == 200 then success s bs else failure s bs where success s bs = do f <- parseErr s bs ts <- liftIO getCurrentTime pure (f ts) failure s bs = do let e = "Failure refreshing token from " <> host <> path logError l $ "[Refresh Error] " <> build e case parseLBS bs of Right x -> refreshErr s (_error x) (_description x) Left _ -> refreshErr s e Nothing parseErr s bs = case parseLBS bs of Right !x -> pure x Left e -> do logError l $ "[Parse Error] Failure parsing token refresh " <> build e refreshErr s e Nothing refreshErr :: MonadIO m => Status -> Text -> Maybe Text -> m a refreshErr s e = liftIO . throwIO . TokenRefreshError s e host = Text.decodeUtf8 (Client.host rq) path = Text.decodeUtf8 (Client.path rq) parseLBS :: FromJSON a => LBS.ByteString -> Either Text a parseLBS = either (Left . Text.pack) Right . eitherDecode' base64Encode :: [Pair] -> ByteString base64Encode = base64 . LBS.toStrict . encode . object base64 :: ByteArray a => a -> ByteString base64 = convertToBase Base64URLUnpadded textBody :: Text -> RequestBody textBody = Client.RequestBodyBS . Text.encodeUtf8
5b1ad281117fb168bb90de4de67efe4a0c38be30da1b54a1595aec93d729c8d4
sneerteam/sneer
invite_test.clj
(ns sneer.invite-test [:require [midje.sweet :refer [facts fact]] [sneer.midje-util :refer :all] [sneer.network-sim :as net] [sneer.sneer-test-util :refer :all] [sneer.core2 :refer :all] [sneer.streem :refer :all]]) (facts "Invite" (let [network (net/network-sim) neide-ui (atom nil) carla-ui (atom nil) neide (join network "Neide da Silva" #(reset! neide-ui %)) carla (join network "Carla Costa" #(reset! carla-ui %))] (handle! neide {:type :contact-new, :nick "Carla"}) (let [n->c-id (get-in @neide-ui [:convo-list 0 :contact-id]) _ (handle! neide {:type :view, :path [:convo n->c-id]}) invite (get-in @neide-ui [:convo :invite])] (fact "Invite appears in convo-list and convo" invite => some? (get-in @neide-ui [:convo-list 0 :invite]) => invite) (fact "Invite disappears on sender's side after being accepted by receiver" (handle! carla {:type :contact-invite-accept :invite invite}) (get-in @neide-ui [:convo :invite]) => nil (get-in @neide-ui [:convo-list 0 :invite]) => nil) (fact "Inviter's name appears as contact nick" (get-in @carla-ui [:convo-list 0 :nick]) => "Neide da Silva"))) " TODO " = > " Duplicate nicks not allowed " " TODO " = > " Duplicate not allowed " )
null
https://raw.githubusercontent.com/sneerteam/sneer/b093c46321a5a42ae9418df427dbb237489b7bcb/core2/test/sneer/invite_test.clj
clojure
(ns sneer.invite-test [:require [midje.sweet :refer [facts fact]] [sneer.midje-util :refer :all] [sneer.network-sim :as net] [sneer.sneer-test-util :refer :all] [sneer.core2 :refer :all] [sneer.streem :refer :all]]) (facts "Invite" (let [network (net/network-sim) neide-ui (atom nil) carla-ui (atom nil) neide (join network "Neide da Silva" #(reset! neide-ui %)) carla (join network "Carla Costa" #(reset! carla-ui %))] (handle! neide {:type :contact-new, :nick "Carla"}) (let [n->c-id (get-in @neide-ui [:convo-list 0 :contact-id]) _ (handle! neide {:type :view, :path [:convo n->c-id]}) invite (get-in @neide-ui [:convo :invite])] (fact "Invite appears in convo-list and convo" invite => some? (get-in @neide-ui [:convo-list 0 :invite]) => invite) (fact "Invite disappears on sender's side after being accepted by receiver" (handle! carla {:type :contact-invite-accept :invite invite}) (get-in @neide-ui [:convo :invite]) => nil (get-in @neide-ui [:convo-list 0 :invite]) => nil) (fact "Inviter's name appears as contact nick" (get-in @carla-ui [:convo-list 0 :nick]) => "Neide da Silva"))) " TODO " = > " Duplicate nicks not allowed " " TODO " = > " Duplicate not allowed " )
bab929159ed644dc4e839f5c60b742744a5c8dfa1e26b986d7bc1e8f63d288fe
fgalassi/cs61a-sp11
assert.scm
(define (assert comparison actual expected msg) (if (not (comparison actual expected)) (display (format #f "ERROR! ~S: actual ~A expected ~A\n" msg actual expected))))
null
https://raw.githubusercontent.com/fgalassi/cs61a-sp11/66df3b54b03ee27f368c716ae314fd7ed85c4dba/projects/blackjack/normal/assert.scm
scheme
(define (assert comparison actual expected msg) (if (not (comparison actual expected)) (display (format #f "ERROR! ~S: actual ~A expected ~A\n" msg actual expected))))
76197838c5746270e681d052e44ecbf283ff2230fbc02de4c0b626be0cb8bdc1
bobzhang/ocaml-book
test_pa_abstract.ml
type t = semi opaque int (** camlp4o -I _build pa_abstract.cmo test_pa_abstract.ml -abstract -printer o type t ocamlbuild -pp 'camlp4o -I _build pa_abstract.cmo -abstract ' test_pa_abstract.cmo *)
null
https://raw.githubusercontent.com/bobzhang/ocaml-book/09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75/camlp4/examples/test_pa_abstract.ml
ocaml
* camlp4o -I _build pa_abstract.cmo test_pa_abstract.ml -abstract -printer o type t ocamlbuild -pp 'camlp4o -I _build pa_abstract.cmo -abstract ' test_pa_abstract.cmo
type t = semi opaque int
82e29e2c5be2ccc7c65aa3d9790c0d1bc948791f667d02554fd8f930e8d900fb
unclebob/AdventOfCode2021
core_spec.clj
(ns day8.core-spec (:require [speclj.core :refer :all] [day8.core :refer :all])) (describe "parse input" (it "parses a line" (should= [["acedgfb" "cdfbe" "gcdfa" "fbcad" "dab" "cefabd" "cdfgeb" "eafb" "cagedb" "ab"] ["cdfeb" "fcadb" "cdfeb" "cdbaf"]] (parse-line "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"))) (it "parses several lines" (should= [ [["be" "cfbegad" "cbdgef" "fgaecd" "cgeb" "fdcge" "agebfd" "fecdb" "fabcd" "edb"] ["fdgacbe" "cefdb" "cefbgd" "gcbe"]] [["edbfga" "begcd" "cbg" "gc" "gcadebf" "fbgde" "acbgfd" "abcde" "gfcbed" "gfec"] ["fcgedb" "cgb" "dgebacf" "gc"]]] (parse-input (str "be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe\n" "edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc\n"))) ) ) (def test-data [["acedgfb" "cdfbe" "gcdfa" "fbcad" "dab" "cefabd" "cdfgeb" "eafb" "cagedb" "ab"] ["cdfeb" "fcadb" "cdfeb" "cdbaf"]]) (def test-digits (first test-data)) (describe "utilities" (it "counts unique digits in empty display" (should= 0 (count-unique []))) (it "counts 1, 4, 7, and 8" (should= 4 (count-unique ["11" "4444" "777" "8888888" "22222"])) ) (it "should translate counts to digits" (should= 1 (to-digit 2)) (should= 4 (to-digit 4)) (should= 7 (to-digit 3)) (should= 8 (to-digit 7)) (should= nil (to-digit 1))) (it "should propose segments" (should= nil (propose-outputs-for-signals "abcdef")) (should= [[\q #{\C \F}] [\r #{\C \F}]] (propose-outputs-for-signals "qr"))) (it "should determine possible outputs" (should= {\a #{\C \F} \b #{\C \F} \c #{\A \B \C \D \E \F \G} \d #{\A \C \F} \e #{\B \C \D \F} \f #{\B \C \D \F} \g #{\A \B \C \D \E \F \G}} (possible-outputs test-digits))) (it "should determine digit signal map" (should= {4 #{\a \b \e \f}, 1 #{\a \b}, 7 #{\a \b \d}} (signals-for-obvious-digits test-digits))) (it "will find signals for digits of length n" (should= [#{\a \b \d}] (signals-for-length 3 test-digits)) (should= [#{\a \b \c \d \e \f} #{\b \c \d \e \f \g} #{\a \b \c \d \e \g}] (signals-for-length 6 test-digits))) (it "will map signals to outputs" (should= {\d \A, \a \C, \b \F, \c \G, \f \D, \e \B, \g \E} (map-signals-to-outputs test-digits))) (it "will map output sets to digits" (let [signal-map (map-signals-to-outputs test-digits)] (should= 0 (outputs-to-digits signal-map "abcged")) (should= 1 (outputs-to-digits signal-map "ab")) (should= 2 (outputs-to-digits signal-map "dafgc")) (should= 3 (outputs-to-digits signal-map "dafbc")) )) (it "will translate a display" (should= 5353 (translate-display test-data))) ) (def sample (str "be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe\n" "edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc\n" "fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg\n" "fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb\n" "aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea\n" "fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb\n" "dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe\n" "bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef\n" "egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb\n" "gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce\n")) (describe "solutions" (context "part 1" (it "should solve sample" (should= 26 (solve-1 sample))) (it "should solve problem" (should= 390 (solve-1 (slurp "input")))) ) (context "part 2" (it "should solve sample" (should= 61229 (solve-2 sample))) (it "should solve problem" (should= 1011785 (solve-2 (slurp "input")))) ) )
null
https://raw.githubusercontent.com/unclebob/AdventOfCode2021/df4b2c1bc7a2c724a95740ea2cba34fdc81476a4/day8/spec/day8/core_spec.clj
clojure
(ns day8.core-spec (:require [speclj.core :refer :all] [day8.core :refer :all])) (describe "parse input" (it "parses a line" (should= [["acedgfb" "cdfbe" "gcdfa" "fbcad" "dab" "cefabd" "cdfgeb" "eafb" "cagedb" "ab"] ["cdfeb" "fcadb" "cdfeb" "cdbaf"]] (parse-line "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"))) (it "parses several lines" (should= [ [["be" "cfbegad" "cbdgef" "fgaecd" "cgeb" "fdcge" "agebfd" "fecdb" "fabcd" "edb"] ["fdgacbe" "cefdb" "cefbgd" "gcbe"]] [["edbfga" "begcd" "cbg" "gc" "gcadebf" "fbgde" "acbgfd" "abcde" "gfcbed" "gfec"] ["fcgedb" "cgb" "dgebacf" "gc"]]] (parse-input (str "be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe\n" "edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc\n"))) ) ) (def test-data [["acedgfb" "cdfbe" "gcdfa" "fbcad" "dab" "cefabd" "cdfgeb" "eafb" "cagedb" "ab"] ["cdfeb" "fcadb" "cdfeb" "cdbaf"]]) (def test-digits (first test-data)) (describe "utilities" (it "counts unique digits in empty display" (should= 0 (count-unique []))) (it "counts 1, 4, 7, and 8" (should= 4 (count-unique ["11" "4444" "777" "8888888" "22222"])) ) (it "should translate counts to digits" (should= 1 (to-digit 2)) (should= 4 (to-digit 4)) (should= 7 (to-digit 3)) (should= 8 (to-digit 7)) (should= nil (to-digit 1))) (it "should propose segments" (should= nil (propose-outputs-for-signals "abcdef")) (should= [[\q #{\C \F}] [\r #{\C \F}]] (propose-outputs-for-signals "qr"))) (it "should determine possible outputs" (should= {\a #{\C \F} \b #{\C \F} \c #{\A \B \C \D \E \F \G} \d #{\A \C \F} \e #{\B \C \D \F} \f #{\B \C \D \F} \g #{\A \B \C \D \E \F \G}} (possible-outputs test-digits))) (it "should determine digit signal map" (should= {4 #{\a \b \e \f}, 1 #{\a \b}, 7 #{\a \b \d}} (signals-for-obvious-digits test-digits))) (it "will find signals for digits of length n" (should= [#{\a \b \d}] (signals-for-length 3 test-digits)) (should= [#{\a \b \c \d \e \f} #{\b \c \d \e \f \g} #{\a \b \c \d \e \g}] (signals-for-length 6 test-digits))) (it "will map signals to outputs" (should= {\d \A, \a \C, \b \F, \c \G, \f \D, \e \B, \g \E} (map-signals-to-outputs test-digits))) (it "will map output sets to digits" (let [signal-map (map-signals-to-outputs test-digits)] (should= 0 (outputs-to-digits signal-map "abcged")) (should= 1 (outputs-to-digits signal-map "ab")) (should= 2 (outputs-to-digits signal-map "dafgc")) (should= 3 (outputs-to-digits signal-map "dafbc")) )) (it "will translate a display" (should= 5353 (translate-display test-data))) ) (def sample (str "be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe\n" "edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc\n" "fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg\n" "fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb\n" "aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea\n" "fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb\n" "dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe\n" "bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef\n" "egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb\n" "gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce\n")) (describe "solutions" (context "part 1" (it "should solve sample" (should= 26 (solve-1 sample))) (it "should solve problem" (should= 390 (solve-1 (slurp "input")))) ) (context "part 2" (it "should solve sample" (should= 61229 (solve-2 sample))) (it "should solve problem" (should= 1011785 (solve-2 (slurp "input")))) ) )
1d1db979fef154ed20970052226260a369c0170e66348a06860c46995c2a300a
static-analysis-engineering/codehawk
cHCilSumTypeSerializer.ml
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk C Analyzer Parser using CIL Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2019 Kestrel Technology LLC Copyright ( c ) 2020 - 2021 ) 2022 Aarno Labs LLC Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk C Analyzer Parser using CIL Author: Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2019 Kestrel Technology LLC Copyright (c) 2020-2021 Henny Sipma Copyright (c) 2022 Aarno Labs LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) (* cil *) open Cil chlib open CHCommon open CHPretty (* chutil *) open CHPrettyUtil open CHSumTypeSerializer module H = Hashtbl let ikind_mfts: ikind mfts_int = mk_mfts "ikind_t" [(IChar, "ichar"); (ISChar, "ischar"); (IUChar, "iuchar"); (IBool, "ibool"); (IInt, "iint"); (IUInt, "iuint"); (IShort, "ishort"); (IUShort, "iushort"); (ILong, "ilong"); (IULong, "iulong"); (ILongLong, "ilonglong"); (IULongLong, "iulonglong"); (IInt128, "int128_t"); (IUInt128, "uint128_t")] let fkind_mfts: fkind mfts_int = mk_mfts "fkind_t" [(FFloat, "float"); (FDouble, "fdouble"); (FLongDouble, "flongdouble"); (FComplexFloat, "fcomplexfloat"); (FComplexDouble, "fcomplexdouble"); (FComplexLongDouble, "fcomplexlongdouble")] let unop_mfts: unop mfts_int = mk_mfts "unop_t" [(Neg, "neg"); (BNot, "bnot"); (LNot, "lnot")] let binop_mfts: binop mfts_int = mk_mfts "binop_t" [(PlusA, "plusa"); (PlusPI, "pluspi"); (IndexPI, "indexpi"); (MinusA, "minusa"); (MinusPI, "minuspi"); (MinusPP, "minuspp"); (Mult, "mult"); (Div, "div"); (Mod, "mod"); (Shiftlt, "shiftlt"); (Shiftrt, "shiftrt"); (Lt, "lt"); (Gt, "gt"); (Le, "le"); (Ge, "ge"); (Eq, "eq"); (Ne, "ne"); (BAnd, "band"); (BXor, "bxor"); (BOr, "bor"); (LAnd, "land"); (LOr, "lor")] let storage_mfts: storage mfts_int = mk_mfts "storage_t" [(NoStorage,"n"); (Static,"s"); (Register,"r"); (Extern,"x")] class typ_mcts_t:[typ] mfts_int = object inherit [typ] mcts_t "typ" method ts (t: typ) = match t with | TVoid _ -> "tvoid" | TInt _ -> "tint" | TFloat _ -> "tfloat" | TPtr _ -> "tptr" | TArray _ -> "tarray" | TFun _ -> "tfun" | TNamed _ -> "tnamed" | TComp _ -> "tcomp" | TEnum _ -> "tenum" | TBuiltin_va_list _ -> "tbuiltin-va-list" method tags = [ "tarray"; "tbuiltin-va-list"; "tcomp"; "tenum"; "tfloat"; "tfun"; "tint"; "tnamed"; "tptr"; "tvoid"] end let typ_mcts: typ mfts_int = new typ_mcts_t class exp_mcts_t:[exp] mfts_int = object inherit [exp] mcts_t "exp" method ts (e: exp) = match e with | Const _ -> "const" | Lval _ -> "lval" | SizeOf _ -> "sizeof" | Real _ -> "real" | Imag _ -> "imag" | SizeOfE _ -> "sizeofe" | SizeOfStr _ -> "sizeofstr" | AlignOf _ -> "alignof" | AlignOfE _ -> "alignofe" | UnOp _ -> "unop" | BinOp _ -> "binop" | Question _ -> "question" | CastE _ -> "caste" | AddrOf _ -> "addrof" | AddrOfLabel _ -> "addroflabel" | StartOf _ -> "startof" method tags = [ "addrof"; "addroflabel"; "alignof"; "alignofe"; "binop"; "caste"; "const"; "lval"; "question"; "sizeof"; "sizeofe"; "startof"; "unop"] end let exp_mcts: exp mfts_int = new exp_mcts_t class attrparam_mcts_t:[attrparam] mfts_int = object inherit [attrparam] mcts_t "attrparam" method ts (a: attrparam) = match a with | AInt _ -> "aint" | AStr _ -> "astr" | ACons _ -> "acons" | ASizeOf _ -> "asizeof" | ASizeOfE _ -> "asizeofe" | ASizeOfS _ -> "asizeofs" | AAlignOf _ -> "aalignof" | AAlignOfE _ -> "aalignofe" | AAlignOfS _ -> "aalignofs" | AUnOp _ -> "aunop" | ABinOp _ -> "abinop" | ADot _ -> "adot" | AStar _ -> "astar" | AAddrOf _ -> "aaddrof" | AIndex _ -> "aindex" | AQuestion _ -> "aquestion" method tags = [ "aaddrof"; "aalignof"; "aalignofe"; "aalignofs"; "abinop"; "acons"; "adot"; "aindex"; "aint"; "aquestion"; "asizeof"; "asizeofe"; "asizeofs"; "astar"; "astr"; "aunop"] end let attrparam_mcts: attrparam mfts_int = new attrparam_mcts_t class constant_mcts_t:[constant] mfts_int = object inherit [constant] mcts_t "constant" method ts (c: constant) = match c with | CInt64 _ -> "int" | CStr _ -> "str" | CWStr _ -> "wstr" | CChr _ -> "chr" | CReal _ -> "real" | CEnum _ -> "enum" method tags = ["chr"; "enum"; "int"; "real"; "str"; "wstr"] end let constant_mcts: constant mfts_int = new constant_mcts_t class offset_mcts_t: [offset] mfts_int = object inherit [offset] mcts_t "offset" method ts (o: offset) = match o with | NoOffset -> "n" | Field _ -> "f" | Index _ -> "i" method tags = ["f"; "i"; "n"] end let offset_mcts: offset mfts_int = new offset_mcts_t class typsig_mcts_t:[typsig] mfts_int = object inherit [typsig] mcts_t "typsig" method ts (t: typsig) = match t with | TSArray _ -> "tsarray" | TSPtr _ -> "tsptr" | TSComp _ -> "tscomp" | TSFun _ -> "tsfun" | TSEnum _ -> "tsenum" | TSBase _ -> "tsbase" method tags = ["tsarray"; "tsbase"; "tscomp"; "tsenum"; "tsfun"; "tsptr"] end let typsig_mcts: typsig mfts_int = new typsig_mcts_t class label_mcts_t:[label] mfts_int = object inherit [label] mcts_t "label" method ts (l: label) = match l with | Label _ -> "label" | Case _ -> "case" | CaseRange _ -> "caserange" | Default _ -> "default" method tags = ["case"; "caserange"; "default"; "label"] end let label_mcts: label mfts_int = new label_mcts_t class stmtkind_mcts_t:[stmtkind] mfts_int = object inherit [stmtkind] mcts_t "stmtkind" method ts (s: stmtkind) = match s with | Instr _ -> "instr" | Return _ -> "return" | Goto _ -> "goto" | ComputedGoto _ -> "computedgoto" | Break _ -> "break" | Continue _ -> "continue" | If _ -> "if" | Switch _ -> "switch" | Loop _ -> "loop" | Block _ -> "block" | TryFinally _ -> "tryfinally" | TryExcept _ -> "tryexcept" method tags = [ "block"; "break"; "computedgoto"; "continue"; "goto"; "if"; "instr"; "loop"; "return"; "switch"; "tryexcept"; "tryfinally"] end let stmtkind_mcts: stmtkind mfts_int = new stmtkind_mcts_t class instr_mcts_t:[instr] mfts_int = object inherit [instr] mcts_t "instr" method ts (i: instr) = match i with | Set _ -> "set" | Call _ -> "call" | VarDecl _ -> "vardecl" | Asm _ -> "asm" method tags = ["asm"; "call"; "set"; "vardecl"] end let instr_mcts: instr mfts_int = new instr_mcts_t
null
https://raw.githubusercontent.com/static-analysis-engineering/codehawk/d2e83cef7430defdc4cf30fc1495fe4ff64d9f9d/CodeHawk/CHC/cchcil/cHCilSumTypeSerializer.ml
ocaml
cil chutil
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk C Analyzer Parser using CIL Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2019 Kestrel Technology LLC Copyright ( c ) 2020 - 2021 ) 2022 Aarno Labs LLC Permission is hereby granted , free of charge , to any person obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without restriction , including without limitation the rights to use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk C Analyzer Parser using CIL Author: Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2019 Kestrel Technology LLC Copyright (c) 2020-2021 Henny Sipma Copyright (c) 2022 Aarno Labs LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) open Cil chlib open CHCommon open CHPretty open CHPrettyUtil open CHSumTypeSerializer module H = Hashtbl let ikind_mfts: ikind mfts_int = mk_mfts "ikind_t" [(IChar, "ichar"); (ISChar, "ischar"); (IUChar, "iuchar"); (IBool, "ibool"); (IInt, "iint"); (IUInt, "iuint"); (IShort, "ishort"); (IUShort, "iushort"); (ILong, "ilong"); (IULong, "iulong"); (ILongLong, "ilonglong"); (IULongLong, "iulonglong"); (IInt128, "int128_t"); (IUInt128, "uint128_t")] let fkind_mfts: fkind mfts_int = mk_mfts "fkind_t" [(FFloat, "float"); (FDouble, "fdouble"); (FLongDouble, "flongdouble"); (FComplexFloat, "fcomplexfloat"); (FComplexDouble, "fcomplexdouble"); (FComplexLongDouble, "fcomplexlongdouble")] let unop_mfts: unop mfts_int = mk_mfts "unop_t" [(Neg, "neg"); (BNot, "bnot"); (LNot, "lnot")] let binop_mfts: binop mfts_int = mk_mfts "binop_t" [(PlusA, "plusa"); (PlusPI, "pluspi"); (IndexPI, "indexpi"); (MinusA, "minusa"); (MinusPI, "minuspi"); (MinusPP, "minuspp"); (Mult, "mult"); (Div, "div"); (Mod, "mod"); (Shiftlt, "shiftlt"); (Shiftrt, "shiftrt"); (Lt, "lt"); (Gt, "gt"); (Le, "le"); (Ge, "ge"); (Eq, "eq"); (Ne, "ne"); (BAnd, "band"); (BXor, "bxor"); (BOr, "bor"); (LAnd, "land"); (LOr, "lor")] let storage_mfts: storage mfts_int = mk_mfts "storage_t" [(NoStorage,"n"); (Static,"s"); (Register,"r"); (Extern,"x")] class typ_mcts_t:[typ] mfts_int = object inherit [typ] mcts_t "typ" method ts (t: typ) = match t with | TVoid _ -> "tvoid" | TInt _ -> "tint" | TFloat _ -> "tfloat" | TPtr _ -> "tptr" | TArray _ -> "tarray" | TFun _ -> "tfun" | TNamed _ -> "tnamed" | TComp _ -> "tcomp" | TEnum _ -> "tenum" | TBuiltin_va_list _ -> "tbuiltin-va-list" method tags = [ "tarray"; "tbuiltin-va-list"; "tcomp"; "tenum"; "tfloat"; "tfun"; "tint"; "tnamed"; "tptr"; "tvoid"] end let typ_mcts: typ mfts_int = new typ_mcts_t class exp_mcts_t:[exp] mfts_int = object inherit [exp] mcts_t "exp" method ts (e: exp) = match e with | Const _ -> "const" | Lval _ -> "lval" | SizeOf _ -> "sizeof" | Real _ -> "real" | Imag _ -> "imag" | SizeOfE _ -> "sizeofe" | SizeOfStr _ -> "sizeofstr" | AlignOf _ -> "alignof" | AlignOfE _ -> "alignofe" | UnOp _ -> "unop" | BinOp _ -> "binop" | Question _ -> "question" | CastE _ -> "caste" | AddrOf _ -> "addrof" | AddrOfLabel _ -> "addroflabel" | StartOf _ -> "startof" method tags = [ "addrof"; "addroflabel"; "alignof"; "alignofe"; "binop"; "caste"; "const"; "lval"; "question"; "sizeof"; "sizeofe"; "startof"; "unop"] end let exp_mcts: exp mfts_int = new exp_mcts_t class attrparam_mcts_t:[attrparam] mfts_int = object inherit [attrparam] mcts_t "attrparam" method ts (a: attrparam) = match a with | AInt _ -> "aint" | AStr _ -> "astr" | ACons _ -> "acons" | ASizeOf _ -> "asizeof" | ASizeOfE _ -> "asizeofe" | ASizeOfS _ -> "asizeofs" | AAlignOf _ -> "aalignof" | AAlignOfE _ -> "aalignofe" | AAlignOfS _ -> "aalignofs" | AUnOp _ -> "aunop" | ABinOp _ -> "abinop" | ADot _ -> "adot" | AStar _ -> "astar" | AAddrOf _ -> "aaddrof" | AIndex _ -> "aindex" | AQuestion _ -> "aquestion" method tags = [ "aaddrof"; "aalignof"; "aalignofe"; "aalignofs"; "abinop"; "acons"; "adot"; "aindex"; "aint"; "aquestion"; "asizeof"; "asizeofe"; "asizeofs"; "astar"; "astr"; "aunop"] end let attrparam_mcts: attrparam mfts_int = new attrparam_mcts_t class constant_mcts_t:[constant] mfts_int = object inherit [constant] mcts_t "constant" method ts (c: constant) = match c with | CInt64 _ -> "int" | CStr _ -> "str" | CWStr _ -> "wstr" | CChr _ -> "chr" | CReal _ -> "real" | CEnum _ -> "enum" method tags = ["chr"; "enum"; "int"; "real"; "str"; "wstr"] end let constant_mcts: constant mfts_int = new constant_mcts_t class offset_mcts_t: [offset] mfts_int = object inherit [offset] mcts_t "offset" method ts (o: offset) = match o with | NoOffset -> "n" | Field _ -> "f" | Index _ -> "i" method tags = ["f"; "i"; "n"] end let offset_mcts: offset mfts_int = new offset_mcts_t class typsig_mcts_t:[typsig] mfts_int = object inherit [typsig] mcts_t "typsig" method ts (t: typsig) = match t with | TSArray _ -> "tsarray" | TSPtr _ -> "tsptr" | TSComp _ -> "tscomp" | TSFun _ -> "tsfun" | TSEnum _ -> "tsenum" | TSBase _ -> "tsbase" method tags = ["tsarray"; "tsbase"; "tscomp"; "tsenum"; "tsfun"; "tsptr"] end let typsig_mcts: typsig mfts_int = new typsig_mcts_t class label_mcts_t:[label] mfts_int = object inherit [label] mcts_t "label" method ts (l: label) = match l with | Label _ -> "label" | Case _ -> "case" | CaseRange _ -> "caserange" | Default _ -> "default" method tags = ["case"; "caserange"; "default"; "label"] end let label_mcts: label mfts_int = new label_mcts_t class stmtkind_mcts_t:[stmtkind] mfts_int = object inherit [stmtkind] mcts_t "stmtkind" method ts (s: stmtkind) = match s with | Instr _ -> "instr" | Return _ -> "return" | Goto _ -> "goto" | ComputedGoto _ -> "computedgoto" | Break _ -> "break" | Continue _ -> "continue" | If _ -> "if" | Switch _ -> "switch" | Loop _ -> "loop" | Block _ -> "block" | TryFinally _ -> "tryfinally" | TryExcept _ -> "tryexcept" method tags = [ "block"; "break"; "computedgoto"; "continue"; "goto"; "if"; "instr"; "loop"; "return"; "switch"; "tryexcept"; "tryfinally"] end let stmtkind_mcts: stmtkind mfts_int = new stmtkind_mcts_t class instr_mcts_t:[instr] mfts_int = object inherit [instr] mcts_t "instr" method ts (i: instr) = match i with | Set _ -> "set" | Call _ -> "call" | VarDecl _ -> "vardecl" | Asm _ -> "asm" method tags = ["asm"; "call"; "set"; "vardecl"] end let instr_mcts: instr mfts_int = new instr_mcts_t
0633e517a7bc4885446b7b487a31c0d5e4b35bf614c1ec3175b8cc8163cbc6a4
zack-bitcoin/verkle
fr_test.erl
-module(fr_test). -export([test/1]). test(1) -> io:fwrite("test pow\n"), Q = fr:prime(), <<A0:256>> = crypto:strong_rand_bytes(32), A0 = 10 , A = A0 rem Q, <<B0:256>> = crypto:strong_rand_bytes(32), = 10 , B = B0 rem Q, AE = fr:encode(A), New = fr:decode(fr:pow(AE, <<B:256/little>>)), %New = decode(fr:pow(AE, B)), % reverse_bytes(<<B:256>>))), %reverse_bytes(<<B:256>>))), Old = basics:rlpow(A, B, Q), if (New == Old) -> ok; true -> io:write({New, Old}) end, success.
null
https://raw.githubusercontent.com/zack-bitcoin/verkle/46bf69f17170a71829f9243faea06ee42f224687/src/crypto/fr_test.erl
erlang
New = decode(fr:pow(AE, B)), reverse_bytes(<<B:256>>))), reverse_bytes(<<B:256>>))),
-module(fr_test). -export([test/1]). test(1) -> io:fwrite("test pow\n"), Q = fr:prime(), <<A0:256>> = crypto:strong_rand_bytes(32), A0 = 10 , A = A0 rem Q, <<B0:256>> = crypto:strong_rand_bytes(32), = 10 , B = B0 rem Q, AE = fr:encode(A), New = fr:decode(fr:pow(AE, <<B:256/little>>)), Old = basics:rlpow(A, B, Q), if (New == Old) -> ok; true -> io:write({New, Old}) end, success.
b1cea63324f13a092cf7411f98f5006d2af8a787bdb0010ade8041fee9d7ed7a
mtesseract/nakadi-client
Subscriptions.hs
| Module : Network . . Types . Subscriptions Description : Nakadi Service Subscription Types Copyright : ( c ) 2018 , 2019 License : : Stability : experimental Portability : POSIX This module exposes types , which are related to consumption of subscriptions , which are not modelled after the API . Module : Network.Nakadi.Types.Subscriptions Description : Nakadi Service Subscription Types Copyright : (c) Moritz Clasmeier 2018, 2019 License : BSD3 Maintainer : Stability : experimental Portability : POSIX This module exposes types, which are related to consumption of subscriptions, which are not modelled after the Nakadi API. -} module Network.Nakadi.Types.Subscriptions ( CommitStrategy(..) , CommitBufferingStrategy(..) , CommitTimeout(..) ) where import Network.Nakadi.Internal.Types.Subscriptions
null
https://raw.githubusercontent.com/mtesseract/nakadi-client/f8eef3ac215459081b01b0b48f0b430ae7701f52/src/Network/Nakadi/Types/Subscriptions.hs
haskell
| Module : Network . . Types . Subscriptions Description : Nakadi Service Subscription Types Copyright : ( c ) 2018 , 2019 License : : Stability : experimental Portability : POSIX This module exposes types , which are related to consumption of subscriptions , which are not modelled after the API . Module : Network.Nakadi.Types.Subscriptions Description : Nakadi Service Subscription Types Copyright : (c) Moritz Clasmeier 2018, 2019 License : BSD3 Maintainer : Stability : experimental Portability : POSIX This module exposes types, which are related to consumption of subscriptions, which are not modelled after the Nakadi API. -} module Network.Nakadi.Types.Subscriptions ( CommitStrategy(..) , CommitBufferingStrategy(..) , CommitTimeout(..) ) where import Network.Nakadi.Internal.Types.Subscriptions
70bb7d796ddf2b5ef2d9b934541ff80d9dcc6e4ebca85b1813f63861844641a9
spurious/sagittarius-scheme-mirror
sboyer.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; File: sboyer.sch Description : The benchmark Author : Created : 5 - Apr-85 Modified : 10 - Apr-85 14:52:20 ( ) 22 - Jul-87 ( ) 2 - Jul-88 ( -- distinguished # f and the empty list ) 13 - Feb-97 ( -- fixed bugs in unifier and rules , ; rewrote to eliminate property lists, and added a scaling parameter suggested by ) 19 - Mar-99 ( -- cleaned up comments ) ; Language: Scheme ; Status: Public Domain ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; SBOYER -- Logic programming benchmark , originally written by . Much less CONS - intensive than NBOYER because it uses ;;; "sharing cons". Note : The version of this benchmark that appears in book ; contained several bugs that are corrected here. These bugs are discussed by , " The Boyer Benchmark Meets Linear Logic " , ACM SIGPLAN Lisp Pointers 6(4 ) , October - December 1993 , pages 3 - 10 . The fixed bugs are : ; ; The benchmark now returns a boolean result. FALSEP and TRUEP use TERM - MEMBER ? rather than MEMV ( which is called MEMBER in ) ONE - WAY - UNIFY1 now treats numbers correctly ONE - WAY - UNIFY1 - LST now treats empty lists correctly Rule 19 has been corrected ( this rule was not touched by the original ; benchmark, but is used by this version) Rules 84 and 101 have been corrected ( but these rules are never touched ; by the benchmark) ; According to , these bug fixes make the benchmark 10 - 25 % slower . ; Please do not compare the timings from this benchmark against those of ; the original benchmark. ; ; This version of the benchmark also prints the number of rewrites as a sanity ; check, because it is too easy for a buggy version to return the correct ; boolean result. The correct number of rewrites is ; ; n rewrites peak live storage (approximate, in bytes) 0 95024 ; 1 591777 ; 2 1813975 3 5375678 4 16445406 5 51507739 Sboyer is a 2 - phase benchmark . The first phase attaches lemmas to symbols . This phase is not timed , ; but it accounts for very little of the runtime anyway. The second phase creates the test problem , and tests to see ; whether it is implied by the lemmas. (define (main . args) (let ((n (if (null? args) 0 (car args)))) (setup-boyer) (run-benchmark (string-append "sboyer" (number->string n)) sboyer-iters (lambda (rewrites) (and (number? rewrites) (case n ((0) (= rewrites 95024)) ((1) (= rewrites 591777)) ((2) (= rewrites 1813975)) ((3) (= rewrites 5375678)) ((4) (= rewrites 16445406)) ((5) (= rewrites 51507739)) If it works for n < = 5 , assume it works . (else #t)))) (lambda (alist term n) (lambda () (test-boyer alist term n))) (quote ((x f (plus (plus a b) (plus c (zero)))) (y f (times (times a b) (plus c d))) (z f (reverse (append (append a b) (nil)))) (u equal (plus a b) (difference x y)) (w lessp (remainder a b) (member a (length b))))) (quote (implies (and (implies x y) (and (implies y z) (and (implies z u) (implies u w)))) (implies x w))) n))) (define (setup-boyer) #t) ; assigned below (define (test-boyer) #t) ; assigned below ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; The first phase . ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; In the original benchmark, it stored a list of lemmas on the ; property lists of symbols. ; In the new benchmark, it maintains an association list of ; symbols and symbol-records, and stores the list of lemmas ; within the symbol-records. (let () (define (setup) (add-lemma-lst (quote ((equal (compile form) (reverse (codegen (optimize form) (nil)))) (equal (eqp x y) (equal (fix x) (fix y))) (equal (greaterp x y) (lessp y x)) (equal (lesseqp x y) (not (lessp y x))) (equal (greatereqp x y) (not (lessp x y))) (equal (boolean x) (or (equal x (t)) (equal x (f)))) (equal (iff x y) (and (implies x y) (implies y x))) (equal (even1 x) (if (zerop x) (t) (odd (_1- x)))) (equal (countps- l pred) (countps-loop l pred (zero))) (equal (fact- i) (fact-loop i 1)) (equal (reverse- x) (reverse-loop x (nil))) (equal (divides x y) (zerop (remainder y x))) (equal (assume-true var alist) (cons (cons var (t)) alist)) (equal (assume-false var alist) (cons (cons var (f)) alist)) (equal (tautology-checker x) (tautologyp (normalize x) (nil))) (equal (falsify x) (falsify1 (normalize x) (nil))) (equal (prime x) (and (not (zerop x)) (not (equal x (add1 (zero)))) (prime1 x (_1- x)))) (equal (and p q) (if p (if q (t) (f)) (f))) (equal (or p q) (if p (t) (if q (t) (f)))) (equal (not p) (if p (f) (t))) (equal (implies p q) (if p (if q (t) (f)) (t))) (equal (fix x) (if (numberp x) x (zero))) (equal (if (if a b c) d e) (if a (if b d e) (if c d e))) (equal (zerop x) (or (equal x (zero)) (not (numberp x)))) (equal (plus (plus x y) z) (plus x (plus y z))) (equal (equal (plus a b) (zero)) (and (zerop a) (zerop b))) (equal (difference x x) (zero)) (equal (equal (plus a b) (plus a c)) (equal (fix b) (fix c))) (equal (equal (zero) (difference x y)) (not (lessp y x))) (equal (equal x (difference x y)) (and (numberp x) (or (equal x (zero)) (zerop y)))) (equal (meaning (plus-tree (append x y)) a) (plus (meaning (plus-tree x) a) (meaning (plus-tree y) a))) (equal (meaning (plus-tree (plus-fringe x)) a) (fix (meaning x a))) (equal (append (append x y) z) (append x (append y z))) (equal (reverse (append a b)) (append (reverse b) (reverse a))) (equal (times x (plus y z)) (plus (times x y) (times x z))) (equal (times (times x y) z) (times x (times y z))) (equal (equal (times x y) (zero)) (or (zerop x) (zerop y))) (equal (exec (append x y) pds envrn) (exec y (exec x pds envrn) envrn)) (equal (mc-flatten x y) (append (flatten x) y)) (equal (member x (append a b)) (or (member x a) (member x b))) (equal (member x (reverse y)) (member x y)) (equal (length (reverse x)) (length x)) (equal (member a (intersect b c)) (and (member a b) (member a c))) (equal (nth (zero) i) (zero)) (equal (exp i (plus j k)) (times (exp i j) (exp i k))) (equal (exp i (times j k)) (exp (exp i j) k)) (equal (reverse-loop x y) (append (reverse x) y)) (equal (reverse-loop x (nil)) (reverse x)) (equal (count-list z (sort-lp x y)) (plus (count-list z x) (count-list z y))) (equal (equal (append a b) (append a c)) (equal b c)) (equal (plus (remainder x y) (times y (quotient x y))) (fix x)) (equal (power-eval (big-plus1 l i base) base) (plus (power-eval l base) i)) (equal (power-eval (big-plus x y i base) base) (plus i (plus (power-eval x base) (power-eval y base)))) (equal (remainder y 1) (zero)) (equal (lessp (remainder x y) y) (not (zerop y))) (equal (remainder x x) (zero)) (equal (lessp (quotient i j) i) (and (not (zerop i)) (or (zerop j) (not (equal j 1))))) (equal (lessp (remainder x y) x) (and (not (zerop y)) (not (zerop x)) (not (lessp x y)))) (equal (power-eval (power-rep i base) base) (fix i)) (equal (power-eval (big-plus (power-rep i base) (power-rep j base) (zero) base) base) (plus i j)) (equal (gcd x y) (gcd y x)) (equal (nth (append a b) i) (append (nth a i) (nth b (difference i (length a))))) (equal (difference (plus x y) x) (fix y)) (equal (difference (plus y x) x) (fix y)) (equal (difference (plus x y) (plus x z)) (difference y z)) (equal (times x (difference c w)) (difference (times c x) (times w x))) (equal (remainder (times x z) z) (zero)) (equal (difference (plus b (plus a c)) a) (plus b c)) (equal (difference (add1 (plus y z)) z) (add1 y)) (equal (lessp (plus x y) (plus x z)) (lessp y z)) (equal (lessp (times x z) (times y z)) (and (not (zerop z)) (lessp x y))) (equal (lessp y (plus x y)) (not (zerop x))) (equal (gcd (times x z) (times y z)) (times z (gcd x y))) (equal (value (normalize x) a) (value x a)) (equal (equal (flatten x) (cons y (nil))) (and (nlistp x) (equal x y))) (equal (listp (gopher x)) (listp x)) (equal (samefringe x y) (equal (flatten x) (flatten y))) (equal (equal (greatest-factor x y) (zero)) (and (or (zerop y) (equal y 1)) (equal x (zero)))) (equal (equal (greatest-factor x y) 1) (equal x 1)) (equal (numberp (greatest-factor x y)) (not (and (or (zerop y) (equal y 1)) (not (numberp x))))) (equal (times-list (append x y)) (times (times-list x) (times-list y))) (equal (prime-list (append x y)) (and (prime-list x) (prime-list y))) (equal (equal z (times w z)) (and (numberp z) (or (equal z (zero)) (equal w 1)))) (equal (greatereqp x y) (not (lessp x y))) (equal (equal x (times x y)) (or (equal x (zero)) (and (numberp x) (equal y 1)))) (equal (remainder (times y x) y) (zero)) (equal (equal (times a b) 1) (and (not (equal a (zero))) (not (equal b (zero))) (numberp a) (numberp b) (equal (_1- a) (zero)) (equal (_1- b) (zero)))) (equal (lessp (length (delete x l)) (length l)) (member x l)) (equal (sort2 (delete x l)) (delete x (sort2 l))) (equal (dsort x) (sort2 x)) (equal (length (cons x1 (cons x2 (cons x3 (cons x4 (cons x5 (cons x6 x7))))))) (plus 6 (length x7))) (equal (difference (add1 (add1 x)) 2) (fix x)) (equal (quotient (plus x (plus x y)) 2) (plus x (quotient y 2))) (equal (sigma (zero) i) (quotient (times i (add1 i)) 2)) (equal (plus x (add1 y)) (if (numberp y) (add1 (plus x y)) (add1 x))) (equal (equal (difference x y) (difference z y)) (if (lessp x y) (not (lessp y z)) (if (lessp z y) (not (lessp y x)) (equal (fix x) (fix z))))) (equal (meaning (plus-tree (delete x y)) a) (if (member x y) (difference (meaning (plus-tree y) a) (meaning x a)) (meaning (plus-tree y) a))) (equal (times x (add1 y)) (if (numberp y) (plus x (times x y)) (fix x))) (equal (nth (nil) i) (if (zerop i) (nil) (zero))) (equal (last (append a b)) (if (listp b) (last b) (if (listp a) (cons (car (last a)) b) b))) (equal (equal (lessp x y) z) (if (lessp x y) (equal (t) z) (equal (f) z))) (equal (assignment x (append a b)) (if (assignedp x a) (assignment x a) (assignment x b))) (equal (car (gopher x)) (if (listp x) (car (flatten x)) (zero))) (equal (flatten (cdr (gopher x))) (if (listp x) (cdr (flatten x)) (cons (zero) (nil)))) (equal (quotient (times y x) y) (if (zerop y) (zero) (fix x))) (equal (get j (set i val mem)) (if (eqp j i) val (get j mem))))))) (define (add-lemma-lst lst) (cond ((null? lst) #t) (else (add-lemma (car lst)) (add-lemma-lst (cdr lst))))) (define (add-lemma term) (cond ((and (pair? term) (eq? (car term) (quote equal)) (pair? (cadr term))) (put (car (cadr term)) (quote lemmas) (cons (translate-term term) (get (car (cadr term)) (quote lemmas))))) (else (fatal-error "ADD-LEMMA did not like term: " term)))) ; Translates a term by replacing its constructor symbols by symbol-records. (define (translate-term term) (cond ((not (pair? term)) term) (else (cons (symbol->symbol-record (car term)) (translate-args (cdr term)))))) (define (translate-args lst) (cond ((null? lst) '()) (else (cons (translate-term (car lst)) (translate-args (cdr lst)))))) For debugging only , so the use of MAP does not change the first - order character of the benchmark . (define (untranslate-term term) (cond ((not (pair? term)) term) (else (cons (get-name (car term)) (map untranslate-term (cdr term)))))) A symbol - record is represented as a vector with two fields : ; the symbol (for debugging) and ; the list of lemmas associated with the symbol. (define (put sym property value) (put-lemmas! (symbol->symbol-record sym) value)) (define (get sym property) (get-lemmas (symbol->symbol-record sym))) (define (symbol->symbol-record sym) (let ((x (assq sym *symbol-records-alist*))) (if x (cdr x) (let ((r (make-symbol-record sym))) (set! *symbol-records-alist* (cons (cons sym r) *symbol-records-alist*)) r)))) ; Association list of symbols and symbol-records. (define *symbol-records-alist* '()) A symbol - record is represented as a vector with two fields : ; the symbol (for debugging) and ; the list of lemmas associated with the symbol. (define (make-symbol-record sym) (vector sym '())) (define (put-lemmas! symbol-record lemmas) (vector-set! symbol-record 1 lemmas)) (define (get-lemmas symbol-record) (vector-ref symbol-record 1)) (define (get-name symbol-record) (vector-ref symbol-record 0)) (define (symbol-record-equal? r1 r2) (eq? r1 r2)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; The second phase . ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (test alist term n) (let ((term (apply-subst (translate-alist alist) (translate-term (do ((term term (list 'or term '(f))) (n n (- n 1))) ((zero? n) term)))))) (tautp term))) (define (translate-alist alist) (cond ((null? alist) '()) (else (cons (cons (caar alist) (translate-term (cdar alist))) (translate-alist (cdr alist)))))) (define (apply-subst alist term) (cond ((not (pair? term)) (let ((temp-temp (assq term alist))) (if temp-temp (cdr temp-temp) term))) (else (cons (car term) (apply-subst-lst alist (cdr term)))))) (define (apply-subst-lst alist lst) (cond ((null? lst) '()) (else (cons (apply-subst alist (car lst)) (apply-subst-lst alist (cdr lst)))))) (define (tautp x) (tautologyp (rewrite x) '() '())) (define (tautologyp x true-lst false-lst) (cond ((truep x true-lst) #t) ((falsep x false-lst) #f) ((not (pair? x)) #f) ((eq? (car x) if-constructor) (cond ((truep (cadr x) true-lst) (tautologyp (caddr x) true-lst false-lst)) ((falsep (cadr x) false-lst) (tautologyp (cadddr x) true-lst false-lst)) (else (and (tautologyp (caddr x) (cons (cadr x) true-lst) false-lst) (tautologyp (cadddr x) true-lst (cons (cadr x) false-lst)))))) (else #f))) (define if-constructor '*) ; becomes (symbol->symbol-record 'if) (define rewrite-count 0) ; sanity check The next procedure is sharing CONS , which avoids ; allocation if the result is already in hand. ; The REWRITE and REWRITE-ARGS procedures have been modified to ; use SCONS instead of CONS. (define (scons x y original) (if (and (eq? x (car original)) (eq? y (cdr original))) original (cons x y))) (define (rewrite term) (set! rewrite-count (+ rewrite-count 1)) (cond ((not (pair? term)) term) (else (rewrite-with-lemmas (scons (car term) (rewrite-args (cdr term)) term) (get-lemmas (car term)))))) (define (rewrite-args lst) (cond ((null? lst) '()) (else (scons (rewrite (car lst)) (rewrite-args (cdr lst)) lst)))) (define (rewrite-with-lemmas term lst) (cond ((null? lst) term) ((one-way-unify term (cadr (car lst))) (rewrite (apply-subst unify-subst (caddr (car lst))))) (else (rewrite-with-lemmas term (cdr lst))))) (define unify-subst '*) (define (one-way-unify term1 term2) (begin (set! unify-subst '()) (one-way-unify1 term1 term2))) (define (one-way-unify1 term1 term2) (cond ((not (pair? term2)) (let ((temp-temp (assq term2 unify-subst))) (cond (temp-temp (term-equal? term1 (cdr temp-temp))) ((number? term2) ; This bug fix makes nboyer 10 - 25 % slower ! (else (set! unify-subst (cons (cons term2 term1) unify-subst)) #t)))) ((not (pair? term1)) #f) ((eq? (car term1) (car term2)) (one-way-unify1-lst (cdr term1) (cdr term2))) (else #f))) (define (one-way-unify1-lst lst1 lst2) (cond ((null? lst1) (null? lst2)) ((null? lst2) #f) ((one-way-unify1 (car lst1) (car lst2)) (one-way-unify1-lst (cdr lst1) (cdr lst2))) (else #f))) (define (falsep x lst) (or (term-equal? x false-term) (term-member? x lst))) (define (truep x lst) (or (term-equal? x true-term) (term-member? x lst))) (define false-term '*) ; becomes (translate-term '(f)) (define true-term '*) ; becomes (translate-term '(t)) The next two procedures were in the original benchmark ; but were never used. (define (trans-of-implies n) (translate-term (list (quote implies) (trans-of-implies1 n) (list (quote implies) 0 n)))) (define (trans-of-implies1 n) (cond ((equal? n 1) (list (quote implies) 0 1)) (else (list (quote and) (list (quote implies) (- n 1) n) (trans-of-implies1 (- n 1)))))) ; Translated terms can be circular structures, which can't be compared using Scheme 's equal ? and member procedures , so we ; use these instead. (define (term-equal? x y) (cond ((pair? x) (and (pair? y) (symbol-record-equal? (car x) (car y)) (term-args-equal? (cdr x) (cdr y)))) (else (equal? x y)))) (define (term-args-equal? lst1 lst2) (cond ((null? lst1) (null? lst2)) ((null? lst2) #f) ((term-equal? (car lst1) (car lst2)) (term-args-equal? (cdr lst1) (cdr lst2))) (else #f))) (define (term-member? x lst) (cond ((null? lst) #f) ((term-equal? x (car lst)) #t) (else (term-member? x (cdr lst))))) (set! setup-boyer (lambda () (set! *symbol-records-alist* '()) (set! if-constructor (symbol->symbol-record 'if)) (set! false-term (translate-term '(f))) (set! true-term (translate-term '(t))) (setup))) (set! test-boyer (lambda (alist term n) (set! rewrite-count 0) (let ((answer (test alist term n))) ; (write rewrite-count) ; (display " rewrites") ; (newline) (if answer rewrite-count #f)))))
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/bench/gambit-benchmarks/sboyer.scm
scheme
File: sboyer.sch rewrote to eliminate property lists, and added Language: Scheme Status: Public Domain "sharing cons". contained several bugs that are corrected here. These bugs are discussed The benchmark now returns a boolean result. benchmark, but is used by this version) by the benchmark) Please do not compare the timings from this benchmark against those of the original benchmark. This version of the benchmark also prints the number of rewrites as a sanity check, because it is too easy for a buggy version to return the correct boolean result. The correct number of rewrites is n rewrites peak live storage (approximate, in bytes) 1 591777 2 1813975 but it accounts for very little of the runtime anyway. whether it is implied by the lemmas. assigned below assigned below In the original benchmark, it stored a list of lemmas on the property lists of symbols. In the new benchmark, it maintains an association list of symbols and symbol-records, and stores the list of lemmas within the symbol-records. Translates a term by replacing its constructor symbols by symbol-records. the symbol (for debugging) and the list of lemmas associated with the symbol. Association list of symbols and symbol-records. the symbol (for debugging) and the list of lemmas associated with the symbol. becomes (symbol->symbol-record 'if) sanity check allocation if the result is already in hand. The REWRITE and REWRITE-ARGS procedures have been modified to use SCONS instead of CONS. This bug fix makes becomes (translate-term '(f)) becomes (translate-term '(t)) but were never used. Translated terms can be circular structures, which can't be use these instead. (write rewrite-count) (display " rewrites") (newline)
Description : The benchmark Author : Created : 5 - Apr-85 Modified : 10 - Apr-85 14:52:20 ( ) 22 - Jul-87 ( ) 2 - Jul-88 ( -- distinguished # f and the empty list ) 13 - Feb-97 ( -- fixed bugs in unifier and rules , a scaling parameter suggested by ) 19 - Mar-99 ( -- cleaned up comments ) SBOYER -- Logic programming benchmark , originally written by . Much less CONS - intensive than NBOYER because it uses Note : The version of this benchmark that appears in book by , " The Boyer Benchmark Meets Linear Logic " , ACM SIGPLAN Lisp Pointers 6(4 ) , October - December 1993 , pages 3 - 10 . The fixed bugs are : FALSEP and TRUEP use TERM - MEMBER ? rather than MEMV ( which is called MEMBER in ) ONE - WAY - UNIFY1 now treats numbers correctly ONE - WAY - UNIFY1 - LST now treats empty lists correctly Rule 19 has been corrected ( this rule was not touched by the original Rules 84 and 101 have been corrected ( but these rules are never touched According to , these bug fixes make the benchmark 10 - 25 % slower . 0 95024 3 5375678 4 16445406 5 51507739 Sboyer is a 2 - phase benchmark . The first phase attaches lemmas to symbols . This phase is not timed , The second phase creates the test problem , and tests to see (define (main . args) (let ((n (if (null? args) 0 (car args)))) (setup-boyer) (run-benchmark (string-append "sboyer" (number->string n)) sboyer-iters (lambda (rewrites) (and (number? rewrites) (case n ((0) (= rewrites 95024)) ((1) (= rewrites 591777)) ((2) (= rewrites 1813975)) ((3) (= rewrites 5375678)) ((4) (= rewrites 16445406)) ((5) (= rewrites 51507739)) If it works for n < = 5 , assume it works . (else #t)))) (lambda (alist term n) (lambda () (test-boyer alist term n))) (quote ((x f (plus (plus a b) (plus c (zero)))) (y f (times (times a b) (plus c d))) (z f (reverse (append (append a b) (nil)))) (u equal (plus a b) (difference x y)) (w lessp (remainder a b) (member a (length b))))) (quote (implies (and (implies x y) (and (implies y z) (and (implies z u) (implies u w)))) (implies x w))) n))) The first phase . (let () (define (setup) (add-lemma-lst (quote ((equal (compile form) (reverse (codegen (optimize form) (nil)))) (equal (eqp x y) (equal (fix x) (fix y))) (equal (greaterp x y) (lessp y x)) (equal (lesseqp x y) (not (lessp y x))) (equal (greatereqp x y) (not (lessp x y))) (equal (boolean x) (or (equal x (t)) (equal x (f)))) (equal (iff x y) (and (implies x y) (implies y x))) (equal (even1 x) (if (zerop x) (t) (odd (_1- x)))) (equal (countps- l pred) (countps-loop l pred (zero))) (equal (fact- i) (fact-loop i 1)) (equal (reverse- x) (reverse-loop x (nil))) (equal (divides x y) (zerop (remainder y x))) (equal (assume-true var alist) (cons (cons var (t)) alist)) (equal (assume-false var alist) (cons (cons var (f)) alist)) (equal (tautology-checker x) (tautologyp (normalize x) (nil))) (equal (falsify x) (falsify1 (normalize x) (nil))) (equal (prime x) (and (not (zerop x)) (not (equal x (add1 (zero)))) (prime1 x (_1- x)))) (equal (and p q) (if p (if q (t) (f)) (f))) (equal (or p q) (if p (t) (if q (t) (f)))) (equal (not p) (if p (f) (t))) (equal (implies p q) (if p (if q (t) (f)) (t))) (equal (fix x) (if (numberp x) x (zero))) (equal (if (if a b c) d e) (if a (if b d e) (if c d e))) (equal (zerop x) (or (equal x (zero)) (not (numberp x)))) (equal (plus (plus x y) z) (plus x (plus y z))) (equal (equal (plus a b) (zero)) (and (zerop a) (zerop b))) (equal (difference x x) (zero)) (equal (equal (plus a b) (plus a c)) (equal (fix b) (fix c))) (equal (equal (zero) (difference x y)) (not (lessp y x))) (equal (equal x (difference x y)) (and (numberp x) (or (equal x (zero)) (zerop y)))) (equal (meaning (plus-tree (append x y)) a) (plus (meaning (plus-tree x) a) (meaning (plus-tree y) a))) (equal (meaning (plus-tree (plus-fringe x)) a) (fix (meaning x a))) (equal (append (append x y) z) (append x (append y z))) (equal (reverse (append a b)) (append (reverse b) (reverse a))) (equal (times x (plus y z)) (plus (times x y) (times x z))) (equal (times (times x y) z) (times x (times y z))) (equal (equal (times x y) (zero)) (or (zerop x) (zerop y))) (equal (exec (append x y) pds envrn) (exec y (exec x pds envrn) envrn)) (equal (mc-flatten x y) (append (flatten x) y)) (equal (member x (append a b)) (or (member x a) (member x b))) (equal (member x (reverse y)) (member x y)) (equal (length (reverse x)) (length x)) (equal (member a (intersect b c)) (and (member a b) (member a c))) (equal (nth (zero) i) (zero)) (equal (exp i (plus j k)) (times (exp i j) (exp i k))) (equal (exp i (times j k)) (exp (exp i j) k)) (equal (reverse-loop x y) (append (reverse x) y)) (equal (reverse-loop x (nil)) (reverse x)) (equal (count-list z (sort-lp x y)) (plus (count-list z x) (count-list z y))) (equal (equal (append a b) (append a c)) (equal b c)) (equal (plus (remainder x y) (times y (quotient x y))) (fix x)) (equal (power-eval (big-plus1 l i base) base) (plus (power-eval l base) i)) (equal (power-eval (big-plus x y i base) base) (plus i (plus (power-eval x base) (power-eval y base)))) (equal (remainder y 1) (zero)) (equal (lessp (remainder x y) y) (not (zerop y))) (equal (remainder x x) (zero)) (equal (lessp (quotient i j) i) (and (not (zerop i)) (or (zerop j) (not (equal j 1))))) (equal (lessp (remainder x y) x) (and (not (zerop y)) (not (zerop x)) (not (lessp x y)))) (equal (power-eval (power-rep i base) base) (fix i)) (equal (power-eval (big-plus (power-rep i base) (power-rep j base) (zero) base) base) (plus i j)) (equal (gcd x y) (gcd y x)) (equal (nth (append a b) i) (append (nth a i) (nth b (difference i (length a))))) (equal (difference (plus x y) x) (fix y)) (equal (difference (plus y x) x) (fix y)) (equal (difference (plus x y) (plus x z)) (difference y z)) (equal (times x (difference c w)) (difference (times c x) (times w x))) (equal (remainder (times x z) z) (zero)) (equal (difference (plus b (plus a c)) a) (plus b c)) (equal (difference (add1 (plus y z)) z) (add1 y)) (equal (lessp (plus x y) (plus x z)) (lessp y z)) (equal (lessp (times x z) (times y z)) (and (not (zerop z)) (lessp x y))) (equal (lessp y (plus x y)) (not (zerop x))) (equal (gcd (times x z) (times y z)) (times z (gcd x y))) (equal (value (normalize x) a) (value x a)) (equal (equal (flatten x) (cons y (nil))) (and (nlistp x) (equal x y))) (equal (listp (gopher x)) (listp x)) (equal (samefringe x y) (equal (flatten x) (flatten y))) (equal (equal (greatest-factor x y) (zero)) (and (or (zerop y) (equal y 1)) (equal x (zero)))) (equal (equal (greatest-factor x y) 1) (equal x 1)) (equal (numberp (greatest-factor x y)) (not (and (or (zerop y) (equal y 1)) (not (numberp x))))) (equal (times-list (append x y)) (times (times-list x) (times-list y))) (equal (prime-list (append x y)) (and (prime-list x) (prime-list y))) (equal (equal z (times w z)) (and (numberp z) (or (equal z (zero)) (equal w 1)))) (equal (greatereqp x y) (not (lessp x y))) (equal (equal x (times x y)) (or (equal x (zero)) (and (numberp x) (equal y 1)))) (equal (remainder (times y x) y) (zero)) (equal (equal (times a b) 1) (and (not (equal a (zero))) (not (equal b (zero))) (numberp a) (numberp b) (equal (_1- a) (zero)) (equal (_1- b) (zero)))) (equal (lessp (length (delete x l)) (length l)) (member x l)) (equal (sort2 (delete x l)) (delete x (sort2 l))) (equal (dsort x) (sort2 x)) (equal (length (cons x1 (cons x2 (cons x3 (cons x4 (cons x5 (cons x6 x7))))))) (plus 6 (length x7))) (equal (difference (add1 (add1 x)) 2) (fix x)) (equal (quotient (plus x (plus x y)) 2) (plus x (quotient y 2))) (equal (sigma (zero) i) (quotient (times i (add1 i)) 2)) (equal (plus x (add1 y)) (if (numberp y) (add1 (plus x y)) (add1 x))) (equal (equal (difference x y) (difference z y)) (if (lessp x y) (not (lessp y z)) (if (lessp z y) (not (lessp y x)) (equal (fix x) (fix z))))) (equal (meaning (plus-tree (delete x y)) a) (if (member x y) (difference (meaning (plus-tree y) a) (meaning x a)) (meaning (plus-tree y) a))) (equal (times x (add1 y)) (if (numberp y) (plus x (times x y)) (fix x))) (equal (nth (nil) i) (if (zerop i) (nil) (zero))) (equal (last (append a b)) (if (listp b) (last b) (if (listp a) (cons (car (last a)) b) b))) (equal (equal (lessp x y) z) (if (lessp x y) (equal (t) z) (equal (f) z))) (equal (assignment x (append a b)) (if (assignedp x a) (assignment x a) (assignment x b))) (equal (car (gopher x)) (if (listp x) (car (flatten x)) (zero))) (equal (flatten (cdr (gopher x))) (if (listp x) (cdr (flatten x)) (cons (zero) (nil)))) (equal (quotient (times y x) y) (if (zerop y) (zero) (fix x))) (equal (get j (set i val mem)) (if (eqp j i) val (get j mem))))))) (define (add-lemma-lst lst) (cond ((null? lst) #t) (else (add-lemma (car lst)) (add-lemma-lst (cdr lst))))) (define (add-lemma term) (cond ((and (pair? term) (eq? (car term) (quote equal)) (pair? (cadr term))) (put (car (cadr term)) (quote lemmas) (cons (translate-term term) (get (car (cadr term)) (quote lemmas))))) (else (fatal-error "ADD-LEMMA did not like term: " term)))) (define (translate-term term) (cond ((not (pair? term)) term) (else (cons (symbol->symbol-record (car term)) (translate-args (cdr term)))))) (define (translate-args lst) (cond ((null? lst) '()) (else (cons (translate-term (car lst)) (translate-args (cdr lst)))))) For debugging only , so the use of MAP does not change the first - order character of the benchmark . (define (untranslate-term term) (cond ((not (pair? term)) term) (else (cons (get-name (car term)) (map untranslate-term (cdr term)))))) A symbol - record is represented as a vector with two fields : (define (put sym property value) (put-lemmas! (symbol->symbol-record sym) value)) (define (get sym property) (get-lemmas (symbol->symbol-record sym))) (define (symbol->symbol-record sym) (let ((x (assq sym *symbol-records-alist*))) (if x (cdr x) (let ((r (make-symbol-record sym))) (set! *symbol-records-alist* (cons (cons sym r) *symbol-records-alist*)) r)))) (define *symbol-records-alist* '()) A symbol - record is represented as a vector with two fields : (define (make-symbol-record sym) (vector sym '())) (define (put-lemmas! symbol-record lemmas) (vector-set! symbol-record 1 lemmas)) (define (get-lemmas symbol-record) (vector-ref symbol-record 1)) (define (get-name symbol-record) (vector-ref symbol-record 0)) (define (symbol-record-equal? r1 r2) (eq? r1 r2)) The second phase . (define (test alist term n) (let ((term (apply-subst (translate-alist alist) (translate-term (do ((term term (list 'or term '(f))) (n n (- n 1))) ((zero? n) term)))))) (tautp term))) (define (translate-alist alist) (cond ((null? alist) '()) (else (cons (cons (caar alist) (translate-term (cdar alist))) (translate-alist (cdr alist)))))) (define (apply-subst alist term) (cond ((not (pair? term)) (let ((temp-temp (assq term alist))) (if temp-temp (cdr temp-temp) term))) (else (cons (car term) (apply-subst-lst alist (cdr term)))))) (define (apply-subst-lst alist lst) (cond ((null? lst) '()) (else (cons (apply-subst alist (car lst)) (apply-subst-lst alist (cdr lst)))))) (define (tautp x) (tautologyp (rewrite x) '() '())) (define (tautologyp x true-lst false-lst) (cond ((truep x true-lst) #t) ((falsep x false-lst) #f) ((not (pair? x)) #f) ((eq? (car x) if-constructor) (cond ((truep (cadr x) true-lst) (tautologyp (caddr x) true-lst false-lst)) ((falsep (cadr x) false-lst) (tautologyp (cadddr x) true-lst false-lst)) (else (and (tautologyp (caddr x) (cons (cadr x) true-lst) false-lst) (tautologyp (cadddr x) true-lst (cons (cadr x) false-lst)))))) (else #f))) The next procedure is sharing CONS , which avoids (define (scons x y original) (if (and (eq? x (car original)) (eq? y (cdr original))) original (cons x y))) (define (rewrite term) (set! rewrite-count (+ rewrite-count 1)) (cond ((not (pair? term)) term) (else (rewrite-with-lemmas (scons (car term) (rewrite-args (cdr term)) term) (get-lemmas (car term)))))) (define (rewrite-args lst) (cond ((null? lst) '()) (else (scons (rewrite (car lst)) (rewrite-args (cdr lst)) lst)))) (define (rewrite-with-lemmas term lst) (cond ((null? lst) term) ((one-way-unify term (cadr (car lst))) (rewrite (apply-subst unify-subst (caddr (car lst))))) (else (rewrite-with-lemmas term (cdr lst))))) (define unify-subst '*) (define (one-way-unify term1 term2) (begin (set! unify-subst '()) (one-way-unify1 term1 term2))) (define (one-way-unify1 term1 term2) (cond ((not (pair? term2)) (let ((temp-temp (assq term2 unify-subst))) (cond (temp-temp (term-equal? term1 (cdr temp-temp))) nboyer 10 - 25 % slower ! (else (set! unify-subst (cons (cons term2 term1) unify-subst)) #t)))) ((not (pair? term1)) #f) ((eq? (car term1) (car term2)) (one-way-unify1-lst (cdr term1) (cdr term2))) (else #f))) (define (one-way-unify1-lst lst1 lst2) (cond ((null? lst1) (null? lst2)) ((null? lst2) #f) ((one-way-unify1 (car lst1) (car lst2)) (one-way-unify1-lst (cdr lst1) (cdr lst2))) (else #f))) (define (falsep x lst) (or (term-equal? x false-term) (term-member? x lst))) (define (truep x lst) (or (term-equal? x true-term) (term-member? x lst))) The next two procedures were in the original benchmark (define (trans-of-implies n) (translate-term (list (quote implies) (trans-of-implies1 n) (list (quote implies) 0 n)))) (define (trans-of-implies1 n) (cond ((equal? n 1) (list (quote implies) 0 1)) (else (list (quote and) (list (quote implies) (- n 1) n) (trans-of-implies1 (- n 1)))))) compared using Scheme 's equal ? and member procedures , so we (define (term-equal? x y) (cond ((pair? x) (and (pair? y) (symbol-record-equal? (car x) (car y)) (term-args-equal? (cdr x) (cdr y)))) (else (equal? x y)))) (define (term-args-equal? lst1 lst2) (cond ((null? lst1) (null? lst2)) ((null? lst2) #f) ((term-equal? (car lst1) (car lst2)) (term-args-equal? (cdr lst1) (cdr lst2))) (else #f))) (define (term-member? x lst) (cond ((null? lst) #f) ((term-equal? x (car lst)) #t) (else (term-member? x (cdr lst))))) (set! setup-boyer (lambda () (set! *symbol-records-alist* '()) (set! if-constructor (symbol->symbol-record 'if)) (set! false-term (translate-term '(f))) (set! true-term (translate-term '(t))) (setup))) (set! test-boyer (lambda (alist term n) (set! rewrite-count 0) (let ((answer (test alist term n))) (if answer rewrite-count #f)))))
1423e43073c3bbf0069e59a10b56fafd921a06464146b6f90b3ed4a41127303f
GaloisInc/halfs
Inode.hs
{-# LANGUAGE Rank2Types, FlexibleContexts #-} module Tests.Inode ( qcProps ) where import Control.Concurrent import Data.ByteString (ByteString) import Prelude hiding (read) import Test.QuickCheck hiding (numTests) import Test.QuickCheck.Monadic import qualified Data.ByteString as BS import qualified Control.Exception as CE import Halfs.BlockMap import Halfs.Classes import Halfs.CoreAPI import Halfs.Errors import Halfs.HalfsState import Halfs.Inode import Halfs.Monad import Halfs.Protection import Halfs.SuperBlock import Halfs.Types import System.Device.BlockDevice (BlockDevice(..)) import Tests.Instances (printableBytes) import Tests.Types import Tests.Utils -- import Debug.Trace -------------------------------------------------------------------------------- Inode properties qcProps :: Bool -> [(Args, Property)] qcProps quick = Inode module invariants exec 10 "Inode module invariants" propM_inodeModuleInvs Inode stream write / read/(over)write / read property exec 10 "Basic WRWR" propM_basicWRWR Inode stream write / read/(truncating)write / read property exec 10 "Truncating WRWR" propM_truncWRWR Inode length - specific stream write / read exec 10 "Length-specific WR" propM_lengthWR Inode single reader / writer lock testing exec 10 "Inode single reader/write mutex" propM_inodeMutexOK ] where exec = mkMemDevExec quick "Inode" -------------------------------------------------------------------------------- -- Property Implementations -- Note that in many of these properties we compare timestamps using < -- and >; these may need to be <= and >= if the underlying clock -- resolution is too coarse! | Tests module invariants propM_inodeModuleInvs :: HalfsCapable b t r l m => BDGeom -> BlockDevice m -> PropertyM m () propM_inodeModuleInvs _g _dev = do -- Check geometry/padding invariants minInodeSz <- run $ computeMinimalInodeSize =<< getTime minExtSz <- run $ minimalExtSize assert (minInodeSz == minExtSz) -- | Tests basic write/reads & overwrites propM_basicWRWR :: HalfsCapable b t r l m => BDGeom -> BlockDevice m -> PropertyM m () propM_basicWRWR _g dev = do withFSData dev $ \fs rdirIR dataSz testData -> do -- Make an inode to muck around with inr <- run $ blockAddrToInodeRef `fmap` (alloc1 (hsBlockMap fs) >>= maybe (fail "can't alloc inode") return ) run $ bdWriteBlock dev (inodeRefToBlockAddr inr) =<< buildEmptyInodeEnc dev RegularFile defaultFilePerms inr rdirIR defaultUser defaultGroup let exec = execH "propM_basicWRWR" fs time = exec "obtain time" getTime dataSzI = fromIntegral dataSz checkWriteMD t = \sz eb -> chk sz eb (t <=) (t <=) (t <=) checkReadMD t = \sz eb -> chk sz eb (t <=) (t >=) (t <=) chk = checkInodeMetadata fs inr RegularFile defaultFilePerms defaultUser defaultGroup exec " Guard against interesting regression " $ do let dataLens = [ 17920 , 18404 , 18481 ] forM _ dataLens $ \len - > do let toWrite = BS.replicate len 0x58 writeStream inr 0 True toWrite ` catchError ` \e - > trace ( " e = " + + show e ) $ CE.assert False ( return ( ) ) exec "Guard against interesting regression" $ do let dataLens = [17920, 18404, 18481] forM_ dataLens $ \len -> do let toWrite = BS.replicate len 0x58 writeStream inr 0 True toWrite `catchError` \e -> trace ("e = " ++ show e) $ CE.assert False (return ()) -} (_, _, api, apc) <- exec "Obtaining sizes" $ computeSizes (bdBlockSize dev) let expBlks = calcExpBlockCount (bdBlockSize dev) api apc dataSz -- Check single-byte write t0 <- time exec "Write stream 1 byte" $ writeStream inr 0 True dummyByte expecting 1 inode block and 1 data block Expected error : write past end of 1 - byte stream ( beyond block boundary ) e0 <- runH fs $ writeStream inr (bdBlockSize dev) False testData case e0 of Left (HE_InvalidStreamIndex idx) -> assert (idx == bdBlockSize dev) _ -> assert False Expected error : write past end of 1 - byte stream ( beyond byte boundary ) e0' <- runH fs $ writeStream inr 2 False testData case e0' of Left (HE_InvalidStreamIndex idx) -> assert (idx == 2) _ -> assert False -- The repeated operations may seem odd here, but their repetition and -- order push on a few inode data persistence bugs. -- Check truncation to 0 bytes t1 <- time exec "Stream trunc to 0 bytes" $ writeStream inr 0 True BS.empty expecting 1 inode block only ( no data blocks ) -- Check single-byte write t2 <- time exec "Write stream 1 byte" $ writeStream inr 0 True dummyByte expecting 1 inode block and 1 data block -- Check truncation to 0 bytes again t3 <- time exec "Stream trunc to 0 bytes" $ writeStream inr 0 True BS.empty expecting 1 inode block only ( no data blocks ) -- Non-truncating write & read-back of generated data t4 <- time exec "Non-truncating write" $ writeStream inr 0 False testData checkWriteMD t4 dataSzI expBlks t5 <- time bs1 <- exec "Readback 1" $ readStream inr 0 Nothing checkReadMD t5 dataSz expBlks assert (BS.length bs1 == BS.length testData) -- when (bs1 /= testData) $ CE.assert False $ return () assert (bs1 == testData) -- Recheck truncation to 0 bytes t6 <- time exec "Stream trunc to 0 bytes" $ writeStream inr 0 True BS.empty expecting 1 inode block only ( no data blocks ) -- Non-truncating rewrite of generated data t7 <- time exec "Non-truncating write" $ writeStream inr 0 False testData checkWriteMD t7 dataSzI expBlks -- Non-truncating partial overwrite of new data & read-back forAllM (choose (1, dataSz `div` 2)) $ \overwriteSz -> do forAllM (choose (0, dataSz `div` 2 - 1)) $ \startByte -> do forAllM (printableBytes overwriteSz) $ \newData -> do -- Useful 512 test for 512B block size -- let overwriteSz = 9201 -- startByte = 8721 newData = BS.replicate overwriteSz 0x58 t8 <- time exec "Non-trunc overwrite" $ writeStream inr (fromIntegral startByte) False newData checkWriteMD t8 dataSzI expBlks t9 <- time bs2 <- exec "Readback 2" $ readStream inr 0 Nothing checkReadMD t9 dataSz expBlks let expected = bsTake startByte testData `BS.append` newData `BS.append` bsDrop (startByte + overwriteSz) testData assert (BS.length bs2 == BS.length expected) when (bs2 /= expected) $ do -- trace ("bs2 = " ++ show bs2) $ do -- trace ("expected = " ++ show expected) $ do CE.assert False $ return () assert (bs2 == expected) -- Check truncation to a single byte again w/ read-back t10 <- time exec "Stream trunc to 1 byte" $ writeStream inr 0 True dummyByte expecting 1 inode block and 1 data block t11 <- time bs3 <- exec "Readback 3" $ readStream inr 0 Nothing checkReadMD t11 1 2 assert (bs3 == dummyByte) where dummyByte = BS.singleton 0 -- | Tests truncate writes and read-backs of random size propM_truncWRWR :: HalfsCapable b t r l m => BDGeom -> BlockDevice m -> PropertyM m () propM_truncWRWR _g dev = do withFSData dev $ \fs rdirIR dataSz testData -> do let exec = execH "propM_truncWRWR" fs time = exec "obtain time" getTime numFree = sreadRef $ bmNumFree $ hsBlockMap fs checkWriteMD t = \sz eb -> chk sz eb (t <=) (t <=) (t <=) checkReadMD t = \sz eb -> chk sz eb (t <=) (t >=) (t <=) chk = checkInodeMetadata fs rdirIR Directory rootDirPerms rootUser rootGroup (_, _, api, apc) <- exec "Obtaining sizes" $ computeSizes (bdBlockSize dev) let expBlks = calcExpBlockCount (bdBlockSize dev) api apc -- Non-truncating write t1 <- time exec "Non-truncating write" $ writeStream rdirIR 0 False testData checkWriteMD t1 dataSz (expBlks dataSz) forAllM (choose (dataSz `div` 8, dataSz `div` 4)) $ \dataSz' -> do forAllM (printableBytes dataSz') $ \testData' -> do forAllM (choose (1, dataSz - dataSz' - 1)) $ \truncIdx -> do let dataSz'' = dataSz' + truncIdx freeBlks <- numFree -- Free blks before truncate -- Truncating write t2 <- time exec "Truncating write" $ writeStream rdirIR (fromIntegral truncIdx) True testData' checkWriteMD t2 dataSz'' (expBlks dataSz'') -- Read until the end of the stream and check truncation t3 <- time bs <- exec "Readback" $ readStream rdirIR (fromIntegral truncIdx) Nothing checkReadMD t3 dataSz'' (expBlks dataSz'') assert (BS.length bs == BS.length testData') assert (bs == testData') Sanity check the BlockMap 's free count freeBlks' <- numFree -- Free blks after truncate let minExpectedFree = (dataSz - dataSz'') `div` (fromIntegral $ bdBlockSize dev) May also have frees on Ext storage , so this is just a lower bound assert $ minExpectedFree <= fromIntegral (freeBlks' - freeBlks) -- | Tests bounded reads of random offset and length propM_lengthWR :: HalfsCapable b t r l m => BDGeom -> BlockDevice m -> PropertyM m () propM_lengthWR _g dev = withFSData dev $ \fs rdirIR dataSz testData -> do let exec = execH "propM_lengthWR" fs time = exec "obtain time" getTime blkSz = bdBlockSize dev checkWriteMD t = \sz eb -> chk sz eb (t <=) (t <=) (t <=) checkReadMD t = \sz eb -> chk sz eb (t <=) (t >=) (t <=) chk = checkInodeMetadata fs rdirIR Directory rootDirPerms rootUser rootGroup (_, _, api, apc) <- exec "Obtaining sizes" $ computeSizes (bdBlockSize dev) let expBlks = calcExpBlockCount blkSz api apc dataSz -- Write random data to the stream t1 <- time exec "Populate" $ writeStream rdirIR 0 False testData checkWriteMD t1 dataSz expBlks If possible , read a minimum of one full inode + 1 byte worth of data -- into the next inode to push on boundary conditions & spill arithmetic. forAllM (arbitrary :: Gen Bool) $ \b -> do blksPerCarrier <- run $ if b then computeNumInodeAddrsM blkSz else computeNumExtAddrsM blkSz let minReadLen = min dataSz (fromIntegral $ blksPerCarrier * blkSz + 1) forAllM (choose (minReadLen, dataSz)) $ \readLen -> do forAllM (choose (0, dataSz - 1)) $ \startIdx -> do let readLen' = min readLen (dataSz - startIdx) stIdxW64 = fromIntegral startIdx t2 <- time bs <- exec "Bounded readback" $ readStream rdirIR stIdxW64 (Just $ fromIntegral readLen') assert (bs == bsTake readLen' (bsDrop startIdx testData)) checkReadMD t2 dataSz expBlks -- | Sanity check: reads/write operations to inode streams are atomic propM_inodeMutexOK :: BDGeom -> BlockDevice IO -> PropertyM IO () propM_inodeMutexOK _g dev = do fs <- runHNoEnv (newfs dev rootUser rootGroup rootDirPerms) >> mountOK dev rdirIR <- rootDir `fmap` sreadRef (hsSuperBlock fs) 1 ) Choose a random number n s.t . 8 < = n < = 32 -- 2 ) Create n unique bytestrings that each cover the entire randomly - sized write region . Call this set of bytestrings ' bstrings ' . -- 3 ) Spawn n test threads , and create a unique bytestring for each to write . -- Each thread: -- * Blindly writes its bytestring ' bs ' to the stream -- -- * Reads back entire stream, and ensures that what is read back is a member of bstrings ; if what is read back is also not -- equal to what was written, we have detected interleaving. -- -- * Terminates -- -- We keep the write regions relatively small since we'll be creating many of -- them. forAllM (min (256*1024) `fmap` choose (lo, hi)) $ \dataSz -> do forAllM (choose (8::Int, 32)) $ \n -> do forAllM (foldM (uniqueBS dataSz) [] [1..n]) $ \bstrings -> do ch <- run newChan -- ^ Kick off the test threads mapM_ (run . forkIO . test fs ch rdirIR dataSz bstrings) bstrings (passed, _interleaved) <- unzip `fmap` replicateM n (run $ readChan ch) -- ^ predicate barrier for all threads assert $ and passed -- The following is not needed, but it's useful information to confirm that -- interleaving is actually being tested (as opposed to the trivial-pass -- scenario where each thread reads what it just wrote). -- when (not $ or interleaved) $ run $ putStrLn " WARNING : No interleaving detected in propM_inodeMutexOK " where maxBlocks = safeToInt (bdNumBlocks dev) lo = blkSize * (maxBlocks `div` 32) hi = blkSize * (maxBlocks `div` 16) blkSize = safeToInt (bdBlockSize dev) -- uniqueBS sz acc _ = (:acc) `fmap` (printableBytes sz `suchThat` (not . (`elem` acc))) -- test fs ch inr sz bstrings bs = do _ <- runHalfs fs $ writeStream inr 0 False bs eeb <- runHalfs fs $ readStream inr 0 Nothing case eeb of Left _err -> writeChan ch (False, error "interleaved not computed") Right rb -> writeChan ch (rb' `elem` bstrings, rb' /= bs) where rb' = bsTake sz rb -- since unbounded readStream -- returns multiples of the -- block size -------------------------------------------------------------------------------- -- Misc utility/helper functions withFSData :: HalfsCapable b t r l m => BlockDevice m -> (HalfsState b r l m -> InodeRef -> Int -> ByteString -> PropertyM m ()) -> PropertyM m () withFSData dev f = do fs <- runHNoEnv (newfs dev rootUser rootGroup rootDirPerms) >> mountOK dev rdirIR <- rootDir `fmap` sreadRef (hsSuperBlock fs) withData dev $ f fs rdirIR newtype FillBlocks a = FillBlocks a deriving Show newtype SpillCnt a = SpillCnt a deriving Show Generates random data of random size between 1/8 - 1/4 of the device withData :: HalfsCapable b t r l m => The blk dev -> (Int -> ByteString -> PropertyM m ()) -- Action -> PropertyM m () withData dev f = do nAddrs <- run $ computeNumExtAddrsM (bdBlockSize dev) let maxBlocks = safeToInt $ bdNumBlocks dev lo = maxBlocks `div` 8 hi = maxBlocks `div` 4 fbr = FillBlocks `fmap` choose (lo, hi) scr = SpillCnt `fmap` choose (0, safeToInt nAddrs) forAllM fbr $ \(FillBlocks fillBlocks) -> do forAllM scr $ \(SpillCnt spillCnt) -> do fillBlocks is the number of blocks to fill on the write ( 1/8 - 1/4 of dev ) -- spillCnt is the number of blocks to write into the last ext in the chain let dataSz = fillBlocks * safeToInt (bdBlockSize dev) + spillCnt forAllM (printableBytes dataSz) (f dataSz) -- Useful debugging test for 512B block size : let dataSz = 35 * 512 + 2 * 512 f dataSz ( BS.replicate dataSz 0x2E ) checkInodeMetadata :: (HalfsCapable b t r l m, Integral a) => HalfsState b r l m -> InodeRef -> FileType -- expected filetype -> FileMode -- expected filemode -> UserID -- expected userid expected -> a -- expected filesize -> a -- expected allocated block count -> (t -> Bool) -- access time predicate -> (t -> Bool) -- modification time predicate -> (t -> Bool) -- status change time predicate -> PropertyM m () checkInodeMetadata fs inr expFileTy expMode expUsr expGrp expFileSz expNumBlocks accessp modifyp changep = do st <- execH "checkInodeMetadata" fs "filestat" $ fileStat inr checkFileStat st expFileSz expFileTy expMode expUsr expGrp expNumBlocks accessp modifyp changep
null
https://raw.githubusercontent.com/GaloisInc/halfs/2eb16fb3744e6221ee706b6bd290681a08c18048/test/src/Tests/Inode.hs
haskell
# LANGUAGE Rank2Types, FlexibleContexts # import Debug.Trace ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Property Implementations Note that in many of these properties we compare timestamps using < and >; these may need to be <= and >= if the underlying clock resolution is too coarse! Check geometry/padding invariants | Tests basic write/reads & overwrites Make an inode to muck around with Check single-byte write The repeated operations may seem odd here, but their repetition and order push on a few inode data persistence bugs. Check truncation to 0 bytes Check single-byte write Check truncation to 0 bytes again Non-truncating write & read-back of generated data when (bs1 /= testData) $ CE.assert False $ return () Recheck truncation to 0 bytes Non-truncating rewrite of generated data Non-truncating partial overwrite of new data & read-back Useful 512 test for 512B block size let overwriteSz = 9201 startByte = 8721 trace ("bs2 = " ++ show bs2) $ do trace ("expected = " ++ show expected) $ do Check truncation to a single byte again w/ read-back | Tests truncate writes and read-backs of random size Non-truncating write Free blks before truncate Truncating write Read until the end of the stream and check truncation Free blks after truncate | Tests bounded reads of random offset and length Write random data to the stream into the next inode to push on boundary conditions & spill arithmetic. | Sanity check: reads/write operations to inode streams are atomic Each thread: * Reads back entire stream, and ensures that what is read back equal to what was written, we have detected interleaving. * Terminates We keep the write regions relatively small since we'll be creating many of them. ^ Kick off the test threads ^ predicate barrier for all threads The following is not needed, but it's useful information to confirm that interleaving is actually being tested (as opposed to the trivial-pass scenario where each thread reads what it just wrote). when (not $ or interleaved) $ since unbounded readStream returns multiples of the block size ------------------------------------------------------------------------------ Misc utility/helper functions Action spillCnt is the number of blocks to write into the last ext in the chain Useful debugging test for 512B block size : expected filetype expected filemode expected userid expected filesize expected allocated block count access time predicate modification time predicate status change time predicate
module Tests.Inode ( qcProps ) where import Control.Concurrent import Data.ByteString (ByteString) import Prelude hiding (read) import Test.QuickCheck hiding (numTests) import Test.QuickCheck.Monadic import qualified Data.ByteString as BS import qualified Control.Exception as CE import Halfs.BlockMap import Halfs.Classes import Halfs.CoreAPI import Halfs.Errors import Halfs.HalfsState import Halfs.Inode import Halfs.Monad import Halfs.Protection import Halfs.SuperBlock import Halfs.Types import System.Device.BlockDevice (BlockDevice(..)) import Tests.Instances (printableBytes) import Tests.Types import Tests.Utils Inode properties qcProps :: Bool -> [(Args, Property)] qcProps quick = Inode module invariants exec 10 "Inode module invariants" propM_inodeModuleInvs Inode stream write / read/(over)write / read property exec 10 "Basic WRWR" propM_basicWRWR Inode stream write / read/(truncating)write / read property exec 10 "Truncating WRWR" propM_truncWRWR Inode length - specific stream write / read exec 10 "Length-specific WR" propM_lengthWR Inode single reader / writer lock testing exec 10 "Inode single reader/write mutex" propM_inodeMutexOK ] where exec = mkMemDevExec quick "Inode" | Tests module invariants propM_inodeModuleInvs :: HalfsCapable b t r l m => BDGeom -> BlockDevice m -> PropertyM m () propM_inodeModuleInvs _g _dev = do minInodeSz <- run $ computeMinimalInodeSize =<< getTime minExtSz <- run $ minimalExtSize assert (minInodeSz == minExtSz) propM_basicWRWR :: HalfsCapable b t r l m => BDGeom -> BlockDevice m -> PropertyM m () propM_basicWRWR _g dev = do withFSData dev $ \fs rdirIR dataSz testData -> do inr <- run $ blockAddrToInodeRef `fmap` (alloc1 (hsBlockMap fs) >>= maybe (fail "can't alloc inode") return ) run $ bdWriteBlock dev (inodeRefToBlockAddr inr) =<< buildEmptyInodeEnc dev RegularFile defaultFilePerms inr rdirIR defaultUser defaultGroup let exec = execH "propM_basicWRWR" fs time = exec "obtain time" getTime dataSzI = fromIntegral dataSz checkWriteMD t = \sz eb -> chk sz eb (t <=) (t <=) (t <=) checkReadMD t = \sz eb -> chk sz eb (t <=) (t >=) (t <=) chk = checkInodeMetadata fs inr RegularFile defaultFilePerms defaultUser defaultGroup exec " Guard against interesting regression " $ do let dataLens = [ 17920 , 18404 , 18481 ] forM _ dataLens $ \len - > do let toWrite = BS.replicate len 0x58 writeStream inr 0 True toWrite ` catchError ` \e - > trace ( " e = " + + show e ) $ CE.assert False ( return ( ) ) exec "Guard against interesting regression" $ do let dataLens = [17920, 18404, 18481] forM_ dataLens $ \len -> do let toWrite = BS.replicate len 0x58 writeStream inr 0 True toWrite `catchError` \e -> trace ("e = " ++ show e) $ CE.assert False (return ()) -} (_, _, api, apc) <- exec "Obtaining sizes" $ computeSizes (bdBlockSize dev) let expBlks = calcExpBlockCount (bdBlockSize dev) api apc dataSz t0 <- time exec "Write stream 1 byte" $ writeStream inr 0 True dummyByte expecting 1 inode block and 1 data block Expected error : write past end of 1 - byte stream ( beyond block boundary ) e0 <- runH fs $ writeStream inr (bdBlockSize dev) False testData case e0 of Left (HE_InvalidStreamIndex idx) -> assert (idx == bdBlockSize dev) _ -> assert False Expected error : write past end of 1 - byte stream ( beyond byte boundary ) e0' <- runH fs $ writeStream inr 2 False testData case e0' of Left (HE_InvalidStreamIndex idx) -> assert (idx == 2) _ -> assert False t1 <- time exec "Stream trunc to 0 bytes" $ writeStream inr 0 True BS.empty expecting 1 inode block only ( no data blocks ) t2 <- time exec "Write stream 1 byte" $ writeStream inr 0 True dummyByte expecting 1 inode block and 1 data block t3 <- time exec "Stream trunc to 0 bytes" $ writeStream inr 0 True BS.empty expecting 1 inode block only ( no data blocks ) t4 <- time exec "Non-truncating write" $ writeStream inr 0 False testData checkWriteMD t4 dataSzI expBlks t5 <- time bs1 <- exec "Readback 1" $ readStream inr 0 Nothing checkReadMD t5 dataSz expBlks assert (BS.length bs1 == BS.length testData) assert (bs1 == testData) t6 <- time exec "Stream trunc to 0 bytes" $ writeStream inr 0 True BS.empty expecting 1 inode block only ( no data blocks ) t7 <- time exec "Non-truncating write" $ writeStream inr 0 False testData checkWriteMD t7 dataSzI expBlks forAllM (choose (1, dataSz `div` 2)) $ \overwriteSz -> do forAllM (choose (0, dataSz `div` 2 - 1)) $ \startByte -> do forAllM (printableBytes overwriteSz) $ \newData -> do newData = BS.replicate overwriteSz 0x58 t8 <- time exec "Non-trunc overwrite" $ writeStream inr (fromIntegral startByte) False newData checkWriteMD t8 dataSzI expBlks t9 <- time bs2 <- exec "Readback 2" $ readStream inr 0 Nothing checkReadMD t9 dataSz expBlks let expected = bsTake startByte testData `BS.append` newData `BS.append` bsDrop (startByte + overwriteSz) testData assert (BS.length bs2 == BS.length expected) when (bs2 /= expected) $ do CE.assert False $ return () assert (bs2 == expected) t10 <- time exec "Stream trunc to 1 byte" $ writeStream inr 0 True dummyByte expecting 1 inode block and 1 data block t11 <- time bs3 <- exec "Readback 3" $ readStream inr 0 Nothing checkReadMD t11 1 2 assert (bs3 == dummyByte) where dummyByte = BS.singleton 0 propM_truncWRWR :: HalfsCapable b t r l m => BDGeom -> BlockDevice m -> PropertyM m () propM_truncWRWR _g dev = do withFSData dev $ \fs rdirIR dataSz testData -> do let exec = execH "propM_truncWRWR" fs time = exec "obtain time" getTime numFree = sreadRef $ bmNumFree $ hsBlockMap fs checkWriteMD t = \sz eb -> chk sz eb (t <=) (t <=) (t <=) checkReadMD t = \sz eb -> chk sz eb (t <=) (t >=) (t <=) chk = checkInodeMetadata fs rdirIR Directory rootDirPerms rootUser rootGroup (_, _, api, apc) <- exec "Obtaining sizes" $ computeSizes (bdBlockSize dev) let expBlks = calcExpBlockCount (bdBlockSize dev) api apc t1 <- time exec "Non-truncating write" $ writeStream rdirIR 0 False testData checkWriteMD t1 dataSz (expBlks dataSz) forAllM (choose (dataSz `div` 8, dataSz `div` 4)) $ \dataSz' -> do forAllM (printableBytes dataSz') $ \testData' -> do forAllM (choose (1, dataSz - dataSz' - 1)) $ \truncIdx -> do let dataSz'' = dataSz' + truncIdx t2 <- time exec "Truncating write" $ writeStream rdirIR (fromIntegral truncIdx) True testData' checkWriteMD t2 dataSz'' (expBlks dataSz'') t3 <- time bs <- exec "Readback" $ readStream rdirIR (fromIntegral truncIdx) Nothing checkReadMD t3 dataSz'' (expBlks dataSz'') assert (BS.length bs == BS.length testData') assert (bs == testData') Sanity check the BlockMap 's free count let minExpectedFree = (dataSz - dataSz'') `div` (fromIntegral $ bdBlockSize dev) May also have frees on Ext storage , so this is just a lower bound assert $ minExpectedFree <= fromIntegral (freeBlks' - freeBlks) propM_lengthWR :: HalfsCapable b t r l m => BDGeom -> BlockDevice m -> PropertyM m () propM_lengthWR _g dev = withFSData dev $ \fs rdirIR dataSz testData -> do let exec = execH "propM_lengthWR" fs time = exec "obtain time" getTime blkSz = bdBlockSize dev checkWriteMD t = \sz eb -> chk sz eb (t <=) (t <=) (t <=) checkReadMD t = \sz eb -> chk sz eb (t <=) (t >=) (t <=) chk = checkInodeMetadata fs rdirIR Directory rootDirPerms rootUser rootGroup (_, _, api, apc) <- exec "Obtaining sizes" $ computeSizes (bdBlockSize dev) let expBlks = calcExpBlockCount blkSz api apc dataSz t1 <- time exec "Populate" $ writeStream rdirIR 0 False testData checkWriteMD t1 dataSz expBlks If possible , read a minimum of one full inode + 1 byte worth of data forAllM (arbitrary :: Gen Bool) $ \b -> do blksPerCarrier <- run $ if b then computeNumInodeAddrsM blkSz else computeNumExtAddrsM blkSz let minReadLen = min dataSz (fromIntegral $ blksPerCarrier * blkSz + 1) forAllM (choose (minReadLen, dataSz)) $ \readLen -> do forAllM (choose (0, dataSz - 1)) $ \startIdx -> do let readLen' = min readLen (dataSz - startIdx) stIdxW64 = fromIntegral startIdx t2 <- time bs <- exec "Bounded readback" $ readStream rdirIR stIdxW64 (Just $ fromIntegral readLen') assert (bs == bsTake readLen' (bsDrop startIdx testData)) checkReadMD t2 dataSz expBlks propM_inodeMutexOK :: BDGeom -> BlockDevice IO -> PropertyM IO () propM_inodeMutexOK _g dev = do fs <- runHNoEnv (newfs dev rootUser rootGroup rootDirPerms) >> mountOK dev rdirIR <- rootDir `fmap` sreadRef (hsSuperBlock fs) 1 ) Choose a random number n s.t . 8 < = n < = 32 2 ) Create n unique bytestrings that each cover the entire randomly - sized write region . Call this set of bytestrings ' bstrings ' . 3 ) Spawn n test threads , and create a unique bytestring for each to write . * Blindly writes its bytestring ' bs ' to the stream is a member of bstrings ; if what is read back is also not forAllM (min (256*1024) `fmap` choose (lo, hi)) $ \dataSz -> do forAllM (choose (8::Int, 32)) $ \n -> do forAllM (foldM (uniqueBS dataSz) [] [1..n]) $ \bstrings -> do ch <- run newChan mapM_ (run . forkIO . test fs ch rdirIR dataSz bstrings) bstrings (passed, _interleaved) <- unzip `fmap` replicateM n (run $ readChan ch) assert $ and passed run $ putStrLn " WARNING : No interleaving detected in propM_inodeMutexOK " where maxBlocks = safeToInt (bdNumBlocks dev) lo = blkSize * (maxBlocks `div` 32) hi = blkSize * (maxBlocks `div` 16) blkSize = safeToInt (bdBlockSize dev) uniqueBS sz acc _ = (:acc) `fmap` (printableBytes sz `suchThat` (not . (`elem` acc))) test fs ch inr sz bstrings bs = do _ <- runHalfs fs $ writeStream inr 0 False bs eeb <- runHalfs fs $ readStream inr 0 Nothing case eeb of Left _err -> writeChan ch (False, error "interleaved not computed") Right rb -> writeChan ch (rb' `elem` bstrings, rb' /= bs) withFSData :: HalfsCapable b t r l m => BlockDevice m -> (HalfsState b r l m -> InodeRef -> Int -> ByteString -> PropertyM m ()) -> PropertyM m () withFSData dev f = do fs <- runHNoEnv (newfs dev rootUser rootGroup rootDirPerms) >> mountOK dev rdirIR <- rootDir `fmap` sreadRef (hsSuperBlock fs) withData dev $ f fs rdirIR newtype FillBlocks a = FillBlocks a deriving Show newtype SpillCnt a = SpillCnt a deriving Show Generates random data of random size between 1/8 - 1/4 of the device withData :: HalfsCapable b t r l m => The blk dev -> PropertyM m () withData dev f = do nAddrs <- run $ computeNumExtAddrsM (bdBlockSize dev) let maxBlocks = safeToInt $ bdNumBlocks dev lo = maxBlocks `div` 8 hi = maxBlocks `div` 4 fbr = FillBlocks `fmap` choose (lo, hi) scr = SpillCnt `fmap` choose (0, safeToInt nAddrs) forAllM fbr $ \(FillBlocks fillBlocks) -> do forAllM scr $ \(SpillCnt spillCnt) -> do fillBlocks is the number of blocks to fill on the write ( 1/8 - 1/4 of dev ) let dataSz = fillBlocks * safeToInt (bdBlockSize dev) + spillCnt forAllM (printableBytes dataSz) (f dataSz) let dataSz = 35 * 512 + 2 * 512 f dataSz ( BS.replicate dataSz 0x2E ) checkInodeMetadata :: (HalfsCapable b t r l m, Integral a) => HalfsState b r l m -> InodeRef expected -> PropertyM m () checkInodeMetadata fs inr expFileTy expMode expUsr expGrp expFileSz expNumBlocks accessp modifyp changep = do st <- execH "checkInodeMetadata" fs "filestat" $ fileStat inr checkFileStat st expFileSz expFileTy expMode expUsr expGrp expNumBlocks accessp modifyp changep
7941c91b7e108098ce0b72a7e628fa1a3b33c8b545c4ce09750ea8334283c676
silviucpp/elocaltime
elocaltime_nif.erl
-module(elocaltime_nif). -define(NOT_LOADED, not_loaded(?LINE)). -on_load(load_nif/0). -export([ new_timezone/1, absolute_lookup/2, civil_lookup/2, format/2, format/3 ]). %% nif functions load_nif() -> SoName = get_priv_path(?MODULE), io:format(<<"Loading library: ~p ~n">>, [SoName]), ok = erlang:load_nif(SoName, 0). get_priv_path(File) -> case code:priv_dir(elocaltime) of {error, bad_name} -> Ebin = filename:dirname(code:which(?MODULE)), filename:join([filename:dirname(Ebin), "priv", File]); Dir -> filename:join(Dir, File) end. not_loaded(Line) -> erlang:nif_error({not_loaded, [{module, ?MODULE}, {line, Line}]}). new_timezone(_Timezone) -> ?NOT_LOADED. absolute_lookup(_Date, _TimezoneRef) -> ?NOT_LOADED. civil_lookup(_Date, _TimezoneRef) -> ?NOT_LOADED. format(_Format, _Ts) -> ?NOT_LOADED. format(_Format, _Ts, _Tz) -> ?NOT_LOADED.
null
https://raw.githubusercontent.com/silviucpp/elocaltime/274a2f78fdc394cd3450c9c247ffbf6d486a48b3/src/elocaltime_nif.erl
erlang
nif functions
-module(elocaltime_nif). -define(NOT_LOADED, not_loaded(?LINE)). -on_load(load_nif/0). -export([ new_timezone/1, absolute_lookup/2, civil_lookup/2, format/2, format/3 ]). load_nif() -> SoName = get_priv_path(?MODULE), io:format(<<"Loading library: ~p ~n">>, [SoName]), ok = erlang:load_nif(SoName, 0). get_priv_path(File) -> case code:priv_dir(elocaltime) of {error, bad_name} -> Ebin = filename:dirname(code:which(?MODULE)), filename:join([filename:dirname(Ebin), "priv", File]); Dir -> filename:join(Dir, File) end. not_loaded(Line) -> erlang:nif_error({not_loaded, [{module, ?MODULE}, {line, Line}]}). new_timezone(_Timezone) -> ?NOT_LOADED. absolute_lookup(_Date, _TimezoneRef) -> ?NOT_LOADED. civil_lookup(_Date, _TimezoneRef) -> ?NOT_LOADED. format(_Format, _Ts) -> ?NOT_LOADED. format(_Format, _Ts, _Tz) -> ?NOT_LOADED.
c76771145cbca3364ec5274e0d031d882c26c64c69af22c72e4300b641225f77
borodust/cl-flow
utils.lisp
(cl:in-package :cl-flow) #+flow-optimized (alexandria:define-constant +optimize-form+ '(optimize (speed 3) (safety 1) (debug 0)) :test #'equal) #-flow-optimized (alexandria:define-constant +optimize-form+ '(optimize) :test #'equal)
null
https://raw.githubusercontent.com/borodust/cl-flow/bb95fda8bdeb35723f71edcdb88cef754dbcf0cc/src/utils.lisp
lisp
(cl:in-package :cl-flow) #+flow-optimized (alexandria:define-constant +optimize-form+ '(optimize (speed 3) (safety 1) (debug 0)) :test #'equal) #-flow-optimized (alexandria:define-constant +optimize-form+ '(optimize) :test #'equal)
add792c878ce543cf4edf520e99b4ccb9210bb202e4338bb770f34f7dc3fefe3
guilespi/clj-zipkin
tracer.clj
(ns clj-zipkin.tracer (:require [thrift-clj.core :as thrift] [clojure.data.codec.base64 :as b64] [clj-scribe :as scribe] [thrift-clj.gen.core :as c] [thrift-clj.thrift.types :as thrift-types] [clj-time.core :as time] [clj-time.coerce :as time-coerce])) (def ^:dynamic *default-service-name* "Unknown Service") ;;the following *hack* is to avoid binary annotations being ;;stringified by the type wrapper, problem is caused because Value field in BinaryAnnotation.java is a binary hinted as a String : ;; new org.apache.thrift.protocol . TField("value " , org.apache.thrift.protocol . TType . STRING , ( short)2 ) ; ;; public ByteBuffer value; // required ;; java file is autogen by thriftc so some validation should be done there ;;by a caritative soul. Now we just avoid string wrapping hijacking the mm (def my-extend-field (var-get (find-var 'thrift-clj.thrift.types/extend-field-metadata-map))) (remove-method my-extend-field :string) (thrift/import (:types [com.twitter.zipkin.gen Span Annotation BinaryAnnotation AnnotationType Endpoint LogEntry StoreAggregatesException AdjustableRateException]) (:clients com.twitter.zipkin.gen.ZipkinCollector)) (defn ip-str-to-int [str-ip] (let [nums (vec (map read-string (clojure.string/split str-ip #"\.")))] (+ (* (nums 0) 16777216) (* (nums 1) 65536) (* (nums 2) 256) (nums 3)))) (defn str->bytes [str] (bytes (byte-array (map (comp byte int) str)))) (defn thrift->base64 "Serializes a thrift span object to be sent through the wires" [data] (let [buffer (org.apache.thrift.transport.TMemoryBuffer. 40000) protocol (org.apache.thrift.protocol.TBinaryProtocol. buffer) ;side effectish step _ (.write (.to_thrift* data) protocol)] (String. (b64/encode (.getArray buffer) 0 (.length buffer)) "UTF-8"))) (defn host->endpoint "Given a host in string or map format creates a thrift zipkin endpoint object" [host] (condp = (class host) java.lang.String (Endpoint. (ip-str-to-int host) 0 *default-service-name*) clojure.lang.PersistentArrayMap (Endpoint. (ip-str-to-int (or (:ip host) (.getHostAddress (java.net.InetAddress/getLocalHost)))) (or (:port host) 0) (or (:service host) *default-service-name*)) nil (Endpoint. (ip-str-to-int (.getHostAddress (java.net.InetAddress/getLocalHost))) 0 *default-service-name*) (throw (str "Invalid host value" (class host) "not supported")))) ;;According to tryfer sources, zipkin has trouble recording traces with ids larger than ( 2 * * 56 ) - 1 (def rand-max (dec (Math/pow 2 24))) (defn create-id "Creates a new id to be used as trace or span id" [] (rand-int rand-max)) (defn create-timestamp-span "Creates a new span with start/finish annotations" [span host trace-id span-id parent-id start finish annotations] (let [endpoint (host->endpoint host) start-annotation (Annotation. (* 1000 (time-coerce/to-long start)) (str "start:" (name span)) endpoint 0) finish-annotation (Annotation. (* 1000 (time-coerce/to-long finish)) (str "end:" (name span)) endpoint 0) binary-annotations (mapv (fn [[k v]] (BinaryAnnotation. (name k) (java.nio.ByteBuffer/wrap (.getBytes (str v))) AnnotationType/STRING endpoint)) annotations)] (thrift->base64 (Span. trace-id (name span) span-id parent-id [start-annotation finish-annotation] binary-annotations 0)))) ;;tracing macro for nested recording (defmulti parse-item (fn [form] (cond (seq? form) :seq (vector? form) :vector :else :default))) ;;if found a call to original trace in the ast ;;change for a call to trace* in order to use only one logger at the top (defmethod parse-item :seq [form] (if (and (symbol? (first form)) (= (ns-resolve *ns* (first form)) (ns-resolve 'clj-zipkin.tracer 'trace))) (let [[_ data body] form] (list* 'clj-zipkin.tracer/trace* data (doall (map parse-item body)) '())) (doall (map parse-item form)))) (defmethod parse-item :vector [v] (vec (doall (map parse-item v)))) (defmethod parse-item :default [item] item) (defn make-logger "Creates a new scribe connection object, config should be a map with scribe endpoint configuration: => {:host h :port p}" ([config] (make-logger config "zipkin")) ([config category] (scribe/async-logger :host (:host config) :port (:port config) :category category))) (defn log "Forward log to scribe" [connection span-list] (scribe/log connection span-list)) (defmacro trace* "Creates a start/finish timestamp annotations span for the code chunk received, defers actual logging to upper trace function." [{:keys [span host span-id annotations]} & body] (let [body (parse-item body)] `(let [parent-id# ~'span-id ~'span-id (or ~span-id (create-id)) ; _# (println "t" ~'trace-id "s" ~'span-id "p" parent-id#) start-time# (time/now) result# ~@body end-time# (time/now) span# (create-timestamp-span ~span ~host ~'trace-id ~'span-id parent-id# start-time# end-time# ~annotations) ;parent spans added at the end, so cons _# (swap! ~'span-list (fn [l#] (cons span# l#)))] result#))) (defmacro trace "Timestamp tracing of a code chunk using timestamp annotations. => (trace options body) options { :host => current host, defaults to InetAddress/getLocalHost if unspecifyed :span => span name :trace-id => optional, new one will be created if unspecifyed :annotations {:k :v} => key/value map to annotate this trace :scribe => scribe/zipkin endpoint configuration {:host h :port p} } Macro uses anaphoras for nested tracing so the following variable names are defined: * trace-id * span-id * span-list (trace {:host \"10.0.2.1\" :span \"GET\" :scribe {host \"localhost\" :port 9410}} (...code to be traced...)) Trace Id can be specified with the :trace-id option (trace {:host \"10.0.2.1\" :trace-id 12345 :span \"GET\" :scribe {host \"localhost\" :port 9410}} (...code to be traced...)) Nested traces are supported and scribe configuration is not needed for inner traces, those will be treated as child spans of the immediate parent trace (trace {:host \"10.0.2.1\" :span \"GET\" :scribe {host \"localhost\" :port 9410}} (...code to be traced... (trace {:span \"OTHER\"} (..code...))))" [& args] `(let [logger# ~(if (symbol? (-> args first :scribe)) (-> args first :scribe) `(make-logger ~(-> args first :scribe))) ~'trace-id (or ~(-> args first :trace-id) (create-id)) ~'span-list (atom []) ~'span-id ~(-> args first :parent-span-id) result# (trace* ~(first args) ~@(rest args)) _# (log logger# (deref ~'span-list))] result#))
null
https://raw.githubusercontent.com/guilespi/clj-zipkin/e76766d29f44e0c1297ff189371b8726fbff4616/src/clj_zipkin/tracer.clj
clojure
the following *hack* is to avoid binary annotations being stringified by the type wrapper, problem is caused because public ByteBuffer value; // required by a caritative soul. Now we just avoid string wrapping hijacking the mm side effectish step According to tryfer sources, zipkin has trouble recording traces with ids tracing macro for nested recording if found a call to original trace in the ast change for a call to trace* in order to use _# (println "t" ~'trace-id "s" ~'span-id "p" parent-id#) parent spans added at the end, so cons
(ns clj-zipkin.tracer (:require [thrift-clj.core :as thrift] [clojure.data.codec.base64 :as b64] [clj-scribe :as scribe] [thrift-clj.gen.core :as c] [thrift-clj.thrift.types :as thrift-types] [clj-time.core :as time] [clj-time.coerce :as time-coerce])) (def ^:dynamic *default-service-name* "Unknown Service") Value field in BinaryAnnotation.java is a binary hinted as a String : java file is autogen by thriftc so some validation should be done there (def my-extend-field (var-get (find-var 'thrift-clj.thrift.types/extend-field-metadata-map))) (remove-method my-extend-field :string) (thrift/import (:types [com.twitter.zipkin.gen Span Annotation BinaryAnnotation AnnotationType Endpoint LogEntry StoreAggregatesException AdjustableRateException]) (:clients com.twitter.zipkin.gen.ZipkinCollector)) (defn ip-str-to-int [str-ip] (let [nums (vec (map read-string (clojure.string/split str-ip #"\.")))] (+ (* (nums 0) 16777216) (* (nums 1) 65536) (* (nums 2) 256) (nums 3)))) (defn str->bytes [str] (bytes (byte-array (map (comp byte int) str)))) (defn thrift->base64 "Serializes a thrift span object to be sent through the wires" [data] (let [buffer (org.apache.thrift.transport.TMemoryBuffer. 40000) protocol (org.apache.thrift.protocol.TBinaryProtocol. buffer) _ (.write (.to_thrift* data) protocol)] (String. (b64/encode (.getArray buffer) 0 (.length buffer)) "UTF-8"))) (defn host->endpoint "Given a host in string or map format creates a thrift zipkin endpoint object" [host] (condp = (class host) java.lang.String (Endpoint. (ip-str-to-int host) 0 *default-service-name*) clojure.lang.PersistentArrayMap (Endpoint. (ip-str-to-int (or (:ip host) (.getHostAddress (java.net.InetAddress/getLocalHost)))) (or (:port host) 0) (or (:service host) *default-service-name*)) nil (Endpoint. (ip-str-to-int (.getHostAddress (java.net.InetAddress/getLocalHost))) 0 *default-service-name*) (throw (str "Invalid host value" (class host) "not supported")))) larger than ( 2 * * 56 ) - 1 (def rand-max (dec (Math/pow 2 24))) (defn create-id "Creates a new id to be used as trace or span id" [] (rand-int rand-max)) (defn create-timestamp-span "Creates a new span with start/finish annotations" [span host trace-id span-id parent-id start finish annotations] (let [endpoint (host->endpoint host) start-annotation (Annotation. (* 1000 (time-coerce/to-long start)) (str "start:" (name span)) endpoint 0) finish-annotation (Annotation. (* 1000 (time-coerce/to-long finish)) (str "end:" (name span)) endpoint 0) binary-annotations (mapv (fn [[k v]] (BinaryAnnotation. (name k) (java.nio.ByteBuffer/wrap (.getBytes (str v))) AnnotationType/STRING endpoint)) annotations)] (thrift->base64 (Span. trace-id (name span) span-id parent-id [start-annotation finish-annotation] binary-annotations 0)))) (defmulti parse-item (fn [form] (cond (seq? form) :seq (vector? form) :vector :else :default))) only one logger at the top (defmethod parse-item :seq [form] (if (and (symbol? (first form)) (= (ns-resolve *ns* (first form)) (ns-resolve 'clj-zipkin.tracer 'trace))) (let [[_ data body] form] (list* 'clj-zipkin.tracer/trace* data (doall (map parse-item body)) '())) (doall (map parse-item form)))) (defmethod parse-item :vector [v] (vec (doall (map parse-item v)))) (defmethod parse-item :default [item] item) (defn make-logger "Creates a new scribe connection object, config should be a map with scribe endpoint configuration: => {:host h :port p}" ([config] (make-logger config "zipkin")) ([config category] (scribe/async-logger :host (:host config) :port (:port config) :category category))) (defn log "Forward log to scribe" [connection span-list] (scribe/log connection span-list)) (defmacro trace* "Creates a start/finish timestamp annotations span for the code chunk received, defers actual logging to upper trace function." [{:keys [span host span-id annotations]} & body] (let [body (parse-item body)] `(let [parent-id# ~'span-id ~'span-id (or ~span-id (create-id)) start-time# (time/now) result# ~@body end-time# (time/now) span# (create-timestamp-span ~span ~host ~'trace-id ~'span-id parent-id# start-time# end-time# ~annotations) _# (swap! ~'span-list (fn [l#] (cons span# l#)))] result#))) (defmacro trace "Timestamp tracing of a code chunk using timestamp annotations. => (trace options body) options { :host => current host, defaults to InetAddress/getLocalHost if unspecifyed :span => span name :trace-id => optional, new one will be created if unspecifyed :annotations {:k :v} => key/value map to annotate this trace :scribe => scribe/zipkin endpoint configuration {:host h :port p} } Macro uses anaphoras for nested tracing so the following variable names are defined: * trace-id * span-id * span-list (trace {:host \"10.0.2.1\" :span \"GET\" :scribe {host \"localhost\" :port 9410}} (...code to be traced...)) Trace Id can be specified with the :trace-id option (trace {:host \"10.0.2.1\" :trace-id 12345 :span \"GET\" :scribe {host \"localhost\" :port 9410}} (...code to be traced...)) Nested traces are supported and scribe configuration is not needed for inner traces, those will be treated as child spans of the immediate parent trace (trace {:host \"10.0.2.1\" :span \"GET\" :scribe {host \"localhost\" :port 9410}} (...code to be traced... (trace {:span \"OTHER\"} (..code...))))" [& args] `(let [logger# ~(if (symbol? (-> args first :scribe)) (-> args first :scribe) `(make-logger ~(-> args first :scribe))) ~'trace-id (or ~(-> args first :trace-id) (create-id)) ~'span-list (atom []) ~'span-id ~(-> args first :parent-span-id) result# (trace* ~(first args) ~@(rest args)) _# (log logger# (deref ~'span-list))] result#))
27d9f3bf4fde46bbbd6f9c33b61f4a2e2a8800c1ccb9a08956238b2a962b8298
OCamlPro/ocp-indent
multiline.ml
let _ = (* multiline-comments can be troublesome: let x = let y = f z in y indented code should be kept as is *) () let _ = (* what about multi-line comments that don't start a line ? *) w let s1 = "a b c d e f g h i j k" let s2 = "a b c d \ e f g h \ i j k\ \ l" let s3 = "a b c d \ e f g h i j k \ l m"
null
https://raw.githubusercontent.com/OCamlPro/ocp-indent/9e26c0a2699b7076cebc04ece59fb354eb84c11c/tests/passing/multiline.ml
ocaml
multiline-comments can be troublesome: let x = let y = f z in y indented code should be kept as is what about multi-line comments that don't start a line ?
let _ = () w let s1 = "a b c d e f g h i j k" let s2 = "a b c d \ e f g h \ i j k\ \ l" let s3 = "a b c d \ e f g h i j k \ l m"
9f714061acb8d4a20dfc0848937a886887fb1ae866bf4365784868557ab36f28
input-output-hk/cardano-ledger-byron
Limits.hs
{-# LANGUAGE TemplateHaskell #-} # LANGUAGE TypeApplications # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE GeneralizedNewtypeDeriving # module Test.Cardano.Crypto.Limits ( tests ) where import Cardano.Prelude import Test.Cardano.Prelude import Crypto.Hash (Blake2b_224, Blake2b_256) import qualified Data.ByteString as BS import qualified Cardano.Crypto.Wallet as CC import Crypto.Hash.IO (HashAlgorithm, hashDigestSize) import Cardano.Binary (ToCBOR, serialize') import Cardano.Crypto (AbstractHash, VerificationKey, Signature(..)) import Hedgehog import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range import Test.Cardano.Crypto.Gen (feedPM, genAbstractHash, genVerificationKey, genSignature) -------------------------------------------------------------------------------- Main Test Action -------------------------------------------------------------------------------- tests :: IO Bool tests = checkParallel $$discover --------------------------------------------------------------------------- -- Limit --------------------------------------------------------------------------- -- | A limit on the length of something (in bytes). TODO should check for overflow in the instance . Although , if the limit is anywhere near maxBound : : then something -- is almost certainly amiss. newtype Limit t = Limit { getLimit :: Word32 } deriving (Eq, Ord, Show, Num, Enum, Real, Integral) instance Functor Limit where fmap _ (Limit x) = Limit x -------------------------------------------------------------------------------- -- Helper Functions -------------------------------------------------------------------------------- mlAbstractHash :: forall algo a . HashAlgorithm algo => Limit (AbstractHash algo a) mlAbstractHash = fromIntegral (hashDigestSize (panic "AbstractHash limit" :: algo) + 4) mlVerificationKey :: Limit VerificationKey mlVerificationKey = 66 mlXSignature :: Limit CC.XSignature mlXSignature = 66 mlSignature :: Limit (Signature a) mlSignature = Signature <$> mlXSignature -------------------------------------------------------------------------------- -- Message Length Properties -------------------------------------------------------------------------------- prop_pubKeyLenLimited :: Property prop_pubKeyLenLimited = eachOf 1000 genVerificationKey (msgLenLimited mlVerificationKey) prop_signatureLenLimited :: Property prop_signatureLenLimited = eachOf 1000 (feedPM (\pm -> genSignature pm (Gen.list (Range.constant 0 1000) (pure ())))) (msgLenLimited mlSignature) prop_abstractHash224LenLimited :: Property prop_abstractHash224LenLimited = eachOf 1000 (genAbstractHash @Int32 @Blake2b_224 (Gen.int32 Range.constantBounded)) (msgLenLimited mlAbstractHash) prop_abstractHash256LenLimited :: Property prop_abstractHash256LenLimited = eachOf 1000 (genAbstractHash @Int32 @Blake2b_256 (Gen.int32 Range.constantBounded)) (msgLenLimited mlAbstractHash) msgLenLimited :: ToCBOR a => Limit a -> a -> PropertyT IO () msgLenLimited limit a = assert $ BS.length (serialize' a) <= fromIntegral limit
null
https://raw.githubusercontent.com/input-output-hk/cardano-ledger-byron/d309449e6c303a9f0dcc8dcf172df6f0b3195ed5/crypto/test/Test/Cardano/Crypto/Limits.hs
haskell
# LANGUAGE TemplateHaskell # # LANGUAGE OverloadedStrings # ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------- Limit ------------------------------------------------------------------------- | A limit on the length of something (in bytes). is almost certainly amiss. ------------------------------------------------------------------------------ Helper Functions ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Message Length Properties ------------------------------------------------------------------------------
# LANGUAGE TypeApplications # # LANGUAGE ScopedTypeVariables # # LANGUAGE GeneralizedNewtypeDeriving # module Test.Cardano.Crypto.Limits ( tests ) where import Cardano.Prelude import Test.Cardano.Prelude import Crypto.Hash (Blake2b_224, Blake2b_256) import qualified Data.ByteString as BS import qualified Cardano.Crypto.Wallet as CC import Crypto.Hash.IO (HashAlgorithm, hashDigestSize) import Cardano.Binary (ToCBOR, serialize') import Cardano.Crypto (AbstractHash, VerificationKey, Signature(..)) import Hedgehog import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range import Test.Cardano.Crypto.Gen (feedPM, genAbstractHash, genVerificationKey, genSignature) Main Test Action tests :: IO Bool tests = checkParallel $$discover TODO should check for overflow in the instance . Although , if the limit is anywhere near maxBound : : then something newtype Limit t = Limit { getLimit :: Word32 } deriving (Eq, Ord, Show, Num, Enum, Real, Integral) instance Functor Limit where fmap _ (Limit x) = Limit x mlAbstractHash :: forall algo a . HashAlgorithm algo => Limit (AbstractHash algo a) mlAbstractHash = fromIntegral (hashDigestSize (panic "AbstractHash limit" :: algo) + 4) mlVerificationKey :: Limit VerificationKey mlVerificationKey = 66 mlXSignature :: Limit CC.XSignature mlXSignature = 66 mlSignature :: Limit (Signature a) mlSignature = Signature <$> mlXSignature prop_pubKeyLenLimited :: Property prop_pubKeyLenLimited = eachOf 1000 genVerificationKey (msgLenLimited mlVerificationKey) prop_signatureLenLimited :: Property prop_signatureLenLimited = eachOf 1000 (feedPM (\pm -> genSignature pm (Gen.list (Range.constant 0 1000) (pure ())))) (msgLenLimited mlSignature) prop_abstractHash224LenLimited :: Property prop_abstractHash224LenLimited = eachOf 1000 (genAbstractHash @Int32 @Blake2b_224 (Gen.int32 Range.constantBounded)) (msgLenLimited mlAbstractHash) prop_abstractHash256LenLimited :: Property prop_abstractHash256LenLimited = eachOf 1000 (genAbstractHash @Int32 @Blake2b_256 (Gen.int32 Range.constantBounded)) (msgLenLimited mlAbstractHash) msgLenLimited :: ToCBOR a => Limit a -> a -> PropertyT IO () msgLenLimited limit a = assert $ BS.length (serialize' a) <= fromIntegral limit
15be2d4faaed80849270b4744b3fbfd0506adeff51c52a1a3281787728aa5173
rems-project/cerberus
lemmata.ml
module IT=IndexTerms module BT = BaseTypes module LS = LogicalSorts module LRT = LogicalReturnTypes module RT = ReturnTypes module AT = ArgumentTypes module LAT = LogicalArgumentTypes module TE = TypeErrors module Loc = Locations module LP = LogicalPredicates module LC = LogicalConstraints module StringSet = Set.Make(String) module StringMap = Map.Make(String) module SymSet = Set.Make(Sym) module SymMap = Map.Make(Sym) module StringList = struct type t = string list let compare = List.compare String.compare let equal = List.equal String.equal end module StringListMap = Map.Make(StringList) module IntMap = Map.Make(Int) (* Some things are defined on-demand, so this state monad stores the set of such things defined and the contents of the various setup sections they may be defined into. *) module PrevDefs = struct type t = {present: (Sym.t list) StringListMap.t; defs: (Pp.doc list) IntMap.t; dt_params: (IT.t * Sym.t * Sym.t) list} let init_t = {present = StringListMap.empty; defs = IntMap.empty; dt_params = []} type ('a, 'e) m = t -> ('a * t, 'e) Result.t let return (x : 'a) : ('a, 'e) m = (fun st -> Result.Ok (x, st)) let bind (x : ('a, 'e) m) (f : 'a -> ('b, 'e) m) : ('b, 'e) m = (fun st -> match x st with | Result.Error e -> Result.Error e | Result.Ok (xv, st) -> f xv st ) let get : (t, 'e) m = (fun st -> Result.Ok (st, st)) let set (st : t) : (unit, 'e) m = (fun _ -> Result.Ok ((), st)) let upd (f : t -> t) : (unit, 'e) m = bind get (fun st -> set (f st)) let get_section section (st : t) = match IntMap.find_opt section st.defs with | None -> [] | Some docs -> docs let add_to_section section doc (st : t) = let current = get_section section st in let defs = IntMap.add section (doc :: current) st.defs in {st with defs} let add_dt_param x = upd (fun st -> {st with dt_params = x :: st.dt_params}) let get_dt_param it m_nm = bind get (fun st -> return (List.find_opt (fun (it2, m2, sym) -> IT.equal it it2 && Sym.equal m_nm m2) st.dt_params |> Option.map (fun (_, _, sym) -> sym))) end module PrevMonad = Effectful.Make(PrevDefs) open PrevDefs open PrevMonad let with_reset_dt_params f = let@ st = get in let@ x = f () in let@ st2 = get in let@ () = set {st2 with dt_params = st.dt_params} in return x module Mu = Mucore let emit_kind kinds k = StringSet.mem k kinds || StringSet.mem "all" kinds let parse_directions directions = (directions, StringSet.singleton "all") let header filename = let open Pp in !^"(*" ^^^ !^ filename ^^ !^": generated lemma specifications from CN *)" ^^ hardline ^^ hardline ^^ !^"Require Import ZArith Bool." ^^ hardline ^^ !^"Require CN_Lemmas.CN_Lib." ^^ hardline ^^ hardline let fail msg details = let open Pp in print stdout (format [Bold; Red] msg ^^ colon ^^ space ^^ details); failwith msg let fail_m loc msg = (fun st -> Result.Error (TypeErrors.{loc; msg = Generic msg})) let fail_check_noop = function | body -> fail "non-noop lemma body element" (Pp_mucore.pp_expr body) TODO let check_noop _ = () let check_trusted_fun_body fsym (lsym, def) = let open Mucore in match def with | Mu.M_Proc (loc, args_body, _trusted) -> let rec check_l = function | M_Define (_, _, l) -> check_l l | M_Resource (_, _, l) -> check_l l | M_Constraint (_, _, l) -> check_l l | M_I (body, _labels, _rt) -> check_noop body in let rec check = function | M_Computational (_, _, t) -> check t | M_L l -> check_l l in check args_body | _ -> fail "non-proc trusted function" (Sym.pp fsym) let add_it_funs it funs = let f _ funs it = match IT.term it with | IT.Pred (name, args) -> SymSet.add name funs | _ -> funs in IT.fold_subterms f funs it let all_undef_foralls = let add (nm, t) nms = StringMap.add nm (Sym.fresh_named nm, t) nms in let intf t = BaseTypes.Map (BaseTypes.Integer, t) in let int3 = intf (intf BaseTypes.Integer) in List.fold_right add [ ("div_undef", int3); ("rem_undef", int3); ("mod_undef", int3) ] StringMap.empty let it_undef_foralls it = let f _ nms it = match IT.term it with | IT.Arith_op op -> begin match op with | IT.Div _ -> StringSet.add "div_undef" nms | IT.Rem _ -> StringSet.add "rem_undef" nms | IT.Mod _ -> StringSet.add "mod_undef" nms | _ -> nms end | _ -> nms in IT.fold_subterms f StringSet.empty it set of functions with boolean return type that are negated etc and must return bool ( be computational ) in Coq . the rest return Prop . FIXME : make this configurable . etc and must return bool (be computational) in Coq. the rest return Prop. FIXME: make this configurable. *) let bool_funs = StringSet.of_list ["order_aligned"; "in_tree"] exception Cannot_Coerce (* attempt to coerce out the resources in this function type. we can do this for some lemmas where resources are passed and returned unchanged as a way of passing their return values. *) let try_coerce_res ftyp = let rec erase_res r t = match t with | LRT.Define (v, info, t) -> LRT.Define (v, info, erase_res r t) | LRT.Constraint (lc, info, t) -> LRT.Constraint (lc, info, erase_res r t) | LRT.Resource ((name, (re, bt)), info, t) -> let (arg_name, arg_re) = r in if ResourceTypes.alpha_equivalent arg_re re then begin Pp.debug 2 (lazy (Pp.item "erasing" (Sym.pp name))); LRT.subst (IT.make_subst [(name, IT.sym_ (arg_name, bt))]) t end else LRT.Resource ((name, (re, bt)), info, erase_res r t) | LRT.I -> Pp.debug 2 (lazy (Pp.string "no counterpart found")); raise Cannot_Coerce (* did not find a matching resource *) in let erase_res2 r t = Pp.debug 2 (lazy (Pp.item "seeking to erase counterpart" (Sym.pp (fst r)))); let res = LAT.map (RT.map (erase_res r)) t in res in let rec coerce_lat t = match t with | LAT.Resource ((name, (re, bt)), info, t) -> let computationals, t = coerce_lat (erase_res2 (name, re) t) in ((name, bt, info) :: computationals), t | LAT.Define (v, info, t) -> let computationals, t = coerce_lat t in computationals, LAT.Define (v, info, t) | LAT.Constraint (lc, info, t) -> let computationals, t = coerce_lat t in computationals, LAT.Constraint (lc, info, t) | LAT.I _ -> [], t in let rec coerce_at t = match t with | AT.Computational (v, info, t) -> AT.Computational (v, info, coerce_at t) | AT.L t -> let computationals, t = coerce_lat t in AT.mComputationals computationals (AT.L t) in try Some (coerce_at ftyp) with Cannot_Coerce -> None type scan_res = {res: string option; ret: bool; res_coerce: RT.t AT.t option} let init_scan_res = {res = None; ret = false; res_coerce = None} (* recurse over a function type and detect resources (impureness), non-unit return types (non-lemma trusted functions), and the set of uninterpreted functions used. *) let scan ftyp = let rec scan_lrt t = match t with | LRT.Define ((_, it), _, t) -> scan_lrt t | LRT.Resource ((name, _), _, t) -> {(scan_lrt t) with res = Some (Sym.pp_string name)} | LRT.Constraint (_, _, t) -> scan_lrt t | LRT.I -> init_scan_res in let scan_rt = function | RT.Computational ((_, bt), _, t) -> {(scan_lrt t) with ret = not (BaseTypes.equal bt BaseTypes.Unit)} in let rec scan_lat t = match t with | LAT.Define (_, _, t) -> scan_lat t | LAT.Resource ((name, _), _, t) -> {(scan_lat t) with res = Some (Sym.pp_string name)} | LAT.Constraint (_, _, t) -> scan_lat t | LAT.I t -> scan_rt t in let rec scan_at t = match t with | AT.Computational (_, _, t) -> scan_at t | AT.L t -> scan_lat t in let x = scan_at ftyp in if Option.is_none x.res then x else begin Pp.debug 2 (lazy (Pp.item "attempting to coerce ftyp" (Pp.string ""))); match try_coerce_res ftyp with | None -> x | Some ftyp2 -> let y = scan_at ftyp2 in if Option.is_none y.res then begin Pp.debug 2 (lazy (Pp.item "coercion" (Pp.string "succeeded"))); {x with res_coerce = Some ftyp2} end else begin Pp.debug 2 (lazy (Pp.item "coercion" (Pp.string "failed"))); {x with res = y.res} end end let struct_layout_field_bts xs = let open Memory in let xs2 = List.filter (fun x -> Option.is_some x.member_or_padding) xs |> List.sort (fun (x : struct_piece) y -> Int.compare x.offset y.offset) |> List.filter_map (fun x -> x.member_or_padding) in (List.map fst xs2, List.map (fun x -> BaseTypes.of_sct (snd x)) xs2) let get_struct_xs struct_decls tag = match SymMap.find_opt tag struct_decls with | Some def -> struct_layout_field_bts def | None -> fail "undefined struct" (Sym.pp tag) let binop s x y = let open Pp in parens (flow (break 1) [x; !^ s; y]) let doc_fun_app sd xs = let open Pp in parens (flow (break 1) (sd :: xs)) let fun_app s xs = let open Pp in doc_fun_app (!^ s) xs let tuple_coq_ty doc fld_tys = let open Pp in let rec stars = function | [] -> fail "tuple_coq_ty: empty" doc | [x] -> [x] | x :: xs -> x :: star :: stars xs in parens (flow (break 1) (stars fld_tys)) (* type conv_info = { *) (* global : Global.t; *) (* (\* pairs ('a, nm) if 'a list is monomorphised to datatype named nm *\) *) (* list_mono : (BT.t * Sym.t) list *) (* } *) type list_mono = (BT.t * Sym.t) list let add_list_mono_datatype (bt, nm) global = let open Global in let bt_name = Sym.pp_string (Option.get (BT.is_datatype_bt bt)) in let nil = Sym.fresh_named ("Nil_of_" ^ bt_name) in let cons = Sym.fresh_named ("Cons_of_" ^ bt_name) in let hd = Sym.fresh_named ("hd_of_" ^ bt_name) in let tl = Sym.fresh_named ("tl_of_" ^ bt_name) in let mems = [(hd, bt); (tl, BT.Datatype nm)] in let datatypes = SymMap.add nm BT.{dt_constrs = [nil; cons]; dt_all_params = mems} global.datatypes in let datatype_constrs = global.datatype_constrs |> SymMap.add nil BT.{c_params = []; c_datatype_tag = nm} |> SymMap.add cons BT.{c_params = mems; c_datatype_tag = nm} in {global with datatypes; datatype_constrs} let mono_list_bt list_mono bt = Option.bind (BT.is_list_bt bt) (fun arg_bt -> Option.bind (List.find_opt (fun (bt2, _) -> BT.equal arg_bt bt2) list_mono) (fun (_, dt_sym) -> Some (BT.Datatype dt_sym))) let monomorphise_dt_lists global = let dt_lists = function | BT.List (BT.Datatype sym) -> Some sym | _ -> None in let all_dt_types = SymMap.fold (fun _ dt_info ss -> List.filter_map dt_lists (List.map snd dt_info.BT.dt_all_params) @ ss) global.Global.datatypes [] in let uniq_dt_types = SymSet.elements (SymSet.of_list all_dt_types) in let new_sym sym = (sym, Sym.fresh_named ("list_of_" ^ Sym.pp_string sym)) in let new_syms = List.map new_sym uniq_dt_types in let list_mono = List.map (fun (s1, s2) -> (BT.Datatype s1, s2)) new_syms in let global = List.fold_right add_list_mono_datatype list_mono global in let map_bt bt = Option.value ~default:bt (mono_list_bt list_mono bt) in let map_mems = List.map (fun (nm, bt) -> (nm, map_bt bt)) in let datatypes = SymMap.map (fun info -> BT.{info with dt_all_params = map_mems info.dt_all_params}) global.Global.datatypes in let datatype_constrs = SymMap.map (fun info -> BT.{info with c_params = map_mems info.c_params}) global.Global.datatype_constrs in let global = Global.{global with datatypes; datatype_constrs} in (list_mono, global) let it_adjust (global : Global.t) it = let rec new_nm s nms i = let s2 = s ^ "_" ^ Int.to_string i in if List.exists (String.equal s2) nms then new_nm s nms (i + 1) else s2 in let rec f t = match IT.term t with | IT.Bool_op op -> begin match op with | IT.And xs -> let xs = List.map f xs |> List.partition IT.is_true |> snd in if List.length xs == 0 then IT.bool_ true else IT.and_ xs | IT.Or xs -> let xs = List.map f xs |> List.partition IT.is_false |> snd in if List.length xs == 0 then IT.bool_ true else IT.or_ xs | IT.EQ (x, y) -> let x = f x in let y = f y in if IT.equal x y then IT.bool_ true else IT.eq__ x y | IT.Impl (x, y) -> let x = f x in let y = f y in if IT.is_false x || IT.is_true y then IT.bool_ true else IT.impl_ (x, y) | IT.EachI ((i1, s, i2), x) -> let x = f x in let vs = IT.free_vars x in let other_nms = List.filter (fun sym -> not (Sym.equal sym s)) (SymSet.elements vs) |> List.map Sym.pp_string in if not (SymSet.mem s vs) then (assert (i1 <= i2); x) else if List.exists (String.equal (Sym.pp_string s)) other_nms then let s2 = Sym.fresh_named (new_nm (Sym.pp_string s) other_nms 0) in let x = IT.subst (IT.make_subst [(s, IT.sym_ (s2, BT.Integer))]) x in IT.eachI_ (i1, s2, i2) x else IT.eachI_ (i1, s, i2) x | _ -> t end | IT.Pred (name, args) -> let open LogicalPredicates in let def = SymMap.find name global.logical_predicates in begin match def.definition with | Def body -> f (Body.to_term def.return_bt (open_pred def.args body args)) | _ -> t end | IT.CT_pred (Good (ct, t2)) -> if Option.is_some (Sctypes.is_struct_ctype ct) then t else f (IT.good_value global.struct_decls ct t2) | IT.CT_pred (Representable (ct, t2)) -> if Option.is_some (Sctypes.is_struct_ctype ct) then t else f (IT.representable global.struct_decls ct t2) | IT.CT_pred (AlignedI t) -> f (IT.divisible_ (IT.pointerToIntegerCast_ t.t, t.align)) | IT.CT_pred (Aligned (t, ct)) -> f (IT.alignedI_ ~t ~align:(IT.int_ (Memory.align_of_ctype ct))) | _ -> t in let res = f it in Pp.debug 9 (lazy (Pp.item "it_adjust" (binop "->" (IT.pp it) (IT.pp res)))); f it let fun_prop_ret (global : Global.t) nm = match SymMap.find_opt nm global.logical_predicates with | None -> fail "fun_prop_ret: not found" (Sym.pp nm) | Some def -> let open LogicalPredicates in BaseTypes.equal BaseTypes.Bool def.return_bt && not (StringSet.mem (Sym.pp_string nm) bool_funs) let tuple_syn xs = let open Pp in parens (flow (comma ^^^ !^ "") xs) let find_tuple_element (eq : 'a -> 'a -> bool) (x : 'a) (pp : 'a -> Pp.doc) (ys : 'a list) = let n_ys = List.mapi (fun i y -> (i, y)) ys in match List.find_opt (fun (i, y) -> eq x y) n_ys with | None -> fail "tuple element not found" (pp x) | Some (i, _) -> (i, List.length ys) let tuple_element t (i, len) = let open Pp in let nm i = string ("x_t_" ^ Int.to_string i) in let lhs = string "'" ^^ tuple_syn (List.init len nm) in parens (!^ "let" ^^^ lhs ^^^ !^ ":=" ^^^ t ^^^ !^ "in" ^^ break 1 ^^ nm i) let tuple_upd_element t (i, len) y = let open Pp in let nm i = string ("x_t_" ^ Int.to_string i) in let lhs = string "'" ^^ tuple_syn (List.init len nm) in let rhs = tuple_syn (List.init len (fun j -> if j = i then y else nm j)) in parens (!^ "let" ^^^ lhs ^^^ !^ ":=" ^^^ t ^^^ !^ "in" ^^ break 1 ^^ rhs) let rets s = return (Pp.string s) let build = function | [] -> fail "build" (Pp.string "empty") | xs -> let@ docs = ListM.mapM (fun x -> x) xs in return (Pp.flow (Pp.break 1) docs) let parensM x = let@ xd = x in return (Pp.parens xd) let defn nm args opt_ty rhs = let open Pp in let tyeq = match opt_ty with | None -> [] | Some ty -> [colon; ty] in flow (break 1) ([!^" Definition"; !^ nm] @ args @ tyeq @ [!^":="]) ^^ hardline ^^ !^" " ^^ rhs ^^ !^ "." ^^ hardline let fun_upd_def = defn "fun_upd" (List.map Pp.string ["{A B : Type}"; "(eq : A -> A -> bool)"; "(f : A -> B)"; "x"; "y"; "z"]) None (Pp.string "if eq x z then y else f z") let gen_ensure section k doc xs = let@ st = get in match StringListMap.find_opt k st.present with | None -> Pp.debug 8 (lazy (Pp.item "finalising doc for section" (Pp.brackets (Pp.list Pp.string k)))); let@ fin_doc = Lazy.force doc in (* n.b. finalising the rhs-s of definitions might change the state *) let@ st = get in let st = add_to_section section fin_doc st in set {st with present = StringListMap.add k xs st.present} | Some ys -> if List.equal Sym.equal xs ys then return () else fail "gen_ensure: mismatch/redef" (Pp.list Pp.string k) let ensure_fun_upd () = let k = ["predefs"; "fun_upd"] in gen_ensure 2 k (lazy (return fun_upd_def)) [] let rec bt_to_coq (global : Global.t) (list_mono : list_mono) loc_info = let open Pp in let open Global in let do_fail nm bt = fail_m (fst loc_info) (Pp.item ("bt_to_coq: " ^ nm) (BaseTypes.pp bt ^^^ !^ "in converting" ^^^ (snd loc_info))) in let rec f bt = match bt with | BaseTypes.Bool -> return (!^ "bool") | BaseTypes.Integer -> return (!^ "Z") | BaseTypes.Map (x, y) -> let@ enc_x = f x in let@ enc_y = f y in return (parens (binop "->" enc_x enc_y)) | BaseTypes.Struct tag -> let (_, fld_bts) = get_struct_xs global.struct_decls tag in let@ enc_fld_bts = ListM.mapM f fld_bts in return (tuple_coq_ty (Sym.pp tag) enc_fld_bts) | BaseTypes.Record mems -> let@ enc_mem_bts = ListM.mapM f (List.map snd mems) in return (tuple_coq_ty (!^ "record") enc_mem_bts) | BaseTypes.Loc -> return (!^ "Z") | BaseTypes.Datatype tag -> let@ () = ensure_datatype global list_mono (fst loc_info) tag in return (Sym.pp tag) | BaseTypes.List bt2 -> begin match mono_list_bt list_mono bt with | Some bt3 -> f bt3 | _ -> do_fail "polymorphic list" bt end | _ -> do_fail "unsupported" bt in f and ensure_datatype (global : Global.t) (list_mono : list_mono) loc dt_tag = let family = Global.mutual_datatypes global dt_tag in let dt_tag = List.hd family in let inf = (loc, Pp.typ (Pp.string "datatype") (Sym.pp dt_tag)) in let bt_to_coq2 bt = match BT.is_datatype_bt bt with | Some dt_tag2 -> if List.exists (Sym.equal dt_tag2) family then return (Sym.pp dt_tag2) else bt_to_coq global list_mono inf bt | _ -> bt_to_coq global list_mono inf bt in gen_ensure 0 ["types"; "datatype"; Sym.pp_string dt_tag] (lazy ( let open Pp in let cons_line dt_tag c_tag = let info = SymMap.find c_tag global.datatype_constrs in let@ argTs = ListM.mapM (fun (_, bt) -> bt_to_coq2 bt) info.c_params in return (!^ " | " ^^ Sym.pp c_tag ^^^ colon ^^^ flow (!^ " -> ") (argTs @ [Sym.pp dt_tag])) in let@ dt_eqs = ListM.mapM (fun dt_tag -> let info = SymMap.find dt_tag global.datatypes in let@ c_lines = ListM.mapM (cons_line dt_tag) info.dt_constrs in return (!^ " " ^^ Sym.pp dt_tag ^^^ colon ^^^ !^"Type :=" ^^ hardline ^^ flow hardline c_lines) ) family in return (flow hardline (List.mapi (fun i doc -> !^ (if i = 0 then " Inductive" else " with") ^^ hardline ^^ doc) dt_eqs) ^^ !^ "." ^^ hardline) )) [dt_tag] let ensure_datatype_member global list_mono loc dt_tag mem_tag bt = let@ () = ensure_datatype global list_mono loc dt_tag in let op_nm = Sym.pp_string dt_tag ^ "_" ^ Sym.pp_string mem_tag in let dt_info = SymMap.find dt_tag global.Global.datatypes in let inf = (loc, Pp.typ (Pp.string "datatype acc for") (Sym.pp dt_tag)) in let@ bt_doc = bt_to_coq global list_mono inf bt in let cons_line c = let c_info = SymMap.find c global.Global.datatype_constrs in let pats = List.map (fun (m2, _) -> if Sym.equal mem_tag m2 then Sym.pp mem_tag else Pp.string "_") c_info.c_params in let open Pp in !^ " |" ^^^ flow (!^ " ") pats ^^^ !^"=>" ^^^ (if List.exists (Sym.equal mem_tag) (List.map fst c_info.c_params) then Sym.pp mem_tag else !^ "default") in let@ () = gen_ensure 0 ["types"; "datatype acc"; Sym.pp_string dt_tag; Sym.pp_string mem_tag] (lazy ( let open Pp in return (defn op_nm [parens (typ (!^ "dt") (Sym.pp dt_tag)); !^ "default"] (Some bt_doc) (flow hardline (!^ "match dt with" :: List.map cons_line dt_info.dt_constrs))) )) [dt_tag; mem_tag] in return op_nm let ensure_list global list_mono loc bt = let@ dt_bt = match mono_list_bt list_mono bt with | Some x -> return x | None -> fail_m loc (Pp.item "ensure_list: not a monomorphised list" (BT.pp bt)) in let dt_sym = Option.get (BT.is_datatype_bt dt_bt) in let dt_info = SymMap.find dt_sym global.Global.datatypes in let (nil_nm, cons_nm) = match dt_info.BT.dt_constrs with | [nil; cons] -> (nil, cons) | _ -> assert false in let open Pp in let cons = parens (!^ "fun x ->" ^^^ Sym.pp cons_nm ^^^ !^ "x") in let dest_op_nm = "dest_" ^ Sym.pp_string dt_sym in let@ () = gen_ensure 0 ["types"; "list destructor"; Sym.pp_string dt_sym] (lazy ( let nil_line = !^ " |" ^^^ Sym.pp nil_nm ^^^ !^ "=>" ^^^ !^"None" in let cons_line = !^ " |" ^^^ Sym.pp cons_nm ^^^ !^ "y ys =>" ^^^ !^"Some (y, ys)" in return (defn dest_op_nm [parens (typ (!^ "xs") (Sym.pp dt_sym))] None (flow hardline [!^ "match xs with"; nil_line; cons_line; !^" end"])) )) [dt_sym] in return (Sym.pp nil_nm, cons, Pp.string dest_op_nm) let ensure_tuple_op is_upd nm (ix, l) = let ix_s = Int.to_string ix in let len_s = Int.to_string l in let dir_s = if is_upd then "upd" else "get" in let k = ["predefs"; "tuple"; dir_s; nm; ix_s; len_s] in let op_nm = dir_s ^ "_" ^ nm ^ "_" ^ ix_s ^ "_" ^ len_s in let doc = lazy ( let open Pp in let ty i = !^ ("T_" ^ Int.to_string i) in let t_ty = tuple_coq_ty (!^ op_nm) (List.init l ty) in let t = parens (typ (!^ "t") t_ty) in let x = parens (typ (!^ "x") (ty ix)) in let infer = !^"{" ^^ flow (!^ " ") (List.init l ty) ^^ colon ^^^ !^"Type}" in return (if is_upd then defn op_nm [infer; t; x] None (tuple_upd_element t (ix, l) x) else defn op_nm [infer; t] None (tuple_element t (ix, l))) ) in let@ () = gen_ensure 2 k doc [] in return op_nm let ensure_pred global list_mono loc name aux = let open LogicalPredicates in let def = SymMap.find name global.Global.logical_predicates in let inf = (loc, Pp.typ (Pp.string "pred") (Sym.pp name)) in begin match def.definition with | Uninterp -> gen_ensure 1 ["params"; "pred"; Sym.pp_string name] (lazy ( let@ arg_tys = ListM.mapM (fun (_, bt) -> bt_to_coq global list_mono inf bt) def.args in let open Pp in let@ ret_ty = if fun_prop_ret global name then return (!^ "Prop") else bt_to_coq global list_mono inf def.return_bt in let ty = List.fold_right (fun at rt -> at ^^^ !^ "->" ^^^ rt) arg_tys ret_ty in return (!^ " Parameter" ^^^ typ (Sym.pp name) ty ^^ !^ "." ^^ hardline) )) [] | Def body -> let body = Body.to_term def.return_bt body in gen_ensure 2 ["predefs"; "pred"; Sym.pp_string name] (lazy ( let@ rhs = aux (it_adjust global body) in let@ args = ListM.mapM (fun (sym, bt) -> let@ coq_bt = bt_to_coq global list_mono inf bt in return (Pp.parens (Pp.typ (Sym.pp sym) coq_bt))) def.args in return (defn (Sym.pp_string name) args None rhs) )) [] | Rec_Def body -> fail_m def.loc (Pp.item "rec-def not yet handled" (Sym.pp name)) end let ensure_struct_mem is_good global list_mono loc ct aux = match Sctypes.is_struct_ctype ct with | None -> fail "ensure_struct_mem: not struct" (Sctypes.pp ct) | Some tag -> let bt = BaseTypes.Struct tag in let nm = if is_good then "good" else "representable" in let k = ["predefs"; "struct"; Sym.pp_string tag; nm] in let op_nm = "struct_" ^ Sym.pp_string tag ^ "_" ^ nm in let@ () = gen_ensure 2 k (lazy ( let@ ty = bt_to_coq global list_mono (loc, Pp.string op_nm) bt in let x = Pp.parens (Pp.typ (Pp.string "x") ty) in let x_it = IT.sym_ (Sym.fresh_named "x", bt) in let@ rhs = aux (it_adjust global (IT.good_value global.struct_decls ct x_it)) in return (defn op_nm [x] None rhs) )) [tag] in return op_nm let rec unfold_if_possible global it = let open IT in let open LogicalPredicates in match it with | IT (IT.Pred (name, args), _) -> let def = Option.get (Global.get_logical_predicate_def global name) in begin match def.definition with | Rec_Def _ -> it | Uninterp -> it | Def body -> unfold_if_possible global (Body.to_term def.return_bt (open_pred def.args body args)) end | _ -> it let mk_forall global list_mono loc sym bt doc = let open Pp in let inf = (loc, !^"forall of" ^^^ Sym.pp sym) in let@ coq_bt = bt_to_coq global list_mono inf bt in return (!^ "forall" ^^^ parens (typ (Sym.pp sym) coq_bt) ^^ !^"," ^^ break 1 ^^ doc) let add_dt_param_counted (it, m_nm) = let@ st = get in let idx = List.length (st.dt_params) in let sym = Sym.fresh_named (Sym.pp_string m_nm ^ "_" ^ Int.to_string idx) in let@ () = add_dt_param (it, m_nm, sym) in return sym let dt_split global x t = let dt = Option.get (BT.is_datatype_bt (IT.bt x)) in let cs_used = IT.fold (fun _ acc t -> match IT.term t with | IT.Datatype_op (IT.DatatypeIsCons (c_nm, y)) when IT.equal x y -> SymSet.add c_nm acc | _ -> acc) [] SymSet.empty t in let mems_used = IT.fold (fun _ acc t -> match IT.term t with | IT.Datatype_op (IT.DatatypeMember (y, m_nm)) when IT.equal x y -> SymSet.add m_nm acc | _ -> acc) [] SymSet.empty t in let dt_info = SymMap.find dt global.Global.datatypes in let need_default = List.length dt_info.BT.dt_constrs > SymSet.cardinal cs_used in let rec redux c_nm t = match IT.term t with | IT.Bool_op (IT.ITE (IT.IT (IT.Datatype_op (IT.DatatypeIsCons (c_nm2, y)), _), x_t, x_f)) when IT.equal x y -> if Sym.equal c_nm c_nm2 then redux c_nm x_t else redux c_nm x_f | _ -> t in let f c_nm = let c_info = SymMap.find c_nm global.Global.datatype_constrs in let ms = List.map fst c_info.c_params in (Sym.pp c_nm, ms, mems_used, redux c_nm t) in List.map f (SymSet.elements cs_used) @ (if need_default then [(Pp.string "_", [], mems_used, redux dt t (* any non-cons symbol will redux correctly *))] else []) let dt_access_error t = Pp.item "cannot convert datatype accessor" (Pp.typ (IT.pp t) (Pp.flow_map (Pp.break 1) Pp.string ["datatype accessor expressions are"; "only available in the branch of an"; "if-then-else expression (_ ? _ : _)"; "whose switch established the datatype"; "shape (_ ?? Constructor {})"])) let with_selected_dt_params it mem_nms set_used f = with_reset_dt_params (fun () -> let@ xs = ListM.mapM (fun m_nm -> if SymSet.mem m_nm set_used then let@ sym = add_dt_param_counted (it, m_nm) in return (Some sym) else return None) mem_nms in f xs) let match_some_dt_params c_doc opt_params = build (return c_doc :: List.map (function | None -> rets "_" | Some m_sym -> return (Sym.pp m_sym) ) opt_params) let it_to_coq loc global list_mono it = let open Pp in let eq_of = function | BaseTypes.Integer -> return "Z.eqb" | bt -> fail_m loc (Pp.item "eq_of" (BaseTypes.pp bt)) in let rec f bool_eq_prop t = let aux t = f bool_eq_prop t in let abinop s x y = parensM (build [aux x; rets s; aux y]) in let with_is_true x = if bool_eq_prop && BaseTypes.equal (IT.bt t) BaseTypes.Bool then parensM (build [rets "Is_true"; x]) else x in let check_pos t f = let t = unfold_if_possible global t in match IT.is_z t with | Some i when Z.gt i Z.zero -> f | _ -> fail_m loc (Pp.item "it_to_coq: divisor not positive const" (IT.pp t)) in match IT.term t with | IT.Lit l -> begin match l with | IT.Sym sym -> return (Sym.pp sym) | IT.Bool b -> with_is_true (rets (if b then "true" else "false")) | IT.Z z -> rets (Z.to_string z) | _ -> fail_m loc (Pp.item "it_to_coq: unsupported lit" (IT.pp t)) end | IT.Arith_op op -> begin match op with | Add (x, y) -> abinop "+" x y | Sub (x, y) -> abinop "-" x y | Mul (x, y) -> abinop "*" x y | MulNoSMT (x, y) -> abinop "*" x y | Div (x, y) -> check_pos y (abinop "/" x y) | DivNoSMT (x, y) -> check_pos y (abinop "/" x y) | Mod (x, y) -> check_pos y (abinop "mod" x y) | ModNoSMT (x, y) -> check_pos y (abinop "mod" x y) (* TODO: this can't be right: mod and rem aren't the same *) | Rem (x, y) -> check_pos y (abinop "mod" x y) | RemNoSMT (x, y) -> check_pos y (abinop "mod" x y) | LT (x, y) -> abinop (if bool_eq_prop then "<" else "<?") x y | LE (x, y) -> abinop (if bool_eq_prop then "<=" else "<=?") x y | Exp (x, y) -> abinop "^" x y | ExpNoSMT (x, y) -> abinop "^" x y | XORNoSMT (x, y) -> parensM (build [rets "Z.lxor"; aux x; aux y]) | _ -> fail_m loc (Pp.item "it_to_coq: unsupported arith op" (IT.pp t)) end | IT.Bool_op op -> begin match op with | IT.And [] -> aux (IT.bool_ true) | IT.And [x] -> aux x | IT.And (x :: xs) -> abinop (if bool_eq_prop then "/\\" else "&&") x (IT.and_ xs) | IT.Or [] -> aux (IT.bool_ false) | IT.Or [x] -> aux x | IT.Or (x :: xs) -> abinop (if bool_eq_prop then "\\/" else "||") x (IT.or_ xs) | IT.Impl (x, y) -> abinop (if bool_eq_prop then "->" else "implb") x y | IT.Not x -> parensM (build [rets (if bool_eq_prop then "~" else "negb"); aux x]) | IT.ITE (IT.IT (IT.Datatype_op (IT.DatatypeIsCons (c_nm, x)), _), _, _) -> let dt = Option.get (BT.is_datatype_bt (IT.bt x)) in let@ () = ensure_datatype global list_mono loc dt in let branches = dt_split global x t in let br (c_doc, ps, ps_used, t2) = with_selected_dt_params x ps ps_used (fun opt_ps -> build [rets "|"; match_some_dt_params c_doc opt_ps; rets "=>"; aux t2]) in parensM (build ([rets "match"; f false x; rets "with"] @ List.map br branches @ [rets "end"])) | IT.ITE (sw, x, y) -> parensM (build [rets "if"; f false sw; rets "then"; aux x; rets "else"; aux y]) | IT.EQ (x, y) -> build [f false x; rets (if bool_eq_prop then "=" else "=?"); f false y] | IT.EachI ((i1, s, i2), x) -> assert bool_eq_prop; let@ x = aux x in let@ enc = mk_forall global list_mono loc s BaseTypes.Integer (binop "->" (binop "/\\" (binop "<=" (Pp.int i1) (Sym.pp s)) (binop "<=" (Sym.pp s) (Pp.int i2))) x) in return (parens enc) end | IT.Map_op op -> begin match op with | IT.Set (m, x, y) -> let@ () = ensure_fun_upd () in let@ e = eq_of (IT.bt x) in parensM (build [rets "fun_upd"; rets e; aux m; aux x; aux y]) | IT.Get (m, x) -> parensM (build [aux m; aux x]) | _ -> fail_m loc (Pp.item "it_to_coq: unsupported map op" (IT.pp t)) end | IT.Record_op op -> begin match op with | IT.RecordMember (t, m) -> let flds = BT.record_bt (IT.bt t) in if List.length flds == 1 then aux t else let ix = find_tuple_element Sym.equal m Sym.pp (List.map fst flds) in let@ op_nm = ensure_tuple_op false (Sym.pp_string m) ix in parensM (build [rets op_nm; aux t]) | IT.RecordUpdate ((t, m), x) -> let flds = BT.record_bt (IT.bt t) in if List.length flds == 1 then aux x else let ix = find_tuple_element Sym.equal m Sym.pp (List.map fst flds) in let@ op_nm = ensure_tuple_op true (Sym.pp_string m) ix in parensM (build [rets op_nm; aux t; aux x]) | IT.Record mems -> let@ xs = ListM.mapM aux (List.map snd mems) in parensM (return (flow (comma ^^ break 1) xs)) end | IT.Struct_op op -> begin match op with | IT.StructMember (t, m) -> let tag = BaseTypes.struct_bt (IT.bt t) in let (mems, bts) = get_struct_xs global.struct_decls tag in let ix = find_tuple_element Id.equal m Id.pp mems in if List.length mems == 1 then aux t else let@ op_nm = ensure_tuple_op false (Id.pp_string m) ix in parensM (build [rets op_nm; aux t]) | IT.StructUpdate ((t, m), x) -> let tag = BaseTypes.struct_bt (IT.bt t) in let (mems, bts) = get_struct_xs global.struct_decls tag in let ix = find_tuple_element Id.equal m Id.pp mems in if List.length mems == 1 then aux x else let@ op_nm = ensure_tuple_op true (Id.pp_string m) ix in parensM (build [rets op_nm; aux t; aux x]) | _ -> fail_m loc (Pp.item "it_to_coq: unsupported struct op" (IT.pp it)) end | IT.Pointer_op op -> begin match op with | IT.IntegerToPointerCast t -> aux t | IT.PointerToIntegerCast t -> aux t | IT.LEPointer (x, y) -> abinop (if bool_eq_prop then "<=" else "<=?") x y | IT.LTPointer (x, y) -> abinop (if bool_eq_prop then "<" else "<?") x y | _ -> fail_m loc (Pp.item "it_to_coq: unsupported pointer op" (IT.pp it)) end | IT.Pred (name, args) -> let prop_ret = fun_prop_ret global name in let body_aux = f prop_ret in let@ () = ensure_pred global list_mono loc name body_aux in let@ r = parensM (build ([return (Sym.pp name)] @ List.map (f false) args)) in if prop_ret then return r else with_is_true (return r) | IT.CT_pred p -> assert bool_eq_prop; begin match p with | IT.Good (ct, t2) when (Option.is_some (Sctypes.is_struct_ctype ct)) -> let@ op_nm = ensure_struct_mem true global list_mono loc ct aux in parensM (build [rets op_nm; aux t2]) | IT.Representable (ct, t2) when (Option.is_some (Sctypes.is_struct_ctype ct)) -> let@ op_nm = ensure_struct_mem true global list_mono loc ct aux in parensM (build [rets op_nm; aux t2]) | _ -> fail_m loc (Pp.item "it_to_coq: unexpected ctype pred" (IT.pp t)) end | IT.Datatype_op op -> begin match op with | IT.DatatypeCons (nm, members_rec) -> let info = SymMap.find nm global.datatype_constrs in let args = List.map (fun (nm, _) -> Simplify.IndexTerms.record_member_reduce members_rec nm) info.c_params in let@ () = ensure_datatype global list_mono loc info.c_datatype_tag in parensM (build ([return (Sym.pp nm)] @ List.map (f false) args)) | IT.DatatypeMember (dt, nm) -> let@ o_sym = get_dt_param dt nm in begin match o_sym with | Some sym -> return (Sym.pp sym) | _ -> fail_m loc (dt_access_error t) end | _ -> fail_m loc (Pp.item "it_to_coq: unsupported datatype op" (IT.pp t)) end | IT.List_op op -> begin match op with | IT.NthList (n, xs, d) -> let@ (_, _, dest) = ensure_list global list_mono loc (IT.bt xs) in parensM (build [rets "CN_Lib.nth_list_z"; return dest; aux n; aux xs; aux d]) | IT.ArrayToList (arr, i, len) -> let@ (nil, cons, _) = ensure_list global list_mono loc (IT.bt t) in parensM (build [rets "CN_Lib.array_to_list"; return nil; return cons; aux arr; aux i; aux len]) | _ -> fail_m loc (Pp.item "it_to_coq: unsupported list op" (IT.pp t)) end | _ -> fail_m loc (Pp.item "it_to_coq: unsupported" (IT.pp t)) in f true it let mk_let sym rhs_doc doc = let open Pp in !^ "let" ^^^ Sym.pp sym ^^^ !^ ":=" ^^^ rhs_doc ^^^ !^ "in" ^^^ doc let lc_to_coq_check_triv loc global list_mono = function | LC.T it -> let it = it_adjust global it in if IT.is_true it then return None else let@ v = it_to_coq loc global list_mono it in return (Some v) | LC.Forall ((sym, bt), it) -> let it = it_adjust global it in if IT.is_true it then return None else let@ v = it_to_coq loc global list_mono it in let@ enc = mk_forall global list_mono loc sym bt v in return (Some (Pp.parens enc)) let nth_str_eq n s ss = Option.equal String.equal (List.nth_opt ss n) (Some s) let types_spec types = let open Pp in !^"Module Types." ^^ hardline ^^ hardline ^^ (if List.length types == 0 then !^ " (* no type definitions required *)" ^^ hardline else flow hardline types) ^^ hardline ^^ !^"End Types." ^^ hardline ^^ hardline let param_spec params = let open Pp in !^"Module Type Parameters." ^^ hardline ^^ !^" Import Types." ^^ hardline ^^ hardline ^^ (if List.length params == 0 then !^ " (* no parameters required *)" ^^ hardline else flow hardline params) ^^ hardline ^^ !^"End Parameters." ^^ hardline ^^ hardline let ftyp_to_coq loc global list_mono ftyp = let open Pp in let lc_to_coq_c = lc_to_coq_check_triv loc global list_mono in let it_tc = it_to_coq loc global list_mono in (* FIXME: handle underdefinition in division *) let oapp f opt_x y = match opt_x with | Some x -> f x y | None -> y in let mk_and doc doc2 = doc ^^^ !^ "/\\" ^^^ doc2 in let mk_imp doc doc2 = doc ^^^ !^ "->" ^^^ doc2 in let omap_split f = Option.map (fun doc -> f (break 1 ^^ doc)) in let rec lrt_doc t = match t with | LRT.Constraint (lc, _, t) -> let@ d = lrt_doc t in let@ c = lc_to_coq_c lc in begin match d, c with | None, _ -> return c | _, None -> return d | Some dd, Some cd -> return (Some (mk_and cd dd)) end | LRT.Define ((sym, it), _, t) -> let@ d = lrt_doc t in let@ l = it_tc it in return (omap_split (mk_let sym l) d) | LRT.I -> return None | _ -> fail_m loc (Pp.item "ftyp_to_coq: unsupported" (LRT.pp t)) in let rt_doc t = match t with | RT.Computational ((_, bt), _, t2) -> if BaseTypes.equal bt BaseTypes.Unit then lrt_doc t2 else fail_m loc (Pp.item "ftyp_to_coq: unsupported return type" (RT.pp t)) in let rec lat_doc t = match t with | LAT.Define ((sym, it), _, t) -> let@ d = lat_doc t in let@ l = it_tc it in return (omap_split (mk_let sym l) d) | LAT.Resource _ -> fail_m loc (Pp.item "ftyp_to_coq: unsupported" (LAT.pp RT.pp t)) | LAT.Constraint (lc, _, t) -> let@ c = lc_to_coq_c lc in let@ d = lat_doc t in return (omap_split (oapp mk_imp c) d) | LAT.I t -> rt_doc t in let rec at_doc t = match t with | AT.Computational ((sym, bt), _, t) -> let@ d = at_doc t in begin match d with | None -> return None | Some doc -> let@ doc2 = mk_forall global list_mono loc sym bt (break 1 ^^ doc) in return (Some doc2) end | AT.L t -> lat_doc t in let@ d = at_doc ftyp in let d2 = d | > Option.map ( ( fun nm d - > let ( sym , bt ) = StringMap.find nm all_undef_foralls in mk_forall global sym bt d ) extra_foralls ) in let d2 = d |> Option.map (List.fold_right (fun nm d -> let (sym, bt) = StringMap.find nm all_undef_foralls in mk_forall global sym bt d) extra_foralls) in *) match d with | Some doc -> return doc | None -> rets "Is_true true" let convert_lemma_defs global list_mono lemma_typs = let lemma_ty (nm, typ, loc, kind) = Pp.progress_simple ("converting " ^ kind ^ " lemma type") (Sym.pp_string nm); let@ rhs = ftyp_to_coq loc global list_mono typ in return (defn (Sym.pp_string nm ^ "_type") [] (Some (Pp.string "Prop")) rhs) in let@ tys = ListM.mapM lemma_ty lemma_typs in let@ st = get in Pp.debug 4 (lazy (Pp.item "saved conversion elements" (Pp.list (fun (ss, _) -> Pp.parens (Pp.list Pp.string ss)) (StringListMap.bindings st.present)))); return (tys, List.rev (get_section 0 st), List.rev (get_section 1 st), List.rev (get_section 2 st)) let defs_module aux_defs lemma_tys = let open Pp in !^"Module Defs (P : Parameters)." ^^ hardline ^^ hardline ^^ !^" Import Types P." ^^ hardline ^^ !^" Open Scope Z." ^^ hardline ^^ hardline ^^ flow hardline aux_defs ^^ hardline ^^ flow hardline lemma_tys ^^ hardline ^^ !^"End Defs." ^^ hardline ^^ hardline let mod_spec lemma_nms = let open Pp in let lemma nm = !^" Parameter" ^^^ typ (Sym.pp nm) (Sym.pp nm ^^ !^ "_type") ^^ !^ "." ^^ hardline in !^"Module Type Lemma_Spec (P : Parameters)." ^^ hardline ^^ hardline ^^ !^" Module D := Defs(P)." ^^ hardline ^^ !^" Import D." ^^ hardline ^^ hardline ^^ flow hardline (List.map lemma lemma_nms) ^^ hardline ^^ !^"End Lemma_Spec." ^^ hardline ^^ hardline let convert_and_print channel global list_mono conv = let@ (conv_defs, types, params, defs) = convert_lemma_defs global list_mono conv in Pp.print channel (types_spec types); Pp.print channel (param_spec params); Pp.print channel (defs_module defs conv_defs); Pp.print channel (mod_spec (List.map (fun (nm, _, _, _) -> nm) conv)); return () let cmp_line_numbers = function | None, None -> 0 | None, _ -> 1 | _, None -> -1 | Some (a, b), Some (c, d) -> let x = Int.compare a c in if x == 0 then Int.compare b d else x let cmp_loc_line_numbers l1 l2 = cmp_line_numbers (Loc.line_numbers l1, Loc.line_numbers l2) an experiment involving calling the Retype features again , this time with " CallByValue " set . this probably does n't work , since the elaboration needs to be compatible let do_re_retype mu_file trusted_funs prev_mode pred_defs pre_retype_mu_file = match prev_mode with | ` CallByValue - > Ok mu_file | ` CallByReference - > let = let open Retype . Old in let info2 = Pmap.filter ( fun fsym _ - > SymSet.mem fsym trusted_funs ) pre_retype_mu_file.mu_funinfo in let = Pmap.filter ( fun fsym _ - > SymSet.mem fsym trusted_funs ) pre_retype_mu_file.mu_funs in { pre_retype_mu_file with mu_funs = funs2 ; mu_funinfo = info2 } in Retype.retype_file pred_defs ` CallByValue prev_cut with "CallByValue" set. this probably doesn't work, since the elaboration needs to be compatible let do_re_retype mu_file trusted_funs prev_mode pred_defs pre_retype_mu_file = match prev_mode with | `CallByValue -> Ok mu_file | `CallByReference -> let prev_cut = let open Retype.Old in let info2 = Pmap.filter (fun fsym _ -> SymSet.mem fsym trusted_funs) pre_retype_mu_file.mu_funinfo in let funs2 = Pmap.filter (fun fsym _ -> SymSet.mem fsym trusted_funs) pre_retype_mu_file.mu_funs in { pre_retype_mu_file with mu_funs = funs2; mu_funinfo = info2 } in Retype.retype_file pred_defs `CallByValue prev_cut *) type scanned = {sym : Sym.t; loc: Loc.t; typ: RT.t AT.t; scan_res: scan_res} let generate (global : Global.t) directions trusted_funs = (* let open Mu in *) let (filename, kinds) = parse_directions directions in let channel = open_out filename in Pp.print channel (header filename); let scan_trusted = List.map (fun (sym, (loc, typ)) -> {sym; loc; typ; scan_res = scan typ} ) trusted_funs |> List.sort (fun x (y : scanned) -> cmp_loc_line_numbers x.loc y.loc) in let (returns, others) = List.partition (fun x -> x.scan_res.ret) scan_trusted in let (impure, pure) = List.partition (fun x -> Option.is_some x.scan_res.res) others in let (coerce, skip) = List.partition (fun x -> Option.is_some x.scan_res.res_coerce) impure in List.iter (fun x -> Pp.progress_simple "skipping trusted fun with return val" (Sym.pp_string x.sym) ) returns; List.iter (fun x -> Pp.progress_simple "skipping trusted fun with resource" (Sym.pp_string x.sym ^ ": " ^ (Option.get x.scan_res.res)) ) skip; let fun_info = ( fun ( s , def ) m - > SymMap.add s def m ) (* mu_file.mu_logical_predicates SymMap.empty in *) (* let struct_decls = get_struct_decls mu_file in *) (* let global = Global.{ctxt.Context.global with struct_decls} in *) let (list_mono, global) = monomorphise_dt_lists global in let ci = { global ; fun_info ; list_mono } in let conv = List.map (fun x -> (x.sym, x.typ, x.loc, "pure")) pure @ List.map (fun x -> (x.sym, Option.get x.scan_res.res_coerce, x.loc, "coerced")) coerce in match convert_and_print channel global list_mono conv init_t with | Result.Ok _ -> Result.Ok () | Result.Error e -> Result.Error e
null
https://raw.githubusercontent.com/rems-project/cerberus/a4893196bd7bde4f5cd5d9da16d85f38a5d4c6d0/backend/cn/lemmata.ml
ocaml
Some things are defined on-demand, so this state monad stores the set of such things defined and the contents of the various setup sections they may be defined into. attempt to coerce out the resources in this function type. we can do this for some lemmas where resources are passed and returned unchanged as a way of passing their return values. did not find a matching resource recurse over a function type and detect resources (impureness), non-unit return types (non-lemma trusted functions), and the set of uninterpreted functions used. type conv_info = { global : Global.t; (\* pairs ('a, nm) if 'a list is monomorphised to datatype named nm *\) list_mono : (BT.t * Sym.t) list } n.b. finalising the rhs-s of definitions might change the state any non-cons symbol will redux correctly TODO: this can't be right: mod and rem aren't the same FIXME: handle underdefinition in division let open Mu in mu_file.mu_logical_predicates SymMap.empty in let struct_decls = get_struct_decls mu_file in let global = Global.{ctxt.Context.global with struct_decls} in
module IT=IndexTerms module BT = BaseTypes module LS = LogicalSorts module LRT = LogicalReturnTypes module RT = ReturnTypes module AT = ArgumentTypes module LAT = LogicalArgumentTypes module TE = TypeErrors module Loc = Locations module LP = LogicalPredicates module LC = LogicalConstraints module StringSet = Set.Make(String) module StringMap = Map.Make(String) module SymSet = Set.Make(Sym) module SymMap = Map.Make(Sym) module StringList = struct type t = string list let compare = List.compare String.compare let equal = List.equal String.equal end module StringListMap = Map.Make(StringList) module IntMap = Map.Make(Int) module PrevDefs = struct type t = {present: (Sym.t list) StringListMap.t; defs: (Pp.doc list) IntMap.t; dt_params: (IT.t * Sym.t * Sym.t) list} let init_t = {present = StringListMap.empty; defs = IntMap.empty; dt_params = []} type ('a, 'e) m = t -> ('a * t, 'e) Result.t let return (x : 'a) : ('a, 'e) m = (fun st -> Result.Ok (x, st)) let bind (x : ('a, 'e) m) (f : 'a -> ('b, 'e) m) : ('b, 'e) m = (fun st -> match x st with | Result.Error e -> Result.Error e | Result.Ok (xv, st) -> f xv st ) let get : (t, 'e) m = (fun st -> Result.Ok (st, st)) let set (st : t) : (unit, 'e) m = (fun _ -> Result.Ok ((), st)) let upd (f : t -> t) : (unit, 'e) m = bind get (fun st -> set (f st)) let get_section section (st : t) = match IntMap.find_opt section st.defs with | None -> [] | Some docs -> docs let add_to_section section doc (st : t) = let current = get_section section st in let defs = IntMap.add section (doc :: current) st.defs in {st with defs} let add_dt_param x = upd (fun st -> {st with dt_params = x :: st.dt_params}) let get_dt_param it m_nm = bind get (fun st -> return (List.find_opt (fun (it2, m2, sym) -> IT.equal it it2 && Sym.equal m_nm m2) st.dt_params |> Option.map (fun (_, _, sym) -> sym))) end module PrevMonad = Effectful.Make(PrevDefs) open PrevDefs open PrevMonad let with_reset_dt_params f = let@ st = get in let@ x = f () in let@ st2 = get in let@ () = set {st2 with dt_params = st.dt_params} in return x module Mu = Mucore let emit_kind kinds k = StringSet.mem k kinds || StringSet.mem "all" kinds let parse_directions directions = (directions, StringSet.singleton "all") let header filename = let open Pp in !^"(*" ^^^ !^ filename ^^ !^": generated lemma specifications from CN *)" ^^ hardline ^^ hardline ^^ !^"Require Import ZArith Bool." ^^ hardline ^^ !^"Require CN_Lemmas.CN_Lib." ^^ hardline ^^ hardline let fail msg details = let open Pp in print stdout (format [Bold; Red] msg ^^ colon ^^ space ^^ details); failwith msg let fail_m loc msg = (fun st -> Result.Error (TypeErrors.{loc; msg = Generic msg})) let fail_check_noop = function | body -> fail "non-noop lemma body element" (Pp_mucore.pp_expr body) TODO let check_noop _ = () let check_trusted_fun_body fsym (lsym, def) = let open Mucore in match def with | Mu.M_Proc (loc, args_body, _trusted) -> let rec check_l = function | M_Define (_, _, l) -> check_l l | M_Resource (_, _, l) -> check_l l | M_Constraint (_, _, l) -> check_l l | M_I (body, _labels, _rt) -> check_noop body in let rec check = function | M_Computational (_, _, t) -> check t | M_L l -> check_l l in check args_body | _ -> fail "non-proc trusted function" (Sym.pp fsym) let add_it_funs it funs = let f _ funs it = match IT.term it with | IT.Pred (name, args) -> SymSet.add name funs | _ -> funs in IT.fold_subterms f funs it let all_undef_foralls = let add (nm, t) nms = StringMap.add nm (Sym.fresh_named nm, t) nms in let intf t = BaseTypes.Map (BaseTypes.Integer, t) in let int3 = intf (intf BaseTypes.Integer) in List.fold_right add [ ("div_undef", int3); ("rem_undef", int3); ("mod_undef", int3) ] StringMap.empty let it_undef_foralls it = let f _ nms it = match IT.term it with | IT.Arith_op op -> begin match op with | IT.Div _ -> StringSet.add "div_undef" nms | IT.Rem _ -> StringSet.add "rem_undef" nms | IT.Mod _ -> StringSet.add "mod_undef" nms | _ -> nms end | _ -> nms in IT.fold_subterms f StringSet.empty it set of functions with boolean return type that are negated etc and must return bool ( be computational ) in Coq . the rest return Prop . FIXME : make this configurable . etc and must return bool (be computational) in Coq. the rest return Prop. FIXME: make this configurable. *) let bool_funs = StringSet.of_list ["order_aligned"; "in_tree"] exception Cannot_Coerce let try_coerce_res ftyp = let rec erase_res r t = match t with | LRT.Define (v, info, t) -> LRT.Define (v, info, erase_res r t) | LRT.Constraint (lc, info, t) -> LRT.Constraint (lc, info, erase_res r t) | LRT.Resource ((name, (re, bt)), info, t) -> let (arg_name, arg_re) = r in if ResourceTypes.alpha_equivalent arg_re re then begin Pp.debug 2 (lazy (Pp.item "erasing" (Sym.pp name))); LRT.subst (IT.make_subst [(name, IT.sym_ (arg_name, bt))]) t end else LRT.Resource ((name, (re, bt)), info, erase_res r t) | LRT.I -> Pp.debug 2 (lazy (Pp.string "no counterpart found")); in let erase_res2 r t = Pp.debug 2 (lazy (Pp.item "seeking to erase counterpart" (Sym.pp (fst r)))); let res = LAT.map (RT.map (erase_res r)) t in res in let rec coerce_lat t = match t with | LAT.Resource ((name, (re, bt)), info, t) -> let computationals, t = coerce_lat (erase_res2 (name, re) t) in ((name, bt, info) :: computationals), t | LAT.Define (v, info, t) -> let computationals, t = coerce_lat t in computationals, LAT.Define (v, info, t) | LAT.Constraint (lc, info, t) -> let computationals, t = coerce_lat t in computationals, LAT.Constraint (lc, info, t) | LAT.I _ -> [], t in let rec coerce_at t = match t with | AT.Computational (v, info, t) -> AT.Computational (v, info, coerce_at t) | AT.L t -> let computationals, t = coerce_lat t in AT.mComputationals computationals (AT.L t) in try Some (coerce_at ftyp) with Cannot_Coerce -> None type scan_res = {res: string option; ret: bool; res_coerce: RT.t AT.t option} let init_scan_res = {res = None; ret = false; res_coerce = None} let scan ftyp = let rec scan_lrt t = match t with | LRT.Define ((_, it), _, t) -> scan_lrt t | LRT.Resource ((name, _), _, t) -> {(scan_lrt t) with res = Some (Sym.pp_string name)} | LRT.Constraint (_, _, t) -> scan_lrt t | LRT.I -> init_scan_res in let scan_rt = function | RT.Computational ((_, bt), _, t) -> {(scan_lrt t) with ret = not (BaseTypes.equal bt BaseTypes.Unit)} in let rec scan_lat t = match t with | LAT.Define (_, _, t) -> scan_lat t | LAT.Resource ((name, _), _, t) -> {(scan_lat t) with res = Some (Sym.pp_string name)} | LAT.Constraint (_, _, t) -> scan_lat t | LAT.I t -> scan_rt t in let rec scan_at t = match t with | AT.Computational (_, _, t) -> scan_at t | AT.L t -> scan_lat t in let x = scan_at ftyp in if Option.is_none x.res then x else begin Pp.debug 2 (lazy (Pp.item "attempting to coerce ftyp" (Pp.string ""))); match try_coerce_res ftyp with | None -> x | Some ftyp2 -> let y = scan_at ftyp2 in if Option.is_none y.res then begin Pp.debug 2 (lazy (Pp.item "coercion" (Pp.string "succeeded"))); {x with res_coerce = Some ftyp2} end else begin Pp.debug 2 (lazy (Pp.item "coercion" (Pp.string "failed"))); {x with res = y.res} end end let struct_layout_field_bts xs = let open Memory in let xs2 = List.filter (fun x -> Option.is_some x.member_or_padding) xs |> List.sort (fun (x : struct_piece) y -> Int.compare x.offset y.offset) |> List.filter_map (fun x -> x.member_or_padding) in (List.map fst xs2, List.map (fun x -> BaseTypes.of_sct (snd x)) xs2) let get_struct_xs struct_decls tag = match SymMap.find_opt tag struct_decls with | Some def -> struct_layout_field_bts def | None -> fail "undefined struct" (Sym.pp tag) let binop s x y = let open Pp in parens (flow (break 1) [x; !^ s; y]) let doc_fun_app sd xs = let open Pp in parens (flow (break 1) (sd :: xs)) let fun_app s xs = let open Pp in doc_fun_app (!^ s) xs let tuple_coq_ty doc fld_tys = let open Pp in let rec stars = function | [] -> fail "tuple_coq_ty: empty" doc | [x] -> [x] | x :: xs -> x :: star :: stars xs in parens (flow (break 1) (stars fld_tys)) type list_mono = (BT.t * Sym.t) list let add_list_mono_datatype (bt, nm) global = let open Global in let bt_name = Sym.pp_string (Option.get (BT.is_datatype_bt bt)) in let nil = Sym.fresh_named ("Nil_of_" ^ bt_name) in let cons = Sym.fresh_named ("Cons_of_" ^ bt_name) in let hd = Sym.fresh_named ("hd_of_" ^ bt_name) in let tl = Sym.fresh_named ("tl_of_" ^ bt_name) in let mems = [(hd, bt); (tl, BT.Datatype nm)] in let datatypes = SymMap.add nm BT.{dt_constrs = [nil; cons]; dt_all_params = mems} global.datatypes in let datatype_constrs = global.datatype_constrs |> SymMap.add nil BT.{c_params = []; c_datatype_tag = nm} |> SymMap.add cons BT.{c_params = mems; c_datatype_tag = nm} in {global with datatypes; datatype_constrs} let mono_list_bt list_mono bt = Option.bind (BT.is_list_bt bt) (fun arg_bt -> Option.bind (List.find_opt (fun (bt2, _) -> BT.equal arg_bt bt2) list_mono) (fun (_, dt_sym) -> Some (BT.Datatype dt_sym))) let monomorphise_dt_lists global = let dt_lists = function | BT.List (BT.Datatype sym) -> Some sym | _ -> None in let all_dt_types = SymMap.fold (fun _ dt_info ss -> List.filter_map dt_lists (List.map snd dt_info.BT.dt_all_params) @ ss) global.Global.datatypes [] in let uniq_dt_types = SymSet.elements (SymSet.of_list all_dt_types) in let new_sym sym = (sym, Sym.fresh_named ("list_of_" ^ Sym.pp_string sym)) in let new_syms = List.map new_sym uniq_dt_types in let list_mono = List.map (fun (s1, s2) -> (BT.Datatype s1, s2)) new_syms in let global = List.fold_right add_list_mono_datatype list_mono global in let map_bt bt = Option.value ~default:bt (mono_list_bt list_mono bt) in let map_mems = List.map (fun (nm, bt) -> (nm, map_bt bt)) in let datatypes = SymMap.map (fun info -> BT.{info with dt_all_params = map_mems info.dt_all_params}) global.Global.datatypes in let datatype_constrs = SymMap.map (fun info -> BT.{info with c_params = map_mems info.c_params}) global.Global.datatype_constrs in let global = Global.{global with datatypes; datatype_constrs} in (list_mono, global) let it_adjust (global : Global.t) it = let rec new_nm s nms i = let s2 = s ^ "_" ^ Int.to_string i in if List.exists (String.equal s2) nms then new_nm s nms (i + 1) else s2 in let rec f t = match IT.term t with | IT.Bool_op op -> begin match op with | IT.And xs -> let xs = List.map f xs |> List.partition IT.is_true |> snd in if List.length xs == 0 then IT.bool_ true else IT.and_ xs | IT.Or xs -> let xs = List.map f xs |> List.partition IT.is_false |> snd in if List.length xs == 0 then IT.bool_ true else IT.or_ xs | IT.EQ (x, y) -> let x = f x in let y = f y in if IT.equal x y then IT.bool_ true else IT.eq__ x y | IT.Impl (x, y) -> let x = f x in let y = f y in if IT.is_false x || IT.is_true y then IT.bool_ true else IT.impl_ (x, y) | IT.EachI ((i1, s, i2), x) -> let x = f x in let vs = IT.free_vars x in let other_nms = List.filter (fun sym -> not (Sym.equal sym s)) (SymSet.elements vs) |> List.map Sym.pp_string in if not (SymSet.mem s vs) then (assert (i1 <= i2); x) else if List.exists (String.equal (Sym.pp_string s)) other_nms then let s2 = Sym.fresh_named (new_nm (Sym.pp_string s) other_nms 0) in let x = IT.subst (IT.make_subst [(s, IT.sym_ (s2, BT.Integer))]) x in IT.eachI_ (i1, s2, i2) x else IT.eachI_ (i1, s, i2) x | _ -> t end | IT.Pred (name, args) -> let open LogicalPredicates in let def = SymMap.find name global.logical_predicates in begin match def.definition with | Def body -> f (Body.to_term def.return_bt (open_pred def.args body args)) | _ -> t end | IT.CT_pred (Good (ct, t2)) -> if Option.is_some (Sctypes.is_struct_ctype ct) then t else f (IT.good_value global.struct_decls ct t2) | IT.CT_pred (Representable (ct, t2)) -> if Option.is_some (Sctypes.is_struct_ctype ct) then t else f (IT.representable global.struct_decls ct t2) | IT.CT_pred (AlignedI t) -> f (IT.divisible_ (IT.pointerToIntegerCast_ t.t, t.align)) | IT.CT_pred (Aligned (t, ct)) -> f (IT.alignedI_ ~t ~align:(IT.int_ (Memory.align_of_ctype ct))) | _ -> t in let res = f it in Pp.debug 9 (lazy (Pp.item "it_adjust" (binop "->" (IT.pp it) (IT.pp res)))); f it let fun_prop_ret (global : Global.t) nm = match SymMap.find_opt nm global.logical_predicates with | None -> fail "fun_prop_ret: not found" (Sym.pp nm) | Some def -> let open LogicalPredicates in BaseTypes.equal BaseTypes.Bool def.return_bt && not (StringSet.mem (Sym.pp_string nm) bool_funs) let tuple_syn xs = let open Pp in parens (flow (comma ^^^ !^ "") xs) let find_tuple_element (eq : 'a -> 'a -> bool) (x : 'a) (pp : 'a -> Pp.doc) (ys : 'a list) = let n_ys = List.mapi (fun i y -> (i, y)) ys in match List.find_opt (fun (i, y) -> eq x y) n_ys with | None -> fail "tuple element not found" (pp x) | Some (i, _) -> (i, List.length ys) let tuple_element t (i, len) = let open Pp in let nm i = string ("x_t_" ^ Int.to_string i) in let lhs = string "'" ^^ tuple_syn (List.init len nm) in parens (!^ "let" ^^^ lhs ^^^ !^ ":=" ^^^ t ^^^ !^ "in" ^^ break 1 ^^ nm i) let tuple_upd_element t (i, len) y = let open Pp in let nm i = string ("x_t_" ^ Int.to_string i) in let lhs = string "'" ^^ tuple_syn (List.init len nm) in let rhs = tuple_syn (List.init len (fun j -> if j = i then y else nm j)) in parens (!^ "let" ^^^ lhs ^^^ !^ ":=" ^^^ t ^^^ !^ "in" ^^ break 1 ^^ rhs) let rets s = return (Pp.string s) let build = function | [] -> fail "build" (Pp.string "empty") | xs -> let@ docs = ListM.mapM (fun x -> x) xs in return (Pp.flow (Pp.break 1) docs) let parensM x = let@ xd = x in return (Pp.parens xd) let defn nm args opt_ty rhs = let open Pp in let tyeq = match opt_ty with | None -> [] | Some ty -> [colon; ty] in flow (break 1) ([!^" Definition"; !^ nm] @ args @ tyeq @ [!^":="]) ^^ hardline ^^ !^" " ^^ rhs ^^ !^ "." ^^ hardline let fun_upd_def = defn "fun_upd" (List.map Pp.string ["{A B : Type}"; "(eq : A -> A -> bool)"; "(f : A -> B)"; "x"; "y"; "z"]) None (Pp.string "if eq x z then y else f z") let gen_ensure section k doc xs = let@ st = get in match StringListMap.find_opt k st.present with | None -> Pp.debug 8 (lazy (Pp.item "finalising doc for section" (Pp.brackets (Pp.list Pp.string k)))); let@ fin_doc = Lazy.force doc in let@ st = get in let st = add_to_section section fin_doc st in set {st with present = StringListMap.add k xs st.present} | Some ys -> if List.equal Sym.equal xs ys then return () else fail "gen_ensure: mismatch/redef" (Pp.list Pp.string k) let ensure_fun_upd () = let k = ["predefs"; "fun_upd"] in gen_ensure 2 k (lazy (return fun_upd_def)) [] let rec bt_to_coq (global : Global.t) (list_mono : list_mono) loc_info = let open Pp in let open Global in let do_fail nm bt = fail_m (fst loc_info) (Pp.item ("bt_to_coq: " ^ nm) (BaseTypes.pp bt ^^^ !^ "in converting" ^^^ (snd loc_info))) in let rec f bt = match bt with | BaseTypes.Bool -> return (!^ "bool") | BaseTypes.Integer -> return (!^ "Z") | BaseTypes.Map (x, y) -> let@ enc_x = f x in let@ enc_y = f y in return (parens (binop "->" enc_x enc_y)) | BaseTypes.Struct tag -> let (_, fld_bts) = get_struct_xs global.struct_decls tag in let@ enc_fld_bts = ListM.mapM f fld_bts in return (tuple_coq_ty (Sym.pp tag) enc_fld_bts) | BaseTypes.Record mems -> let@ enc_mem_bts = ListM.mapM f (List.map snd mems) in return (tuple_coq_ty (!^ "record") enc_mem_bts) | BaseTypes.Loc -> return (!^ "Z") | BaseTypes.Datatype tag -> let@ () = ensure_datatype global list_mono (fst loc_info) tag in return (Sym.pp tag) | BaseTypes.List bt2 -> begin match mono_list_bt list_mono bt with | Some bt3 -> f bt3 | _ -> do_fail "polymorphic list" bt end | _ -> do_fail "unsupported" bt in f and ensure_datatype (global : Global.t) (list_mono : list_mono) loc dt_tag = let family = Global.mutual_datatypes global dt_tag in let dt_tag = List.hd family in let inf = (loc, Pp.typ (Pp.string "datatype") (Sym.pp dt_tag)) in let bt_to_coq2 bt = match BT.is_datatype_bt bt with | Some dt_tag2 -> if List.exists (Sym.equal dt_tag2) family then return (Sym.pp dt_tag2) else bt_to_coq global list_mono inf bt | _ -> bt_to_coq global list_mono inf bt in gen_ensure 0 ["types"; "datatype"; Sym.pp_string dt_tag] (lazy ( let open Pp in let cons_line dt_tag c_tag = let info = SymMap.find c_tag global.datatype_constrs in let@ argTs = ListM.mapM (fun (_, bt) -> bt_to_coq2 bt) info.c_params in return (!^ " | " ^^ Sym.pp c_tag ^^^ colon ^^^ flow (!^ " -> ") (argTs @ [Sym.pp dt_tag])) in let@ dt_eqs = ListM.mapM (fun dt_tag -> let info = SymMap.find dt_tag global.datatypes in let@ c_lines = ListM.mapM (cons_line dt_tag) info.dt_constrs in return (!^ " " ^^ Sym.pp dt_tag ^^^ colon ^^^ !^"Type :=" ^^ hardline ^^ flow hardline c_lines) ) family in return (flow hardline (List.mapi (fun i doc -> !^ (if i = 0 then " Inductive" else " with") ^^ hardline ^^ doc) dt_eqs) ^^ !^ "." ^^ hardline) )) [dt_tag] let ensure_datatype_member global list_mono loc dt_tag mem_tag bt = let@ () = ensure_datatype global list_mono loc dt_tag in let op_nm = Sym.pp_string dt_tag ^ "_" ^ Sym.pp_string mem_tag in let dt_info = SymMap.find dt_tag global.Global.datatypes in let inf = (loc, Pp.typ (Pp.string "datatype acc for") (Sym.pp dt_tag)) in let@ bt_doc = bt_to_coq global list_mono inf bt in let cons_line c = let c_info = SymMap.find c global.Global.datatype_constrs in let pats = List.map (fun (m2, _) -> if Sym.equal mem_tag m2 then Sym.pp mem_tag else Pp.string "_") c_info.c_params in let open Pp in !^ " |" ^^^ flow (!^ " ") pats ^^^ !^"=>" ^^^ (if List.exists (Sym.equal mem_tag) (List.map fst c_info.c_params) then Sym.pp mem_tag else !^ "default") in let@ () = gen_ensure 0 ["types"; "datatype acc"; Sym.pp_string dt_tag; Sym.pp_string mem_tag] (lazy ( let open Pp in return (defn op_nm [parens (typ (!^ "dt") (Sym.pp dt_tag)); !^ "default"] (Some bt_doc) (flow hardline (!^ "match dt with" :: List.map cons_line dt_info.dt_constrs))) )) [dt_tag; mem_tag] in return op_nm let ensure_list global list_mono loc bt = let@ dt_bt = match mono_list_bt list_mono bt with | Some x -> return x | None -> fail_m loc (Pp.item "ensure_list: not a monomorphised list" (BT.pp bt)) in let dt_sym = Option.get (BT.is_datatype_bt dt_bt) in let dt_info = SymMap.find dt_sym global.Global.datatypes in let (nil_nm, cons_nm) = match dt_info.BT.dt_constrs with | [nil; cons] -> (nil, cons) | _ -> assert false in let open Pp in let cons = parens (!^ "fun x ->" ^^^ Sym.pp cons_nm ^^^ !^ "x") in let dest_op_nm = "dest_" ^ Sym.pp_string dt_sym in let@ () = gen_ensure 0 ["types"; "list destructor"; Sym.pp_string dt_sym] (lazy ( let nil_line = !^ " |" ^^^ Sym.pp nil_nm ^^^ !^ "=>" ^^^ !^"None" in let cons_line = !^ " |" ^^^ Sym.pp cons_nm ^^^ !^ "y ys =>" ^^^ !^"Some (y, ys)" in return (defn dest_op_nm [parens (typ (!^ "xs") (Sym.pp dt_sym))] None (flow hardline [!^ "match xs with"; nil_line; cons_line; !^" end"])) )) [dt_sym] in return (Sym.pp nil_nm, cons, Pp.string dest_op_nm) let ensure_tuple_op is_upd nm (ix, l) = let ix_s = Int.to_string ix in let len_s = Int.to_string l in let dir_s = if is_upd then "upd" else "get" in let k = ["predefs"; "tuple"; dir_s; nm; ix_s; len_s] in let op_nm = dir_s ^ "_" ^ nm ^ "_" ^ ix_s ^ "_" ^ len_s in let doc = lazy ( let open Pp in let ty i = !^ ("T_" ^ Int.to_string i) in let t_ty = tuple_coq_ty (!^ op_nm) (List.init l ty) in let t = parens (typ (!^ "t") t_ty) in let x = parens (typ (!^ "x") (ty ix)) in let infer = !^"{" ^^ flow (!^ " ") (List.init l ty) ^^ colon ^^^ !^"Type}" in return (if is_upd then defn op_nm [infer; t; x] None (tuple_upd_element t (ix, l) x) else defn op_nm [infer; t] None (tuple_element t (ix, l))) ) in let@ () = gen_ensure 2 k doc [] in return op_nm let ensure_pred global list_mono loc name aux = let open LogicalPredicates in let def = SymMap.find name global.Global.logical_predicates in let inf = (loc, Pp.typ (Pp.string "pred") (Sym.pp name)) in begin match def.definition with | Uninterp -> gen_ensure 1 ["params"; "pred"; Sym.pp_string name] (lazy ( let@ arg_tys = ListM.mapM (fun (_, bt) -> bt_to_coq global list_mono inf bt) def.args in let open Pp in let@ ret_ty = if fun_prop_ret global name then return (!^ "Prop") else bt_to_coq global list_mono inf def.return_bt in let ty = List.fold_right (fun at rt -> at ^^^ !^ "->" ^^^ rt) arg_tys ret_ty in return (!^ " Parameter" ^^^ typ (Sym.pp name) ty ^^ !^ "." ^^ hardline) )) [] | Def body -> let body = Body.to_term def.return_bt body in gen_ensure 2 ["predefs"; "pred"; Sym.pp_string name] (lazy ( let@ rhs = aux (it_adjust global body) in let@ args = ListM.mapM (fun (sym, bt) -> let@ coq_bt = bt_to_coq global list_mono inf bt in return (Pp.parens (Pp.typ (Sym.pp sym) coq_bt))) def.args in return (defn (Sym.pp_string name) args None rhs) )) [] | Rec_Def body -> fail_m def.loc (Pp.item "rec-def not yet handled" (Sym.pp name)) end let ensure_struct_mem is_good global list_mono loc ct aux = match Sctypes.is_struct_ctype ct with | None -> fail "ensure_struct_mem: not struct" (Sctypes.pp ct) | Some tag -> let bt = BaseTypes.Struct tag in let nm = if is_good then "good" else "representable" in let k = ["predefs"; "struct"; Sym.pp_string tag; nm] in let op_nm = "struct_" ^ Sym.pp_string tag ^ "_" ^ nm in let@ () = gen_ensure 2 k (lazy ( let@ ty = bt_to_coq global list_mono (loc, Pp.string op_nm) bt in let x = Pp.parens (Pp.typ (Pp.string "x") ty) in let x_it = IT.sym_ (Sym.fresh_named "x", bt) in let@ rhs = aux (it_adjust global (IT.good_value global.struct_decls ct x_it)) in return (defn op_nm [x] None rhs) )) [tag] in return op_nm let rec unfold_if_possible global it = let open IT in let open LogicalPredicates in match it with | IT (IT.Pred (name, args), _) -> let def = Option.get (Global.get_logical_predicate_def global name) in begin match def.definition with | Rec_Def _ -> it | Uninterp -> it | Def body -> unfold_if_possible global (Body.to_term def.return_bt (open_pred def.args body args)) end | _ -> it let mk_forall global list_mono loc sym bt doc = let open Pp in let inf = (loc, !^"forall of" ^^^ Sym.pp sym) in let@ coq_bt = bt_to_coq global list_mono inf bt in return (!^ "forall" ^^^ parens (typ (Sym.pp sym) coq_bt) ^^ !^"," ^^ break 1 ^^ doc) let add_dt_param_counted (it, m_nm) = let@ st = get in let idx = List.length (st.dt_params) in let sym = Sym.fresh_named (Sym.pp_string m_nm ^ "_" ^ Int.to_string idx) in let@ () = add_dt_param (it, m_nm, sym) in return sym let dt_split global x t = let dt = Option.get (BT.is_datatype_bt (IT.bt x)) in let cs_used = IT.fold (fun _ acc t -> match IT.term t with | IT.Datatype_op (IT.DatatypeIsCons (c_nm, y)) when IT.equal x y -> SymSet.add c_nm acc | _ -> acc) [] SymSet.empty t in let mems_used = IT.fold (fun _ acc t -> match IT.term t with | IT.Datatype_op (IT.DatatypeMember (y, m_nm)) when IT.equal x y -> SymSet.add m_nm acc | _ -> acc) [] SymSet.empty t in let dt_info = SymMap.find dt global.Global.datatypes in let need_default = List.length dt_info.BT.dt_constrs > SymSet.cardinal cs_used in let rec redux c_nm t = match IT.term t with | IT.Bool_op (IT.ITE (IT.IT (IT.Datatype_op (IT.DatatypeIsCons (c_nm2, y)), _), x_t, x_f)) when IT.equal x y -> if Sym.equal c_nm c_nm2 then redux c_nm x_t else redux c_nm x_f | _ -> t in let f c_nm = let c_info = SymMap.find c_nm global.Global.datatype_constrs in let ms = List.map fst c_info.c_params in (Sym.pp c_nm, ms, mems_used, redux c_nm t) in List.map f (SymSet.elements cs_used) @ (if need_default else []) let dt_access_error t = Pp.item "cannot convert datatype accessor" (Pp.typ (IT.pp t) (Pp.flow_map (Pp.break 1) Pp.string ["datatype accessor expressions are"; "only available in the branch of an"; "if-then-else expression (_ ? _ : _)"; "whose switch established the datatype"; "shape (_ ?? Constructor {})"])) let with_selected_dt_params it mem_nms set_used f = with_reset_dt_params (fun () -> let@ xs = ListM.mapM (fun m_nm -> if SymSet.mem m_nm set_used then let@ sym = add_dt_param_counted (it, m_nm) in return (Some sym) else return None) mem_nms in f xs) let match_some_dt_params c_doc opt_params = build (return c_doc :: List.map (function | None -> rets "_" | Some m_sym -> return (Sym.pp m_sym) ) opt_params) let it_to_coq loc global list_mono it = let open Pp in let eq_of = function | BaseTypes.Integer -> return "Z.eqb" | bt -> fail_m loc (Pp.item "eq_of" (BaseTypes.pp bt)) in let rec f bool_eq_prop t = let aux t = f bool_eq_prop t in let abinop s x y = parensM (build [aux x; rets s; aux y]) in let with_is_true x = if bool_eq_prop && BaseTypes.equal (IT.bt t) BaseTypes.Bool then parensM (build [rets "Is_true"; x]) else x in let check_pos t f = let t = unfold_if_possible global t in match IT.is_z t with | Some i when Z.gt i Z.zero -> f | _ -> fail_m loc (Pp.item "it_to_coq: divisor not positive const" (IT.pp t)) in match IT.term t with | IT.Lit l -> begin match l with | IT.Sym sym -> return (Sym.pp sym) | IT.Bool b -> with_is_true (rets (if b then "true" else "false")) | IT.Z z -> rets (Z.to_string z) | _ -> fail_m loc (Pp.item "it_to_coq: unsupported lit" (IT.pp t)) end | IT.Arith_op op -> begin match op with | Add (x, y) -> abinop "+" x y | Sub (x, y) -> abinop "-" x y | Mul (x, y) -> abinop "*" x y | MulNoSMT (x, y) -> abinop "*" x y | Div (x, y) -> check_pos y (abinop "/" x y) | DivNoSMT (x, y) -> check_pos y (abinop "/" x y) | Mod (x, y) -> check_pos y (abinop "mod" x y) | ModNoSMT (x, y) -> check_pos y (abinop "mod" x y) | Rem (x, y) -> check_pos y (abinop "mod" x y) | RemNoSMT (x, y) -> check_pos y (abinop "mod" x y) | LT (x, y) -> abinop (if bool_eq_prop then "<" else "<?") x y | LE (x, y) -> abinop (if bool_eq_prop then "<=" else "<=?") x y | Exp (x, y) -> abinop "^" x y | ExpNoSMT (x, y) -> abinop "^" x y | XORNoSMT (x, y) -> parensM (build [rets "Z.lxor"; aux x; aux y]) | _ -> fail_m loc (Pp.item "it_to_coq: unsupported arith op" (IT.pp t)) end | IT.Bool_op op -> begin match op with | IT.And [] -> aux (IT.bool_ true) | IT.And [x] -> aux x | IT.And (x :: xs) -> abinop (if bool_eq_prop then "/\\" else "&&") x (IT.and_ xs) | IT.Or [] -> aux (IT.bool_ false) | IT.Or [x] -> aux x | IT.Or (x :: xs) -> abinop (if bool_eq_prop then "\\/" else "||") x (IT.or_ xs) | IT.Impl (x, y) -> abinop (if bool_eq_prop then "->" else "implb") x y | IT.Not x -> parensM (build [rets (if bool_eq_prop then "~" else "negb"); aux x]) | IT.ITE (IT.IT (IT.Datatype_op (IT.DatatypeIsCons (c_nm, x)), _), _, _) -> let dt = Option.get (BT.is_datatype_bt (IT.bt x)) in let@ () = ensure_datatype global list_mono loc dt in let branches = dt_split global x t in let br (c_doc, ps, ps_used, t2) = with_selected_dt_params x ps ps_used (fun opt_ps -> build [rets "|"; match_some_dt_params c_doc opt_ps; rets "=>"; aux t2]) in parensM (build ([rets "match"; f false x; rets "with"] @ List.map br branches @ [rets "end"])) | IT.ITE (sw, x, y) -> parensM (build [rets "if"; f false sw; rets "then"; aux x; rets "else"; aux y]) | IT.EQ (x, y) -> build [f false x; rets (if bool_eq_prop then "=" else "=?"); f false y] | IT.EachI ((i1, s, i2), x) -> assert bool_eq_prop; let@ x = aux x in let@ enc = mk_forall global list_mono loc s BaseTypes.Integer (binop "->" (binop "/\\" (binop "<=" (Pp.int i1) (Sym.pp s)) (binop "<=" (Sym.pp s) (Pp.int i2))) x) in return (parens enc) end | IT.Map_op op -> begin match op with | IT.Set (m, x, y) -> let@ () = ensure_fun_upd () in let@ e = eq_of (IT.bt x) in parensM (build [rets "fun_upd"; rets e; aux m; aux x; aux y]) | IT.Get (m, x) -> parensM (build [aux m; aux x]) | _ -> fail_m loc (Pp.item "it_to_coq: unsupported map op" (IT.pp t)) end | IT.Record_op op -> begin match op with | IT.RecordMember (t, m) -> let flds = BT.record_bt (IT.bt t) in if List.length flds == 1 then aux t else let ix = find_tuple_element Sym.equal m Sym.pp (List.map fst flds) in let@ op_nm = ensure_tuple_op false (Sym.pp_string m) ix in parensM (build [rets op_nm; aux t]) | IT.RecordUpdate ((t, m), x) -> let flds = BT.record_bt (IT.bt t) in if List.length flds == 1 then aux x else let ix = find_tuple_element Sym.equal m Sym.pp (List.map fst flds) in let@ op_nm = ensure_tuple_op true (Sym.pp_string m) ix in parensM (build [rets op_nm; aux t; aux x]) | IT.Record mems -> let@ xs = ListM.mapM aux (List.map snd mems) in parensM (return (flow (comma ^^ break 1) xs)) end | IT.Struct_op op -> begin match op with | IT.StructMember (t, m) -> let tag = BaseTypes.struct_bt (IT.bt t) in let (mems, bts) = get_struct_xs global.struct_decls tag in let ix = find_tuple_element Id.equal m Id.pp mems in if List.length mems == 1 then aux t else let@ op_nm = ensure_tuple_op false (Id.pp_string m) ix in parensM (build [rets op_nm; aux t]) | IT.StructUpdate ((t, m), x) -> let tag = BaseTypes.struct_bt (IT.bt t) in let (mems, bts) = get_struct_xs global.struct_decls tag in let ix = find_tuple_element Id.equal m Id.pp mems in if List.length mems == 1 then aux x else let@ op_nm = ensure_tuple_op true (Id.pp_string m) ix in parensM (build [rets op_nm; aux t; aux x]) | _ -> fail_m loc (Pp.item "it_to_coq: unsupported struct op" (IT.pp it)) end | IT.Pointer_op op -> begin match op with | IT.IntegerToPointerCast t -> aux t | IT.PointerToIntegerCast t -> aux t | IT.LEPointer (x, y) -> abinop (if bool_eq_prop then "<=" else "<=?") x y | IT.LTPointer (x, y) -> abinop (if bool_eq_prop then "<" else "<?") x y | _ -> fail_m loc (Pp.item "it_to_coq: unsupported pointer op" (IT.pp it)) end | IT.Pred (name, args) -> let prop_ret = fun_prop_ret global name in let body_aux = f prop_ret in let@ () = ensure_pred global list_mono loc name body_aux in let@ r = parensM (build ([return (Sym.pp name)] @ List.map (f false) args)) in if prop_ret then return r else with_is_true (return r) | IT.CT_pred p -> assert bool_eq_prop; begin match p with | IT.Good (ct, t2) when (Option.is_some (Sctypes.is_struct_ctype ct)) -> let@ op_nm = ensure_struct_mem true global list_mono loc ct aux in parensM (build [rets op_nm; aux t2]) | IT.Representable (ct, t2) when (Option.is_some (Sctypes.is_struct_ctype ct)) -> let@ op_nm = ensure_struct_mem true global list_mono loc ct aux in parensM (build [rets op_nm; aux t2]) | _ -> fail_m loc (Pp.item "it_to_coq: unexpected ctype pred" (IT.pp t)) end | IT.Datatype_op op -> begin match op with | IT.DatatypeCons (nm, members_rec) -> let info = SymMap.find nm global.datatype_constrs in let args = List.map (fun (nm, _) -> Simplify.IndexTerms.record_member_reduce members_rec nm) info.c_params in let@ () = ensure_datatype global list_mono loc info.c_datatype_tag in parensM (build ([return (Sym.pp nm)] @ List.map (f false) args)) | IT.DatatypeMember (dt, nm) -> let@ o_sym = get_dt_param dt nm in begin match o_sym with | Some sym -> return (Sym.pp sym) | _ -> fail_m loc (dt_access_error t) end | _ -> fail_m loc (Pp.item "it_to_coq: unsupported datatype op" (IT.pp t)) end | IT.List_op op -> begin match op with | IT.NthList (n, xs, d) -> let@ (_, _, dest) = ensure_list global list_mono loc (IT.bt xs) in parensM (build [rets "CN_Lib.nth_list_z"; return dest; aux n; aux xs; aux d]) | IT.ArrayToList (arr, i, len) -> let@ (nil, cons, _) = ensure_list global list_mono loc (IT.bt t) in parensM (build [rets "CN_Lib.array_to_list"; return nil; return cons; aux arr; aux i; aux len]) | _ -> fail_m loc (Pp.item "it_to_coq: unsupported list op" (IT.pp t)) end | _ -> fail_m loc (Pp.item "it_to_coq: unsupported" (IT.pp t)) in f true it let mk_let sym rhs_doc doc = let open Pp in !^ "let" ^^^ Sym.pp sym ^^^ !^ ":=" ^^^ rhs_doc ^^^ !^ "in" ^^^ doc let lc_to_coq_check_triv loc global list_mono = function | LC.T it -> let it = it_adjust global it in if IT.is_true it then return None else let@ v = it_to_coq loc global list_mono it in return (Some v) | LC.Forall ((sym, bt), it) -> let it = it_adjust global it in if IT.is_true it then return None else let@ v = it_to_coq loc global list_mono it in let@ enc = mk_forall global list_mono loc sym bt v in return (Some (Pp.parens enc)) let nth_str_eq n s ss = Option.equal String.equal (List.nth_opt ss n) (Some s) let types_spec types = let open Pp in !^"Module Types." ^^ hardline ^^ hardline ^^ (if List.length types == 0 then !^ " (* no type definitions required *)" ^^ hardline else flow hardline types) ^^ hardline ^^ !^"End Types." ^^ hardline ^^ hardline let param_spec params = let open Pp in !^"Module Type Parameters." ^^ hardline ^^ !^" Import Types." ^^ hardline ^^ hardline ^^ (if List.length params == 0 then !^ " (* no parameters required *)" ^^ hardline else flow hardline params) ^^ hardline ^^ !^"End Parameters." ^^ hardline ^^ hardline let ftyp_to_coq loc global list_mono ftyp = let open Pp in let lc_to_coq_c = lc_to_coq_check_triv loc global list_mono in let it_tc = it_to_coq loc global list_mono in let oapp f opt_x y = match opt_x with | Some x -> f x y | None -> y in let mk_and doc doc2 = doc ^^^ !^ "/\\" ^^^ doc2 in let mk_imp doc doc2 = doc ^^^ !^ "->" ^^^ doc2 in let omap_split f = Option.map (fun doc -> f (break 1 ^^ doc)) in let rec lrt_doc t = match t with | LRT.Constraint (lc, _, t) -> let@ d = lrt_doc t in let@ c = lc_to_coq_c lc in begin match d, c with | None, _ -> return c | _, None -> return d | Some dd, Some cd -> return (Some (mk_and cd dd)) end | LRT.Define ((sym, it), _, t) -> let@ d = lrt_doc t in let@ l = it_tc it in return (omap_split (mk_let sym l) d) | LRT.I -> return None | _ -> fail_m loc (Pp.item "ftyp_to_coq: unsupported" (LRT.pp t)) in let rt_doc t = match t with | RT.Computational ((_, bt), _, t2) -> if BaseTypes.equal bt BaseTypes.Unit then lrt_doc t2 else fail_m loc (Pp.item "ftyp_to_coq: unsupported return type" (RT.pp t)) in let rec lat_doc t = match t with | LAT.Define ((sym, it), _, t) -> let@ d = lat_doc t in let@ l = it_tc it in return (omap_split (mk_let sym l) d) | LAT.Resource _ -> fail_m loc (Pp.item "ftyp_to_coq: unsupported" (LAT.pp RT.pp t)) | LAT.Constraint (lc, _, t) -> let@ c = lc_to_coq_c lc in let@ d = lat_doc t in return (omap_split (oapp mk_imp c) d) | LAT.I t -> rt_doc t in let rec at_doc t = match t with | AT.Computational ((sym, bt), _, t) -> let@ d = at_doc t in begin match d with | None -> return None | Some doc -> let@ doc2 = mk_forall global list_mono loc sym bt (break 1 ^^ doc) in return (Some doc2) end | AT.L t -> lat_doc t in let@ d = at_doc ftyp in let d2 = d | > Option.map ( ( fun nm d - > let ( sym , bt ) = StringMap.find nm all_undef_foralls in mk_forall global sym bt d ) extra_foralls ) in let d2 = d |> Option.map (List.fold_right (fun nm d -> let (sym, bt) = StringMap.find nm all_undef_foralls in mk_forall global sym bt d) extra_foralls) in *) match d with | Some doc -> return doc | None -> rets "Is_true true" let convert_lemma_defs global list_mono lemma_typs = let lemma_ty (nm, typ, loc, kind) = Pp.progress_simple ("converting " ^ kind ^ " lemma type") (Sym.pp_string nm); let@ rhs = ftyp_to_coq loc global list_mono typ in return (defn (Sym.pp_string nm ^ "_type") [] (Some (Pp.string "Prop")) rhs) in let@ tys = ListM.mapM lemma_ty lemma_typs in let@ st = get in Pp.debug 4 (lazy (Pp.item "saved conversion elements" (Pp.list (fun (ss, _) -> Pp.parens (Pp.list Pp.string ss)) (StringListMap.bindings st.present)))); return (tys, List.rev (get_section 0 st), List.rev (get_section 1 st), List.rev (get_section 2 st)) let defs_module aux_defs lemma_tys = let open Pp in !^"Module Defs (P : Parameters)." ^^ hardline ^^ hardline ^^ !^" Import Types P." ^^ hardline ^^ !^" Open Scope Z." ^^ hardline ^^ hardline ^^ flow hardline aux_defs ^^ hardline ^^ flow hardline lemma_tys ^^ hardline ^^ !^"End Defs." ^^ hardline ^^ hardline let mod_spec lemma_nms = let open Pp in let lemma nm = !^" Parameter" ^^^ typ (Sym.pp nm) (Sym.pp nm ^^ !^ "_type") ^^ !^ "." ^^ hardline in !^"Module Type Lemma_Spec (P : Parameters)." ^^ hardline ^^ hardline ^^ !^" Module D := Defs(P)." ^^ hardline ^^ !^" Import D." ^^ hardline ^^ hardline ^^ flow hardline (List.map lemma lemma_nms) ^^ hardline ^^ !^"End Lemma_Spec." ^^ hardline ^^ hardline let convert_and_print channel global list_mono conv = let@ (conv_defs, types, params, defs) = convert_lemma_defs global list_mono conv in Pp.print channel (types_spec types); Pp.print channel (param_spec params); Pp.print channel (defs_module defs conv_defs); Pp.print channel (mod_spec (List.map (fun (nm, _, _, _) -> nm) conv)); return () let cmp_line_numbers = function | None, None -> 0 | None, _ -> 1 | _, None -> -1 | Some (a, b), Some (c, d) -> let x = Int.compare a c in if x == 0 then Int.compare b d else x let cmp_loc_line_numbers l1 l2 = cmp_line_numbers (Loc.line_numbers l1, Loc.line_numbers l2) an experiment involving calling the Retype features again , this time with " CallByValue " set . this probably does n't work , since the elaboration needs to be compatible let do_re_retype mu_file trusted_funs prev_mode pred_defs pre_retype_mu_file = match prev_mode with | ` CallByValue - > Ok mu_file | ` CallByReference - > let = let open Retype . Old in let info2 = Pmap.filter ( fun fsym _ - > SymSet.mem fsym trusted_funs ) pre_retype_mu_file.mu_funinfo in let = Pmap.filter ( fun fsym _ - > SymSet.mem fsym trusted_funs ) pre_retype_mu_file.mu_funs in { pre_retype_mu_file with mu_funs = funs2 ; mu_funinfo = info2 } in Retype.retype_file pred_defs ` CallByValue prev_cut with "CallByValue" set. this probably doesn't work, since the elaboration needs to be compatible let do_re_retype mu_file trusted_funs prev_mode pred_defs pre_retype_mu_file = match prev_mode with | `CallByValue -> Ok mu_file | `CallByReference -> let prev_cut = let open Retype.Old in let info2 = Pmap.filter (fun fsym _ -> SymSet.mem fsym trusted_funs) pre_retype_mu_file.mu_funinfo in let funs2 = Pmap.filter (fun fsym _ -> SymSet.mem fsym trusted_funs) pre_retype_mu_file.mu_funs in { pre_retype_mu_file with mu_funs = funs2; mu_funinfo = info2 } in Retype.retype_file pred_defs `CallByValue prev_cut *) type scanned = {sym : Sym.t; loc: Loc.t; typ: RT.t AT.t; scan_res: scan_res} let generate (global : Global.t) directions trusted_funs = let (filename, kinds) = parse_directions directions in let channel = open_out filename in Pp.print channel (header filename); let scan_trusted = List.map (fun (sym, (loc, typ)) -> {sym; loc; typ; scan_res = scan typ} ) trusted_funs |> List.sort (fun x (y : scanned) -> cmp_loc_line_numbers x.loc y.loc) in let (returns, others) = List.partition (fun x -> x.scan_res.ret) scan_trusted in let (impure, pure) = List.partition (fun x -> Option.is_some x.scan_res.res) others in let (coerce, skip) = List.partition (fun x -> Option.is_some x.scan_res.res_coerce) impure in List.iter (fun x -> Pp.progress_simple "skipping trusted fun with return val" (Sym.pp_string x.sym) ) returns; List.iter (fun x -> Pp.progress_simple "skipping trusted fun with resource" (Sym.pp_string x.sym ^ ": " ^ (Option.get x.scan_res.res)) ) skip; let fun_info = ( fun ( s , def ) m - > SymMap.add s def m ) let (list_mono, global) = monomorphise_dt_lists global in let ci = { global ; fun_info ; list_mono } in let conv = List.map (fun x -> (x.sym, x.typ, x.loc, "pure")) pure @ List.map (fun x -> (x.sym, Option.get x.scan_res.res_coerce, x.loc, "coerced")) coerce in match convert_and_print channel global list_mono conv init_t with | Result.Ok _ -> Result.Ok () | Result.Error e -> Result.Error e
0c334f99acb9a18494e3280f4e7fd91a6ef88c4c0972a7b722329153b1b930d1
crategus/cl-cffi-gtk
rtest-gdk-visual.lisp
(def-suite gdk-visual :in gdk-suite) (in-suite gdk-visual) ;;; --- Types and Values ------------------------------------------------------- ;;; GdkVisualType (test gdk-visual-type ;; Check the type (is (g-type-is-enum "GdkVisualType")) ;; Check the type initializer (is (eq (gtype "GdkVisualType") (gtype (foreign-funcall "gdk_visual_type_get_type" g-size)))) ;; Check the registered name (is (eq 'gdk-visual-type (registered-enum-type "GdkVisualType"))) ;; Check the names (is (equal '("GDK_VISUAL_STATIC_GRAY" "GDK_VISUAL_GRAYSCALE" "GDK_VISUAL_STATIC_COLOR" "GDK_VISUAL_PSEUDO_COLOR" "GDK_VISUAL_TRUE_COLOR" "GDK_VISUAL_DIRECT_COLOR") (mapcar #'enum-item-name (get-enum-items "GdkVisualType")))) ;; Check the values (is (equal '(0 1 2 3 4 5) (mapcar #'enum-item-value (get-enum-items "GdkVisualType")))) Check the nick names (is (equal '("static-gray" "grayscale" "static-color" "pseudo-color" "true-color" "direct-color") (mapcar #'enum-item-nick (get-enum-items "GdkVisualType")))) ;; Check the enum definition (is (equal '(DEFINE-G-ENUM "GdkVisualType" GDK-VISUAL-TYPE (:EXPORT T :TYPE-INITIALIZER "gdk_visual_type_get_type") (:STATIC-GRAY 0) (:GRAYSCALE 1) (:STATIC-COLOR 2) (:PSEUDO-COLOR 3) (:TRUE-COLOR 4) (:DIRECT-COLOR 5)) (get-g-type-definition "GdkVisualType")))) ;;; GdkByteOrder (test gdk-byte-order ;; Check the type (is (g-type-is-enum "GdkByteOrder")) ;; Check the type initializer (is (eq (gtype"GdkByteOrder") (gtype (foreign-funcall "gdk_byte_order_get_type" g-size)))) ;; Check the registered name (is (eq 'gdk-byte-order (registered-enum-type "GdkByteOrder"))) ;; Check the names (is (equal '("GDK_LSB_FIRST" "GDK_MSB_FIRST") (mapcar #'enum-item-name (get-enum-items "GdkByteOrder")))) ;; Check the values (is (equal '(0 1) (mapcar #'enum-item-value (get-enum-items "GdkByteOrder")))) Check the nick names (is (equal '("lsb-first" "msb-first") (mapcar #'enum-item-nick (get-enum-items "GdkByteOrder")))) ;; Check the enum definition (is (equal '(DEFINE-G-ENUM "GdkByteOrder" GDK-BYTE-ORDER (:EXPORT T :TYPE-INITIALIZER "gdk_byte_order_get_type") (:LSB-FIRST 0) (:MSB-FIRST 1)) (get-g-type-definition "GdkByteOrder")))) ;;; GdkVisual (test gdk-visual-class ;; Type check (is (g-type-is-object "GdkVisual")) ;; Check the registered name (is (eq 'gdk-visual (registered-object-type-by-name "GdkVisual"))) ;; Check the type initializer (is (eq (gtype "GdkVisual") (gtype (foreign-funcall "gdk_visual_get_type" g-size)))) ;; Check the parent (is (eq (gtype "GObject") (g-type-parent "GdkVisual"))) ;; Check the children #-windows (is (equal '("GdkX11Visual") (mapcar #'g-type-name (g-type-children "GdkVisual")))) #+windows (is (equal '() (mapcar #'g-type-name (g-type-children "GdkVisual")))) ;; Check the interfaces (is (equal '() (mapcar #'g-type-name (g-type-interfaces "GdkVisual")))) ;; Check the class properties (is (equal '() (stable-sort (mapcar #'g-param-spec-name (g-object-class-list-properties "GdkVisual")) #'string-lessp))) ;; Check the class definition (is (equal '(DEFINE-G-OBJECT-CLASS "GdkVisual" GDK-VISUAL (:SUPERCLASS G-OBJECT :EXPORT T :INTERFACES NIL :TYPE-INITIALIZER "gdk_visual_get_type") NIL) (get-g-type-definition "GdkVisual")))) ;;; --- Functions -------------------------------------------------------------- ;;; gdk-query-depths deprecated (test gdk-query-depths (is (listp (gdk-query-depths))) (is (every #'integerp (gdk-query-depths)))) ;;; gdk-query-visual-types deprecated (test gdk-query-visual-types (is (listp (gdk-query-visual-types))) (is (member :true-color (gdk-query-visual-types)))) - list - visuals deprecated (test gdk-list-visuals (is (> (length (gdk-list-visuals)) 0)) (is (every (lambda (x) (eq x 'gdk-visual)) (mapcar #'type-of (gdk-list-visuals))))) - visual - bits - per - rgb deprecated (test gdk-visual-bits-per-rgb (let ((visual (gdk-visual-system))) (is (integerp (gdk-visual-bits-per-rgb visual))))) - visual - blue - pixel - details (test gdk-visual-blue-pixel-details (let ((visual (gdk-visual-system))) (multiple-value-bind (mask shift prec) (gdk-visual-blue-pixel-details visual) (is (= #xff mask)) (is (= 0 shift)) (is (= 8 prec))))) - visual - byte - order deprecated (test gdk-visual-byte-order (let ((visual (gdk-visual-system))) (is (eq :lsb-first (gdk-visual-byte-order visual))))) - visual - colormap - size deprecated (test gdk-visual-colormap-size (let ((visual (gdk-visual-system))) (is (= 256 (gdk-visual-colormap-size visual))))) - visual - depth (test gdk-visual-depth (let ((visual (gdk-visual-system))) (is (= 24 (gdk-visual-depth visual))))) - visual - green - pixel - details (test gdk-visual-green-pixel-details (let ((visual (gdk-visual-system))) (multiple-value-bind (mask shift prec) (gdk-visual-green-pixel-details visual) (is (= #xff00 mask)) (is (= 8 shift)) (is (= 8 prec))))) - visual - red - pixel - details (test gdk-visual-red-pixel-details (let ((visual (gdk-visual-system))) (multiple-value-bind (mask shift prec) (gdk-visual-red-pixel-details visual) (is (= #xff0000 mask)) (is (= 16 shift)) (is (= 8 prec))))) - visual - visual - type (test gdk-visual-visual-type (let ((visual (gdk-visual-system))) (is (member (gdk-visual-visual-type visual) '(:static-gray :grayscale :static-color :pseudo-color :true-color :direct-color))))) - visual - best - depth deprecated (test gdk-visual-best-depth (is (integerp (gdk-visual-best-depth))) (is (member (gdk-visual-best-depth) (mapcar #'gdk-visual-depth (gdk-list-visuals))))) - visual - best - type deprecated (test gdk-visual-best-type (is (member (gdk-visual-best-type) '(:static-gray :grayscale :static-color :pseudo-color :true-color :direct-color))) (is (member (gdk-visual-best-type) (mapcar #'gdk-visual-visual-type (gdk-list-visuals))))) - visual - system deprecated (test gdk-visual-system (is (eq 'gdk-visual (type-of (gdk-visual-system))))) - visual - best deprecated (test gdk-visual-best (is (eq 'gdk-visual (type-of (gdk-visual-best)))) (is (= 32 (gdk-visual-depth (gdk-visual-best)))) (is (eq :true-color (gdk-visual-visual-type (gdk-visual-best))))) - visual - best - with - depth deprecated (test gdk-visual-best-with-depth (is-false (gdk-visual-best-with-depth 64)) (is (eq 'gdk-visual (type-of (gdk-visual-best-with-depth 32)))) (is (eq 'gdk-visual (type-of (gdk-visual-best-with-depth 24))))) - visual - best - with - type deprecated #-windows (test gdk-visual-best-with-type (is (eq 'gdk-visual (type-of (gdk-visual-best-with-type :true-color)))) (is (eq 'gdk-visual (type-of (gdk-visual-best-with-type :direct-color))))) - visual - best - with - both deprecated #-windows (test gdk-visual-best-with-both (is (eq 'gdk-visual (type-of (gdk-visual-best-with-both 32 :true-color)))) (is (eq 'gdk-visual (type-of (gdk-visual-best-with-both 24 :true-color)))) (is-false (gdk-visual-best-with-both 32 :direct-color)) (is (eq 'gdk-visual (type-of (gdk-visual-best-with-both 24 :direct-color))))) ;;; gdk visual-screen (test gdk-visual-screen (is (eq 'gdk-screen (type-of (gdk-visual-screen (gdk-visual-system)))))) 2021 - 10 - 14
null
https://raw.githubusercontent.com/crategus/cl-cffi-gtk/7f5a09f78d8004a71efa82794265f2587fff98ab/test/rtest-gdk-visual.lisp
lisp
--- Types and Values ------------------------------------------------------- GdkVisualType Check the type Check the type initializer Check the registered name Check the names Check the values Check the enum definition GdkByteOrder Check the type Check the type initializer Check the registered name Check the names Check the values Check the enum definition GdkVisual Type check Check the registered name Check the type initializer Check the parent Check the children Check the interfaces Check the class properties Check the class definition --- Functions -------------------------------------------------------------- gdk-query-depths deprecated gdk-query-visual-types deprecated gdk visual-screen
(def-suite gdk-visual :in gdk-suite) (in-suite gdk-visual) (test gdk-visual-type (is (g-type-is-enum "GdkVisualType")) (is (eq (gtype "GdkVisualType") (gtype (foreign-funcall "gdk_visual_type_get_type" g-size)))) (is (eq 'gdk-visual-type (registered-enum-type "GdkVisualType"))) (is (equal '("GDK_VISUAL_STATIC_GRAY" "GDK_VISUAL_GRAYSCALE" "GDK_VISUAL_STATIC_COLOR" "GDK_VISUAL_PSEUDO_COLOR" "GDK_VISUAL_TRUE_COLOR" "GDK_VISUAL_DIRECT_COLOR") (mapcar #'enum-item-name (get-enum-items "GdkVisualType")))) (is (equal '(0 1 2 3 4 5) (mapcar #'enum-item-value (get-enum-items "GdkVisualType")))) Check the nick names (is (equal '("static-gray" "grayscale" "static-color" "pseudo-color" "true-color" "direct-color") (mapcar #'enum-item-nick (get-enum-items "GdkVisualType")))) (is (equal '(DEFINE-G-ENUM "GdkVisualType" GDK-VISUAL-TYPE (:EXPORT T :TYPE-INITIALIZER "gdk_visual_type_get_type") (:STATIC-GRAY 0) (:GRAYSCALE 1) (:STATIC-COLOR 2) (:PSEUDO-COLOR 3) (:TRUE-COLOR 4) (:DIRECT-COLOR 5)) (get-g-type-definition "GdkVisualType")))) (test gdk-byte-order (is (g-type-is-enum "GdkByteOrder")) (is (eq (gtype"GdkByteOrder") (gtype (foreign-funcall "gdk_byte_order_get_type" g-size)))) (is (eq 'gdk-byte-order (registered-enum-type "GdkByteOrder"))) (is (equal '("GDK_LSB_FIRST" "GDK_MSB_FIRST") (mapcar #'enum-item-name (get-enum-items "GdkByteOrder")))) (is (equal '(0 1) (mapcar #'enum-item-value (get-enum-items "GdkByteOrder")))) Check the nick names (is (equal '("lsb-first" "msb-first") (mapcar #'enum-item-nick (get-enum-items "GdkByteOrder")))) (is (equal '(DEFINE-G-ENUM "GdkByteOrder" GDK-BYTE-ORDER (:EXPORT T :TYPE-INITIALIZER "gdk_byte_order_get_type") (:LSB-FIRST 0) (:MSB-FIRST 1)) (get-g-type-definition "GdkByteOrder")))) (test gdk-visual-class (is (g-type-is-object "GdkVisual")) (is (eq 'gdk-visual (registered-object-type-by-name "GdkVisual"))) (is (eq (gtype "GdkVisual") (gtype (foreign-funcall "gdk_visual_get_type" g-size)))) (is (eq (gtype "GObject") (g-type-parent "GdkVisual"))) #-windows (is (equal '("GdkX11Visual") (mapcar #'g-type-name (g-type-children "GdkVisual")))) #+windows (is (equal '() (mapcar #'g-type-name (g-type-children "GdkVisual")))) (is (equal '() (mapcar #'g-type-name (g-type-interfaces "GdkVisual")))) (is (equal '() (stable-sort (mapcar #'g-param-spec-name (g-object-class-list-properties "GdkVisual")) #'string-lessp))) (is (equal '(DEFINE-G-OBJECT-CLASS "GdkVisual" GDK-VISUAL (:SUPERCLASS G-OBJECT :EXPORT T :INTERFACES NIL :TYPE-INITIALIZER "gdk_visual_get_type") NIL) (get-g-type-definition "GdkVisual")))) (test gdk-query-depths (is (listp (gdk-query-depths))) (is (every #'integerp (gdk-query-depths)))) (test gdk-query-visual-types (is (listp (gdk-query-visual-types))) (is (member :true-color (gdk-query-visual-types)))) - list - visuals deprecated (test gdk-list-visuals (is (> (length (gdk-list-visuals)) 0)) (is (every (lambda (x) (eq x 'gdk-visual)) (mapcar #'type-of (gdk-list-visuals))))) - visual - bits - per - rgb deprecated (test gdk-visual-bits-per-rgb (let ((visual (gdk-visual-system))) (is (integerp (gdk-visual-bits-per-rgb visual))))) - visual - blue - pixel - details (test gdk-visual-blue-pixel-details (let ((visual (gdk-visual-system))) (multiple-value-bind (mask shift prec) (gdk-visual-blue-pixel-details visual) (is (= #xff mask)) (is (= 0 shift)) (is (= 8 prec))))) - visual - byte - order deprecated (test gdk-visual-byte-order (let ((visual (gdk-visual-system))) (is (eq :lsb-first (gdk-visual-byte-order visual))))) - visual - colormap - size deprecated (test gdk-visual-colormap-size (let ((visual (gdk-visual-system))) (is (= 256 (gdk-visual-colormap-size visual))))) - visual - depth (test gdk-visual-depth (let ((visual (gdk-visual-system))) (is (= 24 (gdk-visual-depth visual))))) - visual - green - pixel - details (test gdk-visual-green-pixel-details (let ((visual (gdk-visual-system))) (multiple-value-bind (mask shift prec) (gdk-visual-green-pixel-details visual) (is (= #xff00 mask)) (is (= 8 shift)) (is (= 8 prec))))) - visual - red - pixel - details (test gdk-visual-red-pixel-details (let ((visual (gdk-visual-system))) (multiple-value-bind (mask shift prec) (gdk-visual-red-pixel-details visual) (is (= #xff0000 mask)) (is (= 16 shift)) (is (= 8 prec))))) - visual - visual - type (test gdk-visual-visual-type (let ((visual (gdk-visual-system))) (is (member (gdk-visual-visual-type visual) '(:static-gray :grayscale :static-color :pseudo-color :true-color :direct-color))))) - visual - best - depth deprecated (test gdk-visual-best-depth (is (integerp (gdk-visual-best-depth))) (is (member (gdk-visual-best-depth) (mapcar #'gdk-visual-depth (gdk-list-visuals))))) - visual - best - type deprecated (test gdk-visual-best-type (is (member (gdk-visual-best-type) '(:static-gray :grayscale :static-color :pseudo-color :true-color :direct-color))) (is (member (gdk-visual-best-type) (mapcar #'gdk-visual-visual-type (gdk-list-visuals))))) - visual - system deprecated (test gdk-visual-system (is (eq 'gdk-visual (type-of (gdk-visual-system))))) - visual - best deprecated (test gdk-visual-best (is (eq 'gdk-visual (type-of (gdk-visual-best)))) (is (= 32 (gdk-visual-depth (gdk-visual-best)))) (is (eq :true-color (gdk-visual-visual-type (gdk-visual-best))))) - visual - best - with - depth deprecated (test gdk-visual-best-with-depth (is-false (gdk-visual-best-with-depth 64)) (is (eq 'gdk-visual (type-of (gdk-visual-best-with-depth 32)))) (is (eq 'gdk-visual (type-of (gdk-visual-best-with-depth 24))))) - visual - best - with - type deprecated #-windows (test gdk-visual-best-with-type (is (eq 'gdk-visual (type-of (gdk-visual-best-with-type :true-color)))) (is (eq 'gdk-visual (type-of (gdk-visual-best-with-type :direct-color))))) - visual - best - with - both deprecated #-windows (test gdk-visual-best-with-both (is (eq 'gdk-visual (type-of (gdk-visual-best-with-both 32 :true-color)))) (is (eq 'gdk-visual (type-of (gdk-visual-best-with-both 24 :true-color)))) (is-false (gdk-visual-best-with-both 32 :direct-color)) (is (eq 'gdk-visual (type-of (gdk-visual-best-with-both 24 :direct-color))))) (test gdk-visual-screen (is (eq 'gdk-screen (type-of (gdk-visual-screen (gdk-visual-system)))))) 2021 - 10 - 14
f8b718eb26756c5ae1a375867ecbe56b85609f36c36a9227a57e8f168b0b7f3f
uhc/uhc
CoreToImportEnv.hs
{-| Module : CoreToImportEnv License : GPL Maintainer : Stability : experimental Portability : portable -} module Helium.ModuleSystem.CoreToImportEnv(getImportEnvironment) where import Lvm.Core.Core as Core import Helium.Utils.Utils import Helium.StaticAnalysis.Miscellaneous.TypeConversion import Helium.Parser.ParseLibrary import Helium.Parser.Lexer(lexer) import Helium.Parser.Parser(type_, contextAndType) import Helium.ModuleSystem.ImportEnvironment import Helium.Syntax.UHA_Utils import Lvm.Common.Id import Helium.Syntax.UHA import Helium.Parser.OperatorTable import Top.Types import Lvm.Common.Byte(stringFromBytes) import Helium.Syntax.UHA_Range(makeImportRange, setNameRange) typeFromCustoms :: String -> [Custom] -> TpScheme typeFromCustoms n [] = internalError "CoreToImportEnv" "typeFromCustoms" ("function import without type: " ++ n) typeFromCustoms n ( CustomDecl (DeclKindCustom id) [CustomBytes bytes] : cs) | stringFromId id == "type" = let string = filter (/= '!') (stringFromBytes bytes) in makeTpSchemeFromType (parseFromString contextAndType string) | otherwise = typeFromCustoms n cs parseFromString :: HParser a -> String -> a parseFromString p string = case lexer "CoreToImportEnv" string of Left lexErr -> internalError "CoreToImportEnv" "parseFromString" ("lex error in " ++ string) Right (tokens, _) -> wait for EOF Left parseError -> internalError "CoreToImportEnv" "parseFromString" ("parse error in " ++ string) Right x -> x ! ! ! typeSynFromCustoms n (CustomBytes bs:cs) = let typeSynDecl = stringFromBytes bs ( too ? ) simple parser ; works because type variables in synonym decls are renamed to 1 letter ids = ( map (\x -> nameFromString [x]) . filter (' '/=) . takeWhile ('='/=) . drop (length n + 1) ) typeSynDecl rhsType = ( drop 1 . dropWhile ('='/=) ) typeSynDecl in ( arityFromCustoms n cs , \ts -> makeTpFromType (zip ids ts) (parseFromString type_ rhsType) ) typeSynFromCustoms n _ = internalError "CoreToImportEnv" "typeSynFromCustoms" ("type synonym import missing definition: " ++ n) in compiled Core files types have a kind ( e.g. * - > * ) , -- in Helium the have a number indicating the arity arityFromCustoms :: String -> [Custom] -> Int arityFromCustoms n [] = internalError "CoreToImportEnv" "arityFromCustoms" ("type constructor import without kind: " ++ n) arityFromCustoms n ( CustomInt arity : _ ) = arity arityFromCustoms n ( CustomDecl (DeclKindCustom id) [CustomBytes bytes] : cs ) | stringFromId id == "kind" = (length . filter ('*'==) . stringFromBytes) bytes - 1 -- the number of stars minus 1 is the arity arityFromCustoms n (_:cs) = arityFromCustoms n cs makeOperatorTable :: Name -> [Custom] -> [(Name, (Int, Assoc))] makeOperatorTable op (Core.CustomInt i : Core.CustomBytes bs : cs) = let assoc = case stringFromBytes bs of "left" -> AssocLeft "right" -> AssocRight "none" -> AssocNone assocStr -> intErr ("unknown associativity: " ++ assocStr) intErr = internalError "CoreToImportEnv" "makeOperatorTable" in if getNameName op == "-" then -- special rule: unary minus has the assoc -- and the priority of the infix operator - [ (op, (i, assoc)) , (intUnaryMinusName, (i, assoc)) , (floatUnaryMinusName, (i, assoc)) ] else [(op, (i, assoc))] makeOperatorTable op cs = internalError "CoreToImportEnv" "makeOperatorTable" ("infix decl missing priority or associativity: " ++ show op) makeImportName :: String -> Id -> Id -> Name makeImportName importedInMod importedFromMod n = setNameRange (nameFromId n) (makeImportRange (idFromString importedInMod) importedFromMod) getImportEnvironment :: String -> [CoreDecl] -> ImportEnvironment getImportEnvironment importedInModule = foldr insert emptyEnvironment where insert decl = case decl of -- functions DeclAbstract { declName = n , declAccess = Imported{importModule = importedFromModId} , declCustoms = cs } -> addType (makeImportName importedInModule importedFromModId n) (typeFromCustoms (stringFromId n) cs) -- functions from non-core/non-lvm libraries and lvm-instructions DeclExtern { declName = n , declAccess = Imported{importModule = importedFromModId} , declCustoms = cs } -> addType (makeImportName importedInModule importedFromModId n) (typeFromCustoms (stringFromId n) cs) -- constructors DeclCon { declName = n , declAccess = Imported{importModule = importedFromModId} , declArity = arity , declCustoms = cs } -> addValueConstructor (makeImportName importedInModule importedFromModId n) (typeFromCustoms (stringFromId n) cs) -- type constructor import DeclCustom { declName = n , declAccess = Imported{importModule = importedFromModId} , declKind = DeclKindCustom id , declCustoms = cs } | stringFromId id == "data" -> addTypeConstructor (makeImportName importedInModule importedFromModId n) (arityFromCustoms (stringFromId n) cs) -- type synonym declarations -- important: a type synonym also introduces a new type constructor! DeclCustom { declName = n , declAccess = Imported{importModule = importedFromModId} , declKind = DeclKindCustom id , declCustoms = cs } | stringFromId id == "typedecl" -> let name = makeImportName importedInModule importedFromModId n pair = typeSynFromCustoms (stringFromId n) cs in addTypeSynonym name pair . addTypeConstructor name (fst pair) -- infix decls DeclCustom { declName = n , declKind = DeclKindCustom id , declCustoms = cs } | stringFromId id == "infix" -> flip (foldr (uncurry addOperator)) (makeOperatorTable (nameFromId n) cs) -- typing strategies DeclCustom { declName = _ , declKind = DeclKindCustom id , declCustoms = cs } | stringFromId id == "strategy" -> let (CustomDecl _ [CustomBytes bytes]) = head cs text = stringFromBytes bytes in case reads text of [(rule, [])] -> addTypingStrategies rule _ -> intErr "Could not parse typing strategy from core file" -- !!! Print importedFromModId from "declAccess = Imported{importModule = importedFromModId}" as well DeclAbstract{ declName = n } -> intErr ("don't know how to handle declared DeclAbstract: " ++ stringFromId n) DeclExtern { declName = n } -> intErr ("don't know how to handle declared DeclExtern: " ++ stringFromId n) DeclCon { declName = n } -> intErr ("don't know how to handle declared DeclCon: " ++ stringFromId n) DeclCustom { declName = n } -> intErr ("don't know how to handle DeclCustom: " ++ stringFromId n) DeclValue { declName = n } -> intErr ("don't know how to handle DeclValue: " ++ stringFromId n) DeclImport { declName = n } -> intErr ("don't know how to handle DeclImport: " ++ stringFromId n) _ -> intErr "unknown kind of declaration in import declarations" intErr = internalError "CoreToImportEnv" "getImportEnvironment"
null
https://raw.githubusercontent.com/uhc/uhc/8eb6914df3ba2ba43916a1a4956c6f25aa0e07c5/EHC/src/helium/ModuleSystem/CoreToImportEnv.hs
haskell
| Module : CoreToImportEnv License : GPL Maintainer : Stability : experimental Portability : portable in Helium the have a number indicating the arity the number of stars minus 1 is the arity special rule: unary minus has the assoc and the priority of the infix operator - functions functions from non-core/non-lvm libraries and lvm-instructions constructors type constructor import type synonym declarations important: a type synonym also introduces a new type constructor! infix decls typing strategies !!! Print importedFromModId from "declAccess = Imported{importModule = importedFromModId}" as well
module Helium.ModuleSystem.CoreToImportEnv(getImportEnvironment) where import Lvm.Core.Core as Core import Helium.Utils.Utils import Helium.StaticAnalysis.Miscellaneous.TypeConversion import Helium.Parser.ParseLibrary import Helium.Parser.Lexer(lexer) import Helium.Parser.Parser(type_, contextAndType) import Helium.ModuleSystem.ImportEnvironment import Helium.Syntax.UHA_Utils import Lvm.Common.Id import Helium.Syntax.UHA import Helium.Parser.OperatorTable import Top.Types import Lvm.Common.Byte(stringFromBytes) import Helium.Syntax.UHA_Range(makeImportRange, setNameRange) typeFromCustoms :: String -> [Custom] -> TpScheme typeFromCustoms n [] = internalError "CoreToImportEnv" "typeFromCustoms" ("function import without type: " ++ n) typeFromCustoms n ( CustomDecl (DeclKindCustom id) [CustomBytes bytes] : cs) | stringFromId id == "type" = let string = filter (/= '!') (stringFromBytes bytes) in makeTpSchemeFromType (parseFromString contextAndType string) | otherwise = typeFromCustoms n cs parseFromString :: HParser a -> String -> a parseFromString p string = case lexer "CoreToImportEnv" string of Left lexErr -> internalError "CoreToImportEnv" "parseFromString" ("lex error in " ++ string) Right (tokens, _) -> wait for EOF Left parseError -> internalError "CoreToImportEnv" "parseFromString" ("parse error in " ++ string) Right x -> x ! ! ! typeSynFromCustoms n (CustomBytes bs:cs) = let typeSynDecl = stringFromBytes bs ( too ? ) simple parser ; works because type variables in synonym decls are renamed to 1 letter ids = ( map (\x -> nameFromString [x]) . filter (' '/=) . takeWhile ('='/=) . drop (length n + 1) ) typeSynDecl rhsType = ( drop 1 . dropWhile ('='/=) ) typeSynDecl in ( arityFromCustoms n cs , \ts -> makeTpFromType (zip ids ts) (parseFromString type_ rhsType) ) typeSynFromCustoms n _ = internalError "CoreToImportEnv" "typeSynFromCustoms" ("type synonym import missing definition: " ++ n) in compiled Core files types have a kind ( e.g. * - > * ) , arityFromCustoms :: String -> [Custom] -> Int arityFromCustoms n [] = internalError "CoreToImportEnv" "arityFromCustoms" ("type constructor import without kind: " ++ n) arityFromCustoms n ( CustomInt arity : _ ) = arity arityFromCustoms n ( CustomDecl (DeclKindCustom id) [CustomBytes bytes] : cs ) | stringFromId id == "kind" = (length . filter ('*'==) . stringFromBytes) bytes - 1 arityFromCustoms n (_:cs) = arityFromCustoms n cs makeOperatorTable :: Name -> [Custom] -> [(Name, (Int, Assoc))] makeOperatorTable op (Core.CustomInt i : Core.CustomBytes bs : cs) = let assoc = case stringFromBytes bs of "left" -> AssocLeft "right" -> AssocRight "none" -> AssocNone assocStr -> intErr ("unknown associativity: " ++ assocStr) intErr = internalError "CoreToImportEnv" "makeOperatorTable" in if getNameName op == "-" then [ (op, (i, assoc)) , (intUnaryMinusName, (i, assoc)) , (floatUnaryMinusName, (i, assoc)) ] else [(op, (i, assoc))] makeOperatorTable op cs = internalError "CoreToImportEnv" "makeOperatorTable" ("infix decl missing priority or associativity: " ++ show op) makeImportName :: String -> Id -> Id -> Name makeImportName importedInMod importedFromMod n = setNameRange (nameFromId n) (makeImportRange (idFromString importedInMod) importedFromMod) getImportEnvironment :: String -> [CoreDecl] -> ImportEnvironment getImportEnvironment importedInModule = foldr insert emptyEnvironment where insert decl = case decl of DeclAbstract { declName = n , declAccess = Imported{importModule = importedFromModId} , declCustoms = cs } -> addType (makeImportName importedInModule importedFromModId n) (typeFromCustoms (stringFromId n) cs) DeclExtern { declName = n , declAccess = Imported{importModule = importedFromModId} , declCustoms = cs } -> addType (makeImportName importedInModule importedFromModId n) (typeFromCustoms (stringFromId n) cs) DeclCon { declName = n , declAccess = Imported{importModule = importedFromModId} , declArity = arity , declCustoms = cs } -> addValueConstructor (makeImportName importedInModule importedFromModId n) (typeFromCustoms (stringFromId n) cs) DeclCustom { declName = n , declAccess = Imported{importModule = importedFromModId} , declKind = DeclKindCustom id , declCustoms = cs } | stringFromId id == "data" -> addTypeConstructor (makeImportName importedInModule importedFromModId n) (arityFromCustoms (stringFromId n) cs) DeclCustom { declName = n , declAccess = Imported{importModule = importedFromModId} , declKind = DeclKindCustom id , declCustoms = cs } | stringFromId id == "typedecl" -> let name = makeImportName importedInModule importedFromModId n pair = typeSynFromCustoms (stringFromId n) cs in addTypeSynonym name pair . addTypeConstructor name (fst pair) DeclCustom { declName = n , declKind = DeclKindCustom id , declCustoms = cs } | stringFromId id == "infix" -> flip (foldr (uncurry addOperator)) (makeOperatorTable (nameFromId n) cs) DeclCustom { declName = _ , declKind = DeclKindCustom id , declCustoms = cs } | stringFromId id == "strategy" -> let (CustomDecl _ [CustomBytes bytes]) = head cs text = stringFromBytes bytes in case reads text of [(rule, [])] -> addTypingStrategies rule _ -> intErr "Could not parse typing strategy from core file" DeclAbstract{ declName = n } -> intErr ("don't know how to handle declared DeclAbstract: " ++ stringFromId n) DeclExtern { declName = n } -> intErr ("don't know how to handle declared DeclExtern: " ++ stringFromId n) DeclCon { declName = n } -> intErr ("don't know how to handle declared DeclCon: " ++ stringFromId n) DeclCustom { declName = n } -> intErr ("don't know how to handle DeclCustom: " ++ stringFromId n) DeclValue { declName = n } -> intErr ("don't know how to handle DeclValue: " ++ stringFromId n) DeclImport { declName = n } -> intErr ("don't know how to handle DeclImport: " ++ stringFromId n) _ -> intErr "unknown kind of declaration in import declarations" intErr = internalError "CoreToImportEnv" "getImportEnvironment"
8d1540b8480e868f406f1b00e7efaebe9652329b61cad75ec7c72cbbfdf0d340
soegaard/sketching
sketch-midpoint-displacement-1d.rkt
#lang sketching (require racket/match racket/list) (define (displaced-midpoint p q max-displacement) (match-define (list x1 y1) p) (match-define (list x2 y2) q) (define r (random (- max-displacement) max-displacement)) (list (/ (+ x1 x2) 2.) (+ r (/ (+ y1 y2) 2.)))) (define (add-midpoints ps max-displacement) (define mid-points (for/list ([p ps] [q (rest ps)]) (displaced-midpoint p q max-displacement))) (interleave ps mid-points)) (define (interleave as bs) (if (empty? as) bs (cons (first as) (interleave bs (rest as))))) (define (displaced-midpoints points max-displacement iterations [iteration 1]) (define (loop ps n md) (if (= n iterations) ps (loop (add-midpoints ps md) (+ n 1) (/ md 1.8)))) (loop points 0 max-displacement)) (define (setup) ( frame - rate 2 ) (size 640 360) (stroke "black") (background "white") (rect-mode 'corner) #;(no-loop)) (define (draw) (color-mode 'rgb 255 255 255 100) (fill 255 255 255 1) (rect 0 0 width height) ( fill frame - count 50 100 ) (color-mode 'hsb 360 100 100) (define points (list->vector (displaced-midpoints '((0 0) (640 0)) 20 5))) ( displayln points ) (define ymid (/ height 2)) (for ([p points] [q (in-vector points 1 (vector-length points))]) (match-define (list x1 y1) p) (match-define (list x2 y2) q) (fill frame-count 50 100) ; (stroke "red") (no-stroke) (quad x1 height x1 (+ y1 ymid) x2 (+ ymid y2) x2 height)))
null
https://raw.githubusercontent.com/soegaard/sketching/3773cb790ac69201c967201a2fa1727d90a4ad62/sketching-examples/examples/sketch-midpoint-displacement-1d.rkt
racket
(no-loop)) (stroke "red")
#lang sketching (require racket/match racket/list) (define (displaced-midpoint p q max-displacement) (match-define (list x1 y1) p) (match-define (list x2 y2) q) (define r (random (- max-displacement) max-displacement)) (list (/ (+ x1 x2) 2.) (+ r (/ (+ y1 y2) 2.)))) (define (add-midpoints ps max-displacement) (define mid-points (for/list ([p ps] [q (rest ps)]) (displaced-midpoint p q max-displacement))) (interleave ps mid-points)) (define (interleave as bs) (if (empty? as) bs (cons (first as) (interleave bs (rest as))))) (define (displaced-midpoints points max-displacement iterations [iteration 1]) (define (loop ps n md) (if (= n iterations) ps (loop (add-midpoints ps md) (+ n 1) (/ md 1.8)))) (loop points 0 max-displacement)) (define (setup) ( frame - rate 2 ) (size 640 360) (stroke "black") (background "white") (rect-mode 'corner) (define (draw) (color-mode 'rgb 255 255 255 100) (fill 255 255 255 1) (rect 0 0 width height) ( fill frame - count 50 100 ) (color-mode 'hsb 360 100 100) (define points (list->vector (displaced-midpoints '((0 0) (640 0)) 20 5))) ( displayln points ) (define ymid (/ height 2)) (for ([p points] [q (in-vector points 1 (vector-length points))]) (match-define (list x1 y1) p) (match-define (list x2 y2) q) (fill frame-count 50 100) (no-stroke) (quad x1 height x1 (+ y1 ymid) x2 (+ ymid y2) x2 height)))
a7b9541db60f04b4f6ed641ab0c631dd38fe49aa908dc513eceddd4028b9d1d1
eait-itig/rdp_proto
mppc_nif.erl
%% %% rdpproxy %% remote desktop proxy %% Copyright 2022 < > The University of Queensland %% 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(mppc_nif). -export([ new_context/1, set_level/2, get_level/1, compress/2, decompress/3, reset/2 ]). -on_load(init/0). -export_type([context/0]). try_paths([Last], BaseName) -> filename:join([Last, BaseName]); try_paths([Path | Next], BaseName) -> case filelib:is_dir(Path) of true -> WCard = filename:join([Path, "{lib,}" ++ BaseName ++ ".*"]), case filelib:wildcard(WCard) of [] -> try_paths(Next, BaseName); _ -> filename:join([Path, BaseName]) end; false -> try_paths(Next, BaseName) end. init() -> Paths0 = [ filename:join(["..", lib, rdp_proto, priv]), filename:join(["..", priv]), filename:join([priv]) ], Paths1 = case code:priv_dir(rdp_proto) of {error, bad_name} -> Paths0; Dir -> [Dir | Paths0] end, SoName = try_paths(Paths1, "mppc_nif"), erlang:load_nif(SoName, 0). -opaque context() :: reference(). -type level() :: '8k' | '64k'. -type flags() :: [compressed | at_front | flushed]. -type mode() :: compress | decompress. -spec new_context(mode()) -> {ok, context()}. new_context(_Mode) -> error(no_nif). -spec set_level(context(), level()) -> ok. set_level(_Context, _Level) -> error(no_nif). -spec get_level(context()) -> level(). get_level(_Context) -> error(no_nif). -spec reset(context(), boolean()) -> ok. reset(_Context, _Flush) -> error(no_nif). -spec compress(context(), iolist()) -> {ok, iolist(), flags()}. compress(_Context, _Data) -> error(no_nif). -spec decompress(context(), iolist(), flags()) -> {ok, iolist()}. decompress(_Context, _Data, _Flags) -> error(no_nif).
null
https://raw.githubusercontent.com/eait-itig/rdp_proto/f39dffdc3e9cab24da778834298dc4a72040cc23/src/mppc_nif.erl
erlang
rdpproxy remote desktop proxy 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. notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY (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 2022 < > The University of Queensland 1 . Redistributions of source code must retain the above copyright 2 . Redistributions in binary form must reproduce the above copyright THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS OR INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT -module(mppc_nif). -export([ new_context/1, set_level/2, get_level/1, compress/2, decompress/3, reset/2 ]). -on_load(init/0). -export_type([context/0]). try_paths([Last], BaseName) -> filename:join([Last, BaseName]); try_paths([Path | Next], BaseName) -> case filelib:is_dir(Path) of true -> WCard = filename:join([Path, "{lib,}" ++ BaseName ++ ".*"]), case filelib:wildcard(WCard) of [] -> try_paths(Next, BaseName); _ -> filename:join([Path, BaseName]) end; false -> try_paths(Next, BaseName) end. init() -> Paths0 = [ filename:join(["..", lib, rdp_proto, priv]), filename:join(["..", priv]), filename:join([priv]) ], Paths1 = case code:priv_dir(rdp_proto) of {error, bad_name} -> Paths0; Dir -> [Dir | Paths0] end, SoName = try_paths(Paths1, "mppc_nif"), erlang:load_nif(SoName, 0). -opaque context() :: reference(). -type level() :: '8k' | '64k'. -type flags() :: [compressed | at_front | flushed]. -type mode() :: compress | decompress. -spec new_context(mode()) -> {ok, context()}. new_context(_Mode) -> error(no_nif). -spec set_level(context(), level()) -> ok. set_level(_Context, _Level) -> error(no_nif). -spec get_level(context()) -> level(). get_level(_Context) -> error(no_nif). -spec reset(context(), boolean()) -> ok. reset(_Context, _Flush) -> error(no_nif). -spec compress(context(), iolist()) -> {ok, iolist(), flags()}. compress(_Context, _Data) -> error(no_nif). -spec decompress(context(), iolist(), flags()) -> {ok, iolist()}. decompress(_Context, _Data, _Flags) -> error(no_nif).
a9fcd2af07d0a21528796748b9992757441481f953e12fbeaab45a89fc9501ce
zanderso/cil-template
tut0.ml
open Cil module E = Errormsg let tut0 (f : file) : unit = E.log "I'n in tut0 and I could change %s if I wanted to!\n" f.fileName; ()
null
https://raw.githubusercontent.com/zanderso/cil-template/fc2a0548b2644c53c4840df2a09c1c90b2af2aee/src/tut0.ml
ocaml
open Cil module E = Errormsg let tut0 (f : file) : unit = E.log "I'n in tut0 and I could change %s if I wanted to!\n" f.fileName; ()
ec3ed2c3190eaaf66dd8e4d75aebd45eac8f0583c0a0c342a7bb5bc30bac76cd
SamB/coq
vernacinterp.mli
(************************************************************************) 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 $Id$ i*) (*i*) open Tacexpr (*i*) Interpretation of extended phrases . val disable_drop : exn -> exn val vinterp_add : string -> (raw_generic_argument list -> unit -> unit) -> unit val overwriting_vinterp_add : string -> (raw_generic_argument list -> unit -> unit) -> unit val vinterp_init : unit -> unit val call : string * raw_generic_argument list -> unit
null
https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/toplevel/vernacinterp.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** i $Id$ i i i
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Tacexpr Interpretation of extended phrases . val disable_drop : exn -> exn val vinterp_add : string -> (raw_generic_argument list -> unit -> unit) -> unit val overwriting_vinterp_add : string -> (raw_generic_argument list -> unit -> unit) -> unit val vinterp_init : unit -> unit val call : string * raw_generic_argument list -> unit
c52247058cb95cdfb13eb93c5b0d07a6aacb9a2ab47d78dd4fcdc2abcd4b7e5b
umd-cmsc330/cmsc330spring22
data.mli
type int_tree = | IntLeaf | IntNode of int * int option * int_tree * int_tree * int_tree val empty_int_tree: int_tree val int_insert: int -> int_tree -> int_tree val int_mem: int -> int_tree -> bool val int_size: int_tree -> int val int_max: int_tree -> int type 'a tree_map = | MapLeaf | MapNode of (int * 'a) * (int * 'a) option * 'a tree_map * 'a tree_map * 'a tree_map val empty_tree_map: 'a tree_map val map_put: int -> 'a -> 'a tree_map -> 'a tree_map val map_contains: int -> 'a tree_map -> bool val map_get: int -> 'a tree_map -> 'a type lookup_table val empty_table : lookup_table val push_scope : lookup_table -> lookup_table val pop_scope : lookup_table -> lookup_table val add_var : string -> int -> lookup_table -> lookup_table val lookup : string -> lookup_table -> int
null
https://raw.githubusercontent.com/umd-cmsc330/cmsc330spring22/e499004813cebd2e6aeffc79088ff7279560cbf0/project2b/src/data.mli
ocaml
type int_tree = | IntLeaf | IntNode of int * int option * int_tree * int_tree * int_tree val empty_int_tree: int_tree val int_insert: int -> int_tree -> int_tree val int_mem: int -> int_tree -> bool val int_size: int_tree -> int val int_max: int_tree -> int type 'a tree_map = | MapLeaf | MapNode of (int * 'a) * (int * 'a) option * 'a tree_map * 'a tree_map * 'a tree_map val empty_tree_map: 'a tree_map val map_put: int -> 'a -> 'a tree_map -> 'a tree_map val map_contains: int -> 'a tree_map -> bool val map_get: int -> 'a tree_map -> 'a type lookup_table val empty_table : lookup_table val push_scope : lookup_table -> lookup_table val pop_scope : lookup_table -> lookup_table val add_var : string -> int -> lookup_table -> lookup_table val lookup : string -> lookup_table -> int
efee4d1f8a9f36a776f125ff5d7c675d5f94583b0b996b86004c9356807c06c6
vlstill/hsExprTest
foldr.3.nok.hs
myfoldr :: (a -> b -> b) -> b -> [a] -> b myfoldr _ z [] = z myfoldr f z (x:xs) = x `f` z
null
https://raw.githubusercontent.com/vlstill/hsExprTest/391fc823c1684ec248ac8f76412fefeffb791865/examples/foldr.3.nok.hs
haskell
myfoldr :: (a -> b -> b) -> b -> [a] -> b myfoldr _ z [] = z myfoldr f z (x:xs) = x `f` z
de5dbde9aadfe8e99b350d1851d0cc05d47f8d5a6ec22ba104618f478274acf0
RadNi/uniswap-plutus
uniswap-client.hs
{-# LANGUAGE NumericUnderscores #-} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # module Main ( main ) where import Control.Concurrent import Control.Exception import Control.Monad (forM_, when) import Control.Monad.IO.Class (MonadIO (..)) import Data.Aeson (Result (..), ToJSON, decode, encode, fromJSON) import qualified Data.ByteString.Lazy.Char8 as B8 import qualified Data.ByteString.Lazy as LB import Data.Monoid (Last (..)) import Data.Proxy (Proxy (..)) import Data.String (IsString (..)) import Data.Text (Text, pack) import Data.UUID hiding (fromString) import Ledger.Value (AssetClass (..), CurrencySymbol, Value, flattenValue, TokenName) import Network.HTTP.Req import qualified Uniswap as US import Plutus.PAB.Events.ContractInstanceState (PartiallyDecodedResponse (..)) import Plutus.PAB.Webserver.Types import System.Environment (getArgs) import System.Exit (exitFailure) import Text.Printf (printf) import Text.Read (readMaybe) import Wallet.Emulator.Types (Wallet (..)) import Uniswap1 (cidFile, UniswapContracts) main :: IO () main = do w <- Wallet . read . head <$> getArgs cid <- read <$> readFile (cidFile w) mcs <- decode <$> LB.readFile "symbol.json" case mcs of Nothing -> putStrLn "invalid symbol.json" >> exitFailure Just cs -> do putStrLn $ "cid: " ++ show cid putStrLn $ "symbol: " ++ show (cs :: CurrencySymbol) go cid cs where go :: UUID -> CurrencySymbol -> IO a go cid cs = do cmd <- readCommandIO case cmd of Funds -> getFunds cid Pools -> getPools cid Create amtA tnA amtB tnB -> createPool cid $ toCreateParams cs amtA tnA amtB tnB Add amtA tnA amtB tnB -> addLiquidity cid $ toAddParams cs amtA tnA amtB tnB Remove amt tnA tnB -> removeLiquidity cid $ toRemoveParams cs amt tnA tnB Close tnA tnB -> closePool cid $ toCloseParams cs tnA tnB Swap amtA tnA tnB -> swap cid $ toSwapParams cs amtA tnA tnB SwapExactTokensForTokens amt tns -> swapExactTokensForTokens cid $ toSwapParams2 cs amt tns SwapTokensForExactTokens amt tns -> swapTokensForExactTokens cid $ toSwapParams2 cs amt tns go cid cs data Command = Funds | Pools | Create Integer Char Integer Char | Add Integer Char Integer Char | Remove Integer Char Char | Close Char Char | Swap Integer Char Char | SwapExactTokensForTokens Integer [Char] | SwapTokensForExactTokens Integer [Char] deriving (Show, Read, Eq, Ord) readCommandIO :: IO Command readCommandIO = do putStrLn "Enter a command: Funds, Pools, Create amtA tnA amtB tnB, Add amtA tnA amtB tnB, Remove amt tnA tnB, Close tnA tnB, Swap amtA tnA tnB, SwapExactTokensForTokens amtIn [tnA, tnB, .., tnN], SwapTokensForExactTokens amtOut [tnA, tnB, .., tnN]" s <- getLine maybe readCommandIO return $ readMaybe s toCoin :: CurrencySymbol -> Char -> US.Coin c toCoin cs tn = US.Coin $ AssetClass (cs, fromString [tn]) toCreateParams :: CurrencySymbol -> Integer -> Char -> Integer -> Char -> US.CreateParams toCreateParams cs amtA tnA amtB tnB = US.CreateParams (toCoin cs tnA) (toCoin cs tnB) (US.Amount amtA) (US.Amount amtB) toAddParams :: CurrencySymbol -> Integer -> Char -> Integer -> Char -> US.AddParams toAddParams cs amtA tnA amtB tnB = US.AddParams (toCoin cs tnA) (toCoin cs tnB) (US.Amount amtA) (US.Amount amtB) toRemoveParams :: CurrencySymbol -> Integer -> Char -> Char -> US.RemoveParams toRemoveParams cs amt tnA tnB = US.RemoveParams (toCoin cs tnA) (toCoin cs tnB) (US.Amount amt) toCloseParams :: CurrencySymbol -> Char -> Char -> US.CloseParams toCloseParams cs tnA tnB = US.CloseParams (toCoin cs tnA) (toCoin cs tnB) toSwapParams :: CurrencySymbol -> Integer -> Char -> Char -> US.SwapParams toSwapParams cs amtA tnA tnB = US.SwapParams (toCoin cs tnA) (toCoin cs tnB) (US.Amount amtA) (US.Amount 0) toSwapParams2 :: CurrencySymbol -> Integer -> [Char] -> US.SwapParams2 toSwapParams2 cs amtA ps = US.SwapParams2 (US.Amount amtA) $ map (toCoin cs) ps showCoinHeader :: IO () showCoinHeader = printf "\n currency symbol token name amount\n\n" showCoin :: CurrencySymbol -> TokenName -> Integer -> IO () showCoin cs tn = printf "%64s %66s %15d\n" (show cs) (show tn) getFunds :: UUID -> IO () getFunds cid = do callEndpoint cid "funds" () threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right (US.Funds v) -> showFunds v _ -> go showFunds :: Value -> IO () showFunds v = do showCoinHeader forM_ (flattenValue v) $ \(cs, tn, amt) -> showCoin cs tn amt printf "\n" getPools :: UUID -> IO () getPools cid = do callEndpoint cid "pools" () threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right (US.Pools ps) -> showPools ps _ -> go showPools :: [((US.Coin US.A, US.Amount US.A), (US.Coin US.B, US.Amount US.B))] -> IO () showPools ps = do forM_ ps $ \((US.Coin (AssetClass (csA, tnA)), amtA), (US.Coin (AssetClass (csB, tnB)), amtB)) -> do showCoinHeader showCoin csA tnA (US.unAmount amtA) showCoin csB tnB (US.unAmount amtB) createPool :: UUID -> US.CreateParams -> IO () createPool cid cp = do callEndpoint cid "create" cp threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Created -> putStrLn "created" Left err' -> putStrLn $ "error: " ++ show err' _ -> go addLiquidity :: UUID -> US.AddParams -> IO () addLiquidity cid ap = do callEndpoint cid "add" ap threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Added -> putStrLn "added" Left err' -> putStrLn $ "error: " ++ show err' _ -> go removeLiquidity :: UUID -> US.RemoveParams -> IO () removeLiquidity cid rp = do callEndpoint cid "remove" rp threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Removed -> putStrLn "removed" Left err' -> putStrLn $ "error: " ++ show err' _ -> go closePool :: UUID -> US.CloseParams -> IO () closePool cid cp = do callEndpoint cid "close" cp threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Closed -> putStrLn "closed" Left err' -> putStrLn $ "error: " ++ show err' _ -> go swap :: UUID -> US.SwapParams -> IO () swap cid sp = do callEndpoint cid "swap" sp threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Swapped -> putStrLn "swapped" Left err' -> putStrLn $ "error: " ++ show err' _ -> go swapExactTokensForTokens :: UUID -> US.SwapParams2 -> IO () swapExactTokensForTokens cid sp = do callEndpoint cid "swapExactTokensForTokens" sp threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Swapped2 -> putStrLn "swapped2" Left err' -> putStrLn $ "error: " ++ show err' swapTokensForExactTokens :: UUID -> US.SwapParams2 -> IO () swapTokensForExactTokens cid sp = do callEndpoint cid "swapTokensForExactTokens" sp threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Swapped2 -> putStrLn "swapped2" Left err' -> putStrLn $ "error: " ++ show err' getStatus :: UUID -> IO (Either Text US.UserContractState) getStatus cid = runReq defaultHttpConfig $ do liftIO $ printf "\nget request to 127.0.1:9080/api/contract/instance/%s/status\n" (show cid) w <- req GET (http "127.0.0.1" /: "api" /: "contract" /: "instance" /: pack (show cid) /: "status") NoReqBody (Proxy :: Proxy (JsonResponse (ContractInstanceClientState UniswapContracts))) (port 9080) case fromJSON $ observableState $ cicCurrentState $ responseBody w of Success (Last Nothing) -> liftIO $ threadDelay 1_000_000 >> getStatus cid Success (Last (Just e)) -> return e _ -> liftIO $ ioError $ userError "error decoding state" callEndpoint :: ToJSON a => UUID -> String -> a -> IO () callEndpoint cid name a = handle h $ runReq defaultHttpConfig $ do liftIO $ printf "\npost request to 127.0.1:9080/api/contract/instance/%s/endpoint/%s\n" (show cid) name liftIO $ printf "request body: %s\n\n" $ B8.unpack $ encode a v <- req POST (http "127.0.0.1" /: "api" /: "contract" /: "instance" /: pack (show cid) /: "endpoint" /: pack name) (ReqBodyJson a) (Proxy :: Proxy (JsonResponse ())) (port 9080) when (responseStatusCode v /= 200) $ liftIO $ ioError $ userError $ "error calling endpoint " ++ name where h :: HttpException -> IO () h = ioError . userError . show
null
https://raw.githubusercontent.com/RadNi/uniswap-plutus/38b0a2ce9c47e131360803990011c3a9f38269f1/app/uniswap-client.hs
haskell
# LANGUAGE NumericUnderscores # # LANGUAGE OverloadedStrings #
# LANGUAGE ScopedTypeVariables # module Main ( main ) where import Control.Concurrent import Control.Exception import Control.Monad (forM_, when) import Control.Monad.IO.Class (MonadIO (..)) import Data.Aeson (Result (..), ToJSON, decode, encode, fromJSON) import qualified Data.ByteString.Lazy.Char8 as B8 import qualified Data.ByteString.Lazy as LB import Data.Monoid (Last (..)) import Data.Proxy (Proxy (..)) import Data.String (IsString (..)) import Data.Text (Text, pack) import Data.UUID hiding (fromString) import Ledger.Value (AssetClass (..), CurrencySymbol, Value, flattenValue, TokenName) import Network.HTTP.Req import qualified Uniswap as US import Plutus.PAB.Events.ContractInstanceState (PartiallyDecodedResponse (..)) import Plutus.PAB.Webserver.Types import System.Environment (getArgs) import System.Exit (exitFailure) import Text.Printf (printf) import Text.Read (readMaybe) import Wallet.Emulator.Types (Wallet (..)) import Uniswap1 (cidFile, UniswapContracts) main :: IO () main = do w <- Wallet . read . head <$> getArgs cid <- read <$> readFile (cidFile w) mcs <- decode <$> LB.readFile "symbol.json" case mcs of Nothing -> putStrLn "invalid symbol.json" >> exitFailure Just cs -> do putStrLn $ "cid: " ++ show cid putStrLn $ "symbol: " ++ show (cs :: CurrencySymbol) go cid cs where go :: UUID -> CurrencySymbol -> IO a go cid cs = do cmd <- readCommandIO case cmd of Funds -> getFunds cid Pools -> getPools cid Create amtA tnA amtB tnB -> createPool cid $ toCreateParams cs amtA tnA amtB tnB Add amtA tnA amtB tnB -> addLiquidity cid $ toAddParams cs amtA tnA amtB tnB Remove amt tnA tnB -> removeLiquidity cid $ toRemoveParams cs amt tnA tnB Close tnA tnB -> closePool cid $ toCloseParams cs tnA tnB Swap amtA tnA tnB -> swap cid $ toSwapParams cs amtA tnA tnB SwapExactTokensForTokens amt tns -> swapExactTokensForTokens cid $ toSwapParams2 cs amt tns SwapTokensForExactTokens amt tns -> swapTokensForExactTokens cid $ toSwapParams2 cs amt tns go cid cs data Command = Funds | Pools | Create Integer Char Integer Char | Add Integer Char Integer Char | Remove Integer Char Char | Close Char Char | Swap Integer Char Char | SwapExactTokensForTokens Integer [Char] | SwapTokensForExactTokens Integer [Char] deriving (Show, Read, Eq, Ord) readCommandIO :: IO Command readCommandIO = do putStrLn "Enter a command: Funds, Pools, Create amtA tnA amtB tnB, Add amtA tnA amtB tnB, Remove amt tnA tnB, Close tnA tnB, Swap amtA tnA tnB, SwapExactTokensForTokens amtIn [tnA, tnB, .., tnN], SwapTokensForExactTokens amtOut [tnA, tnB, .., tnN]" s <- getLine maybe readCommandIO return $ readMaybe s toCoin :: CurrencySymbol -> Char -> US.Coin c toCoin cs tn = US.Coin $ AssetClass (cs, fromString [tn]) toCreateParams :: CurrencySymbol -> Integer -> Char -> Integer -> Char -> US.CreateParams toCreateParams cs amtA tnA amtB tnB = US.CreateParams (toCoin cs tnA) (toCoin cs tnB) (US.Amount amtA) (US.Amount amtB) toAddParams :: CurrencySymbol -> Integer -> Char -> Integer -> Char -> US.AddParams toAddParams cs amtA tnA amtB tnB = US.AddParams (toCoin cs tnA) (toCoin cs tnB) (US.Amount amtA) (US.Amount amtB) toRemoveParams :: CurrencySymbol -> Integer -> Char -> Char -> US.RemoveParams toRemoveParams cs amt tnA tnB = US.RemoveParams (toCoin cs tnA) (toCoin cs tnB) (US.Amount amt) toCloseParams :: CurrencySymbol -> Char -> Char -> US.CloseParams toCloseParams cs tnA tnB = US.CloseParams (toCoin cs tnA) (toCoin cs tnB) toSwapParams :: CurrencySymbol -> Integer -> Char -> Char -> US.SwapParams toSwapParams cs amtA tnA tnB = US.SwapParams (toCoin cs tnA) (toCoin cs tnB) (US.Amount amtA) (US.Amount 0) toSwapParams2 :: CurrencySymbol -> Integer -> [Char] -> US.SwapParams2 toSwapParams2 cs amtA ps = US.SwapParams2 (US.Amount amtA) $ map (toCoin cs) ps showCoinHeader :: IO () showCoinHeader = printf "\n currency symbol token name amount\n\n" showCoin :: CurrencySymbol -> TokenName -> Integer -> IO () showCoin cs tn = printf "%64s %66s %15d\n" (show cs) (show tn) getFunds :: UUID -> IO () getFunds cid = do callEndpoint cid "funds" () threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right (US.Funds v) -> showFunds v _ -> go showFunds :: Value -> IO () showFunds v = do showCoinHeader forM_ (flattenValue v) $ \(cs, tn, amt) -> showCoin cs tn amt printf "\n" getPools :: UUID -> IO () getPools cid = do callEndpoint cid "pools" () threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right (US.Pools ps) -> showPools ps _ -> go showPools :: [((US.Coin US.A, US.Amount US.A), (US.Coin US.B, US.Amount US.B))] -> IO () showPools ps = do forM_ ps $ \((US.Coin (AssetClass (csA, tnA)), amtA), (US.Coin (AssetClass (csB, tnB)), amtB)) -> do showCoinHeader showCoin csA tnA (US.unAmount amtA) showCoin csB tnB (US.unAmount amtB) createPool :: UUID -> US.CreateParams -> IO () createPool cid cp = do callEndpoint cid "create" cp threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Created -> putStrLn "created" Left err' -> putStrLn $ "error: " ++ show err' _ -> go addLiquidity :: UUID -> US.AddParams -> IO () addLiquidity cid ap = do callEndpoint cid "add" ap threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Added -> putStrLn "added" Left err' -> putStrLn $ "error: " ++ show err' _ -> go removeLiquidity :: UUID -> US.RemoveParams -> IO () removeLiquidity cid rp = do callEndpoint cid "remove" rp threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Removed -> putStrLn "removed" Left err' -> putStrLn $ "error: " ++ show err' _ -> go closePool :: UUID -> US.CloseParams -> IO () closePool cid cp = do callEndpoint cid "close" cp threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Closed -> putStrLn "closed" Left err' -> putStrLn $ "error: " ++ show err' _ -> go swap :: UUID -> US.SwapParams -> IO () swap cid sp = do callEndpoint cid "swap" sp threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Swapped -> putStrLn "swapped" Left err' -> putStrLn $ "error: " ++ show err' _ -> go swapExactTokensForTokens :: UUID -> US.SwapParams2 -> IO () swapExactTokensForTokens cid sp = do callEndpoint cid "swapExactTokensForTokens" sp threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Swapped2 -> putStrLn "swapped2" Left err' -> putStrLn $ "error: " ++ show err' swapTokensForExactTokens :: UUID -> US.SwapParams2 -> IO () swapTokensForExactTokens cid sp = do callEndpoint cid "swapTokensForExactTokens" sp threadDelay 2_000_000 go where go = do e <- getStatus cid case e of Right US.Swapped2 -> putStrLn "swapped2" Left err' -> putStrLn $ "error: " ++ show err' getStatus :: UUID -> IO (Either Text US.UserContractState) getStatus cid = runReq defaultHttpConfig $ do liftIO $ printf "\nget request to 127.0.1:9080/api/contract/instance/%s/status\n" (show cid) w <- req GET (http "127.0.0.1" /: "api" /: "contract" /: "instance" /: pack (show cid) /: "status") NoReqBody (Proxy :: Proxy (JsonResponse (ContractInstanceClientState UniswapContracts))) (port 9080) case fromJSON $ observableState $ cicCurrentState $ responseBody w of Success (Last Nothing) -> liftIO $ threadDelay 1_000_000 >> getStatus cid Success (Last (Just e)) -> return e _ -> liftIO $ ioError $ userError "error decoding state" callEndpoint :: ToJSON a => UUID -> String -> a -> IO () callEndpoint cid name a = handle h $ runReq defaultHttpConfig $ do liftIO $ printf "\npost request to 127.0.1:9080/api/contract/instance/%s/endpoint/%s\n" (show cid) name liftIO $ printf "request body: %s\n\n" $ B8.unpack $ encode a v <- req POST (http "127.0.0.1" /: "api" /: "contract" /: "instance" /: pack (show cid) /: "endpoint" /: pack name) (ReqBodyJson a) (Proxy :: Proxy (JsonResponse ())) (port 9080) when (responseStatusCode v /= 200) $ liftIO $ ioError $ userError $ "error calling endpoint " ++ name where h :: HttpException -> IO () h = ioError . userError . show
fd2111ade0dbe1ac44dc668a5823c57e009899550923f067aad48928e10c2b38
stanfordhaskell/cs43
Main.hs
{-# LANGUAGE GADTs #-} module Main where main :: IO () main = do putStrLn "hello world" data Expr a where I :: Int -> Expr Int B :: Bool -> Expr Bool Add :: Expr Int -> Expr Int -> Expr Int Mul :: Expr Int -> Expr Int -> Expr Int Eq :: Eq a => Expr a -> Expr a -> Expr Bool eval :: Expr a -> a eval (I n) = n eval (B b) = b eval (Add e1 e2) = eval e1 + eval e2 eval (Mul e1 e2) = eval e1 * eval e2 eval (Eq e1 e2) = eval e1 == eval e2
null
https://raw.githubusercontent.com/stanfordhaskell/cs43/8353da9e27336a7fe23488c3536e0dab4aaabfff/starter-code/assignment6/src/Main.hs
haskell
# LANGUAGE GADTs #
module Main where main :: IO () main = do putStrLn "hello world" data Expr a where I :: Int -> Expr Int B :: Bool -> Expr Bool Add :: Expr Int -> Expr Int -> Expr Int Mul :: Expr Int -> Expr Int -> Expr Int Eq :: Eq a => Expr a -> Expr a -> Expr Bool eval :: Expr a -> a eval (I n) = n eval (B b) = b eval (Add e1 e2) = eval e1 + eval e2 eval (Mul e1 e2) = eval e1 * eval e2 eval (Eq e1 e2) = eval e1 == eval e2
57fee7be608c7d02b510e0b48d176e7baa5fe2d75cf56f1f7be55ca5b6050c32
jimweirich/sicp-study
ex2_31_test.scm
SICP Tests 2.31 (test-case "Ex 2.31 - without map" (assert-equal '(1 (4 (9 16) 25) (36 49)) (square-tree-3 '(1 (2 (3 4) 5) (6 7)))))
null
https://raw.githubusercontent.com/jimweirich/sicp-study/bc5190e04ed6ae321107ed6149241f26efc1b8c8/scheme/chapter2/ex2_31_test.scm
scheme
SICP Tests 2.31 (test-case "Ex 2.31 - without map" (assert-equal '(1 (4 (9 16) 25) (36 49)) (square-tree-3 '(1 (2 (3 4) 5) (6 7)))))
456762db0a6fafed521dcf5a5d0fb7c3a6cd07fc5e7b330fe66f76cbe0988fe2
kitten/bs-flow-parser
expression_parser.ml
* * Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) module Ast = Flow_ast open Token open Parser_env open Flow_ast module Error = Parse_error open Parser_common module type EXPRESSION = sig val assignment: env -> (Loc.t, Loc.t) Expression.t val assignment_cover: env -> pattern_cover val conditional: env -> (Loc.t, Loc.t) Expression.t val property_name_include_private: env -> Loc.t * Loc.t Identifier.t * bool val is_assignable_lhs: (Loc.t, Loc.t) Expression.t -> bool val left_hand_side: env -> (Loc.t, Loc.t) Expression.t val number: env -> number_type -> string -> float val sequence: env -> (Loc.t, Loc.t) Expression.t list -> (Loc.t, Loc.t) Expression.t end module Expression (Parse: PARSER) (Type: Type_parser.TYPE) (Declaration: Declaration_parser.DECLARATION) (Pattern_cover: Pattern_cover.COVER) : EXPRESSION = struct type op_precedence = Left_assoc of int | Right_assoc of int let is_tighter a b = let a_prec = match a with Left_assoc x -> x | Right_assoc x -> x - 1 in let b_prec = match b with Left_assoc x -> x | Right_assoc x -> x in a_prec >= b_prec let is_assignable_lhs = Expression.(function | _, MetaProperty { MetaProperty.meta = (_, "new"); property = (_, "target") } # sec - static - semantics - static - semantics - isvalidsimpleassignmenttarget | _, Array _ | _, Identifier _ | _, Member _ | _, MetaProperty _ | _, Object _ -> true | _, ArrowFunction _ | _, Assignment _ | _, Binary _ | _, Call _ | _, Class _ | _, Comprehension _ | _, Conditional _ | _, Function _ | _, Generator _ | _, Import _ | _, JSXElement _ | _, JSXFragment _ | _, Literal _ | _, Logical _ | _, New _ | _, OptionalCall _ | _, OptionalMember _ | _, Sequence _ | _, Super | _, TaggedTemplate _ | _, TemplateLiteral _ | _, This | _, TypeCast _ | _, Unary _ | _, Update _ | _, Yield _ -> false ) let as_expression = Pattern_cover.as_expression let as_pattern = Pattern_cover.as_pattern AssignmentExpression : * ConditionalExpression * LeftHandSideExpression = AssignmentExpression * * * Originally we were parsing this without backtracking , but * ArrowFunctionExpression got too tricky . Oh well . * ConditionalExpression * LeftHandSideExpression = AssignmentExpression * LeftHandSideExpression AssignmentOperator AssignmentExpression * ArrowFunctionFunction * * Originally we were parsing this without backtracking, but * ArrowFunctionExpression got too tricky. Oh well. *) let rec assignment_cover = let assignment_but_not_arrow_function_cover env = let expr_or_pattern = conditional_cover env in match assignment_op env with | Some operator -> let left = as_pattern env expr_or_pattern in let right = assignment env in let loc = Loc.btwn (fst left) (fst right) in Cover_expr (loc, Expression.(Assignment { Assignment. operator; left; right; })) | _ -> expr_or_pattern in let error_callback _ = function (* Don't rollback on these errors. *) | Error.StrictReservedWord -> () (* Everything else causes a rollback *) | _ -> raise Try.Rollback So we may or may not be parsing the first part of an arrow function * ( the part before the = > ) . We might end up parsing that whole thing or * we might end up parsing only part of it and thinking we 're done . We * need to look at the next token to figure out if we really parsed an * assignment expression or if this is just the beginning of an arrow * function * (the part before the =>). We might end up parsing that whole thing or * we might end up parsing only part of it and thinking we're done. We * need to look at the next token to figure out if we really parsed an * assignment expression or if this is just the beginning of an arrow * function *) in let try_assignment_but_not_arrow_function env = let env = env |> with_error_callback error_callback in let ret = assignment_but_not_arrow_function_cover env in match Peek.token env with x = > 123 raise Try.Rollback ( x ): number = > 123 raise Try.Rollback async x = > 123 -- and we 've already parsed async as an identifier * expression * expression *) | _ when Peek.is_identifier env -> begin match ret with | Cover_expr (_, Expression.Identifier (_, "async")) when not (Peek.is_line_terminator env) -> raise Try.Rollback | _ -> ret end | _ -> ret in fun env -> match Peek.token env, Peek.is_identifier env with | T_YIELD, _ when (allow_yield env) -> Cover_expr (yield env) | T_LPAREN, _ | T_LESS_THAN, _ | _, true -> Ok , we do n't know if this is going to be an arrow function or a * regular assignment expression . Let 's first try to parse it as an * assignment expression . If that fails we 'll try an arrow function . * regular assignment expression. Let's first try to parse it as an * assignment expression. If that fails we'll try an arrow function. *) (match Try.to_parse env try_assignment_but_not_arrow_function with | Try.ParsedSuccessfully expr -> expr | Try.FailedToParse -> (match Try.to_parse env try_arrow_function with | Try.ParsedSuccessfully expr -> expr | Try.FailedToParse -> (* Well shoot. It doesn't parse cleanly as a normal * expression or as an arrow_function. Let's treat it as a * normal assignment expression gone wrong *) assignment_but_not_arrow_function_cover env ) ) | _ -> assignment_but_not_arrow_function_cover env and assignment env = as_expression env (assignment_cover env) and yield env = with_loc (fun env -> if in_formal_parameters env then error env Error.YieldInFormalParameters; Expect.token env T_YIELD; let argument, delegate = if Peek.is_implicit_semicolon env then None, false else let delegate = Expect.maybe env T_MULT in let has_argument = match Peek.token env with | T_SEMICOLON | T_RBRACKET | T_RCURLY | T_RPAREN | T_COLON | T_COMMA -> false | _ -> true in let argument = if delegate || has_argument then Some (assignment env) else None in argument, delegate in Expression.(Yield Yield.({ argument; delegate; })) ) env and is_lhs = Expression.(function | _, MetaProperty { MetaProperty.meta = (_, "new"); property = (_, "target") } # sec - static - semantics - static - semantics - isvalidsimpleassignmenttarget | _, Identifier _ | _, Member _ | _, MetaProperty _ -> true | _, Array _ | _, ArrowFunction _ | _, Assignment _ | _, Binary _ | _, Call _ | _, Class _ | _, Comprehension _ | _, Conditional _ | _, Function _ | _, Generator _ | _, Import _ | _, JSXElement _ | _, JSXFragment _ | _, Literal _ | _, Logical _ | _, New _ | _, Object _ | _, OptionalCall _ | _, OptionalMember _ | _, Sequence _ | _, Super | _, TaggedTemplate _ | _, TemplateLiteral _ | _, This | _, TypeCast _ | _, Unary _ | _, Update _ | _, Yield _ -> false ) and assignment_op env = let op = Expression.Assignment.(match Peek.token env with | T_RSHIFT3_ASSIGN -> Some RShift3Assign | T_RSHIFT_ASSIGN -> Some RShiftAssign | T_LSHIFT_ASSIGN -> Some LShiftAssign | T_BIT_XOR_ASSIGN -> Some BitXorAssign | T_BIT_OR_ASSIGN -> Some BitOrAssign | T_BIT_AND_ASSIGN -> Some BitAndAssign | T_MOD_ASSIGN -> Some ModAssign | T_DIV_ASSIGN -> Some DivAssign | T_MULT_ASSIGN -> Some MultAssign | T_EXP_ASSIGN -> Some ExpAssign | T_MINUS_ASSIGN -> Some MinusAssign | T_PLUS_ASSIGN -> Some PlusAssign | T_ASSIGN -> Some Assign | _ -> None) in if op <> None then Eat.token env; op and conditional_cover env = let start_loc = Peek.loc env in let expr = logical_cover env in if Peek.token env = T_PLING then begin Expect.token env T_PLING; (* no_in is ignored for the consequent *) let env' = env |> with_no_in false in let consequent = assignment env' in Expect.token env T_COLON; let end_loc, alternate = with_loc assignment env in let loc = Loc.btwn start_loc end_loc in Cover_expr (loc, Expression.(Conditional { Conditional. test = as_expression env expr; consequent; alternate; })) end else expr and conditional env = as_expression env (conditional_cover env) and logical_cover = let open Expression in let make_logical env left right operator loc = let left = as_expression env left in let right = as_expression env right in Cover_expr (loc, Logical {Logical.operator; left; right;}) in let rec logical_and env left lloc = match Peek.token env with | T_AND -> Expect.token env T_AND; let rloc, right = with_loc binary_cover env in let loc = Loc.btwn lloc rloc in logical_and env (make_logical env left right Logical.And loc) loc | _ -> lloc, left and logical_or env left lloc = let options = parse_options env in match Peek.token env with | T_OR -> Expect.token env T_OR; let rloc, right = with_loc binary_cover env in let rloc, right = logical_and env right rloc in let loc = Loc.btwn lloc rloc in logical_or env (make_logical env left right Logical.Or loc) loc | T_PLING_PLING -> if not options.esproposal_nullish_coalescing then error env Parse_error.NullishCoalescingDisabled; Expect.token env T_PLING_PLING; let rloc, right = with_loc binary_cover env in let rloc, right = logical_and env right rloc in let loc = Loc.btwn lloc rloc in logical_or env (make_logical env left right Logical.NullishCoalesce loc) loc | _ -> left in fun env -> let loc, left = with_loc binary_cover env in let loc, left = logical_and env left loc in logical_or env left loc and binary_cover = let binary_op env = let ret = Expression.Binary.(match Peek.token env with Most BinaryExpression operators are left associative (* Lowest pri *) | T_BIT_OR -> Some (BitOr, Left_assoc 2) | T_BIT_XOR -> Some (Xor, Left_assoc 3) | T_BIT_AND -> Some (BitAnd, Left_assoc 4) | T_EQUAL -> Some (Equal, Left_assoc 5) | T_STRICT_EQUAL -> Some (StrictEqual, Left_assoc 5) | T_NOT_EQUAL -> Some (NotEqual, Left_assoc 5) | T_STRICT_NOT_EQUAL -> Some (StrictNotEqual, Left_assoc 5) | T_LESS_THAN -> Some (LessThan, Left_assoc 6) | T_LESS_THAN_EQUAL -> Some (LessThanEqual, Left_assoc 6) | T_GREATER_THAN -> Some (GreaterThan, Left_assoc 6) | T_GREATER_THAN_EQUAL -> Some (GreaterThanEqual, Left_assoc 6) | T_IN -> if (no_in env) then None else Some (In, Left_assoc 6) | T_INSTANCEOF -> Some (Instanceof, Left_assoc 6) | T_LSHIFT -> Some (LShift, Left_assoc 7) | T_RSHIFT -> Some (RShift, Left_assoc 7) | T_RSHIFT3 -> Some (RShift3, Left_assoc 7) | T_PLUS -> Some (Plus, Left_assoc 8) | T_MINUS -> Some (Minus, Left_assoc 8) | T_MULT -> Some (Mult, Left_assoc 9) | T_DIV -> Some (Div, Left_assoc 9) | T_MOD -> Some (Mod, Left_assoc 9) | T_EXP -> Some (Exp, Right_assoc 10) (* Highest priority *) | _ -> None) in if ret <> None then Eat.token env; ret in let make_binary left right operator loc = loc, Expression.(Binary Binary.({ operator; left; right; })) in let rec add_to_stack right (rop, rpri) rloc = function | (left, (lop, lpri), lloc)::rest when is_tighter lpri rpri -> let loc = Loc.btwn lloc rloc in let right = make_binary left right lop loc in add_to_stack right (rop, rpri) loc rest | stack -> (right, (rop, rpri), rloc)::stack in let rec collapse_stack right rloc = function | [] -> right | (left, (lop, _), lloc)::rest -> let loc = Loc.btwn lloc rloc in collapse_stack (make_binary left right lop loc) loc rest in let rec helper env stack = let right_loc, (is_unary, right) = with_loc (fun env -> let is_unary = peek_unary_op env <> None in let right = unary_cover (env |> with_no_in false) in is_unary, right ) env in if Peek.token env = T_LESS_THAN then begin match right with | Cover_expr (_, Expression.JSXElement _) -> error env Error.AdjacentJSXElements | _ -> () end; match stack, binary_op env with | [], None -> right | _, None -> let right = as_expression env right in Cover_expr (collapse_stack right right_loc stack) | _, Some (rop, rpri) -> if is_unary && rop = Expression.Binary.Exp then error_at env (right_loc, Error.InvalidLHSInExponentiation); let right = as_expression env right in helper env (add_to_stack right (rop, rpri) right_loc stack) in fun env -> helper env [] and peek_unary_op env = let open Expression.Unary in match Peek.token env with | T_NOT -> Some Not | T_BIT_NOT -> Some BitNot | T_PLUS -> Some Plus | T_MINUS -> Some Minus | T_TYPEOF -> Some Typeof | T_VOID -> Some Void | T_DELETE -> Some Delete (* If we are in a unary expression context, and within an async function, * assume that a use of "await" is intended as a keyword, not an ordinary * identifier. This is a little bit inconsistent, since it can be used as * an identifier in other contexts (such as a variable name), but it's how * Babel does it. *) | T_AWAIT when allow_await env -> Some Await | _ -> None and unary_cover env = let begin_loc = Peek.loc env in let op = peek_unary_op env in match op with | None -> begin let op = Expression.Update.(match Peek.token env with | T_INCR -> Some Increment | T_DECR -> Some Decrement | _ -> None) in match op with | None -> postfix_cover env | Some operator -> Eat.token env; let end_loc, argument = with_loc unary env in if not (is_lhs argument) then error_at env (fst argument, Error.InvalidLHSInAssignment); (match argument with | _, Expression.Identifier (_, name) when is_restricted name -> strict_error env Error.StrictLHSPrefix | _ -> ()); let loc = Loc.btwn begin_loc end_loc in Cover_expr (loc, Expression.(Update { Update. operator; prefix = true; argument; })) end | Some operator -> Eat.token env; let end_loc, argument = with_loc unary env in let loc = Loc.btwn begin_loc end_loc in Expression.(match operator, argument with | Unary.Delete, (_, Identifier _) -> strict_error_at env (loc, Error.StrictDelete) | Unary.Delete, (_, Member member) -> begin match member.Ast.Expression.Member.property with | Ast.Expression.Member.PropertyPrivateName _ -> error_at env (loc, Error.PrivateDelete) | _ -> () end | _ -> ()); Cover_expr (loc, Expression.(Unary { Unary. operator; argument; })) and unary env = as_expression env (unary_cover env) and postfix_cover env = let argument = left_hand_side_cover env in (* No line terminator allowed before operator *) if Peek.is_line_terminator env then argument else let op = Expression.Update.(match Peek.token env with | T_INCR -> Some Increment | T_DECR -> Some Decrement | _ -> None) in match op with | None -> argument | Some operator -> let argument = as_expression env argument in if not (is_lhs argument) then error_at env (fst argument, Error.InvalidLHSInAssignment); (match argument with | _, Expression.Identifier (_, name) when is_restricted name -> strict_error env Error.StrictLHSPostfix | _ -> ()); let end_loc = Peek.loc env in Eat.token env; let loc = Loc.btwn (fst argument) end_loc in Cover_expr (loc, Expression.(Update { Update. operator; prefix = false; argument; })) and left_hand_side_cover env = let start_loc = Peek.loc env in let allow_new = not (no_new env) in let env = with_no_new false env in let expr = match Peek.token env with | T_NEW when allow_new -> Cover_expr (new_expression env) | T_IMPORT -> Cover_expr (import env) | T_SUPER -> Cover_expr (super env) | _ when Peek.is_function env -> Cover_expr (_function env) | _ -> primary_cover env in call_cover env start_loc expr and left_hand_side env = as_expression env (left_hand_side_cover env) and super env = let allowed, call_allowed = match allow_super env with | No_super -> false, false | Super_prop -> true, false | Super_prop_or_call -> true, true in let loc = Peek.loc env in Expect.token env T_SUPER; let super = loc, Expression.Super in match Peek.token env with | T_PERIOD | T_LBRACKET -> let super = if not allowed then begin error_at env (loc, Parse_error.UnexpectedSuper); loc, Expression.Identifier (loc, "super") end else super in call ~allow_optional_chain:false env loc super | T_LPAREN -> let super = if not call_allowed then begin error_at env (loc, Parse_error.UnexpectedSuperCall); loc, Expression.Identifier (loc, "super") end else super in call ~allow_optional_chain:false env loc super | _ -> if not allowed then error_at env (loc, Parse_error.UnexpectedSuper) else error_unexpected env; super and import env = with_loc (fun env -> Expect.token env T_IMPORT; Expect.token env T_LPAREN; let arg = assignment (with_no_in false env) in Expect.token env T_RPAREN; Expression.Import arg ) env and call_cover ?(allow_optional_chain=true) ?(in_optional_chain=false) env start_loc left = let left = member_cover ~allow_optional_chain ~in_optional_chain env start_loc left in let optional = last_token env = Some T_PLING_PERIOD in let arguments ?targs env = let args_loc, arguments = arguments env in let loc = Loc.btwn start_loc args_loc in let call = { Expression.Call. callee = as_expression env left; targs; arguments; } in let call = if optional || in_optional_chain then Expression.(OptionalCall { OptionalCall. call; optional; }) else Expression.Call call in call_cover ~allow_optional_chain ~in_optional_chain env start_loc (Cover_expr (loc, call)) in if no_call env then left else match Peek.token env with | T_LPAREN -> arguments env | T_LESS_THAN when should_parse_types env -> If we are parsing types , then f < T>(e ) is a function call with a type application . If we are n't , it 's a nested binary expression . type application. If we aren't, it's a nested binary expression. *) let error_callback _ _ = raise Try.Rollback in let env = env |> with_error_callback error_callback in (* Parameterized call syntax is ambiguous, so we fall back to standard parsing if it fails. *) Try.or_else env ~fallback:left (fun env -> let targs = type_parameter_instantiation env in arguments ?targs env ) | _ -> left and call ?(allow_optional_chain=true) env start_loc left = as_expression env (call_cover ~allow_optional_chain env start_loc (Cover_expr left)) and new_expression env = let start_loc = Peek.loc env in Expect.token env T_NEW; if in_function env && Peek.token env = T_PERIOD then begin Expect.token env T_PERIOD; let meta = start_loc, "new" in match Peek.token env with | T_IDENTIFIER { raw = "target"; _ } -> let property = Parse.identifier env in let end_loc = fst property in Loc.btwn start_loc end_loc, Expression.(MetaProperty MetaProperty.({ meta; property; })) | _ -> error_unexpected env; Eat.token env; (* skip unknown identifier *) start_loc, Expression.Identifier meta (* return `new` identifier *) end else let callee_loc = Peek.loc env in let expr = match Peek.token env with | T_NEW -> new_expression env | T_SUPER -> super (env |> with_no_call true) | _ when Peek.is_function env -> _function env | _ -> primary env in let callee = member ~allow_optional_chain:false (env |> with_no_call true) callee_loc expr in (* You can do something like * new raw`42` *) let callee = match Peek.token env with | T_TEMPLATE_PART part -> tagged_template env callee_loc callee part | _ -> callee in let targs = (* If we are parsing types, then new C<T>(e) is a constructor with a type application. If we aren't, it's a nested binary expression. *) if should_parse_types env then (* Parameterized call syntax is ambiguous, so we fall back to standard parsing if it fails. *) let error_callback _ _ = raise Try.Rollback in let env = env |> with_error_callback error_callback in Try.or_else env ~fallback:None type_parameter_instantiation else None in let end_loc, arguments = match Peek.token env, targs with | T_LPAREN, _ -> arguments env | _, Some (targs_loc, _) -> targs_loc, [] | _ -> fst callee, [] in Loc.btwn start_loc end_loc, Expression.(New New.({ callee; targs; arguments; })) and type_parameter_instantiation = let args env acc = let rec args_helper env acc = match Peek.token env with | T_EOF | T_GREATER_THAN -> List.rev acc | _ -> let t = match Peek.token env with | T_IDENTIFIER {value = "_"; _} -> let loc = Peek.loc env in Expect.identifier env "_"; Expression.TypeParameterInstantiation.Implicit loc | _ -> Expression.TypeParameterInstantiation.Explicit(Type._type env) in let acc = t::acc in if Peek.token env <> T_GREATER_THAN then Expect.token env T_COMMA; args_helper env acc in args_helper env acc in fun env -> if Peek.token env = T_LESS_THAN then Some (with_loc (fun env -> Expect.token env T_LESS_THAN; let args = args env [] in Expect.token env T_GREATER_THAN; args ) env) else None and arguments = let argument env = match Peek.token env with | T_ELLIPSIS -> let start_loc = Peek.loc env in Expect.token env T_ELLIPSIS; let argument = assignment env in let loc = Loc.btwn start_loc (fst argument) in Expression.(Spread (loc, SpreadElement.({ argument; }))) | _ -> Expression.Expression (assignment env) in let rec arguments' env acc = match Peek.token env with | T_EOF | T_RPAREN -> List.rev acc | _ -> let acc = (argument env)::acc in if Peek.token env <> T_RPAREN then Expect.token env T_COMMA; arguments' env acc in fun env -> let start_loc = Peek.loc env in Expect.token env T_LPAREN; let args = arguments' env [] in let end_loc = Peek.loc env in Expect.token env T_RPAREN; Loc.btwn start_loc end_loc, args and member_cover = let dynamic ?(allow_optional_chain=true) ?(in_optional_chain=false) ?(optional=false) env start_loc left = let expr = Parse.expression (env |> with_no_call false) in let last_loc = Peek.loc env in Expect.token env T_RBRACKET; let loc = Loc.btwn start_loc last_loc in let member = Expression.Member.({ _object = as_expression env left; property = PropertyExpression expr; }) in let member = if in_optional_chain then Expression.(OptionalMember { OptionalMember. member; optional; }) else Expression.Member member in call_cover ~allow_optional_chain ~in_optional_chain env start_loc (Cover_expr (loc, member)) in let static ?(allow_optional_chain=true) ?(in_optional_chain=false) ?(optional=false) env start_loc left = let id_loc, id, is_private = property_name_include_private env in if is_private then add_used_private env (snd id) id_loc; let loc = Loc.btwn start_loc id_loc in let open Expression.Member in let property = if is_private then PropertyPrivateName (id_loc, id) else PropertyIdentifier id in (* super.PrivateName is a syntax error *) begin match left with | Cover_expr (_, Ast.Expression.Super) when is_private -> error_at env (loc, Error.SuperPrivate) | _ -> () end; let member = Expression.Member.({ _object = as_expression env left; property; }) in let member = if in_optional_chain then Expression.(OptionalMember { OptionalMember. member; optional; }) else Expression.Member member in call_cover ~allow_optional_chain ~in_optional_chain env start_loc (Cover_expr (loc, member)) in fun ?(allow_optional_chain=true) ?(in_optional_chain=false) env start_loc left -> let options = parse_options env in match Peek.token env with | T_PLING_PERIOD -> if not options.esproposal_optional_chaining then error env Parse_error.OptionalChainingDisabled; if not allow_optional_chain then error env Parse_error.OptionalChainNew; Expect.token env T_PLING_PERIOD; begin match Peek.token env with | T_TEMPLATE_PART _ -> error env Parse_error.OptionalChainTemplate; left | T_LPAREN -> left | T_LESS_THAN when should_parse_types env -> left | T_LBRACKET -> Expect.token env T_LBRACKET; dynamic ~allow_optional_chain ~in_optional_chain:true ~optional:true env start_loc left | _ -> static ~allow_optional_chain ~in_optional_chain:true ~optional:true env start_loc left end | T_LBRACKET -> Expect.token env T_LBRACKET; dynamic ~allow_optional_chain ~in_optional_chain env start_loc left | T_PERIOD -> Expect.token env T_PERIOD; static ~allow_optional_chain ~in_optional_chain env start_loc left | T_TEMPLATE_PART part -> if in_optional_chain then error env Parse_error.OptionalChainTemplate; let expr = tagged_template env start_loc (as_expression env left) part in call_cover ~allow_optional_chain:false env start_loc (Cover_expr expr) | _ -> left and member ?(allow_optional_chain=true) env start_loc left = as_expression env (member_cover ~allow_optional_chain env start_loc (Cover_expr left)) and _function env = let start_loc = Peek.loc env in let async = Declaration.async env in let sig_loc, (id, params, generator, predicate, return, tparams) = with_loc (fun env -> Expect.token env T_FUNCTION; let generator = Declaration.generator env in let yield, await = match async, generator with | true, true -> true, true (* proposal-async-iteration/#prod-AsyncGeneratorExpression *) # prod - AsyncFunctionExpression # prod - GeneratorExpression | false, false -> false, false (* #prod-FunctionExpression *) in let id, tparams = if Peek.token env = T_LPAREN then None, None else begin let id = match Peek.token env with | T_LESS_THAN -> None | _ -> let env = env |> with_allow_await await |> with_allow_yield yield in Some (Parse.identifier ~restricted_error:Error.StrictFunctionName env) in id, Type.type_parameter_declaration env end in # sec - function - definitions - static - semantics - early - errors let env = env |> with_allow_super No_super in let params = Declaration.function_params ~await ~yield env in let return, predicate = Type.annotation_and_predicate_opt env in (id, params, generator, predicate, return, tparams) ) env in let end_loc, body, strict = Declaration.function_body env ~async ~generator in let simple = Declaration.is_simple_function_params params in Declaration.strict_post_check env ~strict ~simple id params; Loc.btwn start_loc end_loc, Expression.(Function Function.({ id; params; body; generator; async; predicate; return; tparams; sig_loc; })) and number env kind raw = let value = match kind with | LEGACY_OCTAL -> strict_error env Error.StrictOctalLiteral; begin try Int64.to_float (Int64.of_string ("0o"^raw)) with Failure _ -> failwith ("Invalid legacy octal "^raw) end | BINARY | OCTAL -> begin try Int64.to_float (Int64.of_string raw) with Failure _ -> failwith ("Invalid binary/octal "^raw) end | NORMAL -> begin try Lexer.FloatOfString.float_of_string raw with | _ when Sys.win32 -> error env Parse_error.WindowsFloatOfString; 789.0 | Failure _ -> failwith ("Invalid number "^raw) end in Expect.token env (T_NUMBER { kind; raw }); value and primary_cover env = let loc = Peek.loc env in match Peek.token env with | T_THIS -> Expect.token env T_THIS; Cover_expr (loc, Expression.This) | T_NUMBER { kind; raw } -> let value = Literal.Number (number env kind raw) in Cover_expr (loc, Expression.(Literal { Literal.value; raw; })) | T_STRING (loc, value, raw, octal) -> if octal then strict_error env Error.StrictOctalLiteral; Expect.token env (T_STRING (loc, value, raw, octal)); let value = Literal.String value in Cover_expr (loc, Expression.(Literal { Literal.value; raw; })) | (T_TRUE | T_FALSE) as token -> Expect.token env token; let truthy = token = T_TRUE in let raw = if truthy then "true" else "false" in let value = Literal.Boolean truthy in Cover_expr (loc, Expression.(Literal { Literal.value; raw; })) | T_NULL -> Expect.token env T_NULL; let raw = "null" in let value = Literal.Null in Cover_expr (loc, Expression.(Literal { Literal.value; raw; })) | T_LPAREN -> Cover_expr (group env) | T_LCURLY -> let loc, obj, errs = Parse.object_initializer env in Cover_patt ((loc, Expression.Object obj), errs) | T_LBRACKET -> let loc, arr, errs = array_initializer env in Cover_patt ((loc, Expression.Array arr), errs) | T_DIV | T_DIV_ASSIGN -> Cover_expr (regexp env) | T_LESS_THAN -> let loc, expression = match Parse.jsx_element_or_fragment env with | (loc, `Element e) -> (loc, Expression.JSXElement e) | (loc, `Fragment f) -> (loc, Expression.JSXFragment f) in Cover_expr (loc, expression) | T_TEMPLATE_PART part -> let loc, template = template_literal env part in Cover_expr (loc, Expression.TemplateLiteral template) | T_CLASS -> Cover_expr (Parse.class_expression env) | _ when Peek.is_identifier env -> let id = Parse.identifier env in Cover_expr (fst id, Expression.Identifier id) | t -> error_unexpected env; (* Let's get rid of the bad token *) begin match t with T_ERROR _ -> Eat.token env | _ -> () end; (* Really no idea how to recover from this. I suppose a null * expression is as good as anything *) let value = Literal.Null in let raw = "null" in Cover_expr (loc, Expression.(Literal { Literal.value; raw; })) and primary env = as_expression env (primary_cover env) and template_literal = let rec template_parts env quasis expressions = let expr = Parse.expression env in let expressions = expr::expressions in match Peek.token env with | T_RCURLY -> Eat.push_lex_mode env Lex_mode.TEMPLATE; let loc, part, is_tail = match Peek.token env with | T_TEMPLATE_PART (loc, {cooked; raw; _}, tail) -> let open Ast.Expression.TemplateLiteral in Eat.token env; loc, { Element.value = { Element.cooked; raw; }; tail; }, tail | _ -> assert false in Eat.pop_lex_mode env; let quasis = (loc, part)::quasis in if is_tail then loc, List.rev quasis, List.rev expressions else template_parts env quasis expressions | _ -> (* Malformed template *) error_unexpected env; let imaginary_quasi = fst expr, { Expression.TemplateLiteral.Element. value = { Expression.TemplateLiteral.Element. raw = ""; cooked = ""; }; tail = true; } in fst expr, List.rev (imaginary_quasi::quasis), List.rev expressions in fun env ((start_loc, {cooked; raw; _}, is_tail) as part) -> Expect.token env (T_TEMPLATE_PART part); let end_loc, quasis, expressions = let head = Ast.Expression.TemplateLiteral.(start_loc, { Element.value = { Element.cooked; raw; }; tail = is_tail; }) in if is_tail then start_loc, [head], [] else template_parts env [head] [] in let loc = Loc.btwn start_loc end_loc in loc, Expression.TemplateLiteral.({ quasis; expressions; }) and tagged_template env start_loc tag part = let quasi = template_literal env part in Loc.btwn start_loc (fst quasi), Expression.(TaggedTemplate TaggedTemplate.({ tag; quasi; })) and group env = Expect.token env T_LPAREN; let expression = assignment env in let ret = (match Peek.token env with | T_COMMA -> sequence env [expression] | T_COLON -> let annot = Type.annotation env in Expression.(Loc.btwn (fst expression) (fst annot), TypeCast TypeCast.({ expression; annot; })) | _ -> expression) in Expect.token env T_RPAREN; ret and array_initializer = let rec elements env (acc, errs) = match Peek.token env with | T_EOF | T_RBRACKET -> List.rev acc, Pattern_cover.rev_errors errs | T_COMMA -> Expect.token env T_COMMA; elements env (None::acc, errs) | T_ELLIPSIS -> let loc, (argument, new_errs) = with_loc (fun env -> Expect.token env T_ELLIPSIS; match assignment_cover env with | Cover_expr argument -> argument, Pattern_cover.empty_errors | Cover_patt (argument, new_errs) -> argument, new_errs ) env in let elem = Expression.(Spread (loc, SpreadElement.({ argument; }))) in let is_last = Peek.token env = T_RBRACKET in (* if this array is interpreted as a pattern, the spread becomes an AssignmentRestElement which must be the last element. We can easily error about additional elements since they will be in the element list, but a trailing elision, like `[...x,]`, is not part of the AST. so, keep track of the error so we can raise it if this is a pattern. *) let new_errs = if not is_last && Peek.ith_token ~i:1 env = T_RBRACKET then let if_patt = (loc, Parse_error.ElementAfterRestElement)::new_errs.if_patt in { new_errs with if_patt } else new_errs in if not is_last then Expect.token env T_COMMA; let acc = Some elem :: acc in let errs = Pattern_cover.rev_append_errors new_errs errs in elements env (acc, errs) | _ -> let elem, new_errs = match assignment_cover env with | Cover_expr elem -> elem, Pattern_cover.empty_errors | Cover_patt (elem, new_errs) -> elem, new_errs in if Peek.token env <> T_RBRACKET then Expect.token env T_COMMA; let acc = Some (Expression.Expression elem) :: acc in let errs = Pattern_cover.rev_append_errors new_errs errs in elements env (acc, errs) in fun env -> let loc, (elements, errs) = with_loc (fun env -> Expect.token env T_LBRACKET; let res = elements env ([], Pattern_cover.empty_errors) in Expect.token env T_RBRACKET; res ) env in loc, { Expression.Array.elements; }, errs and regexp env = Eat.push_lex_mode env Lex_mode.REGEXP; let loc = Peek.loc env in let raw, pattern, raw_flags = match Peek.token env with | T_REGEXP (_, pattern, flags) -> Eat.token env; let raw = "/" ^ pattern ^ "/" ^ flags in raw, pattern, flags | _ -> assert false in Eat.pop_lex_mode env; let filtered_flags = Buffer.create (String.length raw_flags) in String.iter (function | 'g' | 'i' | 'm' | 's' | 'u' | 'y' as c -> Buffer.add_char filtered_flags c | _ -> ()) raw_flags; let flags = Buffer.contents filtered_flags in if flags <> raw_flags then error env (Error.InvalidRegExpFlags raw_flags); let value = Literal.(RegExp { RegExp.pattern; flags; }) in loc, Expression.(Literal { Literal.value; raw; }) and try_arrow_function = (* Certain errors (almost all errors) cause a rollback *) let error_callback _ = Error.(function (* Don't rollback on these errors. *) | StrictParamName | StrictReservedWord | ParameterAfterRestParameter | NewlineBeforeArrow | YieldInFormalParameters -> () (* Everything else causes a rollback *) | _ -> raise Try.Rollback) in let concise_function_body env ~async = (* arrow functions can't be generators *) let env = enter_function env ~async ~generator:false in match Peek.token env with | T_LCURLY -> let loc, body, strict = Parse.function_block_body env in Function.BodyBlock (loc, body), strict | _ -> let expr = Parse.assignment env in Function.BodyExpression expr, in_strict_mode env in fun env -> let env = env |> with_error_callback error_callback in let start_loc = Peek.loc env in (* a T_ASYNC could either be a parameter name or it could be indicating * that it's an async function *) let async = Peek.ith_token ~i:1 env <> T_ARROW && Declaration.async env in let sig_loc, (tparams, params, return, predicate) = with_loc (fun env -> let tparams = Type.type_parameter_declaration env in (* Disallow all fancy features for identifier => body *) if Peek.is_identifier env && tparams = None then let (loc, _) as name = Parse.identifier ~restricted_error:Error.StrictParamName env in let param = loc, { Ast.Function.Param. argument = loc, Pattern.Identifier { Pattern.Identifier. name; annot = Ast.Type.Missing (Peek.loc_skip_lookahead env); optional = false; }; default = None; } in tparams, (loc, { Ast.Function.Params.params = [param]; rest = None }), Ast.Type.Missing Loc.({ loc with start = loc._end }), None else let params = let yield = allow_yield env in let await = allow_await env in Declaration.function_params ~await ~yield env in (* There's an ambiguity if you use a function type as the return * type for an arrow function. So we disallow anonymous function * types in arrow function return types unless the function type is * enclosed in parens *) let return, predicate = env |> with_no_anon_function_type true |> Type.annotation_and_predicate_opt in tparams, params, return, predicate ) env in It 's hard to tell if an invalid expression was intended to be an * arrow function before we see the = > . If there are no params , that * implies " ( ) " which is only ever found in arrow params . Similarly , * rest params indicate arrow functions . Therefore , if we see a rest * param or an empty param list then we can disable the rollback and * instead generate errors as if we were parsing an arrow function * arrow function before we see the =>. If there are no params, that * implies "()" which is only ever found in arrow params. Similarly, * rest params indicate arrow functions. Therefore, if we see a rest * param or an empty param list then we can disable the rollback and * instead generate errors as if we were parsing an arrow function *) let env = match params with | _, { Ast.Function.Params.rest = Some _; _ } | _, { Ast.Function.Params.params = []; _ } -> without_error_callback env | _ -> env in if Peek.is_line_terminator env && Peek.token env = T_ARROW then error env Error.NewlineBeforeArrow; Expect.token env T_ARROW; (* Now we know for sure this is an arrow function *) let env = without_error_callback env in let end_loc, (body, strict) = with_loc (concise_function_body ~async) env in let simple = Declaration.is_simple_function_params params in Declaration.strict_post_check env ~strict ~simple None params; let loc = Loc.btwn start_loc end_loc in Cover_expr (loc, Expression.(ArrowFunction { Function. id = None; params; body; async; generator = false; (* arrow functions cannot be generators *) predicate; return; tparams; sig_loc; })) and sequence env acc = match Peek.token env with | T_COMMA -> Expect.token env T_COMMA; let expr = assignment env in sequence env (expr::acc) | _ -> let (last_loc, _) = List.hd acc in let expressions = List.rev acc in let (first_loc, _) = List.hd expressions in Loc.btwn first_loc last_loc, Expression.(Sequence Sequence.({ expressions; })) and property_name_include_private env = let start_loc = Peek.loc env in let is_private = Expect.maybe env T_POUND in let id_loc, ident = identifier_name env in let loc = Loc.btwn start_loc id_loc in loc, (id_loc, ident), is_private end
null
https://raw.githubusercontent.com/kitten/bs-flow-parser/00630c06016b51a7040ef4160ed2999cd208babd/src/expression_parser.ml
ocaml
Don't rollback on these errors. Everything else causes a rollback Well shoot. It doesn't parse cleanly as a normal * expression or as an arrow_function. Let's treat it as a * normal assignment expression gone wrong no_in is ignored for the consequent Lowest pri Highest priority If we are in a unary expression context, and within an async function, * assume that a use of "await" is intended as a keyword, not an ordinary * identifier. This is a little bit inconsistent, since it can be used as * an identifier in other contexts (such as a variable name), but it's how * Babel does it. No line terminator allowed before operator Parameterized call syntax is ambiguous, so we fall back to standard parsing if it fails. skip unknown identifier return `new` identifier You can do something like * new raw`42` If we are parsing types, then new C<T>(e) is a constructor with a type application. If we aren't, it's a nested binary expression. Parameterized call syntax is ambiguous, so we fall back to standard parsing if it fails. super.PrivateName is a syntax error proposal-async-iteration/#prod-AsyncGeneratorExpression #prod-FunctionExpression Let's get rid of the bad token Really no idea how to recover from this. I suppose a null * expression is as good as anything Malformed template if this array is interpreted as a pattern, the spread becomes an AssignmentRestElement which must be the last element. We can easily error about additional elements since they will be in the element list, but a trailing elision, like `[...x,]`, is not part of the AST. so, keep track of the error so we can raise it if this is a pattern. Certain errors (almost all errors) cause a rollback Don't rollback on these errors. Everything else causes a rollback arrow functions can't be generators a T_ASYNC could either be a parameter name or it could be indicating * that it's an async function Disallow all fancy features for identifier => body There's an ambiguity if you use a function type as the return * type for an arrow function. So we disallow anonymous function * types in arrow function return types unless the function type is * enclosed in parens Now we know for sure this is an arrow function arrow functions cannot be generators
* * Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) module Ast = Flow_ast open Token open Parser_env open Flow_ast module Error = Parse_error open Parser_common module type EXPRESSION = sig val assignment: env -> (Loc.t, Loc.t) Expression.t val assignment_cover: env -> pattern_cover val conditional: env -> (Loc.t, Loc.t) Expression.t val property_name_include_private: env -> Loc.t * Loc.t Identifier.t * bool val is_assignable_lhs: (Loc.t, Loc.t) Expression.t -> bool val left_hand_side: env -> (Loc.t, Loc.t) Expression.t val number: env -> number_type -> string -> float val sequence: env -> (Loc.t, Loc.t) Expression.t list -> (Loc.t, Loc.t) Expression.t end module Expression (Parse: PARSER) (Type: Type_parser.TYPE) (Declaration: Declaration_parser.DECLARATION) (Pattern_cover: Pattern_cover.COVER) : EXPRESSION = struct type op_precedence = Left_assoc of int | Right_assoc of int let is_tighter a b = let a_prec = match a with Left_assoc x -> x | Right_assoc x -> x - 1 in let b_prec = match b with Left_assoc x -> x | Right_assoc x -> x in a_prec >= b_prec let is_assignable_lhs = Expression.(function | _, MetaProperty { MetaProperty.meta = (_, "new"); property = (_, "target") } # sec - static - semantics - static - semantics - isvalidsimpleassignmenttarget | _, Array _ | _, Identifier _ | _, Member _ | _, MetaProperty _ | _, Object _ -> true | _, ArrowFunction _ | _, Assignment _ | _, Binary _ | _, Call _ | _, Class _ | _, Comprehension _ | _, Conditional _ | _, Function _ | _, Generator _ | _, Import _ | _, JSXElement _ | _, JSXFragment _ | _, Literal _ | _, Logical _ | _, New _ | _, OptionalCall _ | _, OptionalMember _ | _, Sequence _ | _, Super | _, TaggedTemplate _ | _, TemplateLiteral _ | _, This | _, TypeCast _ | _, Unary _ | _, Update _ | _, Yield _ -> false ) let as_expression = Pattern_cover.as_expression let as_pattern = Pattern_cover.as_pattern AssignmentExpression : * ConditionalExpression * LeftHandSideExpression = AssignmentExpression * * * Originally we were parsing this without backtracking , but * ArrowFunctionExpression got too tricky . Oh well . * ConditionalExpression * LeftHandSideExpression = AssignmentExpression * LeftHandSideExpression AssignmentOperator AssignmentExpression * ArrowFunctionFunction * * Originally we were parsing this without backtracking, but * ArrowFunctionExpression got too tricky. Oh well. *) let rec assignment_cover = let assignment_but_not_arrow_function_cover env = let expr_or_pattern = conditional_cover env in match assignment_op env with | Some operator -> let left = as_pattern env expr_or_pattern in let right = assignment env in let loc = Loc.btwn (fst left) (fst right) in Cover_expr (loc, Expression.(Assignment { Assignment. operator; left; right; })) | _ -> expr_or_pattern in let error_callback _ = function | Error.StrictReservedWord -> () | _ -> raise Try.Rollback So we may or may not be parsing the first part of an arrow function * ( the part before the = > ) . We might end up parsing that whole thing or * we might end up parsing only part of it and thinking we 're done . We * need to look at the next token to figure out if we really parsed an * assignment expression or if this is just the beginning of an arrow * function * (the part before the =>). We might end up parsing that whole thing or * we might end up parsing only part of it and thinking we're done. We * need to look at the next token to figure out if we really parsed an * assignment expression or if this is just the beginning of an arrow * function *) in let try_assignment_but_not_arrow_function env = let env = env |> with_error_callback error_callback in let ret = assignment_but_not_arrow_function_cover env in match Peek.token env with x = > 123 raise Try.Rollback ( x ): number = > 123 raise Try.Rollback async x = > 123 -- and we 've already parsed async as an identifier * expression * expression *) | _ when Peek.is_identifier env -> begin match ret with | Cover_expr (_, Expression.Identifier (_, "async")) when not (Peek.is_line_terminator env) -> raise Try.Rollback | _ -> ret end | _ -> ret in fun env -> match Peek.token env, Peek.is_identifier env with | T_YIELD, _ when (allow_yield env) -> Cover_expr (yield env) | T_LPAREN, _ | T_LESS_THAN, _ | _, true -> Ok , we do n't know if this is going to be an arrow function or a * regular assignment expression . Let 's first try to parse it as an * assignment expression . If that fails we 'll try an arrow function . * regular assignment expression. Let's first try to parse it as an * assignment expression. If that fails we'll try an arrow function. *) (match Try.to_parse env try_assignment_but_not_arrow_function with | Try.ParsedSuccessfully expr -> expr | Try.FailedToParse -> (match Try.to_parse env try_arrow_function with | Try.ParsedSuccessfully expr -> expr | Try.FailedToParse -> assignment_but_not_arrow_function_cover env ) ) | _ -> assignment_but_not_arrow_function_cover env and assignment env = as_expression env (assignment_cover env) and yield env = with_loc (fun env -> if in_formal_parameters env then error env Error.YieldInFormalParameters; Expect.token env T_YIELD; let argument, delegate = if Peek.is_implicit_semicolon env then None, false else let delegate = Expect.maybe env T_MULT in let has_argument = match Peek.token env with | T_SEMICOLON | T_RBRACKET | T_RCURLY | T_RPAREN | T_COLON | T_COMMA -> false | _ -> true in let argument = if delegate || has_argument then Some (assignment env) else None in argument, delegate in Expression.(Yield Yield.({ argument; delegate; })) ) env and is_lhs = Expression.(function | _, MetaProperty { MetaProperty.meta = (_, "new"); property = (_, "target") } # sec - static - semantics - static - semantics - isvalidsimpleassignmenttarget | _, Identifier _ | _, Member _ | _, MetaProperty _ -> true | _, Array _ | _, ArrowFunction _ | _, Assignment _ | _, Binary _ | _, Call _ | _, Class _ | _, Comprehension _ | _, Conditional _ | _, Function _ | _, Generator _ | _, Import _ | _, JSXElement _ | _, JSXFragment _ | _, Literal _ | _, Logical _ | _, New _ | _, Object _ | _, OptionalCall _ | _, OptionalMember _ | _, Sequence _ | _, Super | _, TaggedTemplate _ | _, TemplateLiteral _ | _, This | _, TypeCast _ | _, Unary _ | _, Update _ | _, Yield _ -> false ) and assignment_op env = let op = Expression.Assignment.(match Peek.token env with | T_RSHIFT3_ASSIGN -> Some RShift3Assign | T_RSHIFT_ASSIGN -> Some RShiftAssign | T_LSHIFT_ASSIGN -> Some LShiftAssign | T_BIT_XOR_ASSIGN -> Some BitXorAssign | T_BIT_OR_ASSIGN -> Some BitOrAssign | T_BIT_AND_ASSIGN -> Some BitAndAssign | T_MOD_ASSIGN -> Some ModAssign | T_DIV_ASSIGN -> Some DivAssign | T_MULT_ASSIGN -> Some MultAssign | T_EXP_ASSIGN -> Some ExpAssign | T_MINUS_ASSIGN -> Some MinusAssign | T_PLUS_ASSIGN -> Some PlusAssign | T_ASSIGN -> Some Assign | _ -> None) in if op <> None then Eat.token env; op and conditional_cover env = let start_loc = Peek.loc env in let expr = logical_cover env in if Peek.token env = T_PLING then begin Expect.token env T_PLING; let env' = env |> with_no_in false in let consequent = assignment env' in Expect.token env T_COLON; let end_loc, alternate = with_loc assignment env in let loc = Loc.btwn start_loc end_loc in Cover_expr (loc, Expression.(Conditional { Conditional. test = as_expression env expr; consequent; alternate; })) end else expr and conditional env = as_expression env (conditional_cover env) and logical_cover = let open Expression in let make_logical env left right operator loc = let left = as_expression env left in let right = as_expression env right in Cover_expr (loc, Logical {Logical.operator; left; right;}) in let rec logical_and env left lloc = match Peek.token env with | T_AND -> Expect.token env T_AND; let rloc, right = with_loc binary_cover env in let loc = Loc.btwn lloc rloc in logical_and env (make_logical env left right Logical.And loc) loc | _ -> lloc, left and logical_or env left lloc = let options = parse_options env in match Peek.token env with | T_OR -> Expect.token env T_OR; let rloc, right = with_loc binary_cover env in let rloc, right = logical_and env right rloc in let loc = Loc.btwn lloc rloc in logical_or env (make_logical env left right Logical.Or loc) loc | T_PLING_PLING -> if not options.esproposal_nullish_coalescing then error env Parse_error.NullishCoalescingDisabled; Expect.token env T_PLING_PLING; let rloc, right = with_loc binary_cover env in let rloc, right = logical_and env right rloc in let loc = Loc.btwn lloc rloc in logical_or env (make_logical env left right Logical.NullishCoalesce loc) loc | _ -> left in fun env -> let loc, left = with_loc binary_cover env in let loc, left = logical_and env left loc in logical_or env left loc and binary_cover = let binary_op env = let ret = Expression.Binary.(match Peek.token env with Most BinaryExpression operators are left associative | T_BIT_OR -> Some (BitOr, Left_assoc 2) | T_BIT_XOR -> Some (Xor, Left_assoc 3) | T_BIT_AND -> Some (BitAnd, Left_assoc 4) | T_EQUAL -> Some (Equal, Left_assoc 5) | T_STRICT_EQUAL -> Some (StrictEqual, Left_assoc 5) | T_NOT_EQUAL -> Some (NotEqual, Left_assoc 5) | T_STRICT_NOT_EQUAL -> Some (StrictNotEqual, Left_assoc 5) | T_LESS_THAN -> Some (LessThan, Left_assoc 6) | T_LESS_THAN_EQUAL -> Some (LessThanEqual, Left_assoc 6) | T_GREATER_THAN -> Some (GreaterThan, Left_assoc 6) | T_GREATER_THAN_EQUAL -> Some (GreaterThanEqual, Left_assoc 6) | T_IN -> if (no_in env) then None else Some (In, Left_assoc 6) | T_INSTANCEOF -> Some (Instanceof, Left_assoc 6) | T_LSHIFT -> Some (LShift, Left_assoc 7) | T_RSHIFT -> Some (RShift, Left_assoc 7) | T_RSHIFT3 -> Some (RShift3, Left_assoc 7) | T_PLUS -> Some (Plus, Left_assoc 8) | T_MINUS -> Some (Minus, Left_assoc 8) | T_MULT -> Some (Mult, Left_assoc 9) | T_DIV -> Some (Div, Left_assoc 9) | T_MOD -> Some (Mod, Left_assoc 9) | T_EXP -> Some (Exp, Right_assoc 10) | _ -> None) in if ret <> None then Eat.token env; ret in let make_binary left right operator loc = loc, Expression.(Binary Binary.({ operator; left; right; })) in let rec add_to_stack right (rop, rpri) rloc = function | (left, (lop, lpri), lloc)::rest when is_tighter lpri rpri -> let loc = Loc.btwn lloc rloc in let right = make_binary left right lop loc in add_to_stack right (rop, rpri) loc rest | stack -> (right, (rop, rpri), rloc)::stack in let rec collapse_stack right rloc = function | [] -> right | (left, (lop, _), lloc)::rest -> let loc = Loc.btwn lloc rloc in collapse_stack (make_binary left right lop loc) loc rest in let rec helper env stack = let right_loc, (is_unary, right) = with_loc (fun env -> let is_unary = peek_unary_op env <> None in let right = unary_cover (env |> with_no_in false) in is_unary, right ) env in if Peek.token env = T_LESS_THAN then begin match right with | Cover_expr (_, Expression.JSXElement _) -> error env Error.AdjacentJSXElements | _ -> () end; match stack, binary_op env with | [], None -> right | _, None -> let right = as_expression env right in Cover_expr (collapse_stack right right_loc stack) | _, Some (rop, rpri) -> if is_unary && rop = Expression.Binary.Exp then error_at env (right_loc, Error.InvalidLHSInExponentiation); let right = as_expression env right in helper env (add_to_stack right (rop, rpri) right_loc stack) in fun env -> helper env [] and peek_unary_op env = let open Expression.Unary in match Peek.token env with | T_NOT -> Some Not | T_BIT_NOT -> Some BitNot | T_PLUS -> Some Plus | T_MINUS -> Some Minus | T_TYPEOF -> Some Typeof | T_VOID -> Some Void | T_DELETE -> Some Delete | T_AWAIT when allow_await env -> Some Await | _ -> None and unary_cover env = let begin_loc = Peek.loc env in let op = peek_unary_op env in match op with | None -> begin let op = Expression.Update.(match Peek.token env with | T_INCR -> Some Increment | T_DECR -> Some Decrement | _ -> None) in match op with | None -> postfix_cover env | Some operator -> Eat.token env; let end_loc, argument = with_loc unary env in if not (is_lhs argument) then error_at env (fst argument, Error.InvalidLHSInAssignment); (match argument with | _, Expression.Identifier (_, name) when is_restricted name -> strict_error env Error.StrictLHSPrefix | _ -> ()); let loc = Loc.btwn begin_loc end_loc in Cover_expr (loc, Expression.(Update { Update. operator; prefix = true; argument; })) end | Some operator -> Eat.token env; let end_loc, argument = with_loc unary env in let loc = Loc.btwn begin_loc end_loc in Expression.(match operator, argument with | Unary.Delete, (_, Identifier _) -> strict_error_at env (loc, Error.StrictDelete) | Unary.Delete, (_, Member member) -> begin match member.Ast.Expression.Member.property with | Ast.Expression.Member.PropertyPrivateName _ -> error_at env (loc, Error.PrivateDelete) | _ -> () end | _ -> ()); Cover_expr (loc, Expression.(Unary { Unary. operator; argument; })) and unary env = as_expression env (unary_cover env) and postfix_cover env = let argument = left_hand_side_cover env in if Peek.is_line_terminator env then argument else let op = Expression.Update.(match Peek.token env with | T_INCR -> Some Increment | T_DECR -> Some Decrement | _ -> None) in match op with | None -> argument | Some operator -> let argument = as_expression env argument in if not (is_lhs argument) then error_at env (fst argument, Error.InvalidLHSInAssignment); (match argument with | _, Expression.Identifier (_, name) when is_restricted name -> strict_error env Error.StrictLHSPostfix | _ -> ()); let end_loc = Peek.loc env in Eat.token env; let loc = Loc.btwn (fst argument) end_loc in Cover_expr (loc, Expression.(Update { Update. operator; prefix = false; argument; })) and left_hand_side_cover env = let start_loc = Peek.loc env in let allow_new = not (no_new env) in let env = with_no_new false env in let expr = match Peek.token env with | T_NEW when allow_new -> Cover_expr (new_expression env) | T_IMPORT -> Cover_expr (import env) | T_SUPER -> Cover_expr (super env) | _ when Peek.is_function env -> Cover_expr (_function env) | _ -> primary_cover env in call_cover env start_loc expr and left_hand_side env = as_expression env (left_hand_side_cover env) and super env = let allowed, call_allowed = match allow_super env with | No_super -> false, false | Super_prop -> true, false | Super_prop_or_call -> true, true in let loc = Peek.loc env in Expect.token env T_SUPER; let super = loc, Expression.Super in match Peek.token env with | T_PERIOD | T_LBRACKET -> let super = if not allowed then begin error_at env (loc, Parse_error.UnexpectedSuper); loc, Expression.Identifier (loc, "super") end else super in call ~allow_optional_chain:false env loc super | T_LPAREN -> let super = if not call_allowed then begin error_at env (loc, Parse_error.UnexpectedSuperCall); loc, Expression.Identifier (loc, "super") end else super in call ~allow_optional_chain:false env loc super | _ -> if not allowed then error_at env (loc, Parse_error.UnexpectedSuper) else error_unexpected env; super and import env = with_loc (fun env -> Expect.token env T_IMPORT; Expect.token env T_LPAREN; let arg = assignment (with_no_in false env) in Expect.token env T_RPAREN; Expression.Import arg ) env and call_cover ?(allow_optional_chain=true) ?(in_optional_chain=false) env start_loc left = let left = member_cover ~allow_optional_chain ~in_optional_chain env start_loc left in let optional = last_token env = Some T_PLING_PERIOD in let arguments ?targs env = let args_loc, arguments = arguments env in let loc = Loc.btwn start_loc args_loc in let call = { Expression.Call. callee = as_expression env left; targs; arguments; } in let call = if optional || in_optional_chain then Expression.(OptionalCall { OptionalCall. call; optional; }) else Expression.Call call in call_cover ~allow_optional_chain ~in_optional_chain env start_loc (Cover_expr (loc, call)) in if no_call env then left else match Peek.token env with | T_LPAREN -> arguments env | T_LESS_THAN when should_parse_types env -> If we are parsing types , then f < T>(e ) is a function call with a type application . If we are n't , it 's a nested binary expression . type application. If we aren't, it's a nested binary expression. *) let error_callback _ _ = raise Try.Rollback in let env = env |> with_error_callback error_callback in Try.or_else env ~fallback:left (fun env -> let targs = type_parameter_instantiation env in arguments ?targs env ) | _ -> left and call ?(allow_optional_chain=true) env start_loc left = as_expression env (call_cover ~allow_optional_chain env start_loc (Cover_expr left)) and new_expression env = let start_loc = Peek.loc env in Expect.token env T_NEW; if in_function env && Peek.token env = T_PERIOD then begin Expect.token env T_PERIOD; let meta = start_loc, "new" in match Peek.token env with | T_IDENTIFIER { raw = "target"; _ } -> let property = Parse.identifier env in let end_loc = fst property in Loc.btwn start_loc end_loc, Expression.(MetaProperty MetaProperty.({ meta; property; })) | _ -> error_unexpected env; end else let callee_loc = Peek.loc env in let expr = match Peek.token env with | T_NEW -> new_expression env | T_SUPER -> super (env |> with_no_call true) | _ when Peek.is_function env -> _function env | _ -> primary env in let callee = member ~allow_optional_chain:false (env |> with_no_call true) callee_loc expr in let callee = match Peek.token env with | T_TEMPLATE_PART part -> tagged_template env callee_loc callee part | _ -> callee in let targs = if should_parse_types env then let error_callback _ _ = raise Try.Rollback in let env = env |> with_error_callback error_callback in Try.or_else env ~fallback:None type_parameter_instantiation else None in let end_loc, arguments = match Peek.token env, targs with | T_LPAREN, _ -> arguments env | _, Some (targs_loc, _) -> targs_loc, [] | _ -> fst callee, [] in Loc.btwn start_loc end_loc, Expression.(New New.({ callee; targs; arguments; })) and type_parameter_instantiation = let args env acc = let rec args_helper env acc = match Peek.token env with | T_EOF | T_GREATER_THAN -> List.rev acc | _ -> let t = match Peek.token env with | T_IDENTIFIER {value = "_"; _} -> let loc = Peek.loc env in Expect.identifier env "_"; Expression.TypeParameterInstantiation.Implicit loc | _ -> Expression.TypeParameterInstantiation.Explicit(Type._type env) in let acc = t::acc in if Peek.token env <> T_GREATER_THAN then Expect.token env T_COMMA; args_helper env acc in args_helper env acc in fun env -> if Peek.token env = T_LESS_THAN then Some (with_loc (fun env -> Expect.token env T_LESS_THAN; let args = args env [] in Expect.token env T_GREATER_THAN; args ) env) else None and arguments = let argument env = match Peek.token env with | T_ELLIPSIS -> let start_loc = Peek.loc env in Expect.token env T_ELLIPSIS; let argument = assignment env in let loc = Loc.btwn start_loc (fst argument) in Expression.(Spread (loc, SpreadElement.({ argument; }))) | _ -> Expression.Expression (assignment env) in let rec arguments' env acc = match Peek.token env with | T_EOF | T_RPAREN -> List.rev acc | _ -> let acc = (argument env)::acc in if Peek.token env <> T_RPAREN then Expect.token env T_COMMA; arguments' env acc in fun env -> let start_loc = Peek.loc env in Expect.token env T_LPAREN; let args = arguments' env [] in let end_loc = Peek.loc env in Expect.token env T_RPAREN; Loc.btwn start_loc end_loc, args and member_cover = let dynamic ?(allow_optional_chain=true) ?(in_optional_chain=false) ?(optional=false) env start_loc left = let expr = Parse.expression (env |> with_no_call false) in let last_loc = Peek.loc env in Expect.token env T_RBRACKET; let loc = Loc.btwn start_loc last_loc in let member = Expression.Member.({ _object = as_expression env left; property = PropertyExpression expr; }) in let member = if in_optional_chain then Expression.(OptionalMember { OptionalMember. member; optional; }) else Expression.Member member in call_cover ~allow_optional_chain ~in_optional_chain env start_loc (Cover_expr (loc, member)) in let static ?(allow_optional_chain=true) ?(in_optional_chain=false) ?(optional=false) env start_loc left = let id_loc, id, is_private = property_name_include_private env in if is_private then add_used_private env (snd id) id_loc; let loc = Loc.btwn start_loc id_loc in let open Expression.Member in let property = if is_private then PropertyPrivateName (id_loc, id) else PropertyIdentifier id in begin match left with | Cover_expr (_, Ast.Expression.Super) when is_private -> error_at env (loc, Error.SuperPrivate) | _ -> () end; let member = Expression.Member.({ _object = as_expression env left; property; }) in let member = if in_optional_chain then Expression.(OptionalMember { OptionalMember. member; optional; }) else Expression.Member member in call_cover ~allow_optional_chain ~in_optional_chain env start_loc (Cover_expr (loc, member)) in fun ?(allow_optional_chain=true) ?(in_optional_chain=false) env start_loc left -> let options = parse_options env in match Peek.token env with | T_PLING_PERIOD -> if not options.esproposal_optional_chaining then error env Parse_error.OptionalChainingDisabled; if not allow_optional_chain then error env Parse_error.OptionalChainNew; Expect.token env T_PLING_PERIOD; begin match Peek.token env with | T_TEMPLATE_PART _ -> error env Parse_error.OptionalChainTemplate; left | T_LPAREN -> left | T_LESS_THAN when should_parse_types env -> left | T_LBRACKET -> Expect.token env T_LBRACKET; dynamic ~allow_optional_chain ~in_optional_chain:true ~optional:true env start_loc left | _ -> static ~allow_optional_chain ~in_optional_chain:true ~optional:true env start_loc left end | T_LBRACKET -> Expect.token env T_LBRACKET; dynamic ~allow_optional_chain ~in_optional_chain env start_loc left | T_PERIOD -> Expect.token env T_PERIOD; static ~allow_optional_chain ~in_optional_chain env start_loc left | T_TEMPLATE_PART part -> if in_optional_chain then error env Parse_error.OptionalChainTemplate; let expr = tagged_template env start_loc (as_expression env left) part in call_cover ~allow_optional_chain:false env start_loc (Cover_expr expr) | _ -> left and member ?(allow_optional_chain=true) env start_loc left = as_expression env (member_cover ~allow_optional_chain env start_loc (Cover_expr left)) and _function env = let start_loc = Peek.loc env in let async = Declaration.async env in let sig_loc, (id, params, generator, predicate, return, tparams) = with_loc (fun env -> Expect.token env T_FUNCTION; let generator = Declaration.generator env in let yield, await = match async, generator with # prod - AsyncFunctionExpression # prod - GeneratorExpression in let id, tparams = if Peek.token env = T_LPAREN then None, None else begin let id = match Peek.token env with | T_LESS_THAN -> None | _ -> let env = env |> with_allow_await await |> with_allow_yield yield in Some (Parse.identifier ~restricted_error:Error.StrictFunctionName env) in id, Type.type_parameter_declaration env end in # sec - function - definitions - static - semantics - early - errors let env = env |> with_allow_super No_super in let params = Declaration.function_params ~await ~yield env in let return, predicate = Type.annotation_and_predicate_opt env in (id, params, generator, predicate, return, tparams) ) env in let end_loc, body, strict = Declaration.function_body env ~async ~generator in let simple = Declaration.is_simple_function_params params in Declaration.strict_post_check env ~strict ~simple id params; Loc.btwn start_loc end_loc, Expression.(Function Function.({ id; params; body; generator; async; predicate; return; tparams; sig_loc; })) and number env kind raw = let value = match kind with | LEGACY_OCTAL -> strict_error env Error.StrictOctalLiteral; begin try Int64.to_float (Int64.of_string ("0o"^raw)) with Failure _ -> failwith ("Invalid legacy octal "^raw) end | BINARY | OCTAL -> begin try Int64.to_float (Int64.of_string raw) with Failure _ -> failwith ("Invalid binary/octal "^raw) end | NORMAL -> begin try Lexer.FloatOfString.float_of_string raw with | _ when Sys.win32 -> error env Parse_error.WindowsFloatOfString; 789.0 | Failure _ -> failwith ("Invalid number "^raw) end in Expect.token env (T_NUMBER { kind; raw }); value and primary_cover env = let loc = Peek.loc env in match Peek.token env with | T_THIS -> Expect.token env T_THIS; Cover_expr (loc, Expression.This) | T_NUMBER { kind; raw } -> let value = Literal.Number (number env kind raw) in Cover_expr (loc, Expression.(Literal { Literal.value; raw; })) | T_STRING (loc, value, raw, octal) -> if octal then strict_error env Error.StrictOctalLiteral; Expect.token env (T_STRING (loc, value, raw, octal)); let value = Literal.String value in Cover_expr (loc, Expression.(Literal { Literal.value; raw; })) | (T_TRUE | T_FALSE) as token -> Expect.token env token; let truthy = token = T_TRUE in let raw = if truthy then "true" else "false" in let value = Literal.Boolean truthy in Cover_expr (loc, Expression.(Literal { Literal.value; raw; })) | T_NULL -> Expect.token env T_NULL; let raw = "null" in let value = Literal.Null in Cover_expr (loc, Expression.(Literal { Literal.value; raw; })) | T_LPAREN -> Cover_expr (group env) | T_LCURLY -> let loc, obj, errs = Parse.object_initializer env in Cover_patt ((loc, Expression.Object obj), errs) | T_LBRACKET -> let loc, arr, errs = array_initializer env in Cover_patt ((loc, Expression.Array arr), errs) | T_DIV | T_DIV_ASSIGN -> Cover_expr (regexp env) | T_LESS_THAN -> let loc, expression = match Parse.jsx_element_or_fragment env with | (loc, `Element e) -> (loc, Expression.JSXElement e) | (loc, `Fragment f) -> (loc, Expression.JSXFragment f) in Cover_expr (loc, expression) | T_TEMPLATE_PART part -> let loc, template = template_literal env part in Cover_expr (loc, Expression.TemplateLiteral template) | T_CLASS -> Cover_expr (Parse.class_expression env) | _ when Peek.is_identifier env -> let id = Parse.identifier env in Cover_expr (fst id, Expression.Identifier id) | t -> error_unexpected env; begin match t with T_ERROR _ -> Eat.token env | _ -> () end; let value = Literal.Null in let raw = "null" in Cover_expr (loc, Expression.(Literal { Literal.value; raw; })) and primary env = as_expression env (primary_cover env) and template_literal = let rec template_parts env quasis expressions = let expr = Parse.expression env in let expressions = expr::expressions in match Peek.token env with | T_RCURLY -> Eat.push_lex_mode env Lex_mode.TEMPLATE; let loc, part, is_tail = match Peek.token env with | T_TEMPLATE_PART (loc, {cooked; raw; _}, tail) -> let open Ast.Expression.TemplateLiteral in Eat.token env; loc, { Element.value = { Element.cooked; raw; }; tail; }, tail | _ -> assert false in Eat.pop_lex_mode env; let quasis = (loc, part)::quasis in if is_tail then loc, List.rev quasis, List.rev expressions else template_parts env quasis expressions | _ -> error_unexpected env; let imaginary_quasi = fst expr, { Expression.TemplateLiteral.Element. value = { Expression.TemplateLiteral.Element. raw = ""; cooked = ""; }; tail = true; } in fst expr, List.rev (imaginary_quasi::quasis), List.rev expressions in fun env ((start_loc, {cooked; raw; _}, is_tail) as part) -> Expect.token env (T_TEMPLATE_PART part); let end_loc, quasis, expressions = let head = Ast.Expression.TemplateLiteral.(start_loc, { Element.value = { Element.cooked; raw; }; tail = is_tail; }) in if is_tail then start_loc, [head], [] else template_parts env [head] [] in let loc = Loc.btwn start_loc end_loc in loc, Expression.TemplateLiteral.({ quasis; expressions; }) and tagged_template env start_loc tag part = let quasi = template_literal env part in Loc.btwn start_loc (fst quasi), Expression.(TaggedTemplate TaggedTemplate.({ tag; quasi; })) and group env = Expect.token env T_LPAREN; let expression = assignment env in let ret = (match Peek.token env with | T_COMMA -> sequence env [expression] | T_COLON -> let annot = Type.annotation env in Expression.(Loc.btwn (fst expression) (fst annot), TypeCast TypeCast.({ expression; annot; })) | _ -> expression) in Expect.token env T_RPAREN; ret and array_initializer = let rec elements env (acc, errs) = match Peek.token env with | T_EOF | T_RBRACKET -> List.rev acc, Pattern_cover.rev_errors errs | T_COMMA -> Expect.token env T_COMMA; elements env (None::acc, errs) | T_ELLIPSIS -> let loc, (argument, new_errs) = with_loc (fun env -> Expect.token env T_ELLIPSIS; match assignment_cover env with | Cover_expr argument -> argument, Pattern_cover.empty_errors | Cover_patt (argument, new_errs) -> argument, new_errs ) env in let elem = Expression.(Spread (loc, SpreadElement.({ argument; }))) in let is_last = Peek.token env = T_RBRACKET in let new_errs = if not is_last && Peek.ith_token ~i:1 env = T_RBRACKET then let if_patt = (loc, Parse_error.ElementAfterRestElement)::new_errs.if_patt in { new_errs with if_patt } else new_errs in if not is_last then Expect.token env T_COMMA; let acc = Some elem :: acc in let errs = Pattern_cover.rev_append_errors new_errs errs in elements env (acc, errs) | _ -> let elem, new_errs = match assignment_cover env with | Cover_expr elem -> elem, Pattern_cover.empty_errors | Cover_patt (elem, new_errs) -> elem, new_errs in if Peek.token env <> T_RBRACKET then Expect.token env T_COMMA; let acc = Some (Expression.Expression elem) :: acc in let errs = Pattern_cover.rev_append_errors new_errs errs in elements env (acc, errs) in fun env -> let loc, (elements, errs) = with_loc (fun env -> Expect.token env T_LBRACKET; let res = elements env ([], Pattern_cover.empty_errors) in Expect.token env T_RBRACKET; res ) env in loc, { Expression.Array.elements; }, errs and regexp env = Eat.push_lex_mode env Lex_mode.REGEXP; let loc = Peek.loc env in let raw, pattern, raw_flags = match Peek.token env with | T_REGEXP (_, pattern, flags) -> Eat.token env; let raw = "/" ^ pattern ^ "/" ^ flags in raw, pattern, flags | _ -> assert false in Eat.pop_lex_mode env; let filtered_flags = Buffer.create (String.length raw_flags) in String.iter (function | 'g' | 'i' | 'm' | 's' | 'u' | 'y' as c -> Buffer.add_char filtered_flags c | _ -> ()) raw_flags; let flags = Buffer.contents filtered_flags in if flags <> raw_flags then error env (Error.InvalidRegExpFlags raw_flags); let value = Literal.(RegExp { RegExp.pattern; flags; }) in loc, Expression.(Literal { Literal.value; raw; }) and try_arrow_function = let error_callback _ = Error.(function | StrictParamName | StrictReservedWord | ParameterAfterRestParameter | NewlineBeforeArrow | YieldInFormalParameters -> () | _ -> raise Try.Rollback) in let concise_function_body env ~async = let env = enter_function env ~async ~generator:false in match Peek.token env with | T_LCURLY -> let loc, body, strict = Parse.function_block_body env in Function.BodyBlock (loc, body), strict | _ -> let expr = Parse.assignment env in Function.BodyExpression expr, in_strict_mode env in fun env -> let env = env |> with_error_callback error_callback in let start_loc = Peek.loc env in let async = Peek.ith_token ~i:1 env <> T_ARROW && Declaration.async env in let sig_loc, (tparams, params, return, predicate) = with_loc (fun env -> let tparams = Type.type_parameter_declaration env in if Peek.is_identifier env && tparams = None then let (loc, _) as name = Parse.identifier ~restricted_error:Error.StrictParamName env in let param = loc, { Ast.Function.Param. argument = loc, Pattern.Identifier { Pattern.Identifier. name; annot = Ast.Type.Missing (Peek.loc_skip_lookahead env); optional = false; }; default = None; } in tparams, (loc, { Ast.Function.Params.params = [param]; rest = None }), Ast.Type.Missing Loc.({ loc with start = loc._end }), None else let params = let yield = allow_yield env in let await = allow_await env in Declaration.function_params ~await ~yield env in let return, predicate = env |> with_no_anon_function_type true |> Type.annotation_and_predicate_opt in tparams, params, return, predicate ) env in It 's hard to tell if an invalid expression was intended to be an * arrow function before we see the = > . If there are no params , that * implies " ( ) " which is only ever found in arrow params . Similarly , * rest params indicate arrow functions . Therefore , if we see a rest * param or an empty param list then we can disable the rollback and * instead generate errors as if we were parsing an arrow function * arrow function before we see the =>. If there are no params, that * implies "()" which is only ever found in arrow params. Similarly, * rest params indicate arrow functions. Therefore, if we see a rest * param or an empty param list then we can disable the rollback and * instead generate errors as if we were parsing an arrow function *) let env = match params with | _, { Ast.Function.Params.rest = Some _; _ } | _, { Ast.Function.Params.params = []; _ } -> without_error_callback env | _ -> env in if Peek.is_line_terminator env && Peek.token env = T_ARROW then error env Error.NewlineBeforeArrow; Expect.token env T_ARROW; let env = without_error_callback env in let end_loc, (body, strict) = with_loc (concise_function_body ~async) env in let simple = Declaration.is_simple_function_params params in Declaration.strict_post_check env ~strict ~simple None params; let loc = Loc.btwn start_loc end_loc in Cover_expr (loc, Expression.(ArrowFunction { Function. id = None; params; body; async; predicate; return; tparams; sig_loc; })) and sequence env acc = match Peek.token env with | T_COMMA -> Expect.token env T_COMMA; let expr = assignment env in sequence env (expr::acc) | _ -> let (last_loc, _) = List.hd acc in let expressions = List.rev acc in let (first_loc, _) = List.hd expressions in Loc.btwn first_loc last_loc, Expression.(Sequence Sequence.({ expressions; })) and property_name_include_private env = let start_loc = Peek.loc env in let is_private = Expect.maybe env T_POUND in let id_loc, ident = identifier_name env in let loc = Loc.btwn start_loc id_loc in loc, (id_loc, ident), is_private end
395d09acce986421a1db54ceba493be064cd4950afc0474b51a7007d07ef23ca
martijnbastiaan/doctest-parallel
Example.hs
module Test.DocTest.Internal.Runner.Example ( Result (..) , mkResult ) where import Data.Char import Data.List import Test.DocTest.Internal.Util import Test.DocTest.Internal.Parse maxBy :: (Ord a) => (b -> a) -> b -> b -> b maxBy f x y = case compare (f x) (f y) of LT -> y EQ -> x GT -> x data Result = Equal | NotEqual [String] deriving (Eq, Show) mkResult :: ExpectedResult -> [String] -> Result mkResult expected_ actual_ = case expected `matches` actual of Full -> Equal Partial partial -> NotEqual (formatNotEqual expected actual partial) where -- use show to escape special characters in output lines if any output line -- contains any unsafe character escapeOutput | any (not . isSafe) $ concat (expectedAsString ++ actual_) = init . tail . show . stripEnd | otherwise = id actual :: [String] actual = fmap escapeOutput actual_ expected :: ExpectedResult expected = fmap (transformExcpectedLine escapeOutput) expected_ expectedAsString :: [String] expectedAsString = map (\x -> case x of ExpectedLine str -> concatMap lineChunkToString str WildCardLine -> "..." ) expected_ isSafe :: Char -> Bool isSafe c = c == ' ' || (isPrint c && (not . isSpace) c) chunksMatch :: [LineChunk] -> String -> Match ChunksDivergence chunksMatch [] "" = Full chunksMatch [LineChunk xs] ys = if stripEnd xs == stripEnd ys then Full else Partial $ matchingPrefix xs ys chunksMatch (LineChunk x : xs) ys = if x `isPrefixOf` ys then fmap (prependText x) $ (xs `chunksMatch` drop (length x) ys) else Partial $ matchingPrefix x ys chunksMatch zs@(WildCardChunk : xs) (_:ys) = -- Prefer longer matches. fmap prependWildcard $ maxBy (fmap $ length . matchText) (chunksMatch xs ys) (chunksMatch zs ys) chunksMatch [WildCardChunk] [] = Full chunksMatch (WildCardChunk:_) [] = Partial (ChunksDivergence "" "") chunksMatch [] (_:_) = Partial (ChunksDivergence "" "") matchingPrefix xs ys = let common = fmap fst (takeWhile (\(x, y) -> x == y) (xs `zip` ys)) in ChunksDivergence common common matches :: ExpectedResult -> [String] -> Match LinesDivergence matches (ExpectedLine x : xs) (y : ys) = case x `chunksMatch` y of Full -> fmap incLineNo $ xs `matches` ys Partial partial -> Partial (LinesDivergence 1 (expandedWildcards partial)) matches zs@(WildCardLine : xs) us@(_ : ys) = -- Prefer longer matches, and later ones of equal length. let matchWithoutWC = xs `matches` us in let matchWithWC = fmap incLineNo (zs `matches` ys) in let key (LinesDivergence lineNo line) = (length line, lineNo) in maxBy (fmap key) matchWithoutWC matchWithWC matches [WildCardLine] [] = Full matches [] [] = Full matches [] _ = Partial (LinesDivergence 1 "") matches _ [] = Partial (LinesDivergence 1 "") -- Note: order of constructors matters, so that full matches sort as -- greater than partial. data Match a = Partial a | Full deriving (Eq, Ord, Show) instance Functor Match where fmap f (Partial a) = Partial (f a) fmap _ Full = Full data ChunksDivergence = ChunksDivergence { matchText :: String, expandedWildcards :: String } deriving (Show) prependText :: String -> ChunksDivergence -> ChunksDivergence prependText s (ChunksDivergence mt wct) = ChunksDivergence (s++mt) (s++wct) prependWildcard :: ChunksDivergence -> ChunksDivergence prependWildcard (ChunksDivergence mt wct) = ChunksDivergence mt ('.':wct) data LinesDivergence = LinesDivergence { _mismatchLineNo :: Int, _partialLine :: String } deriving (Show) incLineNo :: LinesDivergence -> LinesDivergence incLineNo (LinesDivergence lineNo partialLineMatch) = LinesDivergence (lineNo + 1) partialLineMatch formatNotEqual :: ExpectedResult -> [String] -> LinesDivergence -> [String] formatNotEqual expected_ actual partial = formatLines "expected: " expected ++ formatLines " but got: " (lineMarker wildcard partial actual) where expected :: [String] expected = map (\x -> case x of ExpectedLine str -> concatMap lineChunkToString str WildCardLine -> "..." ) expected_ formatLines :: String -> [String] -> [String] formatLines message xs = case xs of y:ys -> (message ++ y) : map (padding ++) ys [] -> [message] where padding = replicate (length message) ' ' wildcard :: Bool wildcard = any (\x -> case x of ExpectedLine xs -> any (\y -> case y of { WildCardChunk -> True; _ -> False }) xs WildCardLine -> True ) expected_ lineChunkToString :: LineChunk -> String lineChunkToString WildCardChunk = "..." lineChunkToString (LineChunk str) = str transformExcpectedLine :: (String -> String) -> ExpectedLine -> ExpectedLine transformExcpectedLine f (ExpectedLine xs) = ExpectedLine $ fmap (\el -> case el of LineChunk s -> LineChunk $ f s WildCardChunk -> WildCardChunk ) xs transformExcpectedLine _ WildCardLine = WildCardLine lineMarker :: Bool -> LinesDivergence -> [String] -> [String] lineMarker wildcard (LinesDivergence row expanded) actual = let (pre, post) = splitAt row actual in pre ++ [(if wildcard && length expanded > 30 -- show expanded pattern if match is long, to help understanding what matched what then expanded else replicate (length expanded) ' ') ++ "^"] ++ post
null
https://raw.githubusercontent.com/martijnbastiaan/doctest-parallel/f70d6a1c946cc0ada88571b90a39a7cd4d065452/src/Test/DocTest/Internal/Runner/Example.hs
haskell
use show to escape special characters in output lines if any output line contains any unsafe character Prefer longer matches. Prefer longer matches, and later ones of equal length. Note: order of constructors matters, so that full matches sort as greater than partial. show expanded pattern if match is long, to help understanding what matched what
module Test.DocTest.Internal.Runner.Example ( Result (..) , mkResult ) where import Data.Char import Data.List import Test.DocTest.Internal.Util import Test.DocTest.Internal.Parse maxBy :: (Ord a) => (b -> a) -> b -> b -> b maxBy f x y = case compare (f x) (f y) of LT -> y EQ -> x GT -> x data Result = Equal | NotEqual [String] deriving (Eq, Show) mkResult :: ExpectedResult -> [String] -> Result mkResult expected_ actual_ = case expected `matches` actual of Full -> Equal Partial partial -> NotEqual (formatNotEqual expected actual partial) where escapeOutput | any (not . isSafe) $ concat (expectedAsString ++ actual_) = init . tail . show . stripEnd | otherwise = id actual :: [String] actual = fmap escapeOutput actual_ expected :: ExpectedResult expected = fmap (transformExcpectedLine escapeOutput) expected_ expectedAsString :: [String] expectedAsString = map (\x -> case x of ExpectedLine str -> concatMap lineChunkToString str WildCardLine -> "..." ) expected_ isSafe :: Char -> Bool isSafe c = c == ' ' || (isPrint c && (not . isSpace) c) chunksMatch :: [LineChunk] -> String -> Match ChunksDivergence chunksMatch [] "" = Full chunksMatch [LineChunk xs] ys = if stripEnd xs == stripEnd ys then Full else Partial $ matchingPrefix xs ys chunksMatch (LineChunk x : xs) ys = if x `isPrefixOf` ys then fmap (prependText x) $ (xs `chunksMatch` drop (length x) ys) else Partial $ matchingPrefix x ys chunksMatch zs@(WildCardChunk : xs) (_:ys) = fmap prependWildcard $ maxBy (fmap $ length . matchText) (chunksMatch xs ys) (chunksMatch zs ys) chunksMatch [WildCardChunk] [] = Full chunksMatch (WildCardChunk:_) [] = Partial (ChunksDivergence "" "") chunksMatch [] (_:_) = Partial (ChunksDivergence "" "") matchingPrefix xs ys = let common = fmap fst (takeWhile (\(x, y) -> x == y) (xs `zip` ys)) in ChunksDivergence common common matches :: ExpectedResult -> [String] -> Match LinesDivergence matches (ExpectedLine x : xs) (y : ys) = case x `chunksMatch` y of Full -> fmap incLineNo $ xs `matches` ys Partial partial -> Partial (LinesDivergence 1 (expandedWildcards partial)) matches zs@(WildCardLine : xs) us@(_ : ys) = let matchWithoutWC = xs `matches` us in let matchWithWC = fmap incLineNo (zs `matches` ys) in let key (LinesDivergence lineNo line) = (length line, lineNo) in maxBy (fmap key) matchWithoutWC matchWithWC matches [WildCardLine] [] = Full matches [] [] = Full matches [] _ = Partial (LinesDivergence 1 "") matches _ [] = Partial (LinesDivergence 1 "") data Match a = Partial a | Full deriving (Eq, Ord, Show) instance Functor Match where fmap f (Partial a) = Partial (f a) fmap _ Full = Full data ChunksDivergence = ChunksDivergence { matchText :: String, expandedWildcards :: String } deriving (Show) prependText :: String -> ChunksDivergence -> ChunksDivergence prependText s (ChunksDivergence mt wct) = ChunksDivergence (s++mt) (s++wct) prependWildcard :: ChunksDivergence -> ChunksDivergence prependWildcard (ChunksDivergence mt wct) = ChunksDivergence mt ('.':wct) data LinesDivergence = LinesDivergence { _mismatchLineNo :: Int, _partialLine :: String } deriving (Show) incLineNo :: LinesDivergence -> LinesDivergence incLineNo (LinesDivergence lineNo partialLineMatch) = LinesDivergence (lineNo + 1) partialLineMatch formatNotEqual :: ExpectedResult -> [String] -> LinesDivergence -> [String] formatNotEqual expected_ actual partial = formatLines "expected: " expected ++ formatLines " but got: " (lineMarker wildcard partial actual) where expected :: [String] expected = map (\x -> case x of ExpectedLine str -> concatMap lineChunkToString str WildCardLine -> "..." ) expected_ formatLines :: String -> [String] -> [String] formatLines message xs = case xs of y:ys -> (message ++ y) : map (padding ++) ys [] -> [message] where padding = replicate (length message) ' ' wildcard :: Bool wildcard = any (\x -> case x of ExpectedLine xs -> any (\y -> case y of { WildCardChunk -> True; _ -> False }) xs WildCardLine -> True ) expected_ lineChunkToString :: LineChunk -> String lineChunkToString WildCardChunk = "..." lineChunkToString (LineChunk str) = str transformExcpectedLine :: (String -> String) -> ExpectedLine -> ExpectedLine transformExcpectedLine f (ExpectedLine xs) = ExpectedLine $ fmap (\el -> case el of LineChunk s -> LineChunk $ f s WildCardChunk -> WildCardChunk ) xs transformExcpectedLine _ WildCardLine = WildCardLine lineMarker :: Bool -> LinesDivergence -> [String] -> [String] lineMarker wildcard (LinesDivergence row expanded) actual = let (pre, post) = splitAt row actual in pre ++ [(if wildcard && length expanded > 30 then expanded else replicate (length expanded) ' ') ++ "^"] ++ post
111c04b51eef0b0e95061f2ab33b846e17241e9cf0cc98fa3d25e6feca13822e
aws-beam/aws-erlang
aws_codeguru_reviewer.erl
%% WARNING: DO NOT EDIT, AUTO-GENERATED CODE! See -beam/aws-codegen for more details . @doc This section provides documentation for the Amazon CodeGuru Reviewer %% API operations. %% CodeGuru Reviewer is a service that uses program analysis and machine %% learning to detect potential defects that are difficult for developers to find and recommends fixes in your Java and Python code . %% %% By proactively detecting and providing recommendations for addressing code defects and implementing best practices , CodeGuru Reviewer improves the %% overall quality and maintainability of your code base during the code review stage . For more information about CodeGuru Reviewer , see the Amazon CodeGuru Reviewer User Guide . %% To improve the security of your CodeGuru Reviewer API calls , you can establish a private connection between your VPC and CodeGuru Reviewer by creating an interface VPC endpoint . For more information , see CodeGuru Reviewer and interface VPC endpoints ( Amazon Web Services PrivateLink ) in the Amazon CodeGuru Reviewer User Guide . -module(aws_codeguru_reviewer). -export([associate_repository/2, associate_repository/3, create_code_review/2, create_code_review/3, describe_code_review/2, describe_code_review/4, describe_code_review/5, describe_recommendation_feedback/3, describe_recommendation_feedback/5, describe_recommendation_feedback/6, describe_repository_association/2, describe_repository_association/4, describe_repository_association/5, disassociate_repository/3, disassociate_repository/4, list_code_reviews/2, list_code_reviews/4, list_code_reviews/5, list_recommendation_feedback/2, list_recommendation_feedback/4, list_recommendation_feedback/5, list_recommendations/2, list_recommendations/4, list_recommendations/5, list_repository_associations/1, list_repository_associations/3, list_repository_associations/4, list_tags_for_resource/2, list_tags_for_resource/4, list_tags_for_resource/5, put_recommendation_feedback/2, put_recommendation_feedback/3, tag_resource/3, tag_resource/4, untag_resource/3, untag_resource/4]). -include_lib("hackney/include/hackney_lib.hrl"). %%==================================================================== %% API %%==================================================================== @doc Use to associate an Amazon Web Services CodeCommit repository or a repository managed by Amazon Web Services CodeStar Connections with Amazon CodeGuru Reviewer . %% When you associate a repository , CodeGuru Reviewer reviews source code %% changes in the repository's pull requests and provides automatic recommendations . You can view recommendations using the CodeGuru Reviewer console . For more information , see Recommendations in Amazon CodeGuru Reviewer in the Amazon CodeGuru Reviewer User Guide . %% If you associate a CodeCommit or S3 repository , it must be in the same Amazon Web Services Region and Amazon Web Services account where its CodeGuru Reviewer code reviews are configured . %% Bitbucket and GitHub Enterprise Server repositories are managed by Amazon Web Services CodeStar Connections to connect to CodeGuru Reviewer . For more information , see Associate a repository in the Amazon CodeGuru %% Reviewer User Guide. %% You can not use the CodeGuru Reviewer SDK or the Amazon Web Services CLI to associate a GitHub repository with Amazon CodeGuru Reviewer . To associate a GitHub repository , use the console . For more information , see Getting started with CodeGuru Reviewer in the CodeGuru Reviewer User Guide . associate_repository(Client, Input) -> associate_repository(Client, Input, []). associate_repository(Client, Input0, Options0) -> Method = post, Path = ["/associations"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Use to create a code review with a CodeReviewType of ` RepositoryAnalysis ' . %% %% This type of code review analyzes all code under a specified branch in an associated repository . ` PullRequest ' code reviews are automatically %% triggered by a pull request. create_code_review(Client, Input) -> create_code_review(Client, Input, []). create_code_review(Client, Input0, Options0) -> Method = post, Path = ["/codereviews"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Returns the metadata associated with the code review along with its %% status. describe_code_review(Client, CodeReviewArn) when is_map(Client) -> describe_code_review(Client, CodeReviewArn, #{}, #{}). describe_code_review(Client, CodeReviewArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_code_review(Client, CodeReviewArn, QueryMap, HeadersMap, []). describe_code_review(Client, CodeReviewArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/codereviews/", aws_util:encode_uri(CodeReviewArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Describes the customer feedback for a CodeGuru Reviewer %% recommendation. describe_recommendation_feedback(Client, CodeReviewArn, RecommendationId) when is_map(Client) -> describe_recommendation_feedback(Client, CodeReviewArn, RecommendationId, #{}, #{}). describe_recommendation_feedback(Client, CodeReviewArn, RecommendationId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_recommendation_feedback(Client, CodeReviewArn, RecommendationId, QueryMap, HeadersMap, []). describe_recommendation_feedback(Client, CodeReviewArn, RecommendationId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/feedback/", aws_util:encode_uri(CodeReviewArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"RecommendationId">>, RecommendationId}, {<<"UserId">>, maps:get(<<"UserId">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns a RepositoryAssociation object that contains information %% about the requested repository association. describe_repository_association(Client, AssociationArn) when is_map(Client) -> describe_repository_association(Client, AssociationArn, #{}, #{}). describe_repository_association(Client, AssociationArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_repository_association(Client, AssociationArn, QueryMap, HeadersMap, []). describe_repository_association(Client, AssociationArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/associations/", aws_util:encode_uri(AssociationArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Removes the association between Amazon CodeGuru Reviewer and a %% repository. disassociate_repository(Client, AssociationArn, Input) -> disassociate_repository(Client, AssociationArn, Input, []). disassociate_repository(Client, AssociationArn, Input0, Options0) -> Method = delete, Path = ["/associations/", aws_util:encode_uri(AssociationArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Lists all the code reviews that the customer has created in the past 90 days . list_code_reviews(Client, Type) when is_map(Client) -> list_code_reviews(Client, Type, #{}, #{}). list_code_reviews(Client, Type, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_code_reviews(Client, Type, QueryMap, HeadersMap, []). list_code_reviews(Client, Type, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/codereviews"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"MaxResults">>, maps:get(<<"MaxResults">>, QueryMap, undefined)}, {<<"NextToken">>, maps:get(<<"NextToken">>, QueryMap, undefined)}, {<<"ProviderTypes">>, maps:get(<<"ProviderTypes">>, QueryMap, undefined)}, {<<"RepositoryNames">>, maps:get(<<"RepositoryNames">>, QueryMap, undefined)}, {<<"States">>, maps:get(<<"States">>, QueryMap, undefined)}, {<<"Type">>, Type} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns a list of RecommendationFeedbackSummary objects that contain customer recommendation feedback for all CodeGuru Reviewer users . list_recommendation_feedback(Client, CodeReviewArn) when is_map(Client) -> list_recommendation_feedback(Client, CodeReviewArn, #{}, #{}). list_recommendation_feedback(Client, CodeReviewArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_recommendation_feedback(Client, CodeReviewArn, QueryMap, HeadersMap, []). list_recommendation_feedback(Client, CodeReviewArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/feedback/", aws_util:encode_uri(CodeReviewArn), "/RecommendationFeedback"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"MaxResults">>, maps:get(<<"MaxResults">>, QueryMap, undefined)}, {<<"NextToken">>, maps:get(<<"NextToken">>, QueryMap, undefined)}, {<<"RecommendationIds">>, maps:get(<<"RecommendationIds">>, QueryMap, undefined)}, {<<"UserIds">>, maps:get(<<"UserIds">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns the list of all recommendations for a completed code review. list_recommendations(Client, CodeReviewArn) when is_map(Client) -> list_recommendations(Client, CodeReviewArn, #{}, #{}). list_recommendations(Client, CodeReviewArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_recommendations(Client, CodeReviewArn, QueryMap, HeadersMap, []). list_recommendations(Client, CodeReviewArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/codereviews/", aws_util:encode_uri(CodeReviewArn), "/Recommendations"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"MaxResults">>, maps:get(<<"MaxResults">>, QueryMap, undefined)}, {<<"NextToken">>, maps:get(<<"NextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns a list of RepositoryAssociationSummary objects that contain %% summary information about a repository association. %% You can filter the returned list by ProviderType , Name , State , and Owner . list_repository_associations(Client) when is_map(Client) -> list_repository_associations(Client, #{}, #{}). list_repository_associations(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_repository_associations(Client, QueryMap, HeadersMap, []). list_repository_associations(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/associations"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"MaxResults">>, maps:get(<<"MaxResults">>, QueryMap, undefined)}, {<<"Name">>, maps:get(<<"Name">>, QueryMap, undefined)}, {<<"NextToken">>, maps:get(<<"NextToken">>, QueryMap, undefined)}, {<<"Owner">>, maps:get(<<"Owner">>, QueryMap, undefined)}, {<<"ProviderType">>, maps:get(<<"ProviderType">>, QueryMap, undefined)}, {<<"State">>, maps:get(<<"State">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). %% @doc Returns the list of tags associated with an associated repository %% resource. list_tags_for_resource(Client, ResourceArn) when is_map(Client) -> list_tags_for_resource(Client, ResourceArn, #{}, #{}). list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, []). list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Stores customer feedback for a CodeGuru Reviewer recommendation . %% %% When this API is called again with different reactions the previous %% feedback is overwritten. put_recommendation_feedback(Client, Input) -> put_recommendation_feedback(Client, Input, []). put_recommendation_feedback(Client, Input0, Options0) -> Method = put, Path = ["/feedback"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Adds one or more tags to an associated repository . tag_resource(Client, ResourceArn, Input) -> tag_resource(Client, ResourceArn, Input, []). tag_resource(Client, ResourceArn, Input0, Options0) -> Method = post, Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %% @doc Removes a tag from an associated repository. untag_resource(Client, ResourceArn, Input) -> untag_resource(Client, ResourceArn, Input, []). untag_resource(Client, ResourceArn, Input0, Options0) -> Method = delete, Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"tagKeys">>, <<"TagKeys">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). %%==================================================================== Internal functions %%==================================================================== -spec request(aws_client:aws_client(), atom(), iolist(), list(), list(), map() | undefined, list(), pos_integer() | undefined) -> {ok, {integer(), list()}} | {ok, Result, {integer(), list(), hackney:client()}} | {error, Error, {integer(), list(), hackney:client()}} | {error, term()} when Result :: map(), Error :: map(). request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end, aws_request:request(RequestFun, Options). do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> Client1 = Client#{service => <<"codeguru-reviewer">>}, Host = build_host(<<"codeguru-reviewer">>, Client1), URL0 = build_url(Host, Path, Client1), URL = aws_request:add_query(URL0, Query), AdditionalHeaders1 = [ {<<"Host">>, Host} , {<<"Content-Type">>, <<"application/x-amz-json-1.1">>} ], Payload = case proplists:get_value(send_body_as_binary, Options) of true -> maps:get(<<"Body">>, Input, <<"">>); false -> encode_payload(Input) end, AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of true -> add_checksum_hash_header(AdditionalHeaders1, Payload); false -> AdditionalHeaders1 end, Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0), MethodBin = aws_request:method_to_binary(Method), SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload), Response = hackney:request(Method, URL, SignedHeaders, Payload, Options), DecodeBody = not proplists:get_value(receive_body_as_binary, Options), handle_response(Response, SuccessStatusCode, DecodeBody). add_checksum_hash_header(Headers, Body) -> [ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))} | Headers ]. handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> {ok, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) -> {error, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> case hackney:body(Client) of {ok, <<>>} when StatusCode =:= 200; StatusCode =:= SuccessStatusCode -> {ok, #{}, {StatusCode, ResponseHeaders, Client}}; {ok, Body} -> Result = case DecodeBody of true -> try jsx:decode(Body) catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; false -> #{<<"Body">> => Body} end, {ok, Result, {StatusCode, ResponseHeaders, Client}} end; handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody) when StatusCode =:= 503 -> Retriable error if retries are enabled {error, service_unavailable}; handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) -> {ok, Body} = hackney:body(Client), try DecodedError = jsx:decode(Body), {error, DecodedError, {StatusCode, ResponseHeaders, Client}} catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; handle_response({error, Reason}, _, _DecodeBody) -> {error, Reason}. build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) -> Endpoint; build_host(_EndpointPrefix, #{region := <<"local">>}) -> <<"localhost">>; build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) -> aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>). build_url(Host, Path0, Client) -> Proto = aws_client:proto(Client), Path = erlang:iolist_to_binary(Path0), Port = aws_client:port(Client), aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>). -spec encode_payload(undefined | map()) -> binary(). encode_payload(undefined) -> <<>>; encode_payload(Input) -> jsx:encode(Input).
null
https://raw.githubusercontent.com/aws-beam/aws-erlang/699287cee7dfc9dc8c08ced5f090dcc192c9cba8/src/aws_codeguru_reviewer.erl
erlang
WARNING: DO NOT EDIT, AUTO-GENERATED CODE! API operations. learning to detect potential defects that are difficult for developers to By proactively detecting and providing recommendations for addressing code overall quality and maintainability of your code base during the code ==================================================================== API ==================================================================== changes in the repository's pull requests and provides automatic Reviewer User Guide. This type of code review analyzes all code under a specified branch in an triggered by a pull request. @doc Returns the metadata associated with the code review along with its status. recommendation. @doc Returns a RepositoryAssociation object that contains information about the requested repository association. repository. @doc Lists all the code reviews that the customer has created in the past @doc Returns a list of RecommendationFeedbackSummary objects that contain @doc Returns the list of all recommendations for a completed code review. @doc Returns a list of RepositoryAssociationSummary objects that contain summary information about a repository association. @doc Returns the list of tags associated with an associated repository resource. When this API is called again with different reactions the previous feedback is overwritten. @doc Removes a tag from an associated repository. ==================================================================== ====================================================================
See -beam/aws-codegen for more details . @doc This section provides documentation for the Amazon CodeGuru Reviewer CodeGuru Reviewer is a service that uses program analysis and machine find and recommends fixes in your Java and Python code . defects and implementing best practices , CodeGuru Reviewer improves the review stage . For more information about CodeGuru Reviewer , see the Amazon CodeGuru Reviewer User Guide . To improve the security of your CodeGuru Reviewer API calls , you can establish a private connection between your VPC and CodeGuru Reviewer by creating an interface VPC endpoint . For more information , see CodeGuru Reviewer and interface VPC endpoints ( Amazon Web Services PrivateLink ) in the Amazon CodeGuru Reviewer User Guide . -module(aws_codeguru_reviewer). -export([associate_repository/2, associate_repository/3, create_code_review/2, create_code_review/3, describe_code_review/2, describe_code_review/4, describe_code_review/5, describe_recommendation_feedback/3, describe_recommendation_feedback/5, describe_recommendation_feedback/6, describe_repository_association/2, describe_repository_association/4, describe_repository_association/5, disassociate_repository/3, disassociate_repository/4, list_code_reviews/2, list_code_reviews/4, list_code_reviews/5, list_recommendation_feedback/2, list_recommendation_feedback/4, list_recommendation_feedback/5, list_recommendations/2, list_recommendations/4, list_recommendations/5, list_repository_associations/1, list_repository_associations/3, list_repository_associations/4, list_tags_for_resource/2, list_tags_for_resource/4, list_tags_for_resource/5, put_recommendation_feedback/2, put_recommendation_feedback/3, tag_resource/3, tag_resource/4, untag_resource/3, untag_resource/4]). -include_lib("hackney/include/hackney_lib.hrl"). @doc Use to associate an Amazon Web Services CodeCommit repository or a repository managed by Amazon Web Services CodeStar Connections with Amazon CodeGuru Reviewer . When you associate a repository , CodeGuru Reviewer reviews source code recommendations . You can view recommendations using the CodeGuru Reviewer console . For more information , see Recommendations in Amazon CodeGuru Reviewer in the Amazon CodeGuru Reviewer User Guide . If you associate a CodeCommit or S3 repository , it must be in the same Amazon Web Services Region and Amazon Web Services account where its CodeGuru Reviewer code reviews are configured . Bitbucket and GitHub Enterprise Server repositories are managed by Amazon Web Services CodeStar Connections to connect to CodeGuru Reviewer . For more information , see Associate a repository in the Amazon CodeGuru You can not use the CodeGuru Reviewer SDK or the Amazon Web Services CLI to associate a GitHub repository with Amazon CodeGuru Reviewer . To associate a GitHub repository , use the console . For more information , see Getting started with CodeGuru Reviewer in the CodeGuru Reviewer User Guide . associate_repository(Client, Input) -> associate_repository(Client, Input, []). associate_repository(Client, Input0, Options0) -> Method = post, Path = ["/associations"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Use to create a code review with a CodeReviewType of ` RepositoryAnalysis ' . associated repository . ` PullRequest ' code reviews are automatically create_code_review(Client, Input) -> create_code_review(Client, Input, []). create_code_review(Client, Input0, Options0) -> Method = post, Path = ["/codereviews"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). describe_code_review(Client, CodeReviewArn) when is_map(Client) -> describe_code_review(Client, CodeReviewArn, #{}, #{}). describe_code_review(Client, CodeReviewArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_code_review(Client, CodeReviewArn, QueryMap, HeadersMap, []). describe_code_review(Client, CodeReviewArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/codereviews/", aws_util:encode_uri(CodeReviewArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Describes the customer feedback for a CodeGuru Reviewer describe_recommendation_feedback(Client, CodeReviewArn, RecommendationId) when is_map(Client) -> describe_recommendation_feedback(Client, CodeReviewArn, RecommendationId, #{}, #{}). describe_recommendation_feedback(Client, CodeReviewArn, RecommendationId, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_recommendation_feedback(Client, CodeReviewArn, RecommendationId, QueryMap, HeadersMap, []). describe_recommendation_feedback(Client, CodeReviewArn, RecommendationId, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/feedback/", aws_util:encode_uri(CodeReviewArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"RecommendationId">>, RecommendationId}, {<<"UserId">>, maps:get(<<"UserId">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). describe_repository_association(Client, AssociationArn) when is_map(Client) -> describe_repository_association(Client, AssociationArn, #{}, #{}). describe_repository_association(Client, AssociationArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> describe_repository_association(Client, AssociationArn, QueryMap, HeadersMap, []). describe_repository_association(Client, AssociationArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/associations/", aws_util:encode_uri(AssociationArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Removes the association between Amazon CodeGuru Reviewer and a disassociate_repository(Client, AssociationArn, Input) -> disassociate_repository(Client, AssociationArn, Input, []). disassociate_repository(Client, AssociationArn, Input0, Options0) -> Method = delete, Path = ["/associations/", aws_util:encode_uri(AssociationArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). 90 days . list_code_reviews(Client, Type) when is_map(Client) -> list_code_reviews(Client, Type, #{}, #{}). list_code_reviews(Client, Type, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_code_reviews(Client, Type, QueryMap, HeadersMap, []). list_code_reviews(Client, Type, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/codereviews"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"MaxResults">>, maps:get(<<"MaxResults">>, QueryMap, undefined)}, {<<"NextToken">>, maps:get(<<"NextToken">>, QueryMap, undefined)}, {<<"ProviderTypes">>, maps:get(<<"ProviderTypes">>, QueryMap, undefined)}, {<<"RepositoryNames">>, maps:get(<<"RepositoryNames">>, QueryMap, undefined)}, {<<"States">>, maps:get(<<"States">>, QueryMap, undefined)}, {<<"Type">>, Type} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). customer recommendation feedback for all CodeGuru Reviewer users . list_recommendation_feedback(Client, CodeReviewArn) when is_map(Client) -> list_recommendation_feedback(Client, CodeReviewArn, #{}, #{}). list_recommendation_feedback(Client, CodeReviewArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_recommendation_feedback(Client, CodeReviewArn, QueryMap, HeadersMap, []). list_recommendation_feedback(Client, CodeReviewArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/feedback/", aws_util:encode_uri(CodeReviewArn), "/RecommendationFeedback"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"MaxResults">>, maps:get(<<"MaxResults">>, QueryMap, undefined)}, {<<"NextToken">>, maps:get(<<"NextToken">>, QueryMap, undefined)}, {<<"RecommendationIds">>, maps:get(<<"RecommendationIds">>, QueryMap, undefined)}, {<<"UserIds">>, maps:get(<<"UserIds">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). list_recommendations(Client, CodeReviewArn) when is_map(Client) -> list_recommendations(Client, CodeReviewArn, #{}, #{}). list_recommendations(Client, CodeReviewArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_recommendations(Client, CodeReviewArn, QueryMap, HeadersMap, []). list_recommendations(Client, CodeReviewArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/codereviews/", aws_util:encode_uri(CodeReviewArn), "/Recommendations"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"MaxResults">>, maps:get(<<"MaxResults">>, QueryMap, undefined)}, {<<"NextToken">>, maps:get(<<"NextToken">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). You can filter the returned list by ProviderType , Name , State , and Owner . list_repository_associations(Client) when is_map(Client) -> list_repository_associations(Client, #{}, #{}). list_repository_associations(Client, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_repository_associations(Client, QueryMap, HeadersMap, []). list_repository_associations(Client, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/associations"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query0_ = [ {<<"MaxResults">>, maps:get(<<"MaxResults">>, QueryMap, undefined)}, {<<"Name">>, maps:get(<<"Name">>, QueryMap, undefined)}, {<<"NextToken">>, maps:get(<<"NextToken">>, QueryMap, undefined)}, {<<"Owner">>, maps:get(<<"Owner">>, QueryMap, undefined)}, {<<"ProviderType">>, maps:get(<<"ProviderType">>, QueryMap, undefined)}, {<<"State">>, maps:get(<<"State">>, QueryMap, undefined)} ], Query_ = [H || {_, V} = H <- Query0_, V =/= undefined], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). list_tags_for_resource(Client, ResourceArn) when is_map(Client) -> list_tags_for_resource(Client, ResourceArn, #{}, #{}). list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap) when is_map(Client), is_map(QueryMap), is_map(HeadersMap) -> list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, []). list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, Options0) when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) -> Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false} | Options0], Headers = [], Query_ = [], request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode). @doc Stores customer feedback for a CodeGuru Reviewer recommendation . put_recommendation_feedback(Client, Input) -> put_recommendation_feedback(Client, Input, []). put_recommendation_feedback(Client, Input0, Options0) -> Method = put, Path = ["/feedback"], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). @doc Adds one or more tags to an associated repository . tag_resource(Client, ResourceArn, Input) -> tag_resource(Client, ResourceArn, Input, []). tag_resource(Client, ResourceArn, Input0, Options0) -> Method = post, Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, Query_ = [], Input = Input2, request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). untag_resource(Client, ResourceArn, Input) -> untag_resource(Client, ResourceArn, Input, []). untag_resource(Client, ResourceArn, Input0, Options0) -> Method = delete, Path = ["/tags/", aws_util:encode_uri(ResourceArn), ""], SuccessStatusCode = undefined, Options = [{send_body_as_binary, false}, {receive_body_as_binary, false}, {append_sha256_content_hash, false} | Options0], Headers = [], Input1 = Input0, CustomHeaders = [], Input2 = Input1, QueryMapping = [ {<<"tagKeys">>, <<"TagKeys">>} ], {Query_, Input} = aws_request:build_headers(QueryMapping, Input2), request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode). Internal functions -spec request(aws_client:aws_client(), atom(), iolist(), list(), list(), map() | undefined, list(), pos_integer() | undefined) -> {ok, {integer(), list()}} | {ok, Result, {integer(), list(), hackney:client()}} | {error, Error, {integer(), list(), hackney:client()}} | {error, term()} when Result :: map(), Error :: map(). request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end, aws_request:request(RequestFun, Options). do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) -> Client1 = Client#{service => <<"codeguru-reviewer">>}, Host = build_host(<<"codeguru-reviewer">>, Client1), URL0 = build_url(Host, Path, Client1), URL = aws_request:add_query(URL0, Query), AdditionalHeaders1 = [ {<<"Host">>, Host} , {<<"Content-Type">>, <<"application/x-amz-json-1.1">>} ], Payload = case proplists:get_value(send_body_as_binary, Options) of true -> maps:get(<<"Body">>, Input, <<"">>); false -> encode_payload(Input) end, AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of true -> add_checksum_hash_header(AdditionalHeaders1, Payload); false -> AdditionalHeaders1 end, Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0), MethodBin = aws_request:method_to_binary(Method), SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload), Response = hackney:request(Method, URL, SignedHeaders, Payload, Options), DecodeBody = not proplists:get_value(receive_body_as_binary, Options), handle_response(Response, SuccessStatusCode, DecodeBody). add_checksum_hash_header(Headers, Body) -> [ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))} | Headers ]. handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> {ok, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) -> {error, {StatusCode, ResponseHeaders}}; handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody) when StatusCode =:= 200; StatusCode =:= 202; StatusCode =:= 204; StatusCode =:= 206; StatusCode =:= SuccessStatusCode -> case hackney:body(Client) of {ok, <<>>} when StatusCode =:= 200; StatusCode =:= SuccessStatusCode -> {ok, #{}, {StatusCode, ResponseHeaders, Client}}; {ok, Body} -> Result = case DecodeBody of true -> try jsx:decode(Body) catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; false -> #{<<"Body">> => Body} end, {ok, Result, {StatusCode, ResponseHeaders, Client}} end; handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody) when StatusCode =:= 503 -> Retriable error if retries are enabled {error, service_unavailable}; handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) -> {ok, Body} = hackney:body(Client), try DecodedError = jsx:decode(Body), {error, DecodedError, {StatusCode, ResponseHeaders, Client}} catch Error:Reason:Stack -> erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack) end; handle_response({error, Reason}, _, _DecodeBody) -> {error, Reason}. build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) -> Endpoint; build_host(_EndpointPrefix, #{region := <<"local">>}) -> <<"localhost">>; build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) -> aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>). build_url(Host, Path0, Client) -> Proto = aws_client:proto(Client), Path = erlang:iolist_to_binary(Path0), Port = aws_client:port(Client), aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>). -spec encode_payload(undefined | map()) -> binary(). encode_payload(undefined) -> <<>>; encode_payload(Input) -> jsx:encode(Input).
8872df965ddaf45024974be1e3a7d26b09da913616410ea2ab336239e293ae99
ddmcdonald/sparser
academic-degrees.lisp
;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER COMMON-LISP) -*- copyright ( c ) 2021 -- all rights reserved ;;; ;;; File: "academic-degrees" ;;; Module: grammar/model/dossiers/ version : December 2021 ;; initiated 12/27/21 to organize degrees and such evacuated from ;; Middle-east files (in-package :sparser) (make-academic-degree "B.A.") only one in javan - online (make-academic-degree "M.B.A.") (make-academic-degree "M.S.") (make-academic-degree "M.A.") (make-academic-degree "Ph.D.")
null
https://raw.githubusercontent.com/ddmcdonald/sparser/33715946ffe3c45bc88b8b6e69fa4755fa4058e7/Sparser/code/s/grammar/model/dossiers/academic-degrees.lisp
lisp
-*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER COMMON-LISP) -*- File: "academic-degrees" Module: grammar/model/dossiers/ initiated 12/27/21 to organize degrees and such evacuated from Middle-east files
copyright ( c ) 2021 -- all rights reserved version : December 2021 (in-package :sparser) (make-academic-degree "B.A.") only one in javan - online (make-academic-degree "M.B.A.") (make-academic-degree "M.S.") (make-academic-degree "M.A.") (make-academic-degree "Ph.D.")
f8fd776712928736fce20bd732ec5ab3a021935e878343bb5e1c41087d5c11bc
yutopp/rill
phase1_collect_toplevels.ml
* Copyright 2020 - . * * Distributed under the Boost Software License , Version 1.0 . * ( See accompanying file LICENSE_1_0.txt or copy at * ) * Copyright yutopp 2020 - . * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * ) *) open! Base module Span = Common.Span module Ast = Syntax.Ast module TopAst = struct type t = { kind : kind_t; span : Span.t } and kind_t = | Module of { stmts : t } | Stmts of { nodes : t list } | WithEnv of { node : Ast.t; env : Env.t } | WithEnvAndBody of { node : Ast.t; body : t; env : Env.t } | LazyDecl of { node : Ast.t; penv : Env.t } | WithEnvAndBody2 of { node : Ast.t; body : t; env : Env.t; impl_record : Impl.t; } | PassThrough of { node : Ast.t } [@@deriving show] end type ctx_t = { parent : Env.t; ds : Diagnostics.t; subst : Typing.Subst.t; builtin : Builtin.t; } let context ~m ~subst ~builtin = let Mod.{ menv; ds; _ } = m in { parent = menv; ds; subst; builtin } type result_t = (TopAst.t, Diagnostics.Elem.t) Result.t let assume_new inseted_status = match inseted_status with | Env.InsertedHiding -> failwith "[ICE] insertion with hiding" | _ -> () let introduce_builtin penv builtin = let register name inner_ty_gen = let ty = Typing.Type.to_type_ty (inner_ty_gen ~span:Span.undef) in let pty = Typing.Pred.of_type ty in let ty_sc = Typing.Scheme.of_ty pty in let env = Env.create ~is_builtin:true name ~parent:None ~visibility:Env.Private ~ty_sc ~kind:Env.Ty ~lookup_space:Env.LkGlobal in Env.insert penv env |> assume_new in register "bool" builtin.Builtin.bool_; register "i8" builtin.Builtin.i8_; register "i32" builtin.Builtin.i32_; register "i64" builtin.Builtin.i64_; register "u64" builtin.Builtin.u64_; register "isize" builtin.Builtin.isize_; register "usize" builtin.Builtin.usize_; register "string" builtin.Builtin.string_; register "unit" builtin.Builtin.unit_; () let rec collect_toplevels ~ctx ast : (TopAst.t, Diagnostics.Elem.t) Result.t = let open Result.Let_syntax in match ast with (* *) | Ast.{ kind = Module stmts; span } -> (* TODO: fix *) let menv = ctx.parent in introduce_builtin menv ctx.builtin; let%bind stmts = let ctx' = { ctx with parent = menv } in collect_toplevels ~ctx:ctx' stmts in Ok TopAst.{ kind = Module { stmts }; span } (* *) | Ast.{ kind = Stmts nodes; span } -> let%bind nodes = List.fold_result nodes ~init:[] ~f:(fun mapped node -> match collect_toplevels ~ctx node with | Ok node' -> Ok (node' :: mapped) | Error d -> Diagnostics.append ctx.ds d; Ok mapped) |> Result.map ~f:List.rev in Ok TopAst.{ kind = Stmts { nodes }; span } (* *) | Ast.{ kind = Import _; span } as i -> Ok TopAst.{ kind = PassThrough { node = i }; span } (* *) | Ast.{ kind = DefTypeAlias { name; _ }; span } as alias -> let penv = ctx.parent in let%bind () = Guards.guard_dup_value ~span penv name in let ty = let inner = Typing.Subst.fresh_ty ~span ctx.subst in ctx.builtin.Builtin.type_ ~span inner in let pty = Typing.Pred.of_type ty in let ty_sc = Typing.Scheme.of_ty pty in let visibility = Env.Public (* TODO: fix *) in let tenv = Env.create name ~parent:(Some penv) ~visibility ~ty_sc ~kind:Env.Ty ~lookup_space:Env.LkGlobal in Env.insert penv tenv |> assume_new; Ok TopAst.{ kind = WithEnv { node = alias; env = tenv }; span } (* *) | Ast.{ kind = DeclExternStaticVar { attr; name; ty_spec }; span } as decl -> let penv = ctx.parent in let%bind () = Guards.guard_dup_value ~span penv name in let binding_mut = Mut.mutability_of attr in let ty = let span = Ast.(ty_spec.span) in let ty = Typing.Subst.fresh_ty ~span ctx.subst in Typing.(Type.{ ty with binding_mut }) in let pty = Typing.Pred.of_type ty in let ty_sc = Typing.Scheme.of_ty pty in let visibility = Env.Public (* TODO: fix *) in let fenv = Env.create name ~parent:(Some penv) ~visibility ~ty_sc ~kind:Env.Val ~lookup_space:Env.LkGlobal in Env.insert penv fenv |> assume_new; Ok TopAst.{ kind = WithEnv { node = decl; env = fenv }; span } (* *) | Ast.{ kind = DeclExternFunc { name; params; ret_ty; symbol_name; _ }; span } as decl -> let penv = ctx.parent in let%bind () = Guards.guard_dup_value ~span penv name in TODO let linkage = Functions.linkage_of decl in let ty_sc = preconstruct_func_ty_sc ~ctx ~span ~linkage ~ty_params ~params ~ret_ty in let visibility = Env.Public (* TODO: fix *) in let fenv = Env.create name ~parent:(Some penv) ~visibility ~ty_sc ~kind:Env.Val ~lookup_space:Env.LkGlobal in Env.insert penv fenv |> assume_new; Ok TopAst.{ kind = WithEnv { node = decl; env = fenv }; span } (* *) | ( Ast.{ kind = DeclFunc { name; ty_params; params; ret_ty; _ }; span } as decl ) | (Ast.{ kind = DefFunc { name; ty_params; params; ret_ty; _ }; span } as decl) -> let penv = ctx.parent in let%bind () = Guards.guard_dup_value ~span penv name in let linkage = Functions.linkage_of decl in let ty_sc = preconstruct_func_ty_sc ~ctx ~span ~linkage ~ty_params ~params ~ret_ty in let visibility = Env.Public (* TODO: fix *) in let fenv = Env.create name ~parent:(Some penv) ~visibility ~ty_sc ~kind:Env.Val ~lookup_space:Env.LkGlobal in Env.insert penv fenv |> assume_new; Ok TopAst.{ kind = WithEnv { node = decl; env = fenv }; span } (* *) | Ast.{ kind = DefStruct { name }; span } as decl -> let penv = ctx.parent in let%bind () = Guards.guard_dup_value ~span penv name in let ty = let inner = Typing.Subst.fresh_ty ~span ctx.subst in ctx.builtin.Builtin.type_ ~span inner in let pty = Typing.Pred.of_type ty in let ty_sc = Typing.Scheme.of_ty pty in let visibility = Env.Public (* TODO: fix *) in let tenv = Env.create name ~parent:(Some penv) ~visibility ~ty_sc ~kind:Env.Ty ~lookup_space:Env.LkGlobal in Env.insert penv tenv |> assume_new; Ok TopAst.{ kind = WithEnv { node = decl; env = tenv }; span } (* *) | Ast.{ kind = DefTrait { name; decls }; span } as decl -> let penv = ctx.parent in let%bind () = Guards.guard_dup_type ~span penv name in (* T *) let ty = let inner = Typing.Subst.fresh_ty ~span ctx.subst in ctx.builtin.Builtin.type_ ~span inner in let pty = Typing.Pred.of_type ty in let ty_sc = Typing.Scheme.of_ty pty in TODO let tenv = Env.create name ~parent:(Some penv) ~visibility ~ty_sc ~kind:Env.Trait ~lookup_space:Env.LkGlobal in (* a *) let implicits = let inner = Typing.Subst.fresh_forall_ty ~span ~label:"t" ctx.subst in [ inner ] in Env.append_implicits tenv implicits; Trait : : T!(_a ) Env.insert penv tenv |> assume_new; let%bind decls = let ctx = { ctx with parent = tenv } in collect_toplevels ~ctx decls in (* Add 'Self' *) let self_env = let name = "Self" in let ty_sc = List.hd_exn implicits |> Typing.Type.to_type_ty |> Typing.Pred.of_type |> Typing.Scheme.of_ty in Env.create name ~parent:(Some tenv) ~visibility ~ty_sc ~kind:Env.Ty ~lookup_space:Env.LkLocal in Env.insert_type tenv self_env |> assume_new; Ok TopAst. { kind = WithEnvAndBody { node = decl; body = decls; env = tenv }; span; } (* *) | Ast.{ kind = DefImplFor _; span } as decl -> let penv = ctx.parent in Ok TopAst.{ kind = LazyDecl { node = decl; penv }; span } (* *) | Ast.{ span; _ } -> let e = new Diagnostics.Reasons.internal_error ~message:"Not supported node (phase1)" in let elm = Diagnostics.Elem.error ~span e in Error elm and preconstruct_func_ty_sc ~ctx ~span ~linkage ~ty_params ~params ~ret_ty : Typing.Scheme.t = (* TODO: support generic params *) let params_tys = List.map params ~f:(fun param -> let span = Ast.(param.span) in Typing.Subst.fresh_ty ~span ctx.subst) in let ret_ty = let span = Ast.(ret_ty.span) in Typing.Subst.fresh_ty ~span ctx.subst in let binding_mut = Typing.Type.MutImm in let ty = Typing.Type. { ty = Func { params = params_tys; ret = ret_ty; linkage }; binding_mut; span; } in let pty = Typing.Pred.of_type ty in let vars = List.map ty_params ~f:(fun ty_param -> match ty_param with | Ast.{ kind = TyParamDecl { name }; span } -> Typing.Subst.fresh_forall_ty ~span ~label:name ctx.subst | _ -> failwith "[ICE]") in Typing.Scheme.ForAll { implicits = []; vars; ty = pty }
null
https://raw.githubusercontent.com/yutopp/rill/375b67c03ab2087d0a2a833bd9e80f3e51e2694f/rillc/lib/sema/phase1_collect_toplevels.ml
ocaml
TODO: fix TODO: fix TODO: fix TODO: fix TODO: fix TODO: fix T a Add 'Self' TODO: support generic params
* Copyright 2020 - . * * Distributed under the Boost Software License , Version 1.0 . * ( See accompanying file LICENSE_1_0.txt or copy at * ) * Copyright yutopp 2020 - . * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * ) *) open! Base module Span = Common.Span module Ast = Syntax.Ast module TopAst = struct type t = { kind : kind_t; span : Span.t } and kind_t = | Module of { stmts : t } | Stmts of { nodes : t list } | WithEnv of { node : Ast.t; env : Env.t } | WithEnvAndBody of { node : Ast.t; body : t; env : Env.t } | LazyDecl of { node : Ast.t; penv : Env.t } | WithEnvAndBody2 of { node : Ast.t; body : t; env : Env.t; impl_record : Impl.t; } | PassThrough of { node : Ast.t } [@@deriving show] end type ctx_t = { parent : Env.t; ds : Diagnostics.t; subst : Typing.Subst.t; builtin : Builtin.t; } let context ~m ~subst ~builtin = let Mod.{ menv; ds; _ } = m in { parent = menv; ds; subst; builtin } type result_t = (TopAst.t, Diagnostics.Elem.t) Result.t let assume_new inseted_status = match inseted_status with | Env.InsertedHiding -> failwith "[ICE] insertion with hiding" | _ -> () let introduce_builtin penv builtin = let register name inner_ty_gen = let ty = Typing.Type.to_type_ty (inner_ty_gen ~span:Span.undef) in let pty = Typing.Pred.of_type ty in let ty_sc = Typing.Scheme.of_ty pty in let env = Env.create ~is_builtin:true name ~parent:None ~visibility:Env.Private ~ty_sc ~kind:Env.Ty ~lookup_space:Env.LkGlobal in Env.insert penv env |> assume_new in register "bool" builtin.Builtin.bool_; register "i8" builtin.Builtin.i8_; register "i32" builtin.Builtin.i32_; register "i64" builtin.Builtin.i64_; register "u64" builtin.Builtin.u64_; register "isize" builtin.Builtin.isize_; register "usize" builtin.Builtin.usize_; register "string" builtin.Builtin.string_; register "unit" builtin.Builtin.unit_; () let rec collect_toplevels ~ctx ast : (TopAst.t, Diagnostics.Elem.t) Result.t = let open Result.Let_syntax in match ast with | Ast.{ kind = Module stmts; span } -> let menv = ctx.parent in introduce_builtin menv ctx.builtin; let%bind stmts = let ctx' = { ctx with parent = menv } in collect_toplevels ~ctx:ctx' stmts in Ok TopAst.{ kind = Module { stmts }; span } | Ast.{ kind = Stmts nodes; span } -> let%bind nodes = List.fold_result nodes ~init:[] ~f:(fun mapped node -> match collect_toplevels ~ctx node with | Ok node' -> Ok (node' :: mapped) | Error d -> Diagnostics.append ctx.ds d; Ok mapped) |> Result.map ~f:List.rev in Ok TopAst.{ kind = Stmts { nodes }; span } | Ast.{ kind = Import _; span } as i -> Ok TopAst.{ kind = PassThrough { node = i }; span } | Ast.{ kind = DefTypeAlias { name; _ }; span } as alias -> let penv = ctx.parent in let%bind () = Guards.guard_dup_value ~span penv name in let ty = let inner = Typing.Subst.fresh_ty ~span ctx.subst in ctx.builtin.Builtin.type_ ~span inner in let pty = Typing.Pred.of_type ty in let ty_sc = Typing.Scheme.of_ty pty in let tenv = Env.create name ~parent:(Some penv) ~visibility ~ty_sc ~kind:Env.Ty ~lookup_space:Env.LkGlobal in Env.insert penv tenv |> assume_new; Ok TopAst.{ kind = WithEnv { node = alias; env = tenv }; span } | Ast.{ kind = DeclExternStaticVar { attr; name; ty_spec }; span } as decl -> let penv = ctx.parent in let%bind () = Guards.guard_dup_value ~span penv name in let binding_mut = Mut.mutability_of attr in let ty = let span = Ast.(ty_spec.span) in let ty = Typing.Subst.fresh_ty ~span ctx.subst in Typing.(Type.{ ty with binding_mut }) in let pty = Typing.Pred.of_type ty in let ty_sc = Typing.Scheme.of_ty pty in let fenv = Env.create name ~parent:(Some penv) ~visibility ~ty_sc ~kind:Env.Val ~lookup_space:Env.LkGlobal in Env.insert penv fenv |> assume_new; Ok TopAst.{ kind = WithEnv { node = decl; env = fenv }; span } | Ast.{ kind = DeclExternFunc { name; params; ret_ty; symbol_name; _ }; span } as decl -> let penv = ctx.parent in let%bind () = Guards.guard_dup_value ~span penv name in TODO let linkage = Functions.linkage_of decl in let ty_sc = preconstruct_func_ty_sc ~ctx ~span ~linkage ~ty_params ~params ~ret_ty in let fenv = Env.create name ~parent:(Some penv) ~visibility ~ty_sc ~kind:Env.Val ~lookup_space:Env.LkGlobal in Env.insert penv fenv |> assume_new; Ok TopAst.{ kind = WithEnv { node = decl; env = fenv }; span } | ( Ast.{ kind = DeclFunc { name; ty_params; params; ret_ty; _ }; span } as decl ) | (Ast.{ kind = DefFunc { name; ty_params; params; ret_ty; _ }; span } as decl) -> let penv = ctx.parent in let%bind () = Guards.guard_dup_value ~span penv name in let linkage = Functions.linkage_of decl in let ty_sc = preconstruct_func_ty_sc ~ctx ~span ~linkage ~ty_params ~params ~ret_ty in let fenv = Env.create name ~parent:(Some penv) ~visibility ~ty_sc ~kind:Env.Val ~lookup_space:Env.LkGlobal in Env.insert penv fenv |> assume_new; Ok TopAst.{ kind = WithEnv { node = decl; env = fenv }; span } | Ast.{ kind = DefStruct { name }; span } as decl -> let penv = ctx.parent in let%bind () = Guards.guard_dup_value ~span penv name in let ty = let inner = Typing.Subst.fresh_ty ~span ctx.subst in ctx.builtin.Builtin.type_ ~span inner in let pty = Typing.Pred.of_type ty in let ty_sc = Typing.Scheme.of_ty pty in let tenv = Env.create name ~parent:(Some penv) ~visibility ~ty_sc ~kind:Env.Ty ~lookup_space:Env.LkGlobal in Env.insert penv tenv |> assume_new; Ok TopAst.{ kind = WithEnv { node = decl; env = tenv }; span } | Ast.{ kind = DefTrait { name; decls }; span } as decl -> let penv = ctx.parent in let%bind () = Guards.guard_dup_type ~span penv name in let ty = let inner = Typing.Subst.fresh_ty ~span ctx.subst in ctx.builtin.Builtin.type_ ~span inner in let pty = Typing.Pred.of_type ty in let ty_sc = Typing.Scheme.of_ty pty in TODO let tenv = Env.create name ~parent:(Some penv) ~visibility ~ty_sc ~kind:Env.Trait ~lookup_space:Env.LkGlobal in let implicits = let inner = Typing.Subst.fresh_forall_ty ~span ~label:"t" ctx.subst in [ inner ] in Env.append_implicits tenv implicits; Trait : : T!(_a ) Env.insert penv tenv |> assume_new; let%bind decls = let ctx = { ctx with parent = tenv } in collect_toplevels ~ctx decls in let self_env = let name = "Self" in let ty_sc = List.hd_exn implicits |> Typing.Type.to_type_ty |> Typing.Pred.of_type |> Typing.Scheme.of_ty in Env.create name ~parent:(Some tenv) ~visibility ~ty_sc ~kind:Env.Ty ~lookup_space:Env.LkLocal in Env.insert_type tenv self_env |> assume_new; Ok TopAst. { kind = WithEnvAndBody { node = decl; body = decls; env = tenv }; span; } | Ast.{ kind = DefImplFor _; span } as decl -> let penv = ctx.parent in Ok TopAst.{ kind = LazyDecl { node = decl; penv }; span } | Ast.{ span; _ } -> let e = new Diagnostics.Reasons.internal_error ~message:"Not supported node (phase1)" in let elm = Diagnostics.Elem.error ~span e in Error elm and preconstruct_func_ty_sc ~ctx ~span ~linkage ~ty_params ~params ~ret_ty : Typing.Scheme.t = let params_tys = List.map params ~f:(fun param -> let span = Ast.(param.span) in Typing.Subst.fresh_ty ~span ctx.subst) in let ret_ty = let span = Ast.(ret_ty.span) in Typing.Subst.fresh_ty ~span ctx.subst in let binding_mut = Typing.Type.MutImm in let ty = Typing.Type. { ty = Func { params = params_tys; ret = ret_ty; linkage }; binding_mut; span; } in let pty = Typing.Pred.of_type ty in let vars = List.map ty_params ~f:(fun ty_param -> match ty_param with | Ast.{ kind = TyParamDecl { name }; span } -> Typing.Subst.fresh_forall_ty ~span ~label:name ctx.subst | _ -> failwith "[ICE]") in Typing.Scheme.ForAll { implicits = []; vars; ty = pty }
e7bcd995a07f64b02e99999c4306a21d8220c5a545553996e5edb8695dae15dd
argp/bap
batNumber.ml
* Number - Generic interface for numbers * Copyright ( C ) 2007 Bluestorm < bluestorm dot dylc on - the - server gmail dot com > * 2008 * * 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 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * 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. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * Number - Generic interface for numbers * Copyright (C) 2007 Bluestorm <bluestorm dot dylc on-the-server gmail dot com> * 2008 David Teller * * 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 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) type 'a numeric = { zero : 'a; one : 'a; neg : 'a -> 'a; succ : 'a -> 'a; pred : 'a -> 'a; abs : 'a -> 'a; add : 'a -> 'a -> 'a; sub : 'a -> 'a -> 'a; mul : 'a -> 'a -> 'a; div : 'a -> 'a -> 'a; modulo : 'a -> 'a -> 'a; pow : 'a -> 'a -> 'a; compare : 'a -> 'a -> int; of_int : int -> 'a; to_int : 'a -> int; of_string : string -> 'a; to_string : 'a -> string; of_float : float -> 'a; to_float : 'a -> float } (** The infix operators *) module type Infix = sig type bat__infix_t val ( + ) : bat__infix_t -> bat__infix_t -> bat__infix_t val ( - ) : bat__infix_t -> bat__infix_t -> bat__infix_t val ( * ) : bat__infix_t -> bat__infix_t -> bat__infix_t val ( / ) : bat__infix_t -> bat__infix_t -> bat__infix_t val ( ** ) : bat__infix_t -> bat__infix_t -> bat__infix_t val ( -- ): bat__infix_t -> bat__infix_t -> bat__infix_t BatEnum.t val ( --- ): bat__infix_t -> bat__infix_t -> bat__infix_t BatEnum.t end module type Compare = sig type bat__compare_t val ( <> ) : bat__compare_t -> bat__compare_t -> bool val ( >= ) : bat__compare_t -> bat__compare_t -> bool val ( <= ) : bat__compare_t -> bat__compare_t -> bool val ( > ) : bat__compare_t -> bat__compare_t -> bool val ( < ) : bat__compare_t -> bat__compare_t -> bool val ( = ) : bat__compare_t -> bat__compare_t -> bool end * Idea from mathlib module type RefOps = sig type bat__refops_t val (+=): bat__refops_t ref -> bat__refops_t -> unit val (-=): bat__refops_t ref -> bat__refops_t -> unit val ( *=): bat__refops_t ref -> bat__refops_t -> unit val (/=): bat__refops_t ref -> bat__refops_t -> unit end (** The full set of operations of a type of numbers *) module type Numeric = sig type t type discrete = t val zero : t val one : t val neg : t -> t val abs : t -> t val add : t -> t -> t val sub : t -> t -> t val mul : t -> t -> t val div : t -> t -> t val modulo : t -> t -> t val pow : t -> t -> t val compare : t -> t -> int val equal : t -> t -> bool val ord : t BatOrd.ord val of_int : int -> t val to_int : t -> int val of_float: float -> t val to_float: t -> float val of_string : string -> t val to_string : t -> string val operations : t numeric val succ : t -> t val pred : t -> t module Infix : Infix with type bat__infix_t = t module Compare : Compare with type bat__compare_t = t include Infix with type bat__infix_t = t (* Removed compare operators from base module, as they shadow polymorphic ones from stdlib include Compare with type bat__compare_t = t*) include RefOps with type bat__refops_t = t end module type Bounded = sig type bounded val min_num: bounded val max_num: bounded end module type Discrete = sig type discrete val to_int: discrete -> int val succ : discrete -> discrete val pred : discrete -> discrete val ( -- ): discrete -> discrete -> discrete BatEnum.t val ( --- ): discrete -> discrete -> discrete BatEnum.t end (** The smallest set of operations supported by every set of numbers *) module type NUMERIC_BASE = sig type t (** A type of numbers*) val zero : t val one : t * { 6 Arithmetic operations } Depending on the implementation , some of these operations { i may } raise exceptions at run - time to represent over / under - flows . Depending on the implementation, some of these operations {i may} raise exceptions at run-time to represent over/under-flows.*) val neg : t -> t val succ : t -> t val pred : t -> t val abs : t -> t val add : t -> t -> t val sub : t -> t -> t val mul : t -> t -> t val div : t -> t -> t val modulo : t -> t -> t val pow : t -> t -> t val compare : t -> t -> int * { 6 Conversions } val of_int : int -> t (** Convert this number to the closest integer.*) val to_int : t -> int (** Convert an integer to the closest element of set [t].*) val of_string : string -> t (** Convert the representation of a number to the corresponding number. @raise Invalid_argument if the string does not represent a valid number of type [t]*) val to_string : t -> string val of_float : float -> t val to_float : t -> float end (** Automatic generation of infix operators of a NUMERIC_BASE *) module MakeInfix (Base : NUMERIC_BASE) : Infix with type bat__infix_t = Base.t = struct type bat__infix_t = Base.t let ( + ), ( - ), ( * ), ( / ), ( ** ) = Base.add, Base.sub, Base.mul, Base.div, Base.pow let ( -- ) x y = BatEnum.seq x Base.succ ( (>=) y ) let ( --- ) x y = if y >= x then x -- y else BatEnum.seq x Base.pred ((<=) y) end (** Automatic generation of comparison operations of a NUMERIC_BASE *) module MakeCompare (Base : NUMERIC_BASE) : Compare with type bat__compare_t = Base.t = struct type bat__compare_t = Base.t let ( = ) a b = Base.compare a b = 0 let ( < ) a b = Base.compare a b < 0 let ( > ) a b = Base.compare a b > 0 let ( <= ) a b = Base.compare a b <= 0 let ( >= ) a b = Base.compare a b >= 0 let ( <> ) a b = Base.compare a b <> 0 end module MakeRefOps (Base: NUMERIC_BASE) : RefOps with type bat__refops_t = Base.t = struct type bat__refops_t = Base.t let (+=) a b = a := Base.add !a b let (-=) a b = a := Base.sub !a b let ( *=) a b = a := Base.mul !a b let (/=) a b = a := Base.div !a b end (** Automated definition of operators for a given numeric type. see open...in... *) module MakeNumeric (Base : NUMERIC_BASE) : Numeric with type t = Base.t = struct include Base let operations = { zero = Base.zero; one = Base.one; neg = Base.neg; succ = Base.succ; pred = Base.pred; abs = Base.abs; add = Base.add; sub = Base.sub; mul = Base.mul; div = Base.div; modulo = Base.modulo; pow = Base.pow; compare = Base.compare; of_int = Base.of_int; to_int = Base.to_int; of_float = Base.of_float; to_float = Base.to_float; of_string = Base.of_string; to_string = Base.to_string; } type discrete = t let equal x y = Base.compare x y = 0 let ord x y = BatOrd.ord0 (Base.compare x y) module Infix = MakeInfix (Base) module Compare = MakeCompare (Base) include Infix include MakeRefOps (Base) end (** A generic implementation of fast exponentiation *) let generic_pow ~zero ~one ~div_two ~mod_two ~mul:( * ) = let rec pow a n = if n = zero then one else if n = one then a else let b = pow a (div_two n) in b * b * (if mod_two n = zero then one else a) in pow exception Overflow exception NaN
null
https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/src/batNumber.ml
ocaml
* The infix operators * The full set of operations of a type of numbers Removed compare operators from base module, as they shadow polymorphic ones from stdlib include Compare with type bat__compare_t = t * The smallest set of operations supported by every set of numbers * A type of numbers * Convert this number to the closest integer. * Convert an integer to the closest element of set [t]. * Convert the representation of a number to the corresponding number. @raise Invalid_argument if the string does not represent a valid number of type [t] * Automatic generation of infix operators of a NUMERIC_BASE * Automatic generation of comparison operations of a NUMERIC_BASE * Automated definition of operators for a given numeric type. see open...in... * A generic implementation of fast exponentiation
* Number - Generic interface for numbers * Copyright ( C ) 2007 Bluestorm < bluestorm dot dylc on - the - server gmail dot com > * 2008 * * 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 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * 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. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * Number - Generic interface for numbers * Copyright (C) 2007 Bluestorm <bluestorm dot dylc on-the-server gmail dot com> * 2008 David Teller * * 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 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) type 'a numeric = { zero : 'a; one : 'a; neg : 'a -> 'a; succ : 'a -> 'a; pred : 'a -> 'a; abs : 'a -> 'a; add : 'a -> 'a -> 'a; sub : 'a -> 'a -> 'a; mul : 'a -> 'a -> 'a; div : 'a -> 'a -> 'a; modulo : 'a -> 'a -> 'a; pow : 'a -> 'a -> 'a; compare : 'a -> 'a -> int; of_int : int -> 'a; to_int : 'a -> int; of_string : string -> 'a; to_string : 'a -> string; of_float : float -> 'a; to_float : 'a -> float } module type Infix = sig type bat__infix_t val ( + ) : bat__infix_t -> bat__infix_t -> bat__infix_t val ( - ) : bat__infix_t -> bat__infix_t -> bat__infix_t val ( * ) : bat__infix_t -> bat__infix_t -> bat__infix_t val ( / ) : bat__infix_t -> bat__infix_t -> bat__infix_t val ( ** ) : bat__infix_t -> bat__infix_t -> bat__infix_t val ( -- ): bat__infix_t -> bat__infix_t -> bat__infix_t BatEnum.t val ( --- ): bat__infix_t -> bat__infix_t -> bat__infix_t BatEnum.t end module type Compare = sig type bat__compare_t val ( <> ) : bat__compare_t -> bat__compare_t -> bool val ( >= ) : bat__compare_t -> bat__compare_t -> bool val ( <= ) : bat__compare_t -> bat__compare_t -> bool val ( > ) : bat__compare_t -> bat__compare_t -> bool val ( < ) : bat__compare_t -> bat__compare_t -> bool val ( = ) : bat__compare_t -> bat__compare_t -> bool end * Idea from mathlib module type RefOps = sig type bat__refops_t val (+=): bat__refops_t ref -> bat__refops_t -> unit val (-=): bat__refops_t ref -> bat__refops_t -> unit val ( *=): bat__refops_t ref -> bat__refops_t -> unit val (/=): bat__refops_t ref -> bat__refops_t -> unit end module type Numeric = sig type t type discrete = t val zero : t val one : t val neg : t -> t val abs : t -> t val add : t -> t -> t val sub : t -> t -> t val mul : t -> t -> t val div : t -> t -> t val modulo : t -> t -> t val pow : t -> t -> t val compare : t -> t -> int val equal : t -> t -> bool val ord : t BatOrd.ord val of_int : int -> t val to_int : t -> int val of_float: float -> t val to_float: t -> float val of_string : string -> t val to_string : t -> string val operations : t numeric val succ : t -> t val pred : t -> t module Infix : Infix with type bat__infix_t = t module Compare : Compare with type bat__compare_t = t include Infix with type bat__infix_t = t include RefOps with type bat__refops_t = t end module type Bounded = sig type bounded val min_num: bounded val max_num: bounded end module type Discrete = sig type discrete val to_int: discrete -> int val succ : discrete -> discrete val pred : discrete -> discrete val ( -- ): discrete -> discrete -> discrete BatEnum.t val ( --- ): discrete -> discrete -> discrete BatEnum.t end module type NUMERIC_BASE = sig type t val zero : t val one : t * { 6 Arithmetic operations } Depending on the implementation , some of these operations { i may } raise exceptions at run - time to represent over / under - flows . Depending on the implementation, some of these operations {i may} raise exceptions at run-time to represent over/under-flows.*) val neg : t -> t val succ : t -> t val pred : t -> t val abs : t -> t val add : t -> t -> t val sub : t -> t -> t val mul : t -> t -> t val div : t -> t -> t val modulo : t -> t -> t val pow : t -> t -> t val compare : t -> t -> int * { 6 Conversions } val of_int : int -> t val to_int : t -> int val of_string : string -> t val to_string : t -> string val of_float : float -> t val to_float : t -> float end module MakeInfix (Base : NUMERIC_BASE) : Infix with type bat__infix_t = Base.t = struct type bat__infix_t = Base.t let ( + ), ( - ), ( * ), ( / ), ( ** ) = Base.add, Base.sub, Base.mul, Base.div, Base.pow let ( -- ) x y = BatEnum.seq x Base.succ ( (>=) y ) let ( --- ) x y = if y >= x then x -- y else BatEnum.seq x Base.pred ((<=) y) end module MakeCompare (Base : NUMERIC_BASE) : Compare with type bat__compare_t = Base.t = struct type bat__compare_t = Base.t let ( = ) a b = Base.compare a b = 0 let ( < ) a b = Base.compare a b < 0 let ( > ) a b = Base.compare a b > 0 let ( <= ) a b = Base.compare a b <= 0 let ( >= ) a b = Base.compare a b >= 0 let ( <> ) a b = Base.compare a b <> 0 end module MakeRefOps (Base: NUMERIC_BASE) : RefOps with type bat__refops_t = Base.t = struct type bat__refops_t = Base.t let (+=) a b = a := Base.add !a b let (-=) a b = a := Base.sub !a b let ( *=) a b = a := Base.mul !a b let (/=) a b = a := Base.div !a b end module MakeNumeric (Base : NUMERIC_BASE) : Numeric with type t = Base.t = struct include Base let operations = { zero = Base.zero; one = Base.one; neg = Base.neg; succ = Base.succ; pred = Base.pred; abs = Base.abs; add = Base.add; sub = Base.sub; mul = Base.mul; div = Base.div; modulo = Base.modulo; pow = Base.pow; compare = Base.compare; of_int = Base.of_int; to_int = Base.to_int; of_float = Base.of_float; to_float = Base.to_float; of_string = Base.of_string; to_string = Base.to_string; } type discrete = t let equal x y = Base.compare x y = 0 let ord x y = BatOrd.ord0 (Base.compare x y) module Infix = MakeInfix (Base) module Compare = MakeCompare (Base) include Infix include MakeRefOps (Base) end let generic_pow ~zero ~one ~div_two ~mod_two ~mul:( * ) = let rec pow a n = if n = zero then one else if n = one then a else let b = pow a (div_two n) in b * b * (if mod_two n = zero then one else a) in pow exception Overflow exception NaN
ac4758835ed93d32e86c0b8401bd7a53dec0d6a48052d1e893085c6b6a59a484
gsakkas/rite
0098.ml
AppG [LitG,UopG EmptyG] clone 0 (- diff) clone 0 (- lendiff)
null
https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/data/sp14/clusters/0098.ml
ocaml
AppG [LitG,UopG EmptyG] clone 0 (- diff) clone 0 (- lendiff)
47786a0c055b50e73ddf4141c34811fee815c992bac6ff84b7b62216fdd9b033
jessex/CLRS-implementations
0034_merge_sort.scm
MERGE - SORT(A , p , r ) Sorts the given array from indices p to r using a Divide - and - Conquer approach O(n log n ) Chapter 2.3 , Page 34 (define merge (lambda (left right) (cond ((null? left) right) ((null? right) left) ((< (car left) (car right)) (cons (car left) (merge (cdr left) right))) (else (cons (car right) (merge left (cdr right))))))) (define merge-sort (lambda (lst) (let ((half (quotient (length lst) 2))) (cond ((zero? half) lst) (else (merge (merge-sort (list-head lst half)) (merge-sort (list-tail lst half))))))))
null
https://raw.githubusercontent.com/jessex/CLRS-implementations/ed5d3d89cf489646b15941c2529533e98389a58b/scheme/0034_merge_sort.scm
scheme
MERGE - SORT(A , p , r ) Sorts the given array from indices p to r using a Divide - and - Conquer approach O(n log n ) Chapter 2.3 , Page 34 (define merge (lambda (left right) (cond ((null? left) right) ((null? right) left) ((< (car left) (car right)) (cons (car left) (merge (cdr left) right))) (else (cons (car right) (merge left (cdr right))))))) (define merge-sort (lambda (lst) (let ((half (quotient (length lst) 2))) (cond ((zero? half) lst) (else (merge (merge-sort (list-head lst half)) (merge-sort (list-tail lst half))))))))
5bf76f9f5baec8f6eef6c78a69131220654cf570cb8454d255c0f9ea5793fcbf
ocaml-multicore/ocaml-tsan
odoc_html.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cambium , INRIA Paris (* *) Copyright 2022 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** Generation of html documentation. *) module String = Misc.Stdlib.String val with_parameter_list : bool ref val css_style : string option ref val index_only : bool ref val colorize_code : bool ref val html_short_functors : bool ref val charset : string ref val show_navbar : bool ref module Naming : sig val mark_module : string val mark_module_type : string val mark_type : string val mark_type_elt : string val mark_function : string val mark_extension : string val mark_exception : string val mark_value : string val mark_attribute : string val mark_method : string val code_prefix : string val type_prefix : string val html_files : string -> string * string val target : string -> string -> string val complete_target : string -> Odoc_info.Name.t -> string val module_target : Odoc_info.Module.t_module -> string val module_type_target : Odoc_info.Module.t_module_type -> string val type_target : Odoc_info.Type.t_type -> string val const_target : Odoc_info.Type.t_type -> Odoc_info.Type.variant_constructor -> string val recfield_target : Odoc_info.Type.t_type -> Odoc_info.Type.record_field -> string val inline_recfield_target : string -> string -> Odoc_info.Type.record_field -> string val objfield_target : Odoc_info.Type.t_type -> Odoc_info.Type.object_field -> string val complete_type_target : Odoc_info.Type.t_type -> string val complete_recfield_target : Odoc_info.Name.t -> string val complete_const_target : Odoc_info.Name.t -> string val extension_target : Odoc_info.Extension.t_extension_constructor -> string val complete_extension_target : Odoc_info.Extension.t_extension_constructor -> string val exception_target : Odoc_info.Exception.t_exception -> string val complete_exception_target : Odoc_info.Exception.t_exception -> string val value_target : Odoc_info.Value.t_value -> string val subst_infix_symbols : string -> string val complete_value_target : Odoc_info.Value.t_value -> string val file_code_value_complete_target : Odoc_info.Value.t_value -> string val attribute_target : Odoc_info.Value.t_attribute -> string val complete_attribute_target : Odoc_info.Value.t_attribute -> string val file_code_attribute_complete_target : Odoc_info.Value.t_attribute -> string val method_target : Odoc_info.Value.t_method -> string val complete_method_target : Odoc_info.Value.t_method -> string val file_code_method_complete_target : Odoc_info.Value.t_method -> string val label_target : string -> string val complete_label_target : Odoc_info.Name.t -> string val file_type_module_complete_target : string -> string val file_code_module_complete_target : string -> string val file_type_class_complete_target : string -> string end module Generator : sig class html : object val mutable default_style_options : string list val mutable doctype : string val mutable header : Buffer.t -> ?nav:(Odoc_info.Name.t option * Odoc_info.Name.t option * Odoc_info.Name.t) option -> ?comments:Odoc_info.text list -> string -> unit val mutable known_classes_names : String.Set.t val mutable known_modules_names : String.Set.t val mutable known_types_names : String.Set.t val mutable list_attributes : Odoc_info.Value.t_attribute list val mutable list_class_types : Odoc_info.Class.t_class_type list val mutable list_classes : Odoc_info.Class.t_class list val mutable list_exceptions : Odoc_info.Exception.t_exception list val mutable list_extensions : Odoc_info.Extension.t_extension_constructor list val mutable list_methods : Odoc_info.Value.t_method list val mutable list_module_types : Odoc_info.Module.t_module_type list val mutable list_modules : Odoc_info.Module.t_module list val mutable list_types : Odoc_info.Type.t_type list val mutable list_values : Odoc_info.Value.t_value list val mutable style : string val mutable style_file : string val mutable tag_functions : (string * (Odoc_info.text -> string)) list method character_encoding : Buffer.t -> unit method constructor : string -> string method create_fully_qualified_idents_links : Odoc_info.Name.t -> Odoc_info.Name.t -> string method create_fully_qualified_module_idents_links : Odoc_info.Name.t -> Odoc_info.Name.t -> string method create_title_label : int * string option * Odoc_info.text -> string method escape : string -> string method generate : Odoc_info.Module.t_module list -> unit method generate_attributes_index : Odoc_info.Module.t_module list -> unit method generate_class_inheritance_info : Buffer.t -> Odoc_info.Class.t_class -> unit method generate_class_type_inheritance_info : Buffer.t -> Odoc_info.Class.t_class_type -> unit method generate_class_types_index : Odoc_info.Module.t_module list -> unit method generate_classes_index : Odoc_info.Module.t_module list -> unit method generate_elements : ('a option -> 'a option -> 'a -> unit) -> 'a list -> unit method generate_elements_index : ?strip_libname:bool -> 'a list -> ('a -> Odoc_info.Name.t) -> ('a -> Odoc_info.info option) -> ('a -> string) -> string -> string -> unit method generate_exceptions_index : Odoc_info.Module.t_module list -> unit method generate_extensions_index : Odoc_info.Module.t_module list -> unit method generate_for_class : Odoc_info.Class.t_class option -> Odoc_info.Class.t_class option -> Odoc_info.Class.t_class -> unit method generate_for_class_type : Odoc_info.Class.t_class_type option -> Odoc_info.Class.t_class_type option -> Odoc_info.Class.t_class_type -> unit method generate_for_module : Odoc_info.Module.t_module option -> Odoc_info.Module.t_module option -> Odoc_info.Module.t_module -> unit method generate_for_module_type : Odoc_info.Module.t_module_type option -> Odoc_info.Module.t_module_type option -> Odoc_info.Module.t_module_type -> unit method generate_index : Odoc_info.Module.t_module list -> unit method generate_inheritance_info : Buffer.t -> Odoc_info.Class.inherited_class list -> unit method generate_methods_index : Odoc_info.Module.t_module list -> unit method generate_module_types_index : Odoc_info.Module.t_module list -> unit method generate_modules_index : Odoc_info.Module.t_module list -> unit method generate_types_index : Odoc_info.Module.t_module list -> unit method generate_values_index : Odoc_info.Module.t_module list -> unit method html_of_Block : Buffer.t -> Odoc_info.text -> unit method html_of_Bold : Buffer.t -> Odoc_info.text -> unit method html_of_Center : Buffer.t -> Odoc_info.text -> unit method html_of_Code : Buffer.t -> string -> unit method html_of_CodePre : Buffer.t -> string -> unit method html_of_Emphasize : Buffer.t -> Odoc_info.text -> unit method html_of_Enum : Buffer.t -> Odoc_info.text list -> unit method html_of_Index_list : Buffer.t -> unit method html_of_Italic : Buffer.t -> Odoc_info.text -> unit method html_of_Latex : Buffer.t -> string -> unit method html_of_Left : Buffer.t -> Odoc_info.text -> unit method html_of_Link : Buffer.t -> string -> Odoc_info.text -> unit method html_of_List : Buffer.t -> Odoc_info.text list -> unit method html_of_Module_list : Buffer.t -> Odoc_info.Name.t list -> unit method html_of_Newline : Buffer.t -> unit method html_of_Raw : Buffer.t -> string -> unit method html_of_Ref : Buffer.t -> Odoc_info.Name.t -> Odoc_info.ref_kind option -> Odoc_info.text option -> unit method html_of_Right : Buffer.t -> Odoc_info.text -> unit method html_of_Subscript : Buffer.t -> Odoc_info.text -> unit method html_of_Superscript : Buffer.t -> Odoc_info.text -> unit method html_of_Target : Buffer.t -> target:string -> code:string -> unit method html_of_Title : Buffer.t -> int -> string option -> Odoc_info.text -> unit method html_of_Verbatim : Buffer.t -> string -> unit method html_of_alerts : Buffer.t -> Odoc_info.alert list -> unit method html_of_attribute : Buffer.t -> Odoc_info.Value.t_attribute -> unit method html_of_author_list : Buffer.t -> string list -> unit method html_of_before : Buffer.t -> (string * Odoc_info.text) list -> unit method html_of_class : Buffer.t -> ?complete:bool -> ?with_link:bool -> Odoc_info.Class.t_class -> unit method html_of_class_comment : Buffer.t -> Odoc_info.text -> unit method html_of_class_element : Buffer.t -> Odoc_info.Class.class_element -> unit method html_of_class_kind : Buffer.t -> Odoc_info.Name.t -> ?cl:Odoc_info.Class.t_class -> Odoc_info.Class.class_kind -> unit method html_of_class_parameter_list : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Class.t_class -> unit method html_of_class_type : Buffer.t -> ?complete:bool -> ?with_link:bool -> Odoc_info.Class.t_class_type -> unit method html_of_class_type_kind : Buffer.t -> Odoc_info.Name.t -> ?ct:Odoc_info.Class.t_class_type -> Odoc_info.Class.class_type_kind -> unit method html_of_class_type_param_expr_list : Buffer.t -> Odoc_info.Name.t -> Types.type_expr list -> unit method html_of_code : Buffer.t -> ?with_pre:bool -> string -> unit method html_of_cstr_args : ?par:bool -> Buffer.t -> Odoc_info.Name.t -> Odoc_info.Name.t -> string -> Odoc_info.Type.constructor_args -> unit method html_of_custom : Buffer.t -> (string * Odoc_info.text) list -> unit method html_of_custom_text : Buffer.t -> string -> Odoc_info.text -> unit method html_of_dag : (Odoc_info.Name.t * Odoc_info.Class.cct option) Odoc_dag2html.dag -> string method html_of_described_parameter_list : Buffer.t -> Odoc_info.Name.t -> Odoc_parameter.parameter list -> unit method html_of_exception : Buffer.t -> Odoc_info.Exception.t_exception -> unit method html_of_included_module : Buffer.t -> Odoc_info.Module.included_module -> unit method html_of_info : ?cls:string -> ?indent:bool -> Buffer.t -> Odoc_types.info option -> unit method html_of_info_first_sentence : Buffer.t -> Odoc_info.info option -> unit method html_of_method : Buffer.t -> Odoc_info.Value.t_method -> unit method html_of_modtype : Buffer.t -> ?info:bool -> ?complete:bool -> ?with_link:bool -> Odoc_info.Module.t_module_type -> unit method html_of_module : Buffer.t -> ?info:bool -> ?complete:bool -> ?with_link:bool -> Odoc_info.Module.t_module -> unit method html_of_module_comment : Buffer.t -> Odoc_info.text -> unit method html_of_module_element : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Module.module_element -> unit method html_of_module_kind : Buffer.t -> Odoc_info.Name.t -> ?modu:Odoc_info.Module.t_module -> Odoc_info.Module.module_kind -> unit method html_of_module_parameter : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Module.module_parameter -> unit method html_of_module_parameter_list : Buffer.t -> Odoc_info.Name.t -> (Odoc_info.Module.module_parameter * Odoc_info.text option) list -> unit method html_of_module_parameter_type : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Module.module_parameter -> unit method html_of_module_type : Buffer.t -> ?code:string -> Odoc_info.Name.t -> Types.module_type -> unit method html_of_module_type_kind : Buffer.t -> Odoc_info.Name.t -> ?modu:Odoc_info.Module.t_module -> ?mt:Odoc_info.Module.t_module_type -> Odoc_info.Module.module_type_kind -> unit method html_of_parameter_description : Buffer.t -> Odoc_info.Parameter.parameter -> unit method html_of_parameter_list : Buffer.t -> Odoc_info.Name.t -> Odoc_parameter.parameter list -> unit method html_of_raised_exceptions : Buffer.t -> (string * Odoc_info.text) list -> unit method html_of_record : father:Odoc_info.Name.t -> close_env:string -> (Odoc_info.Type.record_field -> string) -> Buffer.t -> Odoc_info.Type.record_field list -> unit method html_of_return_opt : Buffer.t -> Odoc_info.text option -> unit method html_of_see : Buffer.t -> Odoc_info.see_ref * Odoc_info.text -> unit method html_of_sees : Buffer.t -> (Odoc_info.see_ref * Odoc_info.text) list -> unit method html_of_since_opt : Buffer.t -> string option -> unit method html_of_text : ?with_p:bool -> Buffer.t -> Odoc_info.text -> unit method html_of_text_element : Buffer.t -> Odoc_info.text_element -> unit method html_of_text_with_p : Buffer.t -> Odoc_info.text -> unit method html_of_type : Buffer.t -> Odoc_info.Type.t_type -> unit method html_of_type_expr : Buffer.t -> Odoc_info.Name.t -> Types.type_expr -> unit method html_of_type_expr_param_list : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Type.t_type -> unit method html_of_type_extension : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Extension.t_type_extension -> unit method html_of_value : Buffer.t -> Odoc_info.Value.t_value -> unit method html_of_version_opt : Buffer.t -> string option -> unit method html_sections_links : Buffer.t -> Odoc_info.text list -> unit method index : string method index_attributes : string method index_class_types : string method index_classes : string method index_exceptions : string method index_extensions : string method index_methods : string method index_module_types : string method index_modules : string method index_prefix : string method index_types : string method index_values : string method init_style : unit method inner_title : Odoc_info.Name.t -> string method keep_alpha_num : string -> string method keyword : string -> string method label_of_text : Odoc_info.text -> string method list_attributes : Odoc_info.Value.t_attribute list method list_class_types : Odoc_info.Class.t_class_type list method list_classes : Odoc_info.Class.t_class list method list_exceptions : Odoc_info.Exception.t_exception list method list_extensions : Odoc_info.Extension.t_extension_constructor list method list_methods : Odoc_info.Value.t_method list method list_module_types : Odoc_info.Module.t_module_type list method list_modules : Odoc_info.Module.t_module list method list_types : Odoc_info.Type.t_type list method list_values : Odoc_info.Value.t_value list method meta : Buffer.t -> unit method output_class_type : Odoc_info.Name.t -> string -> Types.class_type -> unit method private output_code : ?with_pre:bool -> Odoc_info.Name.t -> string -> string -> unit method output_module_type : Odoc_info.Name.t -> string -> Types.module_type -> unit method prepare_header : Odoc_info.Module.t_module list -> unit method print_header : Buffer.t -> ?nav:(Odoc_info.Name.t option * Odoc_info.Name.t option * Odoc_info.Name.t) option -> ?comments:Odoc_info.text list -> string -> unit method print_navbar : Buffer.t -> Odoc_info.Name.t option -> Odoc_info.Name.t option -> Odoc_info.Name.t -> unit method title : string end end module type Html_generator = sig class html : object val mutable default_style_options : string list val mutable doctype : string val mutable header : Buffer.t -> ?nav:(Odoc_info.Name.t option * Odoc_info.Name.t option * Odoc_info.Name.t) option -> ?comments:Odoc_info.text list -> string -> unit val mutable known_classes_names : String.Set.t val mutable known_modules_names : String.Set.t val mutable known_types_names : String.Set.t val mutable list_attributes : Odoc_info.Value.t_attribute list val mutable list_class_types : Odoc_info.Class.t_class_type list val mutable list_classes : Odoc_info.Class.t_class list val mutable list_exceptions : Odoc_info.Exception.t_exception list val mutable list_extensions : Odoc_info.Extension.t_extension_constructor list val mutable list_methods : Odoc_info.Value.t_method list val mutable list_module_types : Odoc_info.Module.t_module_type list val mutable list_modules : Odoc_info.Module.t_module list val mutable list_types : Odoc_info.Type.t_type list val mutable list_values : Odoc_info.Value.t_value list val mutable style : string val mutable style_file : string val mutable tag_functions : (string * (Odoc_info.text -> string)) list method character_encoding : Buffer.t -> unit method constructor : string -> string method create_fully_qualified_idents_links : Odoc_info.Name.t -> Odoc_info.Name.t -> string method create_fully_qualified_module_idents_links : Odoc_info.Name.t -> Odoc_info.Name.t -> string method create_title_label : int * string option * Odoc_info.text -> string method escape : string -> string method generate : Odoc_info.Module.t_module list -> unit method generate_attributes_index : Odoc_info.Module.t_module list -> unit method generate_class_inheritance_info : Buffer.t -> Odoc_info.Class.t_class -> unit method generate_class_type_inheritance_info : Buffer.t -> Odoc_info.Class.t_class_type -> unit method generate_class_types_index : Odoc_info.Module.t_module list -> unit method generate_classes_index : Odoc_info.Module.t_module list -> unit method generate_elements : ('a option -> 'a option -> 'a -> unit) -> 'a list -> unit method generate_elements_index : ?strip_libname:bool -> 'a list -> ('a -> Odoc_info.Name.t) -> ('a -> Odoc_info.info option) -> ('a -> string) -> string -> string -> unit method generate_exceptions_index : Odoc_info.Module.t_module list -> unit method generate_extensions_index : Odoc_info.Module.t_module list -> unit method generate_for_class : Odoc_info.Class.t_class option -> Odoc_info.Class.t_class option -> Odoc_info.Class.t_class -> unit method generate_for_class_type : Odoc_info.Class.t_class_type option -> Odoc_info.Class.t_class_type option -> Odoc_info.Class.t_class_type -> unit method generate_for_module : Odoc_info.Module.t_module option -> Odoc_info.Module.t_module option -> Odoc_info.Module.t_module -> unit method generate_for_module_type : Odoc_info.Module.t_module_type option -> Odoc_info.Module.t_module_type option -> Odoc_info.Module.t_module_type -> unit method generate_index : Odoc_info.Module.t_module list -> unit method generate_inheritance_info : Buffer.t -> Odoc_info.Class.inherited_class list -> unit method generate_methods_index : Odoc_info.Module.t_module list -> unit method generate_module_types_index : Odoc_info.Module.t_module list -> unit method generate_modules_index : Odoc_info.Module.t_module list -> unit method generate_types_index : Odoc_info.Module.t_module list -> unit method generate_values_index : Odoc_info.Module.t_module list -> unit method html_of_Block : Buffer.t -> Odoc_info.text -> unit method html_of_Bold : Buffer.t -> Odoc_info.text -> unit method html_of_Center : Buffer.t -> Odoc_info.text -> unit method html_of_Code : Buffer.t -> string -> unit method html_of_CodePre : Buffer.t -> string -> unit method html_of_Emphasize : Buffer.t -> Odoc_info.text -> unit method html_of_Enum : Buffer.t -> Odoc_info.text list -> unit method html_of_Index_list : Buffer.t -> unit method html_of_Italic : Buffer.t -> Odoc_info.text -> unit method html_of_Latex : Buffer.t -> string -> unit method html_of_Left : Buffer.t -> Odoc_info.text -> unit method html_of_Link : Buffer.t -> string -> Odoc_info.text -> unit method html_of_List : Buffer.t -> Odoc_info.text list -> unit method html_of_Module_list : Buffer.t -> Odoc_info.Name.t list -> unit method html_of_Newline : Buffer.t -> unit method html_of_Raw : Buffer.t -> string -> unit method html_of_Ref : Buffer.t -> Odoc_info.Name.t -> Odoc_info.ref_kind option -> Odoc_info.text option -> unit method html_of_Right : Buffer.t -> Odoc_info.text -> unit method html_of_Subscript : Buffer.t -> Odoc_info.text -> unit method html_of_Superscript : Buffer.t -> Odoc_info.text -> unit method html_of_Target : Buffer.t -> target:string -> code:string -> unit method html_of_Title : Buffer.t -> int -> string option -> Odoc_info.text -> unit method html_of_Verbatim : Buffer.t -> string -> unit method html_of_alerts : Buffer.t -> Odoc_info.alert list -> unit method html_of_attribute : Buffer.t -> Odoc_info.Value.t_attribute -> unit method html_of_author_list : Buffer.t -> string list -> unit method html_of_before : Buffer.t -> (string * Odoc_info.text) list -> unit method html_of_class : Buffer.t -> ?complete:bool -> ?with_link:bool -> Odoc_info.Class.t_class -> unit method html_of_class_comment : Buffer.t -> Odoc_info.text -> unit method html_of_class_element : Buffer.t -> Odoc_info.Class.class_element -> unit method html_of_class_kind : Buffer.t -> Odoc_info.Name.t -> ?cl:Odoc_info.Class.t_class -> Odoc_info.Class.class_kind -> unit method html_of_class_parameter_list : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Class.t_class -> unit method html_of_class_type : Buffer.t -> ?complete:bool -> ?with_link:bool -> Odoc_info.Class.t_class_type -> unit method html_of_class_type_kind : Buffer.t -> Odoc_info.Name.t -> ?ct:Odoc_info.Class.t_class_type -> Odoc_info.Class.class_type_kind -> unit method html_of_class_type_param_expr_list : Buffer.t -> Odoc_info.Name.t -> Types.type_expr list -> unit method html_of_code : Buffer.t -> ?with_pre:bool -> string -> unit method html_of_cstr_args : ?par:bool -> Buffer.t -> Odoc_info.Name.t -> Odoc_info.Name.t -> string -> Odoc_info.Type.constructor_args -> unit method html_of_custom : Buffer.t -> (string * Odoc_info.text) list -> unit method html_of_custom_text : Buffer.t -> string -> Odoc_info.text -> unit method html_of_dag : (Odoc_info.Name.t * Odoc_info.Class.cct option) Odoc_dag2html.dag -> string method html_of_described_parameter_list : Buffer.t -> Odoc_info.Name.t -> Odoc_parameter.parameter list -> unit method html_of_exception : Buffer.t -> Odoc_info.Exception.t_exception -> unit method html_of_included_module : Buffer.t -> Odoc_info.Module.included_module -> unit method html_of_info : ?cls:string -> ?indent:bool -> Buffer.t -> Odoc_types.info option -> unit method html_of_info_first_sentence : Buffer.t -> Odoc_info.info option -> unit method html_of_method : Buffer.t -> Odoc_info.Value.t_method -> unit method html_of_modtype : Buffer.t -> ?info:bool -> ?complete:bool -> ?with_link:bool -> Odoc_info.Module.t_module_type -> unit method html_of_module : Buffer.t -> ?info:bool -> ?complete:bool -> ?with_link:bool -> Odoc_info.Module.t_module -> unit method html_of_module_comment : Buffer.t -> Odoc_info.text -> unit method html_of_module_element : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Module.module_element -> unit method html_of_module_kind : Buffer.t -> Odoc_info.Name.t -> ?modu:Odoc_info.Module.t_module -> Odoc_info.Module.module_kind -> unit method html_of_module_parameter : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Module.module_parameter -> unit method html_of_module_parameter_list : Buffer.t -> Odoc_info.Name.t -> (Odoc_info.Module.module_parameter * Odoc_info.text option) list -> unit method html_of_module_parameter_type : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Module.module_parameter -> unit method html_of_module_type : Buffer.t -> ?code:string -> Odoc_info.Name.t -> Types.module_type -> unit method html_of_module_type_kind : Buffer.t -> Odoc_info.Name.t -> ?modu:Odoc_info.Module.t_module -> ?mt:Odoc_info.Module.t_module_type -> Odoc_info.Module.module_type_kind -> unit method html_of_parameter_description : Buffer.t -> Odoc_info.Parameter.parameter -> unit method html_of_parameter_list : Buffer.t -> Odoc_info.Name.t -> Odoc_parameter.parameter list -> unit method html_of_raised_exceptions : Buffer.t -> (string * Odoc_info.text) list -> unit method html_of_record : father:Odoc_info.Name.t -> close_env:string -> (Odoc_info.Type.record_field -> string) -> Buffer.t -> Odoc_info.Type.record_field list -> unit method html_of_return_opt : Buffer.t -> Odoc_info.text option -> unit method html_of_see : Buffer.t -> Odoc_info.see_ref * Odoc_info.text -> unit method html_of_sees : Buffer.t -> (Odoc_info.see_ref * Odoc_info.text) list -> unit method html_of_since_opt : Buffer.t -> string option -> unit method html_of_text : ?with_p:bool -> Buffer.t -> Odoc_info.text -> unit method html_of_text_element : Buffer.t -> Odoc_info.text_element -> unit method html_of_text_with_p : Buffer.t -> Odoc_info.text -> unit method html_of_type : Buffer.t -> Odoc_info.Type.t_type -> unit method html_of_type_expr : Buffer.t -> Odoc_info.Name.t -> Types.type_expr -> unit method html_of_type_expr_param_list : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Type.t_type -> unit method html_of_type_extension : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Extension.t_type_extension -> unit method html_of_value : Buffer.t -> Odoc_info.Value.t_value -> unit method html_of_version_opt : Buffer.t -> string option -> unit method html_sections_links : Buffer.t -> Odoc_info.text list -> unit method index : string method index_attributes : string method index_class_types : string method index_classes : string method index_exceptions : string method index_extensions : string method index_methods : string method index_module_types : string method index_modules : string method index_prefix : string method index_types : string method index_values : string method init_style : unit method inner_title : Odoc_info.Name.t -> string method keep_alpha_num : string -> string method keyword : string -> string method label_of_text : Odoc_info.text -> string method list_attributes : Odoc_info.Value.t_attribute list method list_class_types : Odoc_info.Class.t_class_type list method list_classes : Odoc_info.Class.t_class list method list_exceptions : Odoc_info.Exception.t_exception list method list_extensions : Odoc_info.Extension.t_extension_constructor list method list_methods : Odoc_info.Value.t_method list method list_module_types : Odoc_info.Module.t_module_type list method list_modules : Odoc_info.Module.t_module list method list_types : Odoc_info.Type.t_type list method list_values : Odoc_info.Value.t_value list method meta : Buffer.t -> unit method output_class_type : Odoc_info.Name.t -> string -> Types.class_type -> unit method private output_code : ?with_pre:bool -> Odoc_info.Name.t -> string -> string -> unit method output_module_type : Odoc_info.Name.t -> string -> Types.module_type -> unit method prepare_header : Odoc_info.Module.t_module list -> unit method print_header : Buffer.t -> ?nav:(Odoc_info.Name.t option * Odoc_info.Name.t option * Odoc_info.Name.t) option -> ?comments:Odoc_info.text list -> string -> unit method print_navbar : Buffer.t -> Odoc_info.Name.t option -> Odoc_info.Name.t option -> Odoc_info.Name.t -> unit method title : string end end
null
https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/f54002470cc6ab780963cc81b11a85a820a40819/ocamldoc/odoc_html.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Generation of html documentation.
, projet Cambium , INRIA Paris Copyright 2022 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the module String = Misc.Stdlib.String val with_parameter_list : bool ref val css_style : string option ref val index_only : bool ref val colorize_code : bool ref val html_short_functors : bool ref val charset : string ref val show_navbar : bool ref module Naming : sig val mark_module : string val mark_module_type : string val mark_type : string val mark_type_elt : string val mark_function : string val mark_extension : string val mark_exception : string val mark_value : string val mark_attribute : string val mark_method : string val code_prefix : string val type_prefix : string val html_files : string -> string * string val target : string -> string -> string val complete_target : string -> Odoc_info.Name.t -> string val module_target : Odoc_info.Module.t_module -> string val module_type_target : Odoc_info.Module.t_module_type -> string val type_target : Odoc_info.Type.t_type -> string val const_target : Odoc_info.Type.t_type -> Odoc_info.Type.variant_constructor -> string val recfield_target : Odoc_info.Type.t_type -> Odoc_info.Type.record_field -> string val inline_recfield_target : string -> string -> Odoc_info.Type.record_field -> string val objfield_target : Odoc_info.Type.t_type -> Odoc_info.Type.object_field -> string val complete_type_target : Odoc_info.Type.t_type -> string val complete_recfield_target : Odoc_info.Name.t -> string val complete_const_target : Odoc_info.Name.t -> string val extension_target : Odoc_info.Extension.t_extension_constructor -> string val complete_extension_target : Odoc_info.Extension.t_extension_constructor -> string val exception_target : Odoc_info.Exception.t_exception -> string val complete_exception_target : Odoc_info.Exception.t_exception -> string val value_target : Odoc_info.Value.t_value -> string val subst_infix_symbols : string -> string val complete_value_target : Odoc_info.Value.t_value -> string val file_code_value_complete_target : Odoc_info.Value.t_value -> string val attribute_target : Odoc_info.Value.t_attribute -> string val complete_attribute_target : Odoc_info.Value.t_attribute -> string val file_code_attribute_complete_target : Odoc_info.Value.t_attribute -> string val method_target : Odoc_info.Value.t_method -> string val complete_method_target : Odoc_info.Value.t_method -> string val file_code_method_complete_target : Odoc_info.Value.t_method -> string val label_target : string -> string val complete_label_target : Odoc_info.Name.t -> string val file_type_module_complete_target : string -> string val file_code_module_complete_target : string -> string val file_type_class_complete_target : string -> string end module Generator : sig class html : object val mutable default_style_options : string list val mutable doctype : string val mutable header : Buffer.t -> ?nav:(Odoc_info.Name.t option * Odoc_info.Name.t option * Odoc_info.Name.t) option -> ?comments:Odoc_info.text list -> string -> unit val mutable known_classes_names : String.Set.t val mutable known_modules_names : String.Set.t val mutable known_types_names : String.Set.t val mutable list_attributes : Odoc_info.Value.t_attribute list val mutable list_class_types : Odoc_info.Class.t_class_type list val mutable list_classes : Odoc_info.Class.t_class list val mutable list_exceptions : Odoc_info.Exception.t_exception list val mutable list_extensions : Odoc_info.Extension.t_extension_constructor list val mutable list_methods : Odoc_info.Value.t_method list val mutable list_module_types : Odoc_info.Module.t_module_type list val mutable list_modules : Odoc_info.Module.t_module list val mutable list_types : Odoc_info.Type.t_type list val mutable list_values : Odoc_info.Value.t_value list val mutable style : string val mutable style_file : string val mutable tag_functions : (string * (Odoc_info.text -> string)) list method character_encoding : Buffer.t -> unit method constructor : string -> string method create_fully_qualified_idents_links : Odoc_info.Name.t -> Odoc_info.Name.t -> string method create_fully_qualified_module_idents_links : Odoc_info.Name.t -> Odoc_info.Name.t -> string method create_title_label : int * string option * Odoc_info.text -> string method escape : string -> string method generate : Odoc_info.Module.t_module list -> unit method generate_attributes_index : Odoc_info.Module.t_module list -> unit method generate_class_inheritance_info : Buffer.t -> Odoc_info.Class.t_class -> unit method generate_class_type_inheritance_info : Buffer.t -> Odoc_info.Class.t_class_type -> unit method generate_class_types_index : Odoc_info.Module.t_module list -> unit method generate_classes_index : Odoc_info.Module.t_module list -> unit method generate_elements : ('a option -> 'a option -> 'a -> unit) -> 'a list -> unit method generate_elements_index : ?strip_libname:bool -> 'a list -> ('a -> Odoc_info.Name.t) -> ('a -> Odoc_info.info option) -> ('a -> string) -> string -> string -> unit method generate_exceptions_index : Odoc_info.Module.t_module list -> unit method generate_extensions_index : Odoc_info.Module.t_module list -> unit method generate_for_class : Odoc_info.Class.t_class option -> Odoc_info.Class.t_class option -> Odoc_info.Class.t_class -> unit method generate_for_class_type : Odoc_info.Class.t_class_type option -> Odoc_info.Class.t_class_type option -> Odoc_info.Class.t_class_type -> unit method generate_for_module : Odoc_info.Module.t_module option -> Odoc_info.Module.t_module option -> Odoc_info.Module.t_module -> unit method generate_for_module_type : Odoc_info.Module.t_module_type option -> Odoc_info.Module.t_module_type option -> Odoc_info.Module.t_module_type -> unit method generate_index : Odoc_info.Module.t_module list -> unit method generate_inheritance_info : Buffer.t -> Odoc_info.Class.inherited_class list -> unit method generate_methods_index : Odoc_info.Module.t_module list -> unit method generate_module_types_index : Odoc_info.Module.t_module list -> unit method generate_modules_index : Odoc_info.Module.t_module list -> unit method generate_types_index : Odoc_info.Module.t_module list -> unit method generate_values_index : Odoc_info.Module.t_module list -> unit method html_of_Block : Buffer.t -> Odoc_info.text -> unit method html_of_Bold : Buffer.t -> Odoc_info.text -> unit method html_of_Center : Buffer.t -> Odoc_info.text -> unit method html_of_Code : Buffer.t -> string -> unit method html_of_CodePre : Buffer.t -> string -> unit method html_of_Emphasize : Buffer.t -> Odoc_info.text -> unit method html_of_Enum : Buffer.t -> Odoc_info.text list -> unit method html_of_Index_list : Buffer.t -> unit method html_of_Italic : Buffer.t -> Odoc_info.text -> unit method html_of_Latex : Buffer.t -> string -> unit method html_of_Left : Buffer.t -> Odoc_info.text -> unit method html_of_Link : Buffer.t -> string -> Odoc_info.text -> unit method html_of_List : Buffer.t -> Odoc_info.text list -> unit method html_of_Module_list : Buffer.t -> Odoc_info.Name.t list -> unit method html_of_Newline : Buffer.t -> unit method html_of_Raw : Buffer.t -> string -> unit method html_of_Ref : Buffer.t -> Odoc_info.Name.t -> Odoc_info.ref_kind option -> Odoc_info.text option -> unit method html_of_Right : Buffer.t -> Odoc_info.text -> unit method html_of_Subscript : Buffer.t -> Odoc_info.text -> unit method html_of_Superscript : Buffer.t -> Odoc_info.text -> unit method html_of_Target : Buffer.t -> target:string -> code:string -> unit method html_of_Title : Buffer.t -> int -> string option -> Odoc_info.text -> unit method html_of_Verbatim : Buffer.t -> string -> unit method html_of_alerts : Buffer.t -> Odoc_info.alert list -> unit method html_of_attribute : Buffer.t -> Odoc_info.Value.t_attribute -> unit method html_of_author_list : Buffer.t -> string list -> unit method html_of_before : Buffer.t -> (string * Odoc_info.text) list -> unit method html_of_class : Buffer.t -> ?complete:bool -> ?with_link:bool -> Odoc_info.Class.t_class -> unit method html_of_class_comment : Buffer.t -> Odoc_info.text -> unit method html_of_class_element : Buffer.t -> Odoc_info.Class.class_element -> unit method html_of_class_kind : Buffer.t -> Odoc_info.Name.t -> ?cl:Odoc_info.Class.t_class -> Odoc_info.Class.class_kind -> unit method html_of_class_parameter_list : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Class.t_class -> unit method html_of_class_type : Buffer.t -> ?complete:bool -> ?with_link:bool -> Odoc_info.Class.t_class_type -> unit method html_of_class_type_kind : Buffer.t -> Odoc_info.Name.t -> ?ct:Odoc_info.Class.t_class_type -> Odoc_info.Class.class_type_kind -> unit method html_of_class_type_param_expr_list : Buffer.t -> Odoc_info.Name.t -> Types.type_expr list -> unit method html_of_code : Buffer.t -> ?with_pre:bool -> string -> unit method html_of_cstr_args : ?par:bool -> Buffer.t -> Odoc_info.Name.t -> Odoc_info.Name.t -> string -> Odoc_info.Type.constructor_args -> unit method html_of_custom : Buffer.t -> (string * Odoc_info.text) list -> unit method html_of_custom_text : Buffer.t -> string -> Odoc_info.text -> unit method html_of_dag : (Odoc_info.Name.t * Odoc_info.Class.cct option) Odoc_dag2html.dag -> string method html_of_described_parameter_list : Buffer.t -> Odoc_info.Name.t -> Odoc_parameter.parameter list -> unit method html_of_exception : Buffer.t -> Odoc_info.Exception.t_exception -> unit method html_of_included_module : Buffer.t -> Odoc_info.Module.included_module -> unit method html_of_info : ?cls:string -> ?indent:bool -> Buffer.t -> Odoc_types.info option -> unit method html_of_info_first_sentence : Buffer.t -> Odoc_info.info option -> unit method html_of_method : Buffer.t -> Odoc_info.Value.t_method -> unit method html_of_modtype : Buffer.t -> ?info:bool -> ?complete:bool -> ?with_link:bool -> Odoc_info.Module.t_module_type -> unit method html_of_module : Buffer.t -> ?info:bool -> ?complete:bool -> ?with_link:bool -> Odoc_info.Module.t_module -> unit method html_of_module_comment : Buffer.t -> Odoc_info.text -> unit method html_of_module_element : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Module.module_element -> unit method html_of_module_kind : Buffer.t -> Odoc_info.Name.t -> ?modu:Odoc_info.Module.t_module -> Odoc_info.Module.module_kind -> unit method html_of_module_parameter : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Module.module_parameter -> unit method html_of_module_parameter_list : Buffer.t -> Odoc_info.Name.t -> (Odoc_info.Module.module_parameter * Odoc_info.text option) list -> unit method html_of_module_parameter_type : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Module.module_parameter -> unit method html_of_module_type : Buffer.t -> ?code:string -> Odoc_info.Name.t -> Types.module_type -> unit method html_of_module_type_kind : Buffer.t -> Odoc_info.Name.t -> ?modu:Odoc_info.Module.t_module -> ?mt:Odoc_info.Module.t_module_type -> Odoc_info.Module.module_type_kind -> unit method html_of_parameter_description : Buffer.t -> Odoc_info.Parameter.parameter -> unit method html_of_parameter_list : Buffer.t -> Odoc_info.Name.t -> Odoc_parameter.parameter list -> unit method html_of_raised_exceptions : Buffer.t -> (string * Odoc_info.text) list -> unit method html_of_record : father:Odoc_info.Name.t -> close_env:string -> (Odoc_info.Type.record_field -> string) -> Buffer.t -> Odoc_info.Type.record_field list -> unit method html_of_return_opt : Buffer.t -> Odoc_info.text option -> unit method html_of_see : Buffer.t -> Odoc_info.see_ref * Odoc_info.text -> unit method html_of_sees : Buffer.t -> (Odoc_info.see_ref * Odoc_info.text) list -> unit method html_of_since_opt : Buffer.t -> string option -> unit method html_of_text : ?with_p:bool -> Buffer.t -> Odoc_info.text -> unit method html_of_text_element : Buffer.t -> Odoc_info.text_element -> unit method html_of_text_with_p : Buffer.t -> Odoc_info.text -> unit method html_of_type : Buffer.t -> Odoc_info.Type.t_type -> unit method html_of_type_expr : Buffer.t -> Odoc_info.Name.t -> Types.type_expr -> unit method html_of_type_expr_param_list : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Type.t_type -> unit method html_of_type_extension : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Extension.t_type_extension -> unit method html_of_value : Buffer.t -> Odoc_info.Value.t_value -> unit method html_of_version_opt : Buffer.t -> string option -> unit method html_sections_links : Buffer.t -> Odoc_info.text list -> unit method index : string method index_attributes : string method index_class_types : string method index_classes : string method index_exceptions : string method index_extensions : string method index_methods : string method index_module_types : string method index_modules : string method index_prefix : string method index_types : string method index_values : string method init_style : unit method inner_title : Odoc_info.Name.t -> string method keep_alpha_num : string -> string method keyword : string -> string method label_of_text : Odoc_info.text -> string method list_attributes : Odoc_info.Value.t_attribute list method list_class_types : Odoc_info.Class.t_class_type list method list_classes : Odoc_info.Class.t_class list method list_exceptions : Odoc_info.Exception.t_exception list method list_extensions : Odoc_info.Extension.t_extension_constructor list method list_methods : Odoc_info.Value.t_method list method list_module_types : Odoc_info.Module.t_module_type list method list_modules : Odoc_info.Module.t_module list method list_types : Odoc_info.Type.t_type list method list_values : Odoc_info.Value.t_value list method meta : Buffer.t -> unit method output_class_type : Odoc_info.Name.t -> string -> Types.class_type -> unit method private output_code : ?with_pre:bool -> Odoc_info.Name.t -> string -> string -> unit method output_module_type : Odoc_info.Name.t -> string -> Types.module_type -> unit method prepare_header : Odoc_info.Module.t_module list -> unit method print_header : Buffer.t -> ?nav:(Odoc_info.Name.t option * Odoc_info.Name.t option * Odoc_info.Name.t) option -> ?comments:Odoc_info.text list -> string -> unit method print_navbar : Buffer.t -> Odoc_info.Name.t option -> Odoc_info.Name.t option -> Odoc_info.Name.t -> unit method title : string end end module type Html_generator = sig class html : object val mutable default_style_options : string list val mutable doctype : string val mutable header : Buffer.t -> ?nav:(Odoc_info.Name.t option * Odoc_info.Name.t option * Odoc_info.Name.t) option -> ?comments:Odoc_info.text list -> string -> unit val mutable known_classes_names : String.Set.t val mutable known_modules_names : String.Set.t val mutable known_types_names : String.Set.t val mutable list_attributes : Odoc_info.Value.t_attribute list val mutable list_class_types : Odoc_info.Class.t_class_type list val mutable list_classes : Odoc_info.Class.t_class list val mutable list_exceptions : Odoc_info.Exception.t_exception list val mutable list_extensions : Odoc_info.Extension.t_extension_constructor list val mutable list_methods : Odoc_info.Value.t_method list val mutable list_module_types : Odoc_info.Module.t_module_type list val mutable list_modules : Odoc_info.Module.t_module list val mutable list_types : Odoc_info.Type.t_type list val mutable list_values : Odoc_info.Value.t_value list val mutable style : string val mutable style_file : string val mutable tag_functions : (string * (Odoc_info.text -> string)) list method character_encoding : Buffer.t -> unit method constructor : string -> string method create_fully_qualified_idents_links : Odoc_info.Name.t -> Odoc_info.Name.t -> string method create_fully_qualified_module_idents_links : Odoc_info.Name.t -> Odoc_info.Name.t -> string method create_title_label : int * string option * Odoc_info.text -> string method escape : string -> string method generate : Odoc_info.Module.t_module list -> unit method generate_attributes_index : Odoc_info.Module.t_module list -> unit method generate_class_inheritance_info : Buffer.t -> Odoc_info.Class.t_class -> unit method generate_class_type_inheritance_info : Buffer.t -> Odoc_info.Class.t_class_type -> unit method generate_class_types_index : Odoc_info.Module.t_module list -> unit method generate_classes_index : Odoc_info.Module.t_module list -> unit method generate_elements : ('a option -> 'a option -> 'a -> unit) -> 'a list -> unit method generate_elements_index : ?strip_libname:bool -> 'a list -> ('a -> Odoc_info.Name.t) -> ('a -> Odoc_info.info option) -> ('a -> string) -> string -> string -> unit method generate_exceptions_index : Odoc_info.Module.t_module list -> unit method generate_extensions_index : Odoc_info.Module.t_module list -> unit method generate_for_class : Odoc_info.Class.t_class option -> Odoc_info.Class.t_class option -> Odoc_info.Class.t_class -> unit method generate_for_class_type : Odoc_info.Class.t_class_type option -> Odoc_info.Class.t_class_type option -> Odoc_info.Class.t_class_type -> unit method generate_for_module : Odoc_info.Module.t_module option -> Odoc_info.Module.t_module option -> Odoc_info.Module.t_module -> unit method generate_for_module_type : Odoc_info.Module.t_module_type option -> Odoc_info.Module.t_module_type option -> Odoc_info.Module.t_module_type -> unit method generate_index : Odoc_info.Module.t_module list -> unit method generate_inheritance_info : Buffer.t -> Odoc_info.Class.inherited_class list -> unit method generate_methods_index : Odoc_info.Module.t_module list -> unit method generate_module_types_index : Odoc_info.Module.t_module list -> unit method generate_modules_index : Odoc_info.Module.t_module list -> unit method generate_types_index : Odoc_info.Module.t_module list -> unit method generate_values_index : Odoc_info.Module.t_module list -> unit method html_of_Block : Buffer.t -> Odoc_info.text -> unit method html_of_Bold : Buffer.t -> Odoc_info.text -> unit method html_of_Center : Buffer.t -> Odoc_info.text -> unit method html_of_Code : Buffer.t -> string -> unit method html_of_CodePre : Buffer.t -> string -> unit method html_of_Emphasize : Buffer.t -> Odoc_info.text -> unit method html_of_Enum : Buffer.t -> Odoc_info.text list -> unit method html_of_Index_list : Buffer.t -> unit method html_of_Italic : Buffer.t -> Odoc_info.text -> unit method html_of_Latex : Buffer.t -> string -> unit method html_of_Left : Buffer.t -> Odoc_info.text -> unit method html_of_Link : Buffer.t -> string -> Odoc_info.text -> unit method html_of_List : Buffer.t -> Odoc_info.text list -> unit method html_of_Module_list : Buffer.t -> Odoc_info.Name.t list -> unit method html_of_Newline : Buffer.t -> unit method html_of_Raw : Buffer.t -> string -> unit method html_of_Ref : Buffer.t -> Odoc_info.Name.t -> Odoc_info.ref_kind option -> Odoc_info.text option -> unit method html_of_Right : Buffer.t -> Odoc_info.text -> unit method html_of_Subscript : Buffer.t -> Odoc_info.text -> unit method html_of_Superscript : Buffer.t -> Odoc_info.text -> unit method html_of_Target : Buffer.t -> target:string -> code:string -> unit method html_of_Title : Buffer.t -> int -> string option -> Odoc_info.text -> unit method html_of_Verbatim : Buffer.t -> string -> unit method html_of_alerts : Buffer.t -> Odoc_info.alert list -> unit method html_of_attribute : Buffer.t -> Odoc_info.Value.t_attribute -> unit method html_of_author_list : Buffer.t -> string list -> unit method html_of_before : Buffer.t -> (string * Odoc_info.text) list -> unit method html_of_class : Buffer.t -> ?complete:bool -> ?with_link:bool -> Odoc_info.Class.t_class -> unit method html_of_class_comment : Buffer.t -> Odoc_info.text -> unit method html_of_class_element : Buffer.t -> Odoc_info.Class.class_element -> unit method html_of_class_kind : Buffer.t -> Odoc_info.Name.t -> ?cl:Odoc_info.Class.t_class -> Odoc_info.Class.class_kind -> unit method html_of_class_parameter_list : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Class.t_class -> unit method html_of_class_type : Buffer.t -> ?complete:bool -> ?with_link:bool -> Odoc_info.Class.t_class_type -> unit method html_of_class_type_kind : Buffer.t -> Odoc_info.Name.t -> ?ct:Odoc_info.Class.t_class_type -> Odoc_info.Class.class_type_kind -> unit method html_of_class_type_param_expr_list : Buffer.t -> Odoc_info.Name.t -> Types.type_expr list -> unit method html_of_code : Buffer.t -> ?with_pre:bool -> string -> unit method html_of_cstr_args : ?par:bool -> Buffer.t -> Odoc_info.Name.t -> Odoc_info.Name.t -> string -> Odoc_info.Type.constructor_args -> unit method html_of_custom : Buffer.t -> (string * Odoc_info.text) list -> unit method html_of_custom_text : Buffer.t -> string -> Odoc_info.text -> unit method html_of_dag : (Odoc_info.Name.t * Odoc_info.Class.cct option) Odoc_dag2html.dag -> string method html_of_described_parameter_list : Buffer.t -> Odoc_info.Name.t -> Odoc_parameter.parameter list -> unit method html_of_exception : Buffer.t -> Odoc_info.Exception.t_exception -> unit method html_of_included_module : Buffer.t -> Odoc_info.Module.included_module -> unit method html_of_info : ?cls:string -> ?indent:bool -> Buffer.t -> Odoc_types.info option -> unit method html_of_info_first_sentence : Buffer.t -> Odoc_info.info option -> unit method html_of_method : Buffer.t -> Odoc_info.Value.t_method -> unit method html_of_modtype : Buffer.t -> ?info:bool -> ?complete:bool -> ?with_link:bool -> Odoc_info.Module.t_module_type -> unit method html_of_module : Buffer.t -> ?info:bool -> ?complete:bool -> ?with_link:bool -> Odoc_info.Module.t_module -> unit method html_of_module_comment : Buffer.t -> Odoc_info.text -> unit method html_of_module_element : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Module.module_element -> unit method html_of_module_kind : Buffer.t -> Odoc_info.Name.t -> ?modu:Odoc_info.Module.t_module -> Odoc_info.Module.module_kind -> unit method html_of_module_parameter : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Module.module_parameter -> unit method html_of_module_parameter_list : Buffer.t -> Odoc_info.Name.t -> (Odoc_info.Module.module_parameter * Odoc_info.text option) list -> unit method html_of_module_parameter_type : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Module.module_parameter -> unit method html_of_module_type : Buffer.t -> ?code:string -> Odoc_info.Name.t -> Types.module_type -> unit method html_of_module_type_kind : Buffer.t -> Odoc_info.Name.t -> ?modu:Odoc_info.Module.t_module -> ?mt:Odoc_info.Module.t_module_type -> Odoc_info.Module.module_type_kind -> unit method html_of_parameter_description : Buffer.t -> Odoc_info.Parameter.parameter -> unit method html_of_parameter_list : Buffer.t -> Odoc_info.Name.t -> Odoc_parameter.parameter list -> unit method html_of_raised_exceptions : Buffer.t -> (string * Odoc_info.text) list -> unit method html_of_record : father:Odoc_info.Name.t -> close_env:string -> (Odoc_info.Type.record_field -> string) -> Buffer.t -> Odoc_info.Type.record_field list -> unit method html_of_return_opt : Buffer.t -> Odoc_info.text option -> unit method html_of_see : Buffer.t -> Odoc_info.see_ref * Odoc_info.text -> unit method html_of_sees : Buffer.t -> (Odoc_info.see_ref * Odoc_info.text) list -> unit method html_of_since_opt : Buffer.t -> string option -> unit method html_of_text : ?with_p:bool -> Buffer.t -> Odoc_info.text -> unit method html_of_text_element : Buffer.t -> Odoc_info.text_element -> unit method html_of_text_with_p : Buffer.t -> Odoc_info.text -> unit method html_of_type : Buffer.t -> Odoc_info.Type.t_type -> unit method html_of_type_expr : Buffer.t -> Odoc_info.Name.t -> Types.type_expr -> unit method html_of_type_expr_param_list : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Type.t_type -> unit method html_of_type_extension : Buffer.t -> Odoc_info.Name.t -> Odoc_info.Extension.t_type_extension -> unit method html_of_value : Buffer.t -> Odoc_info.Value.t_value -> unit method html_of_version_opt : Buffer.t -> string option -> unit method html_sections_links : Buffer.t -> Odoc_info.text list -> unit method index : string method index_attributes : string method index_class_types : string method index_classes : string method index_exceptions : string method index_extensions : string method index_methods : string method index_module_types : string method index_modules : string method index_prefix : string method index_types : string method index_values : string method init_style : unit method inner_title : Odoc_info.Name.t -> string method keep_alpha_num : string -> string method keyword : string -> string method label_of_text : Odoc_info.text -> string method list_attributes : Odoc_info.Value.t_attribute list method list_class_types : Odoc_info.Class.t_class_type list method list_classes : Odoc_info.Class.t_class list method list_exceptions : Odoc_info.Exception.t_exception list method list_extensions : Odoc_info.Extension.t_extension_constructor list method list_methods : Odoc_info.Value.t_method list method list_module_types : Odoc_info.Module.t_module_type list method list_modules : Odoc_info.Module.t_module list method list_types : Odoc_info.Type.t_type list method list_values : Odoc_info.Value.t_value list method meta : Buffer.t -> unit method output_class_type : Odoc_info.Name.t -> string -> Types.class_type -> unit method private output_code : ?with_pre:bool -> Odoc_info.Name.t -> string -> string -> unit method output_module_type : Odoc_info.Name.t -> string -> Types.module_type -> unit method prepare_header : Odoc_info.Module.t_module list -> unit method print_header : Buffer.t -> ?nav:(Odoc_info.Name.t option * Odoc_info.Name.t option * Odoc_info.Name.t) option -> ?comments:Odoc_info.text list -> string -> unit method print_navbar : Buffer.t -> Odoc_info.Name.t option -> Odoc_info.Name.t option -> Odoc_info.Name.t -> unit method title : string end end
d36bc5228832fe48560292fe3b4682a9060c0595ad28713d68bf82aeb02e9002
shayne-fletcher/zen
slice.ml
module type STREAM = sig type 'a t val empty : 'a t val exhausted : 'a t -> bool val hd : 'a t -> 'a val tl : 'a t -> 'a t val iter : ('a -> unit) -> 'a t -> unit val cons : 'a * (unit -> 'a t) -> 'a t val uncons : 'a t -> ('a * 'a t) val of_list : 'a list -> 'a t val to_list : 'a t -> 'a list val concat : 'a t -> 'a t -> 'a t val map : ('a -> 'b) -> 'a t -> 'b t val print : (Format.formatter -> 'a -> unit) -> (Format.formatter) -> 'a t -> unit end module Stream : STREAM = struct type 'a t = Nil | Cons of 'a * (unit -> 'a t) let empty : 'a t = Nil let exhausted : 'a t -> bool = function | Nil -> true | _ -> false let cons : 'a * (unit -> 'a t) -> 'a t = fun (h, t) -> Cons (h, t) let of_list (l : 'a list) : 'a t = List.fold_right (fun x s -> Cons (x, fun () -> s)) l empty let hd : 'a t -> 'a = function | Nil -> failwith "hd" | Cons (h, _) -> h let tl : 'a t -> 'a t = function | Nil -> failwith "tl" | Cons (_, t) -> t () let uncons : 'a t -> ('a * 'a t) = fun s -> (hd s, tl s) let rec iter : ('a -> unit) -> 'a t -> unit = fun f -> function | Nil -> () | Cons (h, t) -> f h; iter f (t ()) let rec to_list : 'a t -> 'a list = function | Nil -> [] | Cons (h, t) -> h :: (to_list (t ())) let print (f : Format.formatter -> 'a -> unit) (fmt : Format.formatter) (s : 'a t) : unit = let open Format in begin pp_print_list ~pp_sep:pp_print_space f fmt (to_list s); pp_print_newline fmt () end let rec concat (u : 'a t) (v : 'a t) : 'a t = match u with | Nil -> v | Cons (h, tl) -> Cons (h, fun () -> concat (tl ()) v) let rec map (f : 'a -> 'b) (s : 'a t) : 'b t = match s with | Nil -> Nil | Cons (h, tl) -> Cons (f h, fun () -> map f (tl ())) end module type INT = sig type t val zero : t val one : t val add : t -> t -> t val sub : t -> t -> t val compare : t -> t -> int val of_int : int -> t val print : (Format.formatter) -> t -> unit end module type SLICE = functor (I : INT) (S : STREAM) -> sig type int_t = I.t type stream_t = int_t S.t type slice = | Slice_all | Slice_one of int_t | Slice_many of int_t list | Slice_from of int_t | Slice_from_counted of int_t * int_t | Slice_range_incl of int_t * int_t | Slice_range_excl of int_t * int_t | Slice_to_incl of int_t | Slice_to_excl of int_t val iterator : slice -> stream_t val print : (Format.formatter) -> stream_t -> unit end module Slice : SLICE = functor (I : INT) (S : STREAM) -> struct type int_t = I.t type stream_t = int_t S.t type slice = | Slice_all | Slice_one of int_t | Slice_many of int_t list | Slice_from of int_t | Slice_from_counted of int_t * int_t | Slice_range_incl of int_t * int_t | Slice_range_excl of int_t * int_t | Slice_to_incl of int_t | Slice_to_excl of int_t let slice_one (x : int_t) : stream_t = S.cons (x, fun () -> S.empty) let slice_many (l : int_t list) : stream_t = S.of_list l let rec slice_from (first : int_t) : stream_t = let next = I.add first (I.one) in if I.compare first next < 0 then S.empty else S.cons ( first , fun () -> slice_from next ) let slice_all () : stream_t = slice_from (I.zero) let rec slice_from_counted (first : int_t) (count : int_t) : stream_t = if I.compare count (I.zero) <= 0 then S.empty else S.cons ( first , fun () -> slice_from_counted (I.add first I.one) (I.sub count I.one) ) let rec slice_range_incl (first : int_t) (last : int_t) : stream_t = if (I.compare first last) > 0 then S.empty else S.cons ( first , fun () -> slice_range_incl (I.add first I.one) last ) let rec slice_range_excl (first : int_t) (last : int_t) : stream_t = if I.compare first last >= 0 then S.empty else S.cons ( first , fun () -> slice_range_excl (I.add first I.one) last ) let print (fmt : Format.formatter) (s : stream_t) : unit = S.print I.print fmt s let iterator (s : slice) : stream_t = match s with | Slice_all -> slice_all () | Slice_one x -> slice_one x | Slice_many l -> slice_many l | Slice_from i -> slice_from i | Slice_from_counted (i, cnt) -> slice_from_counted i cnt | Slice_range_incl (i, j) -> slice_range_incl i j | Slice_range_excl (i, j) -> slice_range_excl i j | Slice_to_incl j -> slice_range_incl I.zero j | Slice_to_excl j -> slice_range_excl I.zero j end (*Scratch*) module Native_int : INT = struct type t = int let compare = Pervasives.compare let zero = 0 let one = 1 let of_int i = i let add x y = x + y let sub x y = x - y let print fmt x = Format.fprintf fmt "%d" x end module type GSLICE = functor (Int : INT) (Stream : STREAM) -> sig type slice = Slice(Int)(Stream).slice type int_t = Slice(Int)(Stream).int_t type stream_t = Slice(Int)(Stream).stream_t type gslice = | GSlice of slice | GSlice_list of gslice list | GSlice_iter of (unit -> int_t option) | GSlice_map of (int_t -> int_t) * gslice end module GSlice = functor (Int : INT) (Stream : STREAM) -> struct module Slice = Slice(Int)(Stream) type slice = Slice.slice type int_t = Slice.int_t type stream_t = Slice.stream_t type gslice = | GSlice of slice | GSlice_list of gslice list | GSlice_iter of (unit -> stream_t) | GSlice_map of (int_t -> int_t) * gslice let rec iterator : gslice -> stream_t = function | GSlice s -> Slice.iterator s | GSlice_list l -> gslist_iterator l | GSlice_map (f, gs) -> gsmap_iterator f gs | GSlice_iter it -> gslice_iterator it | _ -> failwith "GSlice.iterator : Not implemented" and gslist_iterator (ls : gslice list) : stream_t = match ls with | [] -> Stream.empty | (h :: t) -> Stream.concat (iterator h) (gslist_iterator t) and gsmap_iterator (f : int_t -> int_t) (gs : gslice) : stream_t = Stream.map f (iterator gs) and gslice_iterator (it : unit -> stream_t) : stream_t = it () end module S = Slice (Native_int)(Stream) let stdout : Format.formatter = Format.std_formatter let () = S.print stdout @@ S.iterator @@ S.Slice_from_counted (Native_int.of_int 0, Native_int.of_int 20) let () = S.print stdout @@ S.iterator @@ S.Slice_range_incl (Native_int.of_int 0, Native_int.of_int 20) let () = S.print stdout @@ S.iterator @@ S.Slice_range_excl (Native_int.of_int 0, Native_int.of_int 20) let () = let u = S.Slice_range_excl (Native_int.of_int 0, Native_int.of_int 20) and v = S.Slice_range_excl (Native_int.of_int 20, Native_int.of_int 40) in let w = Stream.concat (S.iterator u) (S.iterator v) in S.print stdout w
null
https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/slice/slice.ml
ocaml
Scratch
module type STREAM = sig type 'a t val empty : 'a t val exhausted : 'a t -> bool val hd : 'a t -> 'a val tl : 'a t -> 'a t val iter : ('a -> unit) -> 'a t -> unit val cons : 'a * (unit -> 'a t) -> 'a t val uncons : 'a t -> ('a * 'a t) val of_list : 'a list -> 'a t val to_list : 'a t -> 'a list val concat : 'a t -> 'a t -> 'a t val map : ('a -> 'b) -> 'a t -> 'b t val print : (Format.formatter -> 'a -> unit) -> (Format.formatter) -> 'a t -> unit end module Stream : STREAM = struct type 'a t = Nil | Cons of 'a * (unit -> 'a t) let empty : 'a t = Nil let exhausted : 'a t -> bool = function | Nil -> true | _ -> false let cons : 'a * (unit -> 'a t) -> 'a t = fun (h, t) -> Cons (h, t) let of_list (l : 'a list) : 'a t = List.fold_right (fun x s -> Cons (x, fun () -> s)) l empty let hd : 'a t -> 'a = function | Nil -> failwith "hd" | Cons (h, _) -> h let tl : 'a t -> 'a t = function | Nil -> failwith "tl" | Cons (_, t) -> t () let uncons : 'a t -> ('a * 'a t) = fun s -> (hd s, tl s) let rec iter : ('a -> unit) -> 'a t -> unit = fun f -> function | Nil -> () | Cons (h, t) -> f h; iter f (t ()) let rec to_list : 'a t -> 'a list = function | Nil -> [] | Cons (h, t) -> h :: (to_list (t ())) let print (f : Format.formatter -> 'a -> unit) (fmt : Format.formatter) (s : 'a t) : unit = let open Format in begin pp_print_list ~pp_sep:pp_print_space f fmt (to_list s); pp_print_newline fmt () end let rec concat (u : 'a t) (v : 'a t) : 'a t = match u with | Nil -> v | Cons (h, tl) -> Cons (h, fun () -> concat (tl ()) v) let rec map (f : 'a -> 'b) (s : 'a t) : 'b t = match s with | Nil -> Nil | Cons (h, tl) -> Cons (f h, fun () -> map f (tl ())) end module type INT = sig type t val zero : t val one : t val add : t -> t -> t val sub : t -> t -> t val compare : t -> t -> int val of_int : int -> t val print : (Format.formatter) -> t -> unit end module type SLICE = functor (I : INT) (S : STREAM) -> sig type int_t = I.t type stream_t = int_t S.t type slice = | Slice_all | Slice_one of int_t | Slice_many of int_t list | Slice_from of int_t | Slice_from_counted of int_t * int_t | Slice_range_incl of int_t * int_t | Slice_range_excl of int_t * int_t | Slice_to_incl of int_t | Slice_to_excl of int_t val iterator : slice -> stream_t val print : (Format.formatter) -> stream_t -> unit end module Slice : SLICE = functor (I : INT) (S : STREAM) -> struct type int_t = I.t type stream_t = int_t S.t type slice = | Slice_all | Slice_one of int_t | Slice_many of int_t list | Slice_from of int_t | Slice_from_counted of int_t * int_t | Slice_range_incl of int_t * int_t | Slice_range_excl of int_t * int_t | Slice_to_incl of int_t | Slice_to_excl of int_t let slice_one (x : int_t) : stream_t = S.cons (x, fun () -> S.empty) let slice_many (l : int_t list) : stream_t = S.of_list l let rec slice_from (first : int_t) : stream_t = let next = I.add first (I.one) in if I.compare first next < 0 then S.empty else S.cons ( first , fun () -> slice_from next ) let slice_all () : stream_t = slice_from (I.zero) let rec slice_from_counted (first : int_t) (count : int_t) : stream_t = if I.compare count (I.zero) <= 0 then S.empty else S.cons ( first , fun () -> slice_from_counted (I.add first I.one) (I.sub count I.one) ) let rec slice_range_incl (first : int_t) (last : int_t) : stream_t = if (I.compare first last) > 0 then S.empty else S.cons ( first , fun () -> slice_range_incl (I.add first I.one) last ) let rec slice_range_excl (first : int_t) (last : int_t) : stream_t = if I.compare first last >= 0 then S.empty else S.cons ( first , fun () -> slice_range_excl (I.add first I.one) last ) let print (fmt : Format.formatter) (s : stream_t) : unit = S.print I.print fmt s let iterator (s : slice) : stream_t = match s with | Slice_all -> slice_all () | Slice_one x -> slice_one x | Slice_many l -> slice_many l | Slice_from i -> slice_from i | Slice_from_counted (i, cnt) -> slice_from_counted i cnt | Slice_range_incl (i, j) -> slice_range_incl i j | Slice_range_excl (i, j) -> slice_range_excl i j | Slice_to_incl j -> slice_range_incl I.zero j | Slice_to_excl j -> slice_range_excl I.zero j end module Native_int : INT = struct type t = int let compare = Pervasives.compare let zero = 0 let one = 1 let of_int i = i let add x y = x + y let sub x y = x - y let print fmt x = Format.fprintf fmt "%d" x end module type GSLICE = functor (Int : INT) (Stream : STREAM) -> sig type slice = Slice(Int)(Stream).slice type int_t = Slice(Int)(Stream).int_t type stream_t = Slice(Int)(Stream).stream_t type gslice = | GSlice of slice | GSlice_list of gslice list | GSlice_iter of (unit -> int_t option) | GSlice_map of (int_t -> int_t) * gslice end module GSlice = functor (Int : INT) (Stream : STREAM) -> struct module Slice = Slice(Int)(Stream) type slice = Slice.slice type int_t = Slice.int_t type stream_t = Slice.stream_t type gslice = | GSlice of slice | GSlice_list of gslice list | GSlice_iter of (unit -> stream_t) | GSlice_map of (int_t -> int_t) * gslice let rec iterator : gslice -> stream_t = function | GSlice s -> Slice.iterator s | GSlice_list l -> gslist_iterator l | GSlice_map (f, gs) -> gsmap_iterator f gs | GSlice_iter it -> gslice_iterator it | _ -> failwith "GSlice.iterator : Not implemented" and gslist_iterator (ls : gslice list) : stream_t = match ls with | [] -> Stream.empty | (h :: t) -> Stream.concat (iterator h) (gslist_iterator t) and gsmap_iterator (f : int_t -> int_t) (gs : gslice) : stream_t = Stream.map f (iterator gs) and gslice_iterator (it : unit -> stream_t) : stream_t = it () end module S = Slice (Native_int)(Stream) let stdout : Format.formatter = Format.std_formatter let () = S.print stdout @@ S.iterator @@ S.Slice_from_counted (Native_int.of_int 0, Native_int.of_int 20) let () = S.print stdout @@ S.iterator @@ S.Slice_range_incl (Native_int.of_int 0, Native_int.of_int 20) let () = S.print stdout @@ S.iterator @@ S.Slice_range_excl (Native_int.of_int 0, Native_int.of_int 20) let () = let u = S.Slice_range_excl (Native_int.of_int 0, Native_int.of_int 20) and v = S.Slice_range_excl (Native_int.of_int 20, Native_int.of_int 40) in let w = Stream.concat (S.iterator u) (S.iterator v) in S.print stdout w
8682f2b9ff08186c2bd00d14cf89d6f19adb6c349790aebd24131c7911814fbe
Perry961002/SICP
exa3.5.4-stream-and-delay.scm
将被积流看作一个延时参数 integral将在需要生成输出流第一个元素之后的元素时force积分对象的求值 (define (integral delayed-integrand initial-value dt) (define int (stream-cons initial-value (let ((integrand (force delayed-integrand))) (add-streams (scale-stream integrand dt) int)))) int) ;定义solve时在y的定义里延时求值dy (define (solve f y0 dt) (define y (integral (delay dy) y0 dt)) (define dy (stream-map f y)) y) ;测试 (stream-ref (solve (lambda (y) y) 1 0.001) 1000) 2.716923932235896
null
https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap3/example/exa3.5.4-stream-and-delay.scm
scheme
定义solve时在y的定义里延时求值dy 测试
将被积流看作一个延时参数 integral将在需要生成输出流第一个元素之后的元素时force积分对象的求值 (define (integral delayed-integrand initial-value dt) (define int (stream-cons initial-value (let ((integrand (force delayed-integrand))) (add-streams (scale-stream integrand dt) int)))) int) (define (solve f y0 dt) (define y (integral (delay dy) y0 dt)) (define dy (stream-map f y)) y) (stream-ref (solve (lambda (y) y) 1 0.001) 1000) 2.716923932235896
8a845e03cfc09650d90f7e132bf759cf1e8a26cbe9e7dc1dfd2a6f4e7778c300
garrigue/labltk
maincompile.ml
(***********************************************************************) (* *) MLTk , Tcl / Tk interface of OCaml (* *) , , and projet Cristal , INRIA Rocquencourt , Kyoto University RIMS (* *) Copyright 2002 Institut National de Recherche en Informatique et en Automatique and Kyoto University . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with the special exception on linking (* described in file LICENSE found in the OCaml source tree. *) (* *) (***********************************************************************) $ Id$ open StdLabels open Tables open Printer open Compile open Intf let flag_verbose = ref false let verbose_string s = if !flag_verbose then prerr_string s let verbose_endline s = if !flag_verbose then prerr_endline s let input_name = ref "Widgets.src" let output_dir = ref "" let destfile f = Filename.concat !output_dir f let usage () = prerr_string "Usage: tkcompiler input.src\n"; flush stderr; exit 1 let prerr_error_header () = prerr_string "File \""; prerr_string !input_name; prerr_string "\", line "; prerr_string (string_of_int !Lexer.current_line); prerr_string ": " parse Widget.src config file let parse_file filename = let ic = open_in_bin filename in let lexbuf = try let code_list = Ppparse.parse_channel ic in close_in ic; let buf = Buffer.create 50000 in List.iter ~f:(Ppexec.exec (fun l -> Buffer.add_string buf (Printf.sprintf "##line %d\n" l)) (Buffer.add_string buf)) (if !Flags.camltk then Code.Define "CAMLTK" :: code_list else code_list); Lexing.from_string (Buffer.contents buf) with | Ppparse.Error s -> close_in ic; raise (Compiler_Error (Printf.sprintf "Preprocess error: %s" s)) in try while true do Parser.entry Lexer.main lexbuf done with | Parsing.Parse_error -> prerr_error_header(); prerr_string "Syntax error \n"; exit 1 | Lexer.Lexical_error s -> prerr_error_header(); prerr_string "Lexical error ("; prerr_string s; prerr_string ")\n"; exit 1 | Duplicate_Definition (s,s') -> prerr_error_header(); prerr_string s; prerr_string " "; prerr_string s'; prerr_string " is defined twice.\n"; exit 1 | Compiler_Error s -> prerr_error_header(); prerr_string "Internal error: "; prerr_string s; prerr_string "\n"; prerr_string "Please report bug\n"; exit 1 | End_of_file -> () The hack to provoke the production of cCAMLtoTKoptions_constrs (* Auxiliary function: the list of all the elements associated to keys in an hash table. *) let elements t = let elems = ref [] in Hashtbl.iter (fun _ d -> elems := d :: !elems) t; !elems;; Verifies that duplicated clauses are semantically equivalent and returns a unique set of clauses . returns a unique set of clauses. *) let uniq_clauses = function | [] -> [] | l -> let check_constr constr1 constr2 = if constr1.template <> constr2.template then begin let code1, vars11, vars12, opts1 = code_of_template ~context_widget:"dummy" constr1.template in let code2, vars12, vars22, opts2 = code_of_template ~context_widget:"dummy" constr2.template in let err = Printf.sprintf "uncompatible redondant clauses for variant %s:\n %s\n and\n %s" constr1.var_name code1 code2 in Format.print_newline(); print_fullcomponent constr1; Format.print_newline(); print_fullcomponent constr2; Format.print_newline(); prerr_endline err; fatal_error err end in let t = Hashtbl.create 11 in List.iter l ~f:(fun constr -> let c = constr.var_name in if Hashtbl.mem t c then (check_constr constr (Hashtbl.find t c)) else Hashtbl.add t c constr); elements t;; let option_hack oc = if Hashtbl.mem types_table "options" then let typdef = Hashtbl.find types_table "options" in let hack = { parser_arity = OneToken; constructors = begin let constrs = List.map typdef.constructors ~f: begin fun c -> { component = Constructor; ml_name = (if !Flags.camltk then "C" ^ c.ml_name else c.ml_name); var_name = c.var_name; (* as variants *) template = begin match c.template with ListArg (x :: _) -> x | _ -> fatal_error "bogus hack" end; result = UserDefined "options_constrs"; safe = true } end in if !Flags.camltk then constrs else uniq_clauses constrs (* JPF ?? *) end; subtypes = []; requires_widget_context = false; variant = false } in write_CAMLtoTK ~w:(output_string oc) ~def:hack ~safetype:false "options_constrs" let realname name = (* module name fix for camltk *) let name = caml_name name in if !Flags.camltk then "c" ^ String.capitalize_ascii name else name ;; analize the parsed Widget.src and output source files let compile () = verbose_endline "Creating _tkgen.ml ..."; let oc = open_out_bin (destfile "_tkgen.ml") in let oc' = open_out_bin (destfile "_tkigen.ml") in let oc'' = open_out_bin (destfile "_tkfgen.ml") in let sorted_types = Tsort.sort types_order in verbose_endline " writing types ..."; List.iter sorted_types ~f: begin fun typname -> verbose_string (" " ^ typname ^ " "); try let typdef = Hashtbl.find types_table typname in verbose_string "type "; write_type ~intf:(output_string oc) ~impl:(output_string oc') typname ~def:typdef; verbose_string "C2T "; write_CAMLtoTK ~w:(output_string oc') typname ~def:typdef; verbose_string "T2C "; if List.mem typname ~set:!types_returned then write_TKtoCAML ~w:(output_string oc') typname ~def:typdef; verbose_string "CO "; if not !Flags.camltk then (* only for LablTk *) write_catch_optionals ~w:(output_string oc') typname ~def:typdef; verbose_endline "." with Not_found -> if not (List.mem_assoc typname ~map:!types_external) then begin verbose_string "Type "; verbose_string typname; verbose_string " is undeclared external or undefined\n" end else verbose_endline "." end; verbose_endline " option hacking ..."; option_hack oc'; verbose_endline " writing functions ..."; List.iter ~f:(write_function ~w:(output_string oc'')) !function_table; close_out oc; close_out oc'; close_out oc''; (* Write the interface for public functions *) (* this interface is used only for documentation *) verbose_endline "Creating _tkgen.mli ..."; let oc = open_out_bin (destfile "_tkgen.mli") in List.iter (sort_components !function_table) ~f:(write_function_type ~w:(output_string oc)); close_out oc; verbose_endline "Creating other ml, mli ..."; let write_module wname wdef = verbose_endline (" "^wname); let modname = realname wname in let oc = open_out_bin (destfile (modname ^ ".ml")) and oc' = open_out_bin (destfile (modname ^ ".mli")) in Copyright.write ~w:(output_string oc); Copyright.write ~w:(output_string oc'); begin match wdef.module_type with Widget -> output_string oc' ("(** The "^wname^" widget *)\n") | Family -> output_string oc' ("(** The "^wname^" commands *)\n") end; List.iter ~f:(fun s -> output_string oc s; output_string oc' s) begin if !Flags.camltk then [ "open CTk\n"; "open Tkintf\n"; "open Widget\n"; "open Textvariable\n\n" ] else [ "open StdLabels\n"; "open Tk\n"; "open Tkintf\n"; "open Widget\n"; "open Textvariable\n\n" ] end; output_string oc "open Protocol\n"; begin match wdef.module_type with Widget -> if !Flags.camltk then begin camltk_write_create ~w:(output_string oc) wname; camltk_write_named_create ~w:(output_string oc) wname; camltk_write_create_p ~w:(output_string oc') wname; camltk_write_named_create_p ~w:(output_string oc') wname; end else begin labltk_write_create ~w:(output_string oc) wname; labltk_write_create_p ~w:(output_string oc') wname end | Family -> () end; List.iter ~f:(write_function ~w:(output_string oc)) (sort_components wdef.commands); List.iter ~f:(write_function_type ~w:(output_string oc')) (sort_components wdef.commands); List.iter ~f:(write_external ~w:(output_string oc)) (sort_components wdef.externals); List.iter ~f:(write_external_type ~w:(output_string oc')) (sort_components wdef.externals); close_out oc; close_out oc' in Hashtbl.iter write_module module_table; (* wrapper code camltk.ml and labltk.ml *) if !Flags.camltk then begin let oc = open_out_bin (destfile "camltk.ml") in Copyright.write ~w:(output_string oc); output_string oc * This module Camltk provides the module name spaces of the CamlTk API.\n\ \n\ The users of the CamlTk API should open this module first to access\n\ the types , functions and modules of the CamlTk API easier.\n\ For the documentation of each sub modules such as [ Button ] and [ Toplevel],\n\ refer to its defintion file , [ cButton.mli ] , [ cToplevel.mli ] , etc.\n\ \n\ The users of the CamlTk API should open this module first to access\n\ the types, functions and modules of the CamlTk API easier.\n\ For the documentation of each sub modules such as [Button] and [Toplevel],\n\ refer to its defintion file, [cButton.mli], [cToplevel.mli], etc.\n\ *)\n\ \n\ "; output_string oc "include CTk\n"; output_string oc "module Tk = CTk\n"; Hashtbl.iter (fun name _ -> let cname = realname name in output_string oc (Printf.sprintf "module %s = %s;;\n" (String.capitalize_ascii (caml_name name)) (String.capitalize_ascii cname))) module_table; close_out oc end else begin let oc = open_out_bin (destfile "labltk.ml") in Copyright.write ~w:(output_string oc); output_string oc * This module Labltk provides the module name spaces of the LablTk API,\n\ useful to call LablTk functions inside CamlTk programs . 100 % LablTk users\n\ do not need to use this . useful to call LablTk functions inside CamlTk programs. 100% LablTk users\n\ do not need to use this. *)\n\ \n\ "; output_string oc "module Widget = Widget;;\n\ module Protocol = Protocol;;\n\ module Textvariable = Textvariable;;\n\ module Fileevent = Fileevent;;\n\ module Timer = Timer;;\n\ "; Hashtbl.iter (fun name _ -> let cname = realname name in output_string oc (Printf.sprintf "module %s = %s;;\n" (String.capitalize_ascii (caml_name name)) (String.capitalize_ascii cname))) module_table; (* widget typer *) output_string oc "\n(** Widget typers *)\n\nopen Widget\n\n"; Hashtbl.iter (fun name def -> match def.module_type with | Widget -> let name = caml_name name in output_string oc (Printf.sprintf "let %s (w : any widget) =\n" name); output_string oc (Printf.sprintf " Rawwidget.check_class w widget_%s_table;\n" name); output_string oc (Printf.sprintf " (Obj.magic w : %s widget);;\n\n" name); | _ -> () ) module_table; close_out oc end; write the module list for the Makefile (* and hack to death until it works *) let oc = open_out_bin (destfile "modules") in if !Flags.camltk then output_string oc "CWIDGETOBJS=" else output_string oc "WIDGETOBJS="; Hashtbl.iter (fun name _ -> let name = realname name in output_string oc " "; output_string oc name; output_string oc ".cmo") module_table; output_string oc "\n"; Hashtbl.iter (fun name _ -> let name = realname name in output_string oc name; output_string oc ".ml ") module_table; output_string oc ": _tkgen.ml\n\n"; Hashtbl.iter (fun name _ -> let name = realname name in output_string oc name; output_string oc ".cmo : "; output_string oc name; output_string oc ".ml\n"; output_string oc name; output_string oc ".cmi : "; output_string oc name; output_string oc ".mli\n") module_table; (* for camltk.ml wrapper *) if !Flags.camltk then begin output_string oc "camltk.cmo : cTk.cmo "; Hashtbl.iter (fun name _ -> let name = realname name in output_string oc name; output_string oc ".cmo ") module_table; output_string oc "\n" end; close_out oc let main () = Arg.parse [ "-verbose", Arg.Unit (fun () -> flag_verbose := true), "Make output verbose"; "-camltk", Arg.Unit (fun () -> Flags.camltk := true), "Make CamlTk interface"; "-outdir", Arg.String (fun s -> output_dir := s), "output directory"; "-debugpp", Arg.Unit (fun () -> Ppexec.debug := true), "debug preprocessor" ] (fun filename -> input_name := filename) "Usage: tkcompiler <source file>" ; if !output_dir = "" then begin prerr_endline "specify -outdir option"; exit 1 end; try verbose_endline "Parsing..."; parse_file !input_name; verbose_endline "Compiling..."; compile (); verbose_endline "Finished"; exit 0 with | Lexer.Lexical_error s -> prerr_string "Invalid lexical character: "; prerr_endline s; exit 1 | Duplicate_Definition (s, s') -> prerr_string s; prerr_string " "; prerr_string s'; prerr_endline " is redefined illegally"; exit 1 | Invalid_implicit_constructor c -> prerr_string "Constructor "; prerr_string c; prerr_endline " is used implicitly before defined"; exit 1 | Tsort.Cyclic -> prerr_endline "Cyclic dependency of types"; exit 1 let () = Printexc.catch main ()
null
https://raw.githubusercontent.com/garrigue/labltk/2cbb92a8c0feacdd8ee69976f3f45a7cf81f805c/compiler/maincompile.ml
ocaml
********************************************************************* described in file LICENSE found in the OCaml source tree. ********************************************************************* Auxiliary function: the list of all the elements associated to keys in an hash table. as variants JPF ?? module name fix for camltk only for LablTk Write the interface for public functions this interface is used only for documentation wrapper code camltk.ml and labltk.ml widget typer and hack to death until it works for camltk.ml wrapper
MLTk , Tcl / Tk interface of OCaml , , and projet Cristal , INRIA Rocquencourt , Kyoto University RIMS Copyright 2002 Institut National de Recherche en Informatique et en Automatique and Kyoto University . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with the special exception on linking $ Id$ open StdLabels open Tables open Printer open Compile open Intf let flag_verbose = ref false let verbose_string s = if !flag_verbose then prerr_string s let verbose_endline s = if !flag_verbose then prerr_endline s let input_name = ref "Widgets.src" let output_dir = ref "" let destfile f = Filename.concat !output_dir f let usage () = prerr_string "Usage: tkcompiler input.src\n"; flush stderr; exit 1 let prerr_error_header () = prerr_string "File \""; prerr_string !input_name; prerr_string "\", line "; prerr_string (string_of_int !Lexer.current_line); prerr_string ": " parse Widget.src config file let parse_file filename = let ic = open_in_bin filename in let lexbuf = try let code_list = Ppparse.parse_channel ic in close_in ic; let buf = Buffer.create 50000 in List.iter ~f:(Ppexec.exec (fun l -> Buffer.add_string buf (Printf.sprintf "##line %d\n" l)) (Buffer.add_string buf)) (if !Flags.camltk then Code.Define "CAMLTK" :: code_list else code_list); Lexing.from_string (Buffer.contents buf) with | Ppparse.Error s -> close_in ic; raise (Compiler_Error (Printf.sprintf "Preprocess error: %s" s)) in try while true do Parser.entry Lexer.main lexbuf done with | Parsing.Parse_error -> prerr_error_header(); prerr_string "Syntax error \n"; exit 1 | Lexer.Lexical_error s -> prerr_error_header(); prerr_string "Lexical error ("; prerr_string s; prerr_string ")\n"; exit 1 | Duplicate_Definition (s,s') -> prerr_error_header(); prerr_string s; prerr_string " "; prerr_string s'; prerr_string " is defined twice.\n"; exit 1 | Compiler_Error s -> prerr_error_header(); prerr_string "Internal error: "; prerr_string s; prerr_string "\n"; prerr_string "Please report bug\n"; exit 1 | End_of_file -> () The hack to provoke the production of cCAMLtoTKoptions_constrs let elements t = let elems = ref [] in Hashtbl.iter (fun _ d -> elems := d :: !elems) t; !elems;; Verifies that duplicated clauses are semantically equivalent and returns a unique set of clauses . returns a unique set of clauses. *) let uniq_clauses = function | [] -> [] | l -> let check_constr constr1 constr2 = if constr1.template <> constr2.template then begin let code1, vars11, vars12, opts1 = code_of_template ~context_widget:"dummy" constr1.template in let code2, vars12, vars22, opts2 = code_of_template ~context_widget:"dummy" constr2.template in let err = Printf.sprintf "uncompatible redondant clauses for variant %s:\n %s\n and\n %s" constr1.var_name code1 code2 in Format.print_newline(); print_fullcomponent constr1; Format.print_newline(); print_fullcomponent constr2; Format.print_newline(); prerr_endline err; fatal_error err end in let t = Hashtbl.create 11 in List.iter l ~f:(fun constr -> let c = constr.var_name in if Hashtbl.mem t c then (check_constr constr (Hashtbl.find t c)) else Hashtbl.add t c constr); elements t;; let option_hack oc = if Hashtbl.mem types_table "options" then let typdef = Hashtbl.find types_table "options" in let hack = { parser_arity = OneToken; constructors = begin let constrs = List.map typdef.constructors ~f: begin fun c -> { component = Constructor; ml_name = (if !Flags.camltk then "C" ^ c.ml_name else c.ml_name); template = begin match c.template with ListArg (x :: _) -> x | _ -> fatal_error "bogus hack" end; result = UserDefined "options_constrs"; safe = true } end in end; subtypes = []; requires_widget_context = false; variant = false } in write_CAMLtoTK ~w:(output_string oc) ~def:hack ~safetype:false "options_constrs" let realname name = let name = caml_name name in if !Flags.camltk then "c" ^ String.capitalize_ascii name else name ;; analize the parsed Widget.src and output source files let compile () = verbose_endline "Creating _tkgen.ml ..."; let oc = open_out_bin (destfile "_tkgen.ml") in let oc' = open_out_bin (destfile "_tkigen.ml") in let oc'' = open_out_bin (destfile "_tkfgen.ml") in let sorted_types = Tsort.sort types_order in verbose_endline " writing types ..."; List.iter sorted_types ~f: begin fun typname -> verbose_string (" " ^ typname ^ " "); try let typdef = Hashtbl.find types_table typname in verbose_string "type "; write_type ~intf:(output_string oc) ~impl:(output_string oc') typname ~def:typdef; verbose_string "C2T "; write_CAMLtoTK ~w:(output_string oc') typname ~def:typdef; verbose_string "T2C "; if List.mem typname ~set:!types_returned then write_TKtoCAML ~w:(output_string oc') typname ~def:typdef; verbose_string "CO "; write_catch_optionals ~w:(output_string oc') typname ~def:typdef; verbose_endline "." with Not_found -> if not (List.mem_assoc typname ~map:!types_external) then begin verbose_string "Type "; verbose_string typname; verbose_string " is undeclared external or undefined\n" end else verbose_endline "." end; verbose_endline " option hacking ..."; option_hack oc'; verbose_endline " writing functions ..."; List.iter ~f:(write_function ~w:(output_string oc'')) !function_table; close_out oc; close_out oc'; close_out oc''; verbose_endline "Creating _tkgen.mli ..."; let oc = open_out_bin (destfile "_tkgen.mli") in List.iter (sort_components !function_table) ~f:(write_function_type ~w:(output_string oc)); close_out oc; verbose_endline "Creating other ml, mli ..."; let write_module wname wdef = verbose_endline (" "^wname); let modname = realname wname in let oc = open_out_bin (destfile (modname ^ ".ml")) and oc' = open_out_bin (destfile (modname ^ ".mli")) in Copyright.write ~w:(output_string oc); Copyright.write ~w:(output_string oc'); begin match wdef.module_type with Widget -> output_string oc' ("(** The "^wname^" widget *)\n") | Family -> output_string oc' ("(** The "^wname^" commands *)\n") end; List.iter ~f:(fun s -> output_string oc s; output_string oc' s) begin if !Flags.camltk then [ "open CTk\n"; "open Tkintf\n"; "open Widget\n"; "open Textvariable\n\n" ] else [ "open StdLabels\n"; "open Tk\n"; "open Tkintf\n"; "open Widget\n"; "open Textvariable\n\n" ] end; output_string oc "open Protocol\n"; begin match wdef.module_type with Widget -> if !Flags.camltk then begin camltk_write_create ~w:(output_string oc) wname; camltk_write_named_create ~w:(output_string oc) wname; camltk_write_create_p ~w:(output_string oc') wname; camltk_write_named_create_p ~w:(output_string oc') wname; end else begin labltk_write_create ~w:(output_string oc) wname; labltk_write_create_p ~w:(output_string oc') wname end | Family -> () end; List.iter ~f:(write_function ~w:(output_string oc)) (sort_components wdef.commands); List.iter ~f:(write_function_type ~w:(output_string oc')) (sort_components wdef.commands); List.iter ~f:(write_external ~w:(output_string oc)) (sort_components wdef.externals); List.iter ~f:(write_external_type ~w:(output_string oc')) (sort_components wdef.externals); close_out oc; close_out oc' in Hashtbl.iter write_module module_table; if !Flags.camltk then begin let oc = open_out_bin (destfile "camltk.ml") in Copyright.write ~w:(output_string oc); output_string oc * This module Camltk provides the module name spaces of the CamlTk API.\n\ \n\ The users of the CamlTk API should open this module first to access\n\ the types , functions and modules of the CamlTk API easier.\n\ For the documentation of each sub modules such as [ Button ] and [ Toplevel],\n\ refer to its defintion file , [ cButton.mli ] , [ cToplevel.mli ] , etc.\n\ \n\ The users of the CamlTk API should open this module first to access\n\ the types, functions and modules of the CamlTk API easier.\n\ For the documentation of each sub modules such as [Button] and [Toplevel],\n\ refer to its defintion file, [cButton.mli], [cToplevel.mli], etc.\n\ *)\n\ \n\ "; output_string oc "include CTk\n"; output_string oc "module Tk = CTk\n"; Hashtbl.iter (fun name _ -> let cname = realname name in output_string oc (Printf.sprintf "module %s = %s;;\n" (String.capitalize_ascii (caml_name name)) (String.capitalize_ascii cname))) module_table; close_out oc end else begin let oc = open_out_bin (destfile "labltk.ml") in Copyright.write ~w:(output_string oc); output_string oc * This module Labltk provides the module name spaces of the LablTk API,\n\ useful to call LablTk functions inside CamlTk programs . 100 % LablTk users\n\ do not need to use this . useful to call LablTk functions inside CamlTk programs. 100% LablTk users\n\ do not need to use this. *)\n\ \n\ "; output_string oc "module Widget = Widget;;\n\ module Protocol = Protocol;;\n\ module Textvariable = Textvariable;;\n\ module Fileevent = Fileevent;;\n\ module Timer = Timer;;\n\ "; Hashtbl.iter (fun name _ -> let cname = realname name in output_string oc (Printf.sprintf "module %s = %s;;\n" (String.capitalize_ascii (caml_name name)) (String.capitalize_ascii cname))) module_table; output_string oc "\n(** Widget typers *)\n\nopen Widget\n\n"; Hashtbl.iter (fun name def -> match def.module_type with | Widget -> let name = caml_name name in output_string oc (Printf.sprintf "let %s (w : any widget) =\n" name); output_string oc (Printf.sprintf " Rawwidget.check_class w widget_%s_table;\n" name); output_string oc (Printf.sprintf " (Obj.magic w : %s widget);;\n\n" name); | _ -> () ) module_table; close_out oc end; write the module list for the Makefile let oc = open_out_bin (destfile "modules") in if !Flags.camltk then output_string oc "CWIDGETOBJS=" else output_string oc "WIDGETOBJS="; Hashtbl.iter (fun name _ -> let name = realname name in output_string oc " "; output_string oc name; output_string oc ".cmo") module_table; output_string oc "\n"; Hashtbl.iter (fun name _ -> let name = realname name in output_string oc name; output_string oc ".ml ") module_table; output_string oc ": _tkgen.ml\n\n"; Hashtbl.iter (fun name _ -> let name = realname name in output_string oc name; output_string oc ".cmo : "; output_string oc name; output_string oc ".ml\n"; output_string oc name; output_string oc ".cmi : "; output_string oc name; output_string oc ".mli\n") module_table; if !Flags.camltk then begin output_string oc "camltk.cmo : cTk.cmo "; Hashtbl.iter (fun name _ -> let name = realname name in output_string oc name; output_string oc ".cmo ") module_table; output_string oc "\n" end; close_out oc let main () = Arg.parse [ "-verbose", Arg.Unit (fun () -> flag_verbose := true), "Make output verbose"; "-camltk", Arg.Unit (fun () -> Flags.camltk := true), "Make CamlTk interface"; "-outdir", Arg.String (fun s -> output_dir := s), "output directory"; "-debugpp", Arg.Unit (fun () -> Ppexec.debug := true), "debug preprocessor" ] (fun filename -> input_name := filename) "Usage: tkcompiler <source file>" ; if !output_dir = "" then begin prerr_endline "specify -outdir option"; exit 1 end; try verbose_endline "Parsing..."; parse_file !input_name; verbose_endline "Compiling..."; compile (); verbose_endline "Finished"; exit 0 with | Lexer.Lexical_error s -> prerr_string "Invalid lexical character: "; prerr_endline s; exit 1 | Duplicate_Definition (s, s') -> prerr_string s; prerr_string " "; prerr_string s'; prerr_endline " is redefined illegally"; exit 1 | Invalid_implicit_constructor c -> prerr_string "Constructor "; prerr_string c; prerr_endline " is used implicitly before defined"; exit 1 | Tsort.Cyclic -> prerr_endline "Cyclic dependency of types"; exit 1 let () = Printexc.catch main ()
843f3ef8da162c72f201bd8e6c57fbbc43235732cbc12c81adb51a0c3d4b79b2
Perry961002/SICP
exe4.55.scm
; a) (superisor ?person (Bitdiddle Ben))) ; b) (job ?name (accounting . ?type)) ; c) (address ?name (Slumerville . ?address))
null
https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap4/exercise/exe4.55.scm
scheme
a) b) c)
(superisor ?person (Bitdiddle Ben))) (job ?name (accounting . ?type)) (address ?name (Slumerville . ?address))
8ed2f1bb104e7808874eaa2ade3a61af37969113a2d386315ab9fb034de0edb5
moon-chilled/loop
count-clause.scm
(defclass count-clause (count/sum-accumulation-clause) ()) (defclass count-it-clause (count-clause it-mixin) () (body-form (clause end-tag) `(when ,*it-var* (set! ,*accumulation-variable* (+ 1 ,*accumulation-variable*))))) (defclass count-form-clause (count-clause form-mixin) () (body-form (clause end-tag) `(when ,(clause 'form) (set! ,*accumulation-variable* (+ 1 ,*accumulation-variable*))))) (defclass count-it-into-clause (into-mixin count-clause it-mixin) () (body-form (clause end-tag) `(when ,*it-var* (set! ,(clause 'into-var) (+ 1 ,(clause 'into-var)))))) (defclass count-form-into-clause (into-mixin count-clause form-mixin) () (body-form (clause end-tag) `(when ,(clause 'form) (set! ,(clause 'into-var) (+ 1 ,(clause 'into-var)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Parsers . (define-parser count-it-into-clause-parser (consecutive (lambda (count it into var type-spec) (make-instance 'count-it-into-clause :into-var var :type-spec type-spec)) (alternative (keyword-parser 'count) (keyword-parser 'counting)) (keyword-parser 'it) (keyword-parser 'into) (singleton identity symbol?) optional-type-spec-parser)) (define-parser count-it-clause-parser (consecutive (lambda (count it type-spec) (make-instance 'count-it-clause :type-spec type-spec)) (alternative (keyword-parser 'count) (keyword-parser 'counting)) (keyword-parser 'it) optional-type-spec-parser)) (define-parser count-form-into-clause-parser (consecutive (lambda (count form into var type-spec) (make-instance 'count-form-into-clause :form form :into-var var :type-spec type-spec)) (alternative (keyword-parser 'count) (keyword-parser 'counting)) anything-parser (keyword-parser 'into) (singleton identity symbol?) optional-type-spec-parser)) (define-parser count-form-clause-parser (consecutive (lambda (count form type-spec) (make-instance 'count-form-clause :form form :type-spec type-spec)) (alternative (keyword-parser 'count) (keyword-parser 'counting)) anything-parser optional-type-spec-parser)) (define-parser count-clause-parser (alternative count-it-into-clause-parser count-it-clause-parser count-form-into-clause-parser count-form-clause-parser)) (add-clause-parser count-clause-parser) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Compute the BODY-FORM.
null
https://raw.githubusercontent.com/moon-chilled/loop/09b08a5f0c442710f129d2de10d78128e21863a3/src/count-clause.scm
scheme
Compute the BODY-FORM.
(defclass count-clause (count/sum-accumulation-clause) ()) (defclass count-it-clause (count-clause it-mixin) () (body-form (clause end-tag) `(when ,*it-var* (set! ,*accumulation-variable* (+ 1 ,*accumulation-variable*))))) (defclass count-form-clause (count-clause form-mixin) () (body-form (clause end-tag) `(when ,(clause 'form) (set! ,*accumulation-variable* (+ 1 ,*accumulation-variable*))))) (defclass count-it-into-clause (into-mixin count-clause it-mixin) () (body-form (clause end-tag) `(when ,*it-var* (set! ,(clause 'into-var) (+ 1 ,(clause 'into-var)))))) (defclass count-form-into-clause (into-mixin count-clause form-mixin) () (body-form (clause end-tag) `(when ,(clause 'form) (set! ,(clause 'into-var) (+ 1 ,(clause 'into-var)))))) Parsers . (define-parser count-it-into-clause-parser (consecutive (lambda (count it into var type-spec) (make-instance 'count-it-into-clause :into-var var :type-spec type-spec)) (alternative (keyword-parser 'count) (keyword-parser 'counting)) (keyword-parser 'it) (keyword-parser 'into) (singleton identity symbol?) optional-type-spec-parser)) (define-parser count-it-clause-parser (consecutive (lambda (count it type-spec) (make-instance 'count-it-clause :type-spec type-spec)) (alternative (keyword-parser 'count) (keyword-parser 'counting)) (keyword-parser 'it) optional-type-spec-parser)) (define-parser count-form-into-clause-parser (consecutive (lambda (count form into var type-spec) (make-instance 'count-form-into-clause :form form :into-var var :type-spec type-spec)) (alternative (keyword-parser 'count) (keyword-parser 'counting)) anything-parser (keyword-parser 'into) (singleton identity symbol?) optional-type-spec-parser)) (define-parser count-form-clause-parser (consecutive (lambda (count form type-spec) (make-instance 'count-form-clause :form form :type-spec type-spec)) (alternative (keyword-parser 'count) (keyword-parser 'counting)) anything-parser optional-type-spec-parser)) (define-parser count-clause-parser (alternative count-it-into-clause-parser count-it-clause-parser count-form-into-clause-parser count-form-clause-parser)) (add-clause-parser count-clause-parser)
d61e0e352517fc372bc93c74ad2d4f382a32ecbd58ffec89683bc15ccf7fb9b4
serokell/haskell-crypto
Nonce.hs
SPDX - FileCopyrightText : 2020 -- SPDX - License - Identifier : MPL-2.0 module Test.Crypto.Sodium.Nonce where import Test.HUnit ((@?), (@?=), Assertion) import Control.DeepSeq (deepseq) import Data.ByteArray.Sized (unSizedByteArray) import Data.ByteString (ByteString) import Data.Ratio ((%)) import System.CPUTime (getCPUTime) import qualified Data.ByteString as BS import qualified Libsodium as Na import Crypto.Sodium.Nonce (generate) import qualified Crypto.Sodium.Encrypt.Symmetric as Symmetric import qualified Crypto.Sodium.Nonce as Nonce (generate) import qualified Crypto.Sodium.Pwhash.Internal as Pwhash import qualified Crypto.Sodium.Random as Random (generate) Well , this is kinda stupid , because we merely generate one random sequence , -- but this is just to check that the lengths are correctly propagated -- through types. So, good enough. unit_generate_Symmetric_nonce :: Assertion unit_generate_Symmetric_nonce = do nonce <- generate :: IO (Symmetric.Nonce ByteString) let bs = unSizedByteArray nonce BS.length bs @?= fromIntegral Na.crypto_secretbox_noncebytes unit_generate_Pwhash_salt :: Assertion unit_generate_Pwhash_salt = do nonce <- generate :: IO (Pwhash.Salt ByteString) let bs = unSizedByteArray nonce BS.length bs @?= fromIntegral Na.crypto_pwhash_saltbytes -- Benchmark to make sure this all makes sense and insecure nonse generation -- is actually faster than cryptographically-secure generation. unit_bench_against_crypto :: Assertion unit_bench_against_crypto = do tNonce <- measure $ (unSizedByteArray <$> Nonce.generate @64) tCrypto <- measure $ (unSizedByteArray <$> Random.generate @ByteString @64) let ratio = fromRational (tNonce % tCrypto) :: Double -- XXX: The benchmark is disabled, because we don’t yet have an -- implementation that would actually be faster :/. -- vvvvvvvv ratio < 1 || True @? "Crypto gen is " <> show ratio <> "x faster" -- ^^^^^^^^ where measure act = do t1 <- getCPUTime go 1000 t2 <- getCPUTime pure $ t2 - t1 where go :: Int -> IO () go n | n <= 0 = pure () | otherwise = do res <- act res `deepseq` go (n - 1)
null
https://raw.githubusercontent.com/serokell/haskell-crypto/e57b04d103b428b03c83565060a36da442663a5a/crypto-sodium/test/Test/Crypto/Sodium/Nonce.hs
haskell
but this is just to check that the lengths are correctly propagated through types. So, good enough. Benchmark to make sure this all makes sense and insecure nonse generation is actually faster than cryptographically-secure generation. XXX: The benchmark is disabled, because we don’t yet have an implementation that would actually be faster :/. vvvvvvvv ^^^^^^^^
SPDX - FileCopyrightText : 2020 SPDX - License - Identifier : MPL-2.0 module Test.Crypto.Sodium.Nonce where import Test.HUnit ((@?), (@?=), Assertion) import Control.DeepSeq (deepseq) import Data.ByteArray.Sized (unSizedByteArray) import Data.ByteString (ByteString) import Data.Ratio ((%)) import System.CPUTime (getCPUTime) import qualified Data.ByteString as BS import qualified Libsodium as Na import Crypto.Sodium.Nonce (generate) import qualified Crypto.Sodium.Encrypt.Symmetric as Symmetric import qualified Crypto.Sodium.Nonce as Nonce (generate) import qualified Crypto.Sodium.Pwhash.Internal as Pwhash import qualified Crypto.Sodium.Random as Random (generate) Well , this is kinda stupid , because we merely generate one random sequence , unit_generate_Symmetric_nonce :: Assertion unit_generate_Symmetric_nonce = do nonce <- generate :: IO (Symmetric.Nonce ByteString) let bs = unSizedByteArray nonce BS.length bs @?= fromIntegral Na.crypto_secretbox_noncebytes unit_generate_Pwhash_salt :: Assertion unit_generate_Pwhash_salt = do nonce <- generate :: IO (Pwhash.Salt ByteString) let bs = unSizedByteArray nonce BS.length bs @?= fromIntegral Na.crypto_pwhash_saltbytes unit_bench_against_crypto :: Assertion unit_bench_against_crypto = do tNonce <- measure $ (unSizedByteArray <$> Nonce.generate @64) tCrypto <- measure $ (unSizedByteArray <$> Random.generate @ByteString @64) let ratio = fromRational (tNonce % tCrypto) :: Double ratio < 1 || True @? "Crypto gen is " <> show ratio <> "x faster" where measure act = do t1 <- getCPUTime go 1000 t2 <- getCPUTime pure $ t2 - t1 where go :: Int -> IO () go n | n <= 0 = pure () | otherwise = do res <- act res `deepseq` go (n - 1)
52e143248701ecdce6825f5196974ea80d73fe2acd3871ba5c125881aae2c778
eponai/sulolive
product_list.cljc
(ns eponai.common.ui.store.product-list (:require [eponai.client.routes :as routes] [eponai.common.ui.dom :as dom] [eponai.common.ui.elements.css :as css] #?(:cljs [cljsjs.react-grid-layout]) #?(:cljs [goog.crypt.base64 :as crypt]) #?(:cljs [eponai.web.utils :as web-utils]) [om.next :as om :refer [defui]] [taoensso.timbre :refer [debug]] [eponai.common.format.date :as date] [eponai.common.ui.utils :as utils] [eponai.common.ui.elements.table :as table] [eponai.common.ui.elements.grid :as grid] [eponai.web.ui.photo :as photo] [eponai.common.ui.elements.callout :as callout] [eponai.web.ui.photo :as photo] [clojure.string :as string] [eponai.client.parser.message :as msg] [eponai.web.ui.button :as button] [eponai.common.mixpanel :as mixpanel] [eponai.common.ui.elements.menu :as menu] [eponai.common.ui.common :as common] [eponai.common.database :as db])) (defn products->grid-layout [component products] (let [num-cols 3 layout-fn (fn [i p] {:x (mod i num-cols) :y (int (/ i num-cols)) :w 1 :h 1 :i (str (:db/id p))})] (map-indexed layout-fn products))) (defn grid-layout->products [component layout] (let [{:keys [query/inventory]} (om/props component) grouped-by-id (group-by #(str (:db/id %)) inventory) _ (debug "Items by id; " grouped-by-id) items-by-position (reduce (fn [m grid-item] (if (map? grid-item) (let [product (first (get grouped-by-id (:i grid-item)))] (assoc m (str (:x grid-item) (:y grid-item)) product)) (let [product (first (get grouped-by-id (.-i grid-item)))] (assoc m (str (.-x grid-item) (.-y grid-item)) product)))) (sorted-map) layout)] (debug "Sorted items: " (sort-by #(string/reverse (key %)) items-by-position)) (map-indexed (fn [i [_ product]] (assoc product :store.item/index i)) (sort-by #(string/reverse (key %)) items-by-position)))) (defn product-element [component p] (let [{:query/keys [current-route]} (om/props component) {:store.item/keys [price] item-name :store.item/name} p {:keys [grid-editable?]} (om/get-state component)] (dom/a (cond->> (->> (when-not grid-editable? {:href (routes/url :store-dashboard/product (assoc (:route-params current-route) :product-id (:db/id p)))}) (css/add-class :content-item) (css/add-class :product-item)) grid-editable? (css/add-class :product-move)) (dom/div (->> (css/add-class :primary-photo)) (photo/product-preview p {} (photo/overlay nil))) (dom/div (->> (css/add-class :header) (css/add-class :text)) (dom/div nil (dom/span nil item-name))) (dom/div (css/add-class :text) (dom/strong nil (utils/two-decimal-price price)))))) (defn edit-sections-modal [component] (let [{:products/keys [edit-sections]} (om/get-state component) {:query/keys [store]} (om/props component)] (when (some? edit-sections) (common/modal {:on-close #(om/update-state! component dissoc :products/edit-sections)} (let [items-by-section (group-by #(get-in % [:store.item/section :db/id]) (:store/items store))] (dom/div nil (dom/h4 nil "Edit sections") (menu/vertical (css/add-class :edit-sections-menu) (map-indexed (fn [i s] (let [no-items (count (get items-by-section (:db/id s)))] (menu/item (css/add-class :edit-sections-item) (dom/input {:type "text" :id (str "input.section-" i) :placeholder "New section" :value (:store.section/label s "") :onChange #(om/update-state! component update :products/edit-sections (fn [sections] (let [old (get sections i) new (assoc old :store.section/label (.-value (.-target %)))] (assoc sections i new))))}) (if (= 1 no-items) (dom/small nil (str no-items " item")) (dom/small nil (str no-items " items"))) (dom/a {:onClick #(om/update-state! component update :products/edit-sections (fn [sections] (into [] (remove nil? (assoc sections i nil)))))} (dom/small nil "remove"))))) edit-sections) (menu/item (css/add-class :edit-sections-item) (button/store-setting-default {:onClick #(om/update-state! component update :products/edit-sections conj {})} (dom/span nil "Add section...")))) (dom/div (->> (css/text-align :right) (css/add-class :action-buttons)) (button/cancel {:onClick #(om/update-state! component dissoc :products/edit-sections)}) (button/save {:onClick #(.save-sections component)})))))))) (def row-heights {:xxlarge 370 :xlarge 350 :large 400 :medium 350 :small 350 :tiny 250}) (defui ProductList static om/IQuery (query [_] [{:query/inventory [:store.item/name :store.item/description :store.item/index :store.item/price {:store.item/section [:db/id]} {:store.item/photos [{:store.item.photo/photo [:photo/id :photo/path]} :store.item.photo/index]}]} {:query/store [{:store/sections [:db/id :store.section/label]}]} {:query/ui-state [:ui.singleton.state/product-view]} :query/messages :query/current-route]) Object (update-layout [this] #?(:cljs (let [{:keys [query/inventory]} (om/props this) WidthProvider (.-WidthProvider (.-ReactGridLayout js/window)) grid-element (WidthProvider (.-Responsive (.-ReactGridLayout js/window))) size js/window.innerWidth breakpoint (if (> 460 size) :tiny (web-utils/breakpoint size)) sorted-products (sort-by :store.item/index inventory)] (debug "State update in did mount size: ") (om/update-state! this assoc :grid-element grid-element :breakpoint breakpoint :layout (clj->js (products->grid-layout this sorted-products)))))) (save-product-order [this] (let [{:keys [layout]} (om/get-state this) {:keys [query/current-route]} (om/props this) products (grid-layout->products this layout)] (debug "Save products: " (into [] (grid-layout->products this layout))) (msg/om-transact! this [(list 'store/update-product-order {:items products :store-id (db/store-id->dbid this (get-in current-route [:route-params :store-id]))}) :query/inventory]) (om/update-state! this assoc :grid-editable? false))) (save-sections [this] (let [{:products/keys [edit-sections]} (om/get-state this) {:query/keys [current-route]} (om/props this) new-sections (filter #(not-empty (string/trim (:store.section/label % ""))) edit-sections)] (msg/om-transact! this [(list 'store/update-sections {:sections new-sections :store-id (db/store-id->dbid this (get-in current-route [:route-params :store-id]))}) :query/store]) (om/update-state! this dissoc :products/edit-sections))) (change-product-view [this view] (debug "Transacting new product view: " view) (om/transact! this [(list 'dashboard/change-product-view {:product-view view}) :query/ui-state]) (om/update-state! this assoc :grid-editable? false)) (componentDidMount [this] (debug "State component did mount") (.update-layout this)) (on-drag-stop [this layout] (om/update-state! this assoc :layout (products->grid-layout this (grid-layout->products this layout)))) (on-breakpoint-change [this bp] #?(:cljs (let [size js/window.innerWidth breakpoint (if (> 460 size) :tiny (web-utils/breakpoint size))] (debug "Updating breakpoint: " breakpoint) (when-not (= breakpoint (:breakpoint (om/get-state this))) (.update-layout this)) ))) (initLocalState [this] {:cols {:xxlarge 3 :xlarge 3 :large 3 :medium 3 :small 2 :tiny 2} :products/listing-layout :products/list :products/selected-section :all}) (render [this] (let [{:query/keys [store inventory ui-state]} (om/props this) {:keys [search-input cols layout grid-element grid-editable? breakpoint] :products/keys [selected-section edit-sections]} (om/get-state this) product-view (:ui.singleton.state/product-view ui-state) {:keys [route-params]} (om/get-computed this) products (if grid-editable? (sort-by :store.item/index inventory) (cond->> (sort-by :store.item/index inventory) (not= selected-section :all) (filter #(= selected-section (get-in % [:store.item/section :db/id]))) (not-empty search-input) (filter #(clojure.string/includes? (.toLowerCase (:store.item/name %)) (.toLowerCase search-input))))) ] (dom/div {:id "sulo-product-list"} (edit-sections-modal this) (dom/div (css/add-class :section-title) (dom/h1 nil "Products")) (callout/callout (css/add-class :edit-sections-callout) (grid/row (css/add-classes [:collapse :expanded]) (grid/column nil (menu/horizontal (css/add-class :product-section-menu) (menu/item (when (= selected-section :all) (css/add-class :is-active)) (dom/a {:onClick #(om/update-state! this assoc :products/selected-section :all)} (dom/span nil "All items"))) (map (fn [s] (menu/item (when (= selected-section (:db/id s)) (css/add-class :is-active)) (dom/a {:onClick #(om/update-state! this assoc :products/selected-section (:db/id s))} (dom/span nil (string/capitalize (:store.section/label s)))))) (:store/sections store)))) (grid/column (->> (css/text-align :right) (grid/column-size {:small 12 :medium 3 :large 2})) (button/store-setting-default {:onClick #(do (mixpanel/track "Store: Edit product sections") (om/update-state! this assoc :products/edit-sections (into [] (:store/sections store))))} (dom/span nil "Edit sections"))))) (callout/callout (css/add-class :submenu) (dom/div (css/hide-for :medium) (menu/horizontal nil (menu/item (when (= product-view :products/list) (css/add-class :is-active)) (dom/a {:onClick #(.change-product-view this :products/list)} (dom/i {:classes ["fa fa-list"]}) (dom/span (css/show-for-sr) "List"))) (menu/item (when (= product-view :products/grid) (css/add-class :is-active)) (dom/a {:onClick #(.change-product-view this :products/grid)} (dom/i {:classes ["fa fa-th"]}) (dom/span (css/show-for-sr) "Grid"))) (menu/item (css/add-class :button-item) (dom/div (css/text-align :right) (button/store-navigation-cta {:href (routes/url :store-dashboard/create-product {:store-id (:store-id route-params) :action "create"}) :onClick #(mixpanel/track "Store: Add product")} (dom/span nil "Add product"))))) (dom/input {:value (or search-input "") :onChange #(om/update-state! this assoc :search-input (.. % -target -value)) :placeholder "Search Products..." :type "text"})) (menu/horizontal (css/show-for :medium) (menu/item (when (= product-view :products/list) (css/add-class :is-active)) (dom/a {:onClick #(.change-product-view this :products/list)} (dom/i {:classes ["fa fa-list"]}))) (menu/item (when (= product-view :products/grid) (css/add-class :is-active)) (dom/a {:onClick #(.change-product-view this :products/grid)} (dom/i {:classes ["fa fa-th"]}))) (menu/item (css/add-class :search-input) (dom/input {:value (or search-input "") :onChange #(om/update-state! this assoc :search-input (.. % -target -value)) :placeholder "Search Products..." :type "text"})) (menu/item nil (button/store-navigation-cta {:href (routes/url :store-dashboard/create-product {:store-id (:store-id route-params) :action "create"}) :onClick #(mixpanel/track "Store: Add product")} (dom/span nil "Add product"))))) (if (= product-view :products/list) (callout/callout nil (table/table (css/add-class :hover) (dom/div (css/add-class :thead) (dom/div (css/add-class :tr) (dom/span (css/add-class :th) (dom/span nil "")) (dom/span (css/add-class :th) "Product name") (dom/span (->> (css/add-class :th) (css/text-align :right)) "Price"))) (dom/div (css/add-class :tbody) (map (fn [p] (let [product-link (routes/url :store-dashboard/product {:store-id (:store-id route-params) :product-id (:db/id p)})] (dom/a (css/add-class :tr {:href product-link}) (dom/span (css/add-class :td) (photo/product-preview p {:transformation :transformation/thumbnail-tiny})) (dom/span (css/add-class :td) (:store.item/name p)) (dom/span (->> (css/add-class :td) (css/text-align :right)) (utils/two-decimal-price (:store.item/price p))) (dom/span (->> (css/add-class :td) (css/show-for :medium)) (when (:store.item/updated p) (date/date->string (* 1000 (:store.item/updated p)) "MMM dd yyyy HH:mm")))))) products)))) (callout/callout nil (grid/row (css/add-class :expanded) (grid/column (css/add-class :shrink) (dom/div nil (if grid-editable? (dom/div (css/add-class :action-buttons) (button/save (css/add-class :small {:onClick #(.save-product-order this)})) (button/cancel (css/add-class :small {:onClick #(do (.update-layout this) (om/update-state! this assoc :grid-editable? false))}))) (button/store-setting-default (css/add-class :small {:onClick #(om/update-state! this assoc :grid-editable? true :products/selected-section :all)}) (dom/span nil "Edit layout"))))) (grid/column nil (when grid-editable? (callout/callout-small (cond->> (css/add-class :sulo-dark) (not grid-editable?) (css/add-class :sl-invisible)) (dom/small nil "This is how your products will appear in your store. Try moving them around and find a layout you like and save when you're done."))))) (dom/div nil #?(:cljs (when (and grid-editable? (some? layout) (some? grid-element) (not-empty products)) (do (debug "Creating grid layout with row-hweight: " (get row-heights breakpoint) " breakpoint " breakpoint) (.createElement (.-React js/window) grid-element (clj->js {:className (if grid-editable? "layout editable animate" "layout"), :draggableHandle ".product-move" :layouts {:xxlarge layout :xlarge layout :large layout :medium layout :small layout :tiny layout} :breakpoints {:xxlarge 1440, :xlarge 1200, :large 1024, :medium 750, :small 460 :tiny 0} :rowHeight (get row-heights breakpoint) :cols cols :useCSSTransforms true :isDraggable grid-editable? :isResizable false :verticalCompact true :onBreakpointChange #(.on-breakpoint-change this %) :onDragStop #(.on-drag-stop this %) }) (into-array (map (fn [p] (dom/div {:key (str (:db/id p))} (product-element this p))) products))))))) (when-not grid-editable? (grid/products products (fn [p] (product-element this p)))))))))) (def ->ProductList (om/factory ProductList))
null
https://raw.githubusercontent.com/eponai/sulolive/7a70701bbd3df6bbb92682679dcedb53f8822c18/src/eponai/common/ui/store/product_list.cljc
clojure
(ns eponai.common.ui.store.product-list (:require [eponai.client.routes :as routes] [eponai.common.ui.dom :as dom] [eponai.common.ui.elements.css :as css] #?(:cljs [cljsjs.react-grid-layout]) #?(:cljs [goog.crypt.base64 :as crypt]) #?(:cljs [eponai.web.utils :as web-utils]) [om.next :as om :refer [defui]] [taoensso.timbre :refer [debug]] [eponai.common.format.date :as date] [eponai.common.ui.utils :as utils] [eponai.common.ui.elements.table :as table] [eponai.common.ui.elements.grid :as grid] [eponai.web.ui.photo :as photo] [eponai.common.ui.elements.callout :as callout] [eponai.web.ui.photo :as photo] [clojure.string :as string] [eponai.client.parser.message :as msg] [eponai.web.ui.button :as button] [eponai.common.mixpanel :as mixpanel] [eponai.common.ui.elements.menu :as menu] [eponai.common.ui.common :as common] [eponai.common.database :as db])) (defn products->grid-layout [component products] (let [num-cols 3 layout-fn (fn [i p] {:x (mod i num-cols) :y (int (/ i num-cols)) :w 1 :h 1 :i (str (:db/id p))})] (map-indexed layout-fn products))) (defn grid-layout->products [component layout] (let [{:keys [query/inventory]} (om/props component) grouped-by-id (group-by #(str (:db/id %)) inventory) _ (debug "Items by id; " grouped-by-id) items-by-position (reduce (fn [m grid-item] (if (map? grid-item) (let [product (first (get grouped-by-id (:i grid-item)))] (assoc m (str (:x grid-item) (:y grid-item)) product)) (let [product (first (get grouped-by-id (.-i grid-item)))] (assoc m (str (.-x grid-item) (.-y grid-item)) product)))) (sorted-map) layout)] (debug "Sorted items: " (sort-by #(string/reverse (key %)) items-by-position)) (map-indexed (fn [i [_ product]] (assoc product :store.item/index i)) (sort-by #(string/reverse (key %)) items-by-position)))) (defn product-element [component p] (let [{:query/keys [current-route]} (om/props component) {:store.item/keys [price] item-name :store.item/name} p {:keys [grid-editable?]} (om/get-state component)] (dom/a (cond->> (->> (when-not grid-editable? {:href (routes/url :store-dashboard/product (assoc (:route-params current-route) :product-id (:db/id p)))}) (css/add-class :content-item) (css/add-class :product-item)) grid-editable? (css/add-class :product-move)) (dom/div (->> (css/add-class :primary-photo)) (photo/product-preview p {} (photo/overlay nil))) (dom/div (->> (css/add-class :header) (css/add-class :text)) (dom/div nil (dom/span nil item-name))) (dom/div (css/add-class :text) (dom/strong nil (utils/two-decimal-price price)))))) (defn edit-sections-modal [component] (let [{:products/keys [edit-sections]} (om/get-state component) {:query/keys [store]} (om/props component)] (when (some? edit-sections) (common/modal {:on-close #(om/update-state! component dissoc :products/edit-sections)} (let [items-by-section (group-by #(get-in % [:store.item/section :db/id]) (:store/items store))] (dom/div nil (dom/h4 nil "Edit sections") (menu/vertical (css/add-class :edit-sections-menu) (map-indexed (fn [i s] (let [no-items (count (get items-by-section (:db/id s)))] (menu/item (css/add-class :edit-sections-item) (dom/input {:type "text" :id (str "input.section-" i) :placeholder "New section" :value (:store.section/label s "") :onChange #(om/update-state! component update :products/edit-sections (fn [sections] (let [old (get sections i) new (assoc old :store.section/label (.-value (.-target %)))] (assoc sections i new))))}) (if (= 1 no-items) (dom/small nil (str no-items " item")) (dom/small nil (str no-items " items"))) (dom/a {:onClick #(om/update-state! component update :products/edit-sections (fn [sections] (into [] (remove nil? (assoc sections i nil)))))} (dom/small nil "remove"))))) edit-sections) (menu/item (css/add-class :edit-sections-item) (button/store-setting-default {:onClick #(om/update-state! component update :products/edit-sections conj {})} (dom/span nil "Add section...")))) (dom/div (->> (css/text-align :right) (css/add-class :action-buttons)) (button/cancel {:onClick #(om/update-state! component dissoc :products/edit-sections)}) (button/save {:onClick #(.save-sections component)})))))))) (def row-heights {:xxlarge 370 :xlarge 350 :large 400 :medium 350 :small 350 :tiny 250}) (defui ProductList static om/IQuery (query [_] [{:query/inventory [:store.item/name :store.item/description :store.item/index :store.item/price {:store.item/section [:db/id]} {:store.item/photos [{:store.item.photo/photo [:photo/id :photo/path]} :store.item.photo/index]}]} {:query/store [{:store/sections [:db/id :store.section/label]}]} {:query/ui-state [:ui.singleton.state/product-view]} :query/messages :query/current-route]) Object (update-layout [this] #?(:cljs (let [{:keys [query/inventory]} (om/props this) WidthProvider (.-WidthProvider (.-ReactGridLayout js/window)) grid-element (WidthProvider (.-Responsive (.-ReactGridLayout js/window))) size js/window.innerWidth breakpoint (if (> 460 size) :tiny (web-utils/breakpoint size)) sorted-products (sort-by :store.item/index inventory)] (debug "State update in did mount size: ") (om/update-state! this assoc :grid-element grid-element :breakpoint breakpoint :layout (clj->js (products->grid-layout this sorted-products)))))) (save-product-order [this] (let [{:keys [layout]} (om/get-state this) {:keys [query/current-route]} (om/props this) products (grid-layout->products this layout)] (debug "Save products: " (into [] (grid-layout->products this layout))) (msg/om-transact! this [(list 'store/update-product-order {:items products :store-id (db/store-id->dbid this (get-in current-route [:route-params :store-id]))}) :query/inventory]) (om/update-state! this assoc :grid-editable? false))) (save-sections [this] (let [{:products/keys [edit-sections]} (om/get-state this) {:query/keys [current-route]} (om/props this) new-sections (filter #(not-empty (string/trim (:store.section/label % ""))) edit-sections)] (msg/om-transact! this [(list 'store/update-sections {:sections new-sections :store-id (db/store-id->dbid this (get-in current-route [:route-params :store-id]))}) :query/store]) (om/update-state! this dissoc :products/edit-sections))) (change-product-view [this view] (debug "Transacting new product view: " view) (om/transact! this [(list 'dashboard/change-product-view {:product-view view}) :query/ui-state]) (om/update-state! this assoc :grid-editable? false)) (componentDidMount [this] (debug "State component did mount") (.update-layout this)) (on-drag-stop [this layout] (om/update-state! this assoc :layout (products->grid-layout this (grid-layout->products this layout)))) (on-breakpoint-change [this bp] #?(:cljs (let [size js/window.innerWidth breakpoint (if (> 460 size) :tiny (web-utils/breakpoint size))] (debug "Updating breakpoint: " breakpoint) (when-not (= breakpoint (:breakpoint (om/get-state this))) (.update-layout this)) ))) (initLocalState [this] {:cols {:xxlarge 3 :xlarge 3 :large 3 :medium 3 :small 2 :tiny 2} :products/listing-layout :products/list :products/selected-section :all}) (render [this] (let [{:query/keys [store inventory ui-state]} (om/props this) {:keys [search-input cols layout grid-element grid-editable? breakpoint] :products/keys [selected-section edit-sections]} (om/get-state this) product-view (:ui.singleton.state/product-view ui-state) {:keys [route-params]} (om/get-computed this) products (if grid-editable? (sort-by :store.item/index inventory) (cond->> (sort-by :store.item/index inventory) (not= selected-section :all) (filter #(= selected-section (get-in % [:store.item/section :db/id]))) (not-empty search-input) (filter #(clojure.string/includes? (.toLowerCase (:store.item/name %)) (.toLowerCase search-input))))) ] (dom/div {:id "sulo-product-list"} (edit-sections-modal this) (dom/div (css/add-class :section-title) (dom/h1 nil "Products")) (callout/callout (css/add-class :edit-sections-callout) (grid/row (css/add-classes [:collapse :expanded]) (grid/column nil (menu/horizontal (css/add-class :product-section-menu) (menu/item (when (= selected-section :all) (css/add-class :is-active)) (dom/a {:onClick #(om/update-state! this assoc :products/selected-section :all)} (dom/span nil "All items"))) (map (fn [s] (menu/item (when (= selected-section (:db/id s)) (css/add-class :is-active)) (dom/a {:onClick #(om/update-state! this assoc :products/selected-section (:db/id s))} (dom/span nil (string/capitalize (:store.section/label s)))))) (:store/sections store)))) (grid/column (->> (css/text-align :right) (grid/column-size {:small 12 :medium 3 :large 2})) (button/store-setting-default {:onClick #(do (mixpanel/track "Store: Edit product sections") (om/update-state! this assoc :products/edit-sections (into [] (:store/sections store))))} (dom/span nil "Edit sections"))))) (callout/callout (css/add-class :submenu) (dom/div (css/hide-for :medium) (menu/horizontal nil (menu/item (when (= product-view :products/list) (css/add-class :is-active)) (dom/a {:onClick #(.change-product-view this :products/list)} (dom/i {:classes ["fa fa-list"]}) (dom/span (css/show-for-sr) "List"))) (menu/item (when (= product-view :products/grid) (css/add-class :is-active)) (dom/a {:onClick #(.change-product-view this :products/grid)} (dom/i {:classes ["fa fa-th"]}) (dom/span (css/show-for-sr) "Grid"))) (menu/item (css/add-class :button-item) (dom/div (css/text-align :right) (button/store-navigation-cta {:href (routes/url :store-dashboard/create-product {:store-id (:store-id route-params) :action "create"}) :onClick #(mixpanel/track "Store: Add product")} (dom/span nil "Add product"))))) (dom/input {:value (or search-input "") :onChange #(om/update-state! this assoc :search-input (.. % -target -value)) :placeholder "Search Products..." :type "text"})) (menu/horizontal (css/show-for :medium) (menu/item (when (= product-view :products/list) (css/add-class :is-active)) (dom/a {:onClick #(.change-product-view this :products/list)} (dom/i {:classes ["fa fa-list"]}))) (menu/item (when (= product-view :products/grid) (css/add-class :is-active)) (dom/a {:onClick #(.change-product-view this :products/grid)} (dom/i {:classes ["fa fa-th"]}))) (menu/item (css/add-class :search-input) (dom/input {:value (or search-input "") :onChange #(om/update-state! this assoc :search-input (.. % -target -value)) :placeholder "Search Products..." :type "text"})) (menu/item nil (button/store-navigation-cta {:href (routes/url :store-dashboard/create-product {:store-id (:store-id route-params) :action "create"}) :onClick #(mixpanel/track "Store: Add product")} (dom/span nil "Add product"))))) (if (= product-view :products/list) (callout/callout nil (table/table (css/add-class :hover) (dom/div (css/add-class :thead) (dom/div (css/add-class :tr) (dom/span (css/add-class :th) (dom/span nil "")) (dom/span (css/add-class :th) "Product name") (dom/span (->> (css/add-class :th) (css/text-align :right)) "Price"))) (dom/div (css/add-class :tbody) (map (fn [p] (let [product-link (routes/url :store-dashboard/product {:store-id (:store-id route-params) :product-id (:db/id p)})] (dom/a (css/add-class :tr {:href product-link}) (dom/span (css/add-class :td) (photo/product-preview p {:transformation :transformation/thumbnail-tiny})) (dom/span (css/add-class :td) (:store.item/name p)) (dom/span (->> (css/add-class :td) (css/text-align :right)) (utils/two-decimal-price (:store.item/price p))) (dom/span (->> (css/add-class :td) (css/show-for :medium)) (when (:store.item/updated p) (date/date->string (* 1000 (:store.item/updated p)) "MMM dd yyyy HH:mm")))))) products)))) (callout/callout nil (grid/row (css/add-class :expanded) (grid/column (css/add-class :shrink) (dom/div nil (if grid-editable? (dom/div (css/add-class :action-buttons) (button/save (css/add-class :small {:onClick #(.save-product-order this)})) (button/cancel (css/add-class :small {:onClick #(do (.update-layout this) (om/update-state! this assoc :grid-editable? false))}))) (button/store-setting-default (css/add-class :small {:onClick #(om/update-state! this assoc :grid-editable? true :products/selected-section :all)}) (dom/span nil "Edit layout"))))) (grid/column nil (when grid-editable? (callout/callout-small (cond->> (css/add-class :sulo-dark) (not grid-editable?) (css/add-class :sl-invisible)) (dom/small nil "This is how your products will appear in your store. Try moving them around and find a layout you like and save when you're done."))))) (dom/div nil #?(:cljs (when (and grid-editable? (some? layout) (some? grid-element) (not-empty products)) (do (debug "Creating grid layout with row-hweight: " (get row-heights breakpoint) " breakpoint " breakpoint) (.createElement (.-React js/window) grid-element (clj->js {:className (if grid-editable? "layout editable animate" "layout"), :draggableHandle ".product-move" :layouts {:xxlarge layout :xlarge layout :large layout :medium layout :small layout :tiny layout} :breakpoints {:xxlarge 1440, :xlarge 1200, :large 1024, :medium 750, :small 460 :tiny 0} :rowHeight (get row-heights breakpoint) :cols cols :useCSSTransforms true :isDraggable grid-editable? :isResizable false :verticalCompact true :onBreakpointChange #(.on-breakpoint-change this %) :onDragStop #(.on-drag-stop this %) }) (into-array (map (fn [p] (dom/div {:key (str (:db/id p))} (product-element this p))) products))))))) (when-not grid-editable? (grid/products products (fn [p] (product-element this p)))))))))) (def ->ProductList (om/factory ProductList))
ce3a44584a1a6ac214e89bcd021a27b3a807b0bb3f19905125039d8902860b6d
serokell/qtah
QItemSelectionRange.hs
This file is part of Qtah . -- Copyright 2015 - 2018 The Qtah Authors . -- -- 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 . -- You should have received a copy of the GNU Lesser General Public License -- along with this program. If not, see </>. module Graphics.UI.Qtah.Generator.Interface.Core.QItemSelectionRange ( aModule, c_QItemSelectionRange, ) where import Foreign.Hoppy.Generator.Spec ( Export (ExportClass), addReqIncludes, classSetConversionToGc, classSetEntityPrefix, ident, includeStd, makeClass, mkConstMethod, mkConstMethod', mkCtor, mkMethod, ) import Foreign.Hoppy.Generator.Spec.ClassFeature ( ClassFeature (Assignable, Copyable, Equatable), classAddFeatures, ) import Foreign.Hoppy.Generator.Types (boolT, constT, intT, objT, ptrT, refT, voidT) import Foreign.Hoppy.Generator.Version (collect, just, test) import Graphics.UI.Qtah.Generator.Flags (qtVersion) import {-# SOURCE #-} Graphics.UI.Qtah.Generator.Interface.Core.QList (c_QListQModelIndex) import {-# SOURCE #-} Graphics.UI.Qtah.Generator.Interface.Core.QAbstractItemModel ( c_QAbstractItemModel, ) import Graphics.UI.Qtah.Generator.Interface.Core.QModelIndex (c_QModelIndex) import Graphics.UI.Qtah.Generator.Interface.Core.QPersistentModelIndex (c_QPersistentModelIndex) import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), makeQtModule) import Graphics.UI.Qtah.Generator.Types {-# ANN module "HLint: ignore Use camelCase" #-} aModule = AQtModule $ makeQtModule ["Core", "QItemSelectionRange"] [ QtExport $ ExportClass c_QItemSelectionRange ] c_QItemSelectionRange = addReqIncludes [includeStd "QItemSelectionRange"] $ classSetConversionToGc $ classAddFeatures [Assignable, Copyable, Equatable] $ classSetEntityPrefix "" $ makeClass (ident "QItemSelectionRange") Nothing [] $ collect [ just $ mkCtor "new" [] , just $ mkCtor "newWithIndex" [objT c_QModelIndex] , just $ mkCtor "newWithIndices" [objT c_QModelIndex, objT c_QModelIndex] , just $ mkConstMethod "bottom" [] intT , just $ mkConstMethod "bottomRight" [] $ if qtVersion >= [5, 0] then refT $ constT $ objT c_QPersistentModelIndex else objT c_QModelIndex , just $ mkConstMethod' "contains" "containsIndex" [objT c_QModelIndex] boolT , just $ mkConstMethod' "contains" "containsBelowParent" [intT, intT, objT c_QModelIndex] boolT , just $ mkConstMethod "height" [] intT , just $ mkConstMethod "indexes" [] $ objT c_QListQModelIndex , just $ mkConstMethod "intersected" [objT c_QItemSelectionRange] $ objT c_QItemSelectionRange , just $ mkConstMethod "intersects" [objT c_QItemSelectionRange] boolT , just $ mkConstMethod "isEmpty" [] boolT , just $ mkConstMethod "isValid" [] boolT , just $ mkConstMethod "left" [] intT , just $ mkConstMethod "model" [] $ ptrT $ constT $ objT c_QAbstractItemModel , just $ mkConstMethod "parent" [] $ objT c_QModelIndex , just $ mkConstMethod "right" [] intT , test (qtVersion >= [5, 6]) $ mkMethod "swap" [refT $ objT c_QItemSelectionRange] voidT , just $ mkConstMethod "top" [] intT , just $ mkConstMethod "topLeft" [] $ if qtVersion >= [5, 0] then refT $ constT $ objT c_QPersistentModelIndex else objT c_QModelIndex , just $ mkConstMethod "width" [] intT ]
null
https://raw.githubusercontent.com/serokell/qtah/abb4932248c82dc5c662a20d8f177acbc7cfa722/qtah-generator/src/Graphics/UI/Qtah/Generator/Interface/Core/QItemSelectionRange.hs
haskell
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 (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 along with this program. If not, see </>. # SOURCE # # SOURCE # # ANN module "HLint: ignore Use camelCase" #
This file is part of Qtah . Copyright 2015 - 2018 The Qtah Authors . the Free Software Foundation , either version 3 of the License , or GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License module Graphics.UI.Qtah.Generator.Interface.Core.QItemSelectionRange ( aModule, c_QItemSelectionRange, ) where import Foreign.Hoppy.Generator.Spec ( Export (ExportClass), addReqIncludes, classSetConversionToGc, classSetEntityPrefix, ident, includeStd, makeClass, mkConstMethod, mkConstMethod', mkCtor, mkMethod, ) import Foreign.Hoppy.Generator.Spec.ClassFeature ( ClassFeature (Assignable, Copyable, Equatable), classAddFeatures, ) import Foreign.Hoppy.Generator.Types (boolT, constT, intT, objT, ptrT, refT, voidT) import Foreign.Hoppy.Generator.Version (collect, just, test) import Graphics.UI.Qtah.Generator.Flags (qtVersion) c_QAbstractItemModel, ) import Graphics.UI.Qtah.Generator.Interface.Core.QModelIndex (c_QModelIndex) import Graphics.UI.Qtah.Generator.Interface.Core.QPersistentModelIndex (c_QPersistentModelIndex) import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), makeQtModule) import Graphics.UI.Qtah.Generator.Types aModule = AQtModule $ makeQtModule ["Core", "QItemSelectionRange"] [ QtExport $ ExportClass c_QItemSelectionRange ] c_QItemSelectionRange = addReqIncludes [includeStd "QItemSelectionRange"] $ classSetConversionToGc $ classAddFeatures [Assignable, Copyable, Equatable] $ classSetEntityPrefix "" $ makeClass (ident "QItemSelectionRange") Nothing [] $ collect [ just $ mkCtor "new" [] , just $ mkCtor "newWithIndex" [objT c_QModelIndex] , just $ mkCtor "newWithIndices" [objT c_QModelIndex, objT c_QModelIndex] , just $ mkConstMethod "bottom" [] intT , just $ mkConstMethod "bottomRight" [] $ if qtVersion >= [5, 0] then refT $ constT $ objT c_QPersistentModelIndex else objT c_QModelIndex , just $ mkConstMethod' "contains" "containsIndex" [objT c_QModelIndex] boolT , just $ mkConstMethod' "contains" "containsBelowParent" [intT, intT, objT c_QModelIndex] boolT , just $ mkConstMethod "height" [] intT , just $ mkConstMethod "indexes" [] $ objT c_QListQModelIndex , just $ mkConstMethod "intersected" [objT c_QItemSelectionRange] $ objT c_QItemSelectionRange , just $ mkConstMethod "intersects" [objT c_QItemSelectionRange] boolT , just $ mkConstMethod "isEmpty" [] boolT , just $ mkConstMethod "isValid" [] boolT , just $ mkConstMethod "left" [] intT , just $ mkConstMethod "model" [] $ ptrT $ constT $ objT c_QAbstractItemModel , just $ mkConstMethod "parent" [] $ objT c_QModelIndex , just $ mkConstMethod "right" [] intT , test (qtVersion >= [5, 6]) $ mkMethod "swap" [refT $ objT c_QItemSelectionRange] voidT , just $ mkConstMethod "top" [] intT , just $ mkConstMethod "topLeft" [] $ if qtVersion >= [5, 0] then refT $ constT $ objT c_QPersistentModelIndex else objT c_QModelIndex , just $ mkConstMethod "width" [] intT ]
b32a2fac3aae1fbd738b58431e6b7744800834fe7409b737c578ce7af3e13214
lisp/de.setf.xml
xcl.lisp
-*- package : common - lisp - user ; Syntax : Common - lisp ; Base : 10 -*- (in-package :common-lisp-user) (defPackage :de.setf.xcl (:use :common-lisp :xqdm :xml-parser :xml-utils) (:export :xcl-parser :xcl-construction-context :asexp-construction-context :parse )) (let ((*default-pathname-defaults* *load-pathname*)) (map #'load '("xcl-construction-context" "conditions" "parse"))) :EOF
null
https://raw.githubusercontent.com/lisp/de.setf.xml/827681c969342096c3b95735d84b447befa69fa6/demos/xcl/xcl.lisp
lisp
Syntax : Common - lisp ; Base : 10 -*-
(in-package :common-lisp-user) (defPackage :de.setf.xcl (:use :common-lisp :xqdm :xml-parser :xml-utils) (:export :xcl-parser :xcl-construction-context :asexp-construction-context :parse )) (let ((*default-pathname-defaults* *load-pathname*)) (map #'load '("xcl-construction-context" "conditions" "parse"))) :EOF
db87a94cce27d630bce84cb034e8f5bc2a798aa0bba8d62b37d5956da62a96be
MLanguage/mlang
bir_to_dgfip_c.mli
Copyright ( C ) 2019 - 2021 Inria , contributor : < > 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 < / > . <> 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 </>. *) * This module with a single entry point generates C files from a { ! Bir.program } . {!Bir.program}. *) * The optimized code generation for M code , which represents the vast majority of the output , is built in { ! } . of the output, is built in {!DecoupledExpr}. *) val generate_c_program : Dgfip_options.flags -> Bir.program -> Bir_interface.bir_function -> (* filename *) string -> Dgfip_varid.var_id_map -> unit
null
https://raw.githubusercontent.com/MLanguage/mlang/e84aa40757d1ce5bf2d45060c6d201402afab8d5/src/mlang/backend_compilers/bir_to_dgfip_c.mli
ocaml
filename
Copyright ( C ) 2019 - 2021 Inria , contributor : < > 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 < / > . <> 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 </>. *) * This module with a single entry point generates C files from a { ! Bir.program } . {!Bir.program}. *) * The optimized code generation for M code , which represents the vast majority of the output , is built in { ! } . of the output, is built in {!DecoupledExpr}. *) val generate_c_program : Dgfip_options.flags -> Bir.program -> Bir_interface.bir_function -> Dgfip_varid.var_id_map -> unit
3506edb0090a0be1aa7248778bd1460b25e54a2659a00e9ae96827da8df3212a
privet-kitty/cl-competitive
xor.lisp
(defpackage :cp/test/xor (:use :cl :fiveam :cp/xor) (:import-from :cp/test/base #:base-suite)) (in-package :cp/test/xor) (in-suite base-suite) (test xor (is (null (xor))) (is (null (xor nil))) (is (= 3 (xor 3))) (is (= 1 (xor 1 nil))) (is (= 2 (xor nil 2))) (is (null (xor nil nil))) (is (null (xor 1 2))) (is (null (xor 1 2 nil))) (signals error (xor 1 2 (error "Huh?"))) (is (null (xor 1 nil 2))) (is (= 2 (xor nil nil 2))))
null
https://raw.githubusercontent.com/privet-kitty/cl-competitive/d09802269e63ccea479fe140a9a39cb07852e630/module/test/xor.lisp
lisp
(defpackage :cp/test/xor (:use :cl :fiveam :cp/xor) (:import-from :cp/test/base #:base-suite)) (in-package :cp/test/xor) (in-suite base-suite) (test xor (is (null (xor))) (is (null (xor nil))) (is (= 3 (xor 3))) (is (= 1 (xor 1 nil))) (is (= 2 (xor nil 2))) (is (null (xor nil nil))) (is (null (xor 1 2))) (is (null (xor 1 2 nil))) (signals error (xor 1 2 (error "Huh?"))) (is (null (xor 1 nil 2))) (is (= 2 (xor nil nil 2))))
2af433243aa105f6b3edd8757c530edf570785be2076387a8bcf593da72e9f9f
MagnusS/okra
conf.mli
* Copyright ( c ) 2021 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2021 Patrick Ferris <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) type t (** The type for okra configurations *) val default : t (** A default configuration *) val projects : t -> Okra.Activity.project list * A user 's list of activer projects val locations : t -> string list (** A list of locations to use when aggregating reports *) val footer : t -> string option (** An optional footer to append to the end of your engineer reports *) val okr_db : t -> string option * [ okr_db ] is the location of the OKR database . val gitlab_token : t -> string option * [ gitlab_token ] is the optional Gitlab token , if present your Gitlab activity will also be queried . will also be queried. *) val load : string -> (t, [ `Msg of string ]) result (** [load file] attempts to load a configuration from [file] *) val cmdliner : string Cmdliner.Term.t (** Cmdliner term for configuration file location *)
null
https://raw.githubusercontent.com/MagnusS/okra/bc64448939c70d93ff20f4dbc0fd3b3db483338f/bin/conf.mli
ocaml
* The type for okra configurations * A default configuration * A list of locations to use when aggregating reports * An optional footer to append to the end of your engineer reports * [load file] attempts to load a configuration from [file] * Cmdliner term for configuration file location
* Copyright ( c ) 2021 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2021 Patrick Ferris <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) type t val default : t val projects : t -> Okra.Activity.project list * A user 's list of activer projects val locations : t -> string list val footer : t -> string option val okr_db : t -> string option * [ okr_db ] is the location of the OKR database . val gitlab_token : t -> string option * [ gitlab_token ] is the optional Gitlab token , if present your Gitlab activity will also be queried . will also be queried. *) val load : string -> (t, [ `Msg of string ]) result val cmdliner : string Cmdliner.Term.t
d0379e57d072af53f940160a555a981392fe1e393fca416011c7bd9073347143
CodyReichert/qi
util.lisp
(in-package :cl-user) (defpackage libyaml.util (:use :cl :cffi) (:export :size-t) (:documentation "FFI utilities.")) (in-package :libyaml.util) (defmacro define-size-t () "Define size_t according to the architecture." (if (eql (foreign-type-size '(:pointer :int)) 8) 64 bits `(defctype size-t :unsigned-long "The size_t type.") 32 bits `(defctype size-t :unsigned-int "The size_t type."))) (define-size-t)
null
https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/dependencies/cl-libyaml-latest/src/util.lisp
lisp
(in-package :cl-user) (defpackage libyaml.util (:use :cl :cffi) (:export :size-t) (:documentation "FFI utilities.")) (in-package :libyaml.util) (defmacro define-size-t () "Define size_t according to the architecture." (if (eql (foreign-type-size '(:pointer :int)) 8) 64 bits `(defctype size-t :unsigned-long "The size_t type.") 32 bits `(defctype size-t :unsigned-int "The size_t type."))) (define-size-t)
ac32a2d2689a740d8dd23b58ca16583378e1c05833e32bec940a0c589a88c3dd
eeng/mercurius
user_repository.clj
(ns mercurius.accounts.domain.repositories.user-repository) (defprotocol UserRepository (add-user [this user] "Adds the user to the repository and returns it.") (find-by-username [this username] "Returns the user with the `username` or nil if it doesn't exists"))
null
https://raw.githubusercontent.com/eeng/mercurius/f83778ddde99aa13692e4fe2e70b2e9dc2fd70e9/src/mercurius/accounts/domain/repositories/user_repository.clj
clojure
(ns mercurius.accounts.domain.repositories.user-repository) (defprotocol UserRepository (add-user [this user] "Adds the user to the repository and returns it.") (find-by-username [this username] "Returns the user with the `username` or nil if it doesn't exists"))
892f4539c2e4ae6e37020cf3900d1cb1213621d81a873780cead2eb2abf7d2cd
oofp/Beseder
TypeExp.hs
# LANGUAGE TypeFamilies # # LANGUAGE KindSignatures # # LANGUAGE PolyKinds # # LANGUAGE DataKinds # {-# LANGUAGE TypeInType #-} # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # # LANGUAGE MultiParamTypeClasses # module Beseder.Base.Internal.TypeExp where import Data.Kind import Protolude type Exp a = a -> Type type family Eval (e :: Exp a) :: a type family Unwrap (wrapped :: *) :: * data TFilterList :: (a -> Exp Bool) -> [*] -> Exp [*] type instance Eval (TFilterList f '[]) = '[] type instance Eval (TFilterList f (a ': as)) = PrependIfTrue (Eval (f a)) a (Eval (TFilterList f as)) type family PrependIfTrue (f ::Bool) a (as :: [*]) where PrependIfTrue 'False a as = as PrependIfTrue 'True a as = a ': as
null
https://raw.githubusercontent.com/oofp/Beseder/a0f5c5e3138938b6fa18811d646535ee6df1a4f4/src/Beseder/Base/Internal/TypeExp.hs
haskell
# LANGUAGE TypeInType #
# LANGUAGE TypeFamilies # # LANGUAGE KindSignatures # # LANGUAGE PolyKinds # # LANGUAGE DataKinds # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # # LANGUAGE MultiParamTypeClasses # module Beseder.Base.Internal.TypeExp where import Data.Kind import Protolude type Exp a = a -> Type type family Eval (e :: Exp a) :: a type family Unwrap (wrapped :: *) :: * data TFilterList :: (a -> Exp Bool) -> [*] -> Exp [*] type instance Eval (TFilterList f '[]) = '[] type instance Eval (TFilterList f (a ': as)) = PrependIfTrue (Eval (f a)) a (Eval (TFilterList f as)) type family PrependIfTrue (f ::Bool) a (as :: [*]) where PrependIfTrue 'False a as = as PrependIfTrue 'True a as = a ': as
70103a2ebc8541f465c9ca6ee18680f62b4a792c73fe9478e125aad3e03cbff3
janestreet/universe
explicit_dependencies.ml
(*_ Generated by ${ROOT}/bin/gen-explicit-dependencies.sh *) module Explicitly_depend_on_Zstd_c = Zstd_c
null
https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/zstandard/src/explicit_dependencies.ml
ocaml
_ Generated by ${ROOT}/bin/gen-explicit-dependencies.sh
module Explicitly_depend_on_Zstd_c = Zstd_c
84a36cc9256e519fa883783a0cb43f3ea461f0976361f738977dcee55b661a74
takeoutweight/clojure-scheme
repl.clj
Copyright ( c ) . All rights reserved . ;; The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ( -1.0.php ) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns cljscm.repl (:refer-clojure :exclude [load-file]) (:import java.io.File) (:require [clojure.string :as string] [clojure.java.io :as io] [cljscm.compiler :as comp] [cljscm.analyzer :as ana] [cljscm.tagged-literals :as tags] [cljscm.closure :as cljsc])) (def ^:dynamic *cljs-verbose* false) (defprotocol IJavaScriptEnv (-setup [this] "initialize the environment") (-evaluate [this filename line js] "evaluate a javascript string") (-load [this ns url] "load code at url into the environment") (-tear-down [this] "dispose of the environment")) (defn load-namespace "Load a namespace and all of its dependencies into the evaluation environment. The environment is responsible for ensuring that each namespace is loaded once and only once." [repl-env sym] (let [sym (if (and (seq? sym) (= (first sym) 'quote)) (second sym) sym) opts {:output-dir (get repl-env :working-dir ".repl")} deps (->> (cljsc/add-dependencies opts {:requires [(name sym)] :type :seed}) (remove (comp #{["goog"]} :provides)) (remove (comp #{:seed} :type)) (map #(select-keys % [:provides :url])))] (doseq [{:keys [url provides]} deps] (-load repl-env provides url)))) (defn- load-dependencies [repl-env requires] (doseq [ns requires] (load-namespace repl-env ns))) (defn- display-error ([ret form] (display-error ret form (constantly nil))) ([ret form f] (when-not (and (seq? form) (= 'ns (first form))) (f) (println (:value ret)) (when-let [st (:stacktrace ret)] (println st))))) (defn evaluate-form "Evaluate a ClojureScript form in the JavaScript environment. Returns a string which is the ClojureScript return value. This string may or may not be readable by the Clojure reader." ([repl-env env filename form] (evaluate-form repl-env env filename form identity)) ([repl-env env filename form wrap] (try (let [ast (ana/analyze env form) js (comp/emit-str ast) wrap-js (comp/emit-str (binding [ana/*cljs-warn-on-undeclared* false ana/*cljs-warn-on-redef* false ana/*cljs-warn-on-dynamic* false ana/*cljs-warn-on-fn-var* false ana/*cljs-warn-fn-arity* false] (ana/analyze env (wrap form))))] (when (= (:op ast) :ns) (load-dependencies repl-env (into (vals (:requires ast)) (distinct (vals (:uses ast)))))) (when *cljs-verbose* (print js)) (let [ret (-evaluate repl-env filename (:line (meta form)) wrap-js)] (case (:status ret) ;;we eat ns errors because we know goog.provide() will throw when reloaded ;;TODO - file bug with google, this is bs error ;;this is what you get when you try to 'teach new developers' via errors ( goog / base.js 104 ) :error (display-error ret form) :exception (display-error ret form #(prn "Error evaluating:" form :as js)) :success (:value ret)))) (catch Throwable ex (.printStackTrace ex) (println (str ex)))))) (defn load-stream [repl-env filename stream] (with-open [r (io/reader stream)] (let [env (ana/empty-env) pbr (clojure.lang.LineNumberingPushbackReader. r) eof (Object.)] (loop [r (read pbr false eof false)] (let [env (assoc env :ns (ana/get-namespace ana/*cljs-ns*))] (when-not (identical? eof r) (evaluate-form repl-env env filename r) (recur (read pbr false eof false)))))))) (defn load-file [repl-env f] (binding [ana/*cljs-ns* 'cljscm.user] (let [res (if (= \/ (first f)) f (io/resource f))] (assert res (str "Can't find " f " in classpath")) (load-stream repl-env f res)))) (defn- wrap-fn [form] (cond (and (seq? form) (= 'ns (first form))) identity ('#{*1 *2 *3} form) (fn [x] `(cljscm.core.pr-str ~x)) :else (fn [x] `(cljscm.core.pr-str (let [ret# ~x] (do (set! *3 *2) (set! *2 *1) (set! *1 ret#) ret#)))))) (defn- eval-and-print [repl-env env form] (let [ret (evaluate-form repl-env (assoc env :ns (ana/get-namespace ana/*cljs-ns*)) "<cljs repl>" form (wrap-fn form))] (try (prn (read-string ret)) (catch Exception e (if (string? ret) (println ret) (prn nil)))))) (defn- read-next-form [] (try {:status :success :form (binding [*ns* (create-ns ana/*cljs-ns*) *data-readers* tags/*cljs-data-readers*] (read))} (catch Exception e (println (.getMessage e)) {:status :error}))) (def default-special-fns (let [load-file-fn (fn [repl-env file] (load-file repl-env file))] {'in-ns (fn [_ quoted-ns] (let [ns-name (second quoted-ns)] (when-not (ana/get-namespace ns-name) (ana/set-namespace ns-name {:name ns-name})) (set! ana/*cljs-ns* ns-name))) 'load-file load-file-fn 'clojure.core/load-file load-file-fn 'load-namespace (fn [repl-env ns] (load-namespace repl-env ns))})) (defn analyze-source "Given a source directory, analyzes all .cljs files. Used to populate cljscm.analyzer/namespaces so as to support code reflection." [src-dir] (if-let [src-dir (and (not (empty? src-dir)) (File. src-dir))] (doseq [file (comp/cljs-files-in src-dir)] (ana/analyze-file (str "file://" (.getAbsolutePath file)))))) (defn repl "Note - repl will reload core.cljs every time, even if supplied old repl-env" [repl-env & {:keys [analyze-path verbose warn-on-undeclared special-fns]}] (prn "Type: " :cljs/quit " to quit") (binding [ana/*cljs-ns* 'cljscm.user *cljs-verbose* verbose ana/*cljs-warn-on-undeclared* warn-on-undeclared] (when analyze-path (analyze-source analyze-path)) (let [env {:context :expr :locals {}} special-fns (merge default-special-fns special-fns) is-special-fn? (set (keys special-fns))] (-setup repl-env) (loop [] (print (str "ClojureScript:" ana/*cljs-ns* "> ")) (flush) (let [{:keys [status form]} (read-next-form)] (cond (= form :cljs/quit) :quit (= status :error) (recur) (and (seq? form) (is-special-fn? (first form))) (do (apply (get special-fns (first form)) repl-env (rest form)) (newline) (recur)) :else (do (eval-and-print repl-env env form) (recur))))) (-tear-down repl-env))))
null
https://raw.githubusercontent.com/takeoutweight/clojure-scheme/6121de1690a6a52c7dbbe7fa722aaf3ddd4920dd/src/clj/cljscm/repl.clj
clojure
The use and distribution terms for this software are covered by the which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. we eat ns errors because we know goog.provide() will throw when reloaded TODO - file bug with google, this is bs error this is what you get when you try to 'teach new developers'
Copyright ( c ) . All rights reserved . Eclipse Public License 1.0 ( -1.0.php ) (ns cljscm.repl (:refer-clojure :exclude [load-file]) (:import java.io.File) (:require [clojure.string :as string] [clojure.java.io :as io] [cljscm.compiler :as comp] [cljscm.analyzer :as ana] [cljscm.tagged-literals :as tags] [cljscm.closure :as cljsc])) (def ^:dynamic *cljs-verbose* false) (defprotocol IJavaScriptEnv (-setup [this] "initialize the environment") (-evaluate [this filename line js] "evaluate a javascript string") (-load [this ns url] "load code at url into the environment") (-tear-down [this] "dispose of the environment")) (defn load-namespace "Load a namespace and all of its dependencies into the evaluation environment. The environment is responsible for ensuring that each namespace is loaded once and only once." [repl-env sym] (let [sym (if (and (seq? sym) (= (first sym) 'quote)) (second sym) sym) opts {:output-dir (get repl-env :working-dir ".repl")} deps (->> (cljsc/add-dependencies opts {:requires [(name sym)] :type :seed}) (remove (comp #{["goog"]} :provides)) (remove (comp #{:seed} :type)) (map #(select-keys % [:provides :url])))] (doseq [{:keys [url provides]} deps] (-load repl-env provides url)))) (defn- load-dependencies [repl-env requires] (doseq [ns requires] (load-namespace repl-env ns))) (defn- display-error ([ret form] (display-error ret form (constantly nil))) ([ret form f] (when-not (and (seq? form) (= 'ns (first form))) (f) (println (:value ret)) (when-let [st (:stacktrace ret)] (println st))))) (defn evaluate-form "Evaluate a ClojureScript form in the JavaScript environment. Returns a string which is the ClojureScript return value. This string may or may not be readable by the Clojure reader." ([repl-env env filename form] (evaluate-form repl-env env filename form identity)) ([repl-env env filename form wrap] (try (let [ast (ana/analyze env form) js (comp/emit-str ast) wrap-js (comp/emit-str (binding [ana/*cljs-warn-on-undeclared* false ana/*cljs-warn-on-redef* false ana/*cljs-warn-on-dynamic* false ana/*cljs-warn-on-fn-var* false ana/*cljs-warn-fn-arity* false] (ana/analyze env (wrap form))))] (when (= (:op ast) :ns) (load-dependencies repl-env (into (vals (:requires ast)) (distinct (vals (:uses ast)))))) (when *cljs-verbose* (print js)) (let [ret (-evaluate repl-env filename (:line (meta form)) wrap-js)] (case (:status ret) via errors ( goog / base.js 104 ) :error (display-error ret form) :exception (display-error ret form #(prn "Error evaluating:" form :as js)) :success (:value ret)))) (catch Throwable ex (.printStackTrace ex) (println (str ex)))))) (defn load-stream [repl-env filename stream] (with-open [r (io/reader stream)] (let [env (ana/empty-env) pbr (clojure.lang.LineNumberingPushbackReader. r) eof (Object.)] (loop [r (read pbr false eof false)] (let [env (assoc env :ns (ana/get-namespace ana/*cljs-ns*))] (when-not (identical? eof r) (evaluate-form repl-env env filename r) (recur (read pbr false eof false)))))))) (defn load-file [repl-env f] (binding [ana/*cljs-ns* 'cljscm.user] (let [res (if (= \/ (first f)) f (io/resource f))] (assert res (str "Can't find " f " in classpath")) (load-stream repl-env f res)))) (defn- wrap-fn [form] (cond (and (seq? form) (= 'ns (first form))) identity ('#{*1 *2 *3} form) (fn [x] `(cljscm.core.pr-str ~x)) :else (fn [x] `(cljscm.core.pr-str (let [ret# ~x] (do (set! *3 *2) (set! *2 *1) (set! *1 ret#) ret#)))))) (defn- eval-and-print [repl-env env form] (let [ret (evaluate-form repl-env (assoc env :ns (ana/get-namespace ana/*cljs-ns*)) "<cljs repl>" form (wrap-fn form))] (try (prn (read-string ret)) (catch Exception e (if (string? ret) (println ret) (prn nil)))))) (defn- read-next-form [] (try {:status :success :form (binding [*ns* (create-ns ana/*cljs-ns*) *data-readers* tags/*cljs-data-readers*] (read))} (catch Exception e (println (.getMessage e)) {:status :error}))) (def default-special-fns (let [load-file-fn (fn [repl-env file] (load-file repl-env file))] {'in-ns (fn [_ quoted-ns] (let [ns-name (second quoted-ns)] (when-not (ana/get-namespace ns-name) (ana/set-namespace ns-name {:name ns-name})) (set! ana/*cljs-ns* ns-name))) 'load-file load-file-fn 'clojure.core/load-file load-file-fn 'load-namespace (fn [repl-env ns] (load-namespace repl-env ns))})) (defn analyze-source "Given a source directory, analyzes all .cljs files. Used to populate cljscm.analyzer/namespaces so as to support code reflection." [src-dir] (if-let [src-dir (and (not (empty? src-dir)) (File. src-dir))] (doseq [file (comp/cljs-files-in src-dir)] (ana/analyze-file (str "file://" (.getAbsolutePath file)))))) (defn repl "Note - repl will reload core.cljs every time, even if supplied old repl-env" [repl-env & {:keys [analyze-path verbose warn-on-undeclared special-fns]}] (prn "Type: " :cljs/quit " to quit") (binding [ana/*cljs-ns* 'cljscm.user *cljs-verbose* verbose ana/*cljs-warn-on-undeclared* warn-on-undeclared] (when analyze-path (analyze-source analyze-path)) (let [env {:context :expr :locals {}} special-fns (merge default-special-fns special-fns) is-special-fn? (set (keys special-fns))] (-setup repl-env) (loop [] (print (str "ClojureScript:" ana/*cljs-ns* "> ")) (flush) (let [{:keys [status form]} (read-next-form)] (cond (= form :cljs/quit) :quit (= status :error) (recur) (and (seq? form) (is-special-fn? (first form))) (do (apply (get special-fns (first form)) repl-env (rest form)) (newline) (recur)) :else (do (eval-and-print repl-env env form) (recur))))) (-tear-down repl-env))))
cb986b0e4ee88405af470fc42c50330008037421c63af9479f7e47f3aa1a1264
NinjaTrappeur/ex-hack
ProcessingSteps.hs
| Module : ExHack . ProcessingSteps Description : Processing operations used to both generate the ExHack database and the HTML documentation . Copyright : ( c ) , 2018 License : GPL-3 Stability : experimental Portability : POSIX Module : ExHack.ProcessingSteps Description : Processing operations used to both generate the ExHack database and the HTML documentation. Copyright : (c) Félix Baylac-Jacqué, 2018 License : GPL-3 Stability : experimental Portability : POSIX -} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # module ExHack.ProcessingSteps ( dlAssets, generateDb, generateHtmlPages, genGraphDep, indexSymbols, parseStackage, retrievePkgsExports, saveGraphDep ) where import Control.Lens (view) import Control.Monad (foldM_) import Control.Monad.Catch (MonadCatch, MonadThrow, displayException, handleAll, throwM) import Control.Monad.IO.Class (liftIO) import Control.Monad.Reader.Class (asks) import qualified Data.ByteString as BS (readFile, writeFile) import qualified Data.ByteString.Lazy as BL (writeFile) import Data.FileEmbed (embedFile) import qualified Data.HashMap.Strict as HM (HashMap, elems, empty, filterWithKey, insert, lookup) import qualified Data.HashSet as HS (foldl', unions) import Data.List (foldl') import Data.Maybe (fromJust) import qualified Data.Text as T (pack, replace, unpack) import qualified Data.Text.IO as T (readFile) import qualified Data.Text.Lazy as TL (Text) import qualified Data.Text.Lazy.IO as TL (hPutStr) import Database.Selda (RowID, SeldaM) import Database.Selda.SQLite (withSQLite) import Network.HTTP.Client (Manager, httpLbs, managerSetProxy, newManager, parseRequest_, proxyEnvironment, responseBody) import Network.HTTP.Client.TLS (tlsManagerSettings) import System.Directory (createDirectoryIfMissing) import System.FilePath ((<.>), (</>)) import System.IO (IOMode (WriteMode), hSetEncoding, utf8, withFile) import Text.Blaze.Html.Renderer.Text (renderHtml) import ExHack.Cabal.CabalParser (parseCabalFile) import ExHack.Data.Db (getHomePagePackages, getModulePageSyms, getPackageId, getPackagePageMods, getPkgImportScopes, initDb, saveModuleExports, saveModuleUnifiedSymbols, savePackageDeps, savePackages) import ExHack.Ghc (getModImports, getModSymbols, unLoc) import ExHack.Hackage.Hackage (findComponentRoot, getModExports, getModNames, unpackHackageTarball) import ExHack.ModulePaths (toModFilePath) import ExHack.Renderer.Html (addLineMarker, highLightCode, homePageTemplate, modulePageTemplate, packagePageTemplate) import qualified ExHack.Renderer.Types as RT (HighlightedSourceCodeFile (..), HighlightedSymbolOccurs (..), HomePagePackage (..), ModuleName (..), PackageName (..), SymbolOccurs (..), renderRoute) import ExHack.Stackage.Stack (buildPackage) import ExHack.Stackage.StackageParser (getHackageUrls, parseStackageYaml) import ExHack.Types (AlterDatabase, CabalBuildError (..), CabalFilesDir (..), ComponentRoot (..), DatabaseHandle, DatabaseStatus (..), HtmlDir (..), ImportsScope, IndexedModuleNameT (..), IndexedSym (..), LocatedSym (..), ModuleName, ModuleNameT (..), MonadLog (..), MonadStep, Package (allComponents, exposedModules, packageFilePath), PackageComponent (..), PackageDesc (..), PackageDlDesc, PackageDlDesc (..), PackageFilePath (..), SourceCodeFile (..), StackageFile (..), SymName, TarballsDir (..), UnifiedSym (..), WorkDir (..), getDatabaseHandle, getModNameT, getName, getPackageNameT, logInfo, packagedlDescName) import ExHack.Utils (Has (..), foldM') | ` Step ` 1 : database generation . -- This function creates a new SQLite database initialized according -- to ex-hack's internal SQL scheme. generateDb :: forall c m. (Has c (DatabaseHandle 'New), MonadStep c m) => m (DatabaseHandle (AlterDatabase 'New)) generateDb = do logInfoTitle "[Step 1] Generating database scheme." dh <- asks (view hasLens) :: m (DatabaseHandle 'New) let (fp, dh') = getDatabaseHandle dh withSQLite fp initDb pure dh' | ` Step ` 2 : stackage file parsing . -- -- This function parses the stackage file that will be used to -- generate the packages dependancy graph. parseStackage :: forall c m. (Has c StackageFile, MonadStep c m) => m [PackageDlDesc] parseStackage = do logInfoTitle "[Step 2] Parsing Stackage file" (StackageFile stackageFp) <- asks (view hasLens) stackageYaml <- liftIO $ T.readFile stackageFp let packages = fromJust $ parseStackageYaml stackageYaml pure $ getHackageUrls packages | ` Step ` 3 : assets downloading . -- -- This function downloads both the cabal files and the taballs of the packages. -- Everything will be downloaded from the <> mirror. dlAssets :: forall c m. (Has c TarballsDir, Has c CabalFilesDir, MonadStep c m) => [PackageDlDesc] -> m () dlAssets packages = do logInfoTitle "[Step 3] Downloading hackage assets (cabal files, tarballs)." let settings = managerSetProxy (proxyEnvironment Nothing) tlsManagerSettings tbd <- asks (view hasLens) cd <- asks (view hasLens) m <- liftIO $ newManager settings _ <- foldr (dlFoldCabalFiles cd tbd m (length packages)) (return 1) packages return () where dlFoldCabalFiles :: CabalFilesDir -> TarballsDir -> Manager -> Int -> PackageDlDesc -> m Int -> m Int dlFoldCabalFiles !cd !td man totalSteps !p step = handleAll logErrors $ do step' <- step let !pn = packagedlDescName p logInfoProgress 3 totalSteps step' $ "Downloading " <> pn <> " assets." downloadHackageFiles cd td man p return $ step' + 1 where logErrors e = do logError $ "[Step 3] ERROR while downloading " <> packagedlDescName p <> " assets: " <> T.pack (displayException e) step' <- step pure (step' + 1) downloadHackageFiles :: CabalFilesDir -> TarballsDir -> Manager -> PackageDlDesc -> m () downloadHackageFiles (CabalFilesDir cabalFilesDir) (TarballsDir tarballsDir) man (PackageDlDesc (name, cabalUrl, tarballUrl)) = liftIO $ do f <- httpLbs (parseRequest_ $ T.unpack cabalUrl) man BL.writeFile (cabalFilesDir </> T.unpack name <.> "cabal") $ responseBody f f' <- httpLbs (parseRequest_ $ T.unpack tarballUrl) man BL.writeFile (tarballsDir </> T.unpack name <.> "tar.gz") $ responseBody f' return () | ` Step ` 4 : Dependencies graph generation . -- -- This function generates the packages dependancy graph. -- genGraphDep :: forall c m. (Has c TarballsDir, Has c CabalFilesDir, Has c WorkDir, Has c (DatabaseHandle 'Initialized), MonadStep c m) => [PackageDlDesc] -> m [Package] genGraphDep pd = do logInfoTitle "[Step 4] Generating dependencies graph." tbd <- asks (view hasLens) cd <- asks (view hasLens) wd <- asks (view hasLens) logInfo "[+] Parsing cabal files." (_, !pkgs) <- foldM' (readPkgsFiles cd wd tbd (length pd)) (1,[]) pd pure pkgs where readPkgsFiles (CabalFilesDir cabalFilesDir) (WorkDir wd) (TarballsDir tarballsDir) !totalSteps (!step, xs) p = handleAll logErrors $ do logInfoProgress 4 totalSteps step $ "Unzip " <> packagedlDescName p <> " package." let tbp = tarballsDir </> T.unpack (packagedlDescName p) <.> "tar.gz" tb <- liftIO $ BS.readFile tbp pfp <- unpackHackageTarball wd tb logInfoProgress 4 totalSteps step $ "Reading " <> packagedlDescName p <> " cabal file." !cf <- liftIO $ T.readFile $ cabalFilesDir </> T.unpack (packagedlDescName p) <.> "cabal" let !pack = parseCabalFile $ PackageDesc (pfp,cf) case pack of Nothing -> pure (step + 1, xs) Just !x -> pure (step + 1, x:xs) where logErrors e = do logError $ "[Step 4] ERROR cannot read " <> packagedlDescName p <> " cabal file: " <> T.pack (displayException e) pure (step + 1, xs) | ` Step ` 5 : Save dependancies graph . -- -- This step takes the previously generated dependancies graph and saves it -- in the database. -- -- Caution: this step can be **really** long. saveGraphDep :: forall c m. (Has c TarballsDir, Has c CabalFilesDir, Has c (DatabaseHandle 'Initialized), MonadStep c m) => [Package] -> m (DatabaseHandle 'DepsGraph) saveGraphDep pkgs = do logInfoTitle "[Step 5] Saving dependencies graph." dbHandle <- asks (view hasLens) :: m (DatabaseHandle 'Initialized) let (dbFp, dbHandle') = getDatabaseHandle dbHandle liftIO $ withSQLite dbFp $ do logInfo "[+] Saving packages to DB (may take some time)..." savePackages pkgs logInfo "[+] Done." logInfo "[+] Saving dependancies to DB..." -- TODO: maybe speedup this insert by caching the packages ids -- in a hasmap in the memory. (or use sqlite in memory system????) foldM_ (foldInsertDep (length pkgs)) 1 pkgs logInfo "[+] Done." return () pure dbHandle' where foldInsertDep :: Int -> Int -> Package -> SeldaM Int foldInsertDep totalDeps step pkg = handleAll logErrors $ do savePackageDeps pkg logInfoProgress 5 totalDeps step $ "Saving " <> getName pkg <> " dependancies to DB." pure $ step + 1 where logErrors e = do logError $ "[Step 5] ERROR cannot insert " <> getName pkg <> " dependancies to DB: " <> T.pack (displayException e) pure $ step + 1 | ` Step ` 6 : extracting and indexing modules exports . -- -- Builds the packages using cabal, load the modules in a GHC - API program which extracts the exports and finally save -- everything in the ex-hack database. retrievePkgsExports :: forall c m. (Has c (DatabaseHandle 'DepsGraph), MonadStep c m) => [Package] -> m (DatabaseHandle 'PkgExports) retrievePkgsExports pkgs = do logInfoTitle "[Step 6] Retrieving modules exports." dbHandle <- asks (view hasLens) :: m (DatabaseHandle 'DepsGraph) let (dbFp, dbHandle') = getDatabaseHandle dbHandle foldM_ (getPkgExports dbFp (length pkgs)) 1 pkgs pure dbHandle' where getPkgExports :: FilePath -> Int -> Int -> Package -> m Int getPkgExports dbFp totalSteps !nb p = handleAll logErrors $ do logInfoProgress 6 totalSteps nb $ "Retrieving "<> getName p <> " exports." let pfp = packageFilePath p cr <- buildPackage pfp maybe (pure ()) (\(errCode, errStr) -> throwM $ CabalBuildError errCode errStr) cr let mns = getModNames p croots = maybe [ComponentRoot "./"] roots $ exposedModules p pid <- liftIO $ withSQLite dbFp $ getPackageId p processMod pid pfp croots `mapM_` mns pure $ nb + 1 where processMod :: RowID -> PackageFilePath -> [ComponentRoot] -> ModuleName -> m () processMod pid pfp crs mn = do (_, me) <- getModExports pfp crs mn -- Breaks a bit the design but necessary to keep -- memory usage under control. liftIO $ withSQLite dbFp $ saveModuleExports pid mn me pure () logErrors e = do logError $ "[Step 6] ERROR cannot get exports for " <> getName p <> ": " <> T.pack (displayException e) pure $ nb + 1 | ` Step ` 7 : Indexes the code source symbols in the database . -- -- For each package, component and module, this step will: -- 1 . Retrieve the imported symbols and try to match them to the previously -- indexed package exports. 2 . Use GHC parser to get this file symbols . 3 . Unify these symbols to the imported one . 4 . We save each unified occurence in the database . indexSymbols :: forall c m. (MonadStep c m, MonadCatch m, MonadThrow m, Has c (DatabaseHandle 'PkgExports)) => [Package] -> m (DatabaseHandle 'IndexedSyms) indexSymbols pkgs = do logInfoTitle "[Step 7] Indexing used symbols." dbh <- asks (view hasLens) :: m (DatabaseHandle 'PkgExports) let (dbfp, dbh') = getDatabaseHandle dbh foldM_ (indexPackage dbfp (length pkgs)) 1 pkgs pure dbh' where indexPackage :: FilePath -> Int -> Int -> Package -> m Int indexPackage !dbFp nb cur p = do logInfoProgress 7 nb cur $ "Indexing " <> getName p <> " used symbols." is <- liftIO $ withSQLite dbFp $ getPkgImportScopes p indexComponent dbFp p (packageFilePath p) is `mapM_` allComponents p pure $ cur + 1 indexComponent :: FilePath -> Package -> PackageFilePath -> ImportsScope -> PackageComponent -> m () indexComponent dbh p pfp is pc = handleAll logErrors $ do mfps <- findModuleFilePath pfp (roots pc) `mapM` mods pc indexModule dbh p pfp is `mapM_` mfps where logErrors e = logError $ "[Step 7] ERROR while indexing component " <> T.pack (show pc) <> " from package " <> getName p <> ": " <> T.pack (displayException e) indexModule :: FilePath -> Package -> PackageFilePath -> ImportsScope -> (ModuleName, ComponentRoot) -> m () indexModule dbFp p pfp is (mn,cr) = handleAll logErrors $ do imports <- getModImports pfp cr mn -- fis: filtered import scope according to this module imports -- isyms: imported symbols hashsets on which we will perform the unification let !fis = HM.filterWithKey (\(IndexedModuleNameT (n, _)) _ -> n `elem` imports) is !isyms = HS.unions $ HM.elems fis !isymsMap = HS.foldl' (\hm is'@(IndexedSym (n, _)) -> HM.insert n is' hm) HM.empty isyms syms <- getModSymbols p pfp cr mn fileContent <- liftIO $ T.readFile $ toModFilePath pfp cr mn let !file = SourceCodeFile fileContent (getModNameT mn) (getPackageNameT p) unsyms = unifySymbols isymsMap syms withSQLite dbFp $ saveModuleUnifiedSymbols unsyms file where logErrors e = do let (ModuleNameT mnt) = getModNameT mn logError $ "[Step 7] ERROR while indexing module " <> mnt <> " from package " <> getName p <> ": " <> T.pack (displayException e) findModuleFilePath :: PackageFilePath -> [ComponentRoot] -> ModuleName -> m (ModuleName, ComponentRoot) findModuleFilePath pfp crs mn = do cr <- findComponentRoot pfp crs mn pure (mn, cr) unifySymbols :: HM.HashMap SymName IndexedSym -> [LocatedSym] -> [UnifiedSym] unifySymbols isyms = foldl' foldLSym [] where foldLSym xs ls@(LocatedSym (_, _, locSym)) = maybe xs (\is -> UnifiedSym(is,ls) : xs) (HM.lookup (unLoc locSym) isyms) | ` Step ` 8 : Generates the HTML documentation using the previously -- generated database. generateHtmlPages :: forall c m. (MonadStep c m, MonadCatch m, MonadThrow m, Has c (DatabaseHandle 'IndexedSyms), Has c HtmlDir) => m () generateHtmlPages = do logInfoTitle "[Step 8] Generating the HTML documentation." HtmlDir outfp <- asks (view hasLens) :: m HtmlDir dbh <- asks (view hasLens) :: m (DatabaseHandle 'IndexedSyms) let (dbfp,_) = getDatabaseHandle dbh pkgs <- liftIO $ withSQLite dbfp getHomePagePackages let hp = renderHtml $ homePageTemplate pkgs RT.renderRoute liftIO $ withFile (outfp </> "index.html") WriteMode (\h -> hSetEncoding h utf8 >> TL.hPutStr h hp) foldM_ (generatePackPage dbfp outfp (length pkgs)) 1 pkgs copyAssets outfp where generatePackPage :: FilePath -> FilePath -> Int -> Int -> RT.HomePagePackage -> m Int generatePackPage !dbfp outfp nbI i hp@(RT.HomePagePackage pack@(RT.PackageName (_,pname)) _) = handleAll logErrors $ do expmods <- liftIO $ withSQLite dbfp (getPackagePageMods pack) logInfoProgress 8 nbI i $ "Generating HTML documentation for " <> pname let fp = outfp </> "packages" </> T.unpack pname pp = renderHtml $ packagePageTemplate hp expmods RT.renderRoute liftIO $ do createDirectoryIfMissing True fp writeUtf8File fp pp generateModPage dbfp fp hp `mapM_` expmods pure $ i + 1 where logErrors e = do logError $ "[Step 7] ERROR while generating " <> pname <> " HTML documentation: " <> T.pack (displayException e) pure $ i + 1 generateModPage :: FilePath -> FilePath -> RT.HomePagePackage -> RT.ModuleName -> m () generateModPage dbfp packfp hp@(RT.HomePagePackage pack _) modn@(RT.ModuleName (_,modnt)) = do syms <- liftIO $ withSQLite dbfp (getModulePageSyms pack modn) hsyms <- highLightOccs syms let mp = renderHtml $ modulePageTemplate hp modn hsyms RT.renderRoute fp = packfp </> T.unpack (T.replace "." "-" modnt) liftIO $ do createDirectoryIfMissing True fp writeUtf8File fp mp -- | TODO: highlighting shouldn't be performed here but directly when extracted from the DB. This hack has been performed in a rush , should be fixed after V0 . highLightOccs :: [RT.SymbolOccurs] -> m [RT.HighlightedSymbolOccurs] highLightOccs xs = highSyms `mapM` xs where highSyms (RT.SymbolOccurs sn xs') = do hs <- highSym `mapM` xs' pure $ RT.HighlightedSymbolOccurs sn hs highSym (col, line, SourceCodeFile c p m) = do hc <- handleAll highErr $ highLightCode c pure (col, line, RT.HighlightedSourceCodeFile (addLineMarker line hc) p m) where highErr e = do logError $ "[Step 8] HIGHLIGHT ERROR " <> T.pack (displayException e) pure c copyAssets :: FilePath -> m () copyAssets fp = do let font = $(embedFile "./src/ExHack/Renderer/templates/static/Inter-UI-Regular.woff") list = $(embedFile "./src/ExHack/Renderer/templates/static/list.min.js") style = $(embedFile "./src/ExHack/Renderer/templates/static/style.css") logo = $(embedFile "./img/logo/ex-hack-logo.svg") stat = fp </> "static" liftIO $ do createDirectoryIfMissing True stat BS.writeFile (stat </> "Inter-UI-Regular.woff") font BS.writeFile (stat </> "list.min.js") list BS.writeFile (stat </> "style.css") style BS.writeFile (stat </> "ex-hack-logo.svg") logo writeUtf8File :: FilePath -> TL.Text -> IO () writeUtf8File fp txt = withFile (fp </> "index.html") WriteMode (\h -> hSetEncoding h utf8 >> TL.hPutStr h txt)
null
https://raw.githubusercontent.com/NinjaTrappeur/ex-hack/dace36926065d5a0dd0076beec1a6eeacd848732/src/ExHack/ProcessingSteps.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # to ex-hack's internal SQL scheme. This function parses the stackage file that will be used to generate the packages dependancy graph. This function downloads both the cabal files and the taballs of the packages. Everything will be downloaded from the <> mirror. This function generates the packages dependancy graph. This step takes the previously generated dependancies graph and saves it in the database. Caution: this step can be **really** long. TODO: maybe speedup this insert by caching the packages ids in a hasmap in the memory. (or use sqlite in memory system????) Builds the packages using cabal, load the modules in a everything in the ex-hack database. Breaks a bit the design but necessary to keep memory usage under control. For each package, component and module, this step will: indexed package exports. fis: filtered import scope according to this module imports isyms: imported symbols hashsets on which we will perform the unification generated database. | TODO: highlighting shouldn't be performed here but directly when extracted from the DB.
| Module : ExHack . ProcessingSteps Description : Processing operations used to both generate the ExHack database and the HTML documentation . Copyright : ( c ) , 2018 License : GPL-3 Stability : experimental Portability : POSIX Module : ExHack.ProcessingSteps Description : Processing operations used to both generate the ExHack database and the HTML documentation. Copyright : (c) Félix Baylac-Jacqué, 2018 License : GPL-3 Stability : experimental Portability : POSIX -} # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # module ExHack.ProcessingSteps ( dlAssets, generateDb, generateHtmlPages, genGraphDep, indexSymbols, parseStackage, retrievePkgsExports, saveGraphDep ) where import Control.Lens (view) import Control.Monad (foldM_) import Control.Monad.Catch (MonadCatch, MonadThrow, displayException, handleAll, throwM) import Control.Monad.IO.Class (liftIO) import Control.Monad.Reader.Class (asks) import qualified Data.ByteString as BS (readFile, writeFile) import qualified Data.ByteString.Lazy as BL (writeFile) import Data.FileEmbed (embedFile) import qualified Data.HashMap.Strict as HM (HashMap, elems, empty, filterWithKey, insert, lookup) import qualified Data.HashSet as HS (foldl', unions) import Data.List (foldl') import Data.Maybe (fromJust) import qualified Data.Text as T (pack, replace, unpack) import qualified Data.Text.IO as T (readFile) import qualified Data.Text.Lazy as TL (Text) import qualified Data.Text.Lazy.IO as TL (hPutStr) import Database.Selda (RowID, SeldaM) import Database.Selda.SQLite (withSQLite) import Network.HTTP.Client (Manager, httpLbs, managerSetProxy, newManager, parseRequest_, proxyEnvironment, responseBody) import Network.HTTP.Client.TLS (tlsManagerSettings) import System.Directory (createDirectoryIfMissing) import System.FilePath ((<.>), (</>)) import System.IO (IOMode (WriteMode), hSetEncoding, utf8, withFile) import Text.Blaze.Html.Renderer.Text (renderHtml) import ExHack.Cabal.CabalParser (parseCabalFile) import ExHack.Data.Db (getHomePagePackages, getModulePageSyms, getPackageId, getPackagePageMods, getPkgImportScopes, initDb, saveModuleExports, saveModuleUnifiedSymbols, savePackageDeps, savePackages) import ExHack.Ghc (getModImports, getModSymbols, unLoc) import ExHack.Hackage.Hackage (findComponentRoot, getModExports, getModNames, unpackHackageTarball) import ExHack.ModulePaths (toModFilePath) import ExHack.Renderer.Html (addLineMarker, highLightCode, homePageTemplate, modulePageTemplate, packagePageTemplate) import qualified ExHack.Renderer.Types as RT (HighlightedSourceCodeFile (..), HighlightedSymbolOccurs (..), HomePagePackage (..), ModuleName (..), PackageName (..), SymbolOccurs (..), renderRoute) import ExHack.Stackage.Stack (buildPackage) import ExHack.Stackage.StackageParser (getHackageUrls, parseStackageYaml) import ExHack.Types (AlterDatabase, CabalBuildError (..), CabalFilesDir (..), ComponentRoot (..), DatabaseHandle, DatabaseStatus (..), HtmlDir (..), ImportsScope, IndexedModuleNameT (..), IndexedSym (..), LocatedSym (..), ModuleName, ModuleNameT (..), MonadLog (..), MonadStep, Package (allComponents, exposedModules, packageFilePath), PackageComponent (..), PackageDesc (..), PackageDlDesc, PackageDlDesc (..), PackageFilePath (..), SourceCodeFile (..), StackageFile (..), SymName, TarballsDir (..), UnifiedSym (..), WorkDir (..), getDatabaseHandle, getModNameT, getName, getPackageNameT, logInfo, packagedlDescName) import ExHack.Utils (Has (..), foldM') | ` Step ` 1 : database generation . This function creates a new SQLite database initialized according generateDb :: forall c m. (Has c (DatabaseHandle 'New), MonadStep c m) => m (DatabaseHandle (AlterDatabase 'New)) generateDb = do logInfoTitle "[Step 1] Generating database scheme." dh <- asks (view hasLens) :: m (DatabaseHandle 'New) let (fp, dh') = getDatabaseHandle dh withSQLite fp initDb pure dh' | ` Step ` 2 : stackage file parsing . parseStackage :: forall c m. (Has c StackageFile, MonadStep c m) => m [PackageDlDesc] parseStackage = do logInfoTitle "[Step 2] Parsing Stackage file" (StackageFile stackageFp) <- asks (view hasLens) stackageYaml <- liftIO $ T.readFile stackageFp let packages = fromJust $ parseStackageYaml stackageYaml pure $ getHackageUrls packages | ` Step ` 3 : assets downloading . dlAssets :: forall c m. (Has c TarballsDir, Has c CabalFilesDir, MonadStep c m) => [PackageDlDesc] -> m () dlAssets packages = do logInfoTitle "[Step 3] Downloading hackage assets (cabal files, tarballs)." let settings = managerSetProxy (proxyEnvironment Nothing) tlsManagerSettings tbd <- asks (view hasLens) cd <- asks (view hasLens) m <- liftIO $ newManager settings _ <- foldr (dlFoldCabalFiles cd tbd m (length packages)) (return 1) packages return () where dlFoldCabalFiles :: CabalFilesDir -> TarballsDir -> Manager -> Int -> PackageDlDesc -> m Int -> m Int dlFoldCabalFiles !cd !td man totalSteps !p step = handleAll logErrors $ do step' <- step let !pn = packagedlDescName p logInfoProgress 3 totalSteps step' $ "Downloading " <> pn <> " assets." downloadHackageFiles cd td man p return $ step' + 1 where logErrors e = do logError $ "[Step 3] ERROR while downloading " <> packagedlDescName p <> " assets: " <> T.pack (displayException e) step' <- step pure (step' + 1) downloadHackageFiles :: CabalFilesDir -> TarballsDir -> Manager -> PackageDlDesc -> m () downloadHackageFiles (CabalFilesDir cabalFilesDir) (TarballsDir tarballsDir) man (PackageDlDesc (name, cabalUrl, tarballUrl)) = liftIO $ do f <- httpLbs (parseRequest_ $ T.unpack cabalUrl) man BL.writeFile (cabalFilesDir </> T.unpack name <.> "cabal") $ responseBody f f' <- httpLbs (parseRequest_ $ T.unpack tarballUrl) man BL.writeFile (tarballsDir </> T.unpack name <.> "tar.gz") $ responseBody f' return () | ` Step ` 4 : Dependencies graph generation . genGraphDep :: forall c m. (Has c TarballsDir, Has c CabalFilesDir, Has c WorkDir, Has c (DatabaseHandle 'Initialized), MonadStep c m) => [PackageDlDesc] -> m [Package] genGraphDep pd = do logInfoTitle "[Step 4] Generating dependencies graph." tbd <- asks (view hasLens) cd <- asks (view hasLens) wd <- asks (view hasLens) logInfo "[+] Parsing cabal files." (_, !pkgs) <- foldM' (readPkgsFiles cd wd tbd (length pd)) (1,[]) pd pure pkgs where readPkgsFiles (CabalFilesDir cabalFilesDir) (WorkDir wd) (TarballsDir tarballsDir) !totalSteps (!step, xs) p = handleAll logErrors $ do logInfoProgress 4 totalSteps step $ "Unzip " <> packagedlDescName p <> " package." let tbp = tarballsDir </> T.unpack (packagedlDescName p) <.> "tar.gz" tb <- liftIO $ BS.readFile tbp pfp <- unpackHackageTarball wd tb logInfoProgress 4 totalSteps step $ "Reading " <> packagedlDescName p <> " cabal file." !cf <- liftIO $ T.readFile $ cabalFilesDir </> T.unpack (packagedlDescName p) <.> "cabal" let !pack = parseCabalFile $ PackageDesc (pfp,cf) case pack of Nothing -> pure (step + 1, xs) Just !x -> pure (step + 1, x:xs) where logErrors e = do logError $ "[Step 4] ERROR cannot read " <> packagedlDescName p <> " cabal file: " <> T.pack (displayException e) pure (step + 1, xs) | ` Step ` 5 : Save dependancies graph . saveGraphDep :: forall c m. (Has c TarballsDir, Has c CabalFilesDir, Has c (DatabaseHandle 'Initialized), MonadStep c m) => [Package] -> m (DatabaseHandle 'DepsGraph) saveGraphDep pkgs = do logInfoTitle "[Step 5] Saving dependencies graph." dbHandle <- asks (view hasLens) :: m (DatabaseHandle 'Initialized) let (dbFp, dbHandle') = getDatabaseHandle dbHandle liftIO $ withSQLite dbFp $ do logInfo "[+] Saving packages to DB (may take some time)..." savePackages pkgs logInfo "[+] Done." logInfo "[+] Saving dependancies to DB..." foldM_ (foldInsertDep (length pkgs)) 1 pkgs logInfo "[+] Done." return () pure dbHandle' where foldInsertDep :: Int -> Int -> Package -> SeldaM Int foldInsertDep totalDeps step pkg = handleAll logErrors $ do savePackageDeps pkg logInfoProgress 5 totalDeps step $ "Saving " <> getName pkg <> " dependancies to DB." pure $ step + 1 where logErrors e = do logError $ "[Step 5] ERROR cannot insert " <> getName pkg <> " dependancies to DB: " <> T.pack (displayException e) pure $ step + 1 | ` Step ` 6 : extracting and indexing modules exports . GHC - API program which extracts the exports and finally save retrievePkgsExports :: forall c m. (Has c (DatabaseHandle 'DepsGraph), MonadStep c m) => [Package] -> m (DatabaseHandle 'PkgExports) retrievePkgsExports pkgs = do logInfoTitle "[Step 6] Retrieving modules exports." dbHandle <- asks (view hasLens) :: m (DatabaseHandle 'DepsGraph) let (dbFp, dbHandle') = getDatabaseHandle dbHandle foldM_ (getPkgExports dbFp (length pkgs)) 1 pkgs pure dbHandle' where getPkgExports :: FilePath -> Int -> Int -> Package -> m Int getPkgExports dbFp totalSteps !nb p = handleAll logErrors $ do logInfoProgress 6 totalSteps nb $ "Retrieving "<> getName p <> " exports." let pfp = packageFilePath p cr <- buildPackage pfp maybe (pure ()) (\(errCode, errStr) -> throwM $ CabalBuildError errCode errStr) cr let mns = getModNames p croots = maybe [ComponentRoot "./"] roots $ exposedModules p pid <- liftIO $ withSQLite dbFp $ getPackageId p processMod pid pfp croots `mapM_` mns pure $ nb + 1 where processMod :: RowID -> PackageFilePath -> [ComponentRoot] -> ModuleName -> m () processMod pid pfp crs mn = do (_, me) <- getModExports pfp crs mn liftIO $ withSQLite dbFp $ saveModuleExports pid mn me pure () logErrors e = do logError $ "[Step 6] ERROR cannot get exports for " <> getName p <> ": " <> T.pack (displayException e) pure $ nb + 1 | ` Step ` 7 : Indexes the code source symbols in the database . 1 . Retrieve the imported symbols and try to match them to the previously 2 . Use GHC parser to get this file symbols . 3 . Unify these symbols to the imported one . 4 . We save each unified occurence in the database . indexSymbols :: forall c m. (MonadStep c m, MonadCatch m, MonadThrow m, Has c (DatabaseHandle 'PkgExports)) => [Package] -> m (DatabaseHandle 'IndexedSyms) indexSymbols pkgs = do logInfoTitle "[Step 7] Indexing used symbols." dbh <- asks (view hasLens) :: m (DatabaseHandle 'PkgExports) let (dbfp, dbh') = getDatabaseHandle dbh foldM_ (indexPackage dbfp (length pkgs)) 1 pkgs pure dbh' where indexPackage :: FilePath -> Int -> Int -> Package -> m Int indexPackage !dbFp nb cur p = do logInfoProgress 7 nb cur $ "Indexing " <> getName p <> " used symbols." is <- liftIO $ withSQLite dbFp $ getPkgImportScopes p indexComponent dbFp p (packageFilePath p) is `mapM_` allComponents p pure $ cur + 1 indexComponent :: FilePath -> Package -> PackageFilePath -> ImportsScope -> PackageComponent -> m () indexComponent dbh p pfp is pc = handleAll logErrors $ do mfps <- findModuleFilePath pfp (roots pc) `mapM` mods pc indexModule dbh p pfp is `mapM_` mfps where logErrors e = logError $ "[Step 7] ERROR while indexing component " <> T.pack (show pc) <> " from package " <> getName p <> ": " <> T.pack (displayException e) indexModule :: FilePath -> Package -> PackageFilePath -> ImportsScope -> (ModuleName, ComponentRoot) -> m () indexModule dbFp p pfp is (mn,cr) = handleAll logErrors $ do imports <- getModImports pfp cr mn let !fis = HM.filterWithKey (\(IndexedModuleNameT (n, _)) _ -> n `elem` imports) is !isyms = HS.unions $ HM.elems fis !isymsMap = HS.foldl' (\hm is'@(IndexedSym (n, _)) -> HM.insert n is' hm) HM.empty isyms syms <- getModSymbols p pfp cr mn fileContent <- liftIO $ T.readFile $ toModFilePath pfp cr mn let !file = SourceCodeFile fileContent (getModNameT mn) (getPackageNameT p) unsyms = unifySymbols isymsMap syms withSQLite dbFp $ saveModuleUnifiedSymbols unsyms file where logErrors e = do let (ModuleNameT mnt) = getModNameT mn logError $ "[Step 7] ERROR while indexing module " <> mnt <> " from package " <> getName p <> ": " <> T.pack (displayException e) findModuleFilePath :: PackageFilePath -> [ComponentRoot] -> ModuleName -> m (ModuleName, ComponentRoot) findModuleFilePath pfp crs mn = do cr <- findComponentRoot pfp crs mn pure (mn, cr) unifySymbols :: HM.HashMap SymName IndexedSym -> [LocatedSym] -> [UnifiedSym] unifySymbols isyms = foldl' foldLSym [] where foldLSym xs ls@(LocatedSym (_, _, locSym)) = maybe xs (\is -> UnifiedSym(is,ls) : xs) (HM.lookup (unLoc locSym) isyms) | ` Step ` 8 : Generates the HTML documentation using the previously generateHtmlPages :: forall c m. (MonadStep c m, MonadCatch m, MonadThrow m, Has c (DatabaseHandle 'IndexedSyms), Has c HtmlDir) => m () generateHtmlPages = do logInfoTitle "[Step 8] Generating the HTML documentation." HtmlDir outfp <- asks (view hasLens) :: m HtmlDir dbh <- asks (view hasLens) :: m (DatabaseHandle 'IndexedSyms) let (dbfp,_) = getDatabaseHandle dbh pkgs <- liftIO $ withSQLite dbfp getHomePagePackages let hp = renderHtml $ homePageTemplate pkgs RT.renderRoute liftIO $ withFile (outfp </> "index.html") WriteMode (\h -> hSetEncoding h utf8 >> TL.hPutStr h hp) foldM_ (generatePackPage dbfp outfp (length pkgs)) 1 pkgs copyAssets outfp where generatePackPage :: FilePath -> FilePath -> Int -> Int -> RT.HomePagePackage -> m Int generatePackPage !dbfp outfp nbI i hp@(RT.HomePagePackage pack@(RT.PackageName (_,pname)) _) = handleAll logErrors $ do expmods <- liftIO $ withSQLite dbfp (getPackagePageMods pack) logInfoProgress 8 nbI i $ "Generating HTML documentation for " <> pname let fp = outfp </> "packages" </> T.unpack pname pp = renderHtml $ packagePageTemplate hp expmods RT.renderRoute liftIO $ do createDirectoryIfMissing True fp writeUtf8File fp pp generateModPage dbfp fp hp `mapM_` expmods pure $ i + 1 where logErrors e = do logError $ "[Step 7] ERROR while generating " <> pname <> " HTML documentation: " <> T.pack (displayException e) pure $ i + 1 generateModPage :: FilePath -> FilePath -> RT.HomePagePackage -> RT.ModuleName -> m () generateModPage dbfp packfp hp@(RT.HomePagePackage pack _) modn@(RT.ModuleName (_,modnt)) = do syms <- liftIO $ withSQLite dbfp (getModulePageSyms pack modn) hsyms <- highLightOccs syms let mp = renderHtml $ modulePageTemplate hp modn hsyms RT.renderRoute fp = packfp </> T.unpack (T.replace "." "-" modnt) liftIO $ do createDirectoryIfMissing True fp writeUtf8File fp mp This hack has been performed in a rush , should be fixed after V0 . highLightOccs :: [RT.SymbolOccurs] -> m [RT.HighlightedSymbolOccurs] highLightOccs xs = highSyms `mapM` xs where highSyms (RT.SymbolOccurs sn xs') = do hs <- highSym `mapM` xs' pure $ RT.HighlightedSymbolOccurs sn hs highSym (col, line, SourceCodeFile c p m) = do hc <- handleAll highErr $ highLightCode c pure (col, line, RT.HighlightedSourceCodeFile (addLineMarker line hc) p m) where highErr e = do logError $ "[Step 8] HIGHLIGHT ERROR " <> T.pack (displayException e) pure c copyAssets :: FilePath -> m () copyAssets fp = do let font = $(embedFile "./src/ExHack/Renderer/templates/static/Inter-UI-Regular.woff") list = $(embedFile "./src/ExHack/Renderer/templates/static/list.min.js") style = $(embedFile "./src/ExHack/Renderer/templates/static/style.css") logo = $(embedFile "./img/logo/ex-hack-logo.svg") stat = fp </> "static" liftIO $ do createDirectoryIfMissing True stat BS.writeFile (stat </> "Inter-UI-Regular.woff") font BS.writeFile (stat </> "list.min.js") list BS.writeFile (stat </> "style.css") style BS.writeFile (stat </> "ex-hack-logo.svg") logo writeUtf8File :: FilePath -> TL.Text -> IO () writeUtf8File fp txt = withFile (fp </> "index.html") WriteMode (\h -> hSetEncoding h utf8 >> TL.hPutStr h txt)
e0490ff619d9d86a7c9b8d299e3952fd784feb41857a54263961c7dd479f8840
montyly/gueb
gueb.ml
open Absenvgenerique open Stubfunc open Ir open Uafgenerique open Graph open Program_piqi open Program open Heap_functions (* global vars *) let verbose = ref false let show_call = ref false let show_free = ref false let show_values = ref false /let details_values = ref false let program = ref "reil" let func = ref "main" let funcs_file = ref "" let stub_name = ref "" let type_analysis = ref 0 let dir_output = ref "results" let print_graph = ref false (*let merge_output = ref false*) let flow_graph_dot = ref false let flow_graph_gml = ref false let flow_graph_disjoint = ref false let max_func = ref 400 let max_ins = ref None let total_max_ins = ref None let group_by = ref "alloc" let no_clean_stack = ref false let analyze_irreducible_loop = ref false let depth = ref None let absenv = ref "" Signature module type TAnalysis = functor (Absenv_v : AbsEnvGenerique)-> functor (Ir_v : IR) -> functor (Stubfunc_v : Stubfunc) -> functor (Uaf_v : UafGenerique) -> sig val init : string -> unit val launch_analysis : string -> unit val launch_analysis_list : string list -> unit val end_analysis : unit -> unit end ;; (* Main analysis *) module GuebAnalysis: TAnalysis = functor (Absenv_v : AbsEnvGenerique) -> functor (Ir_v : IR) -> functor (Stubfunc_v : Stubfunc) -> functor (Uaf_v : UafGenerique)-> struct module GraphIR = My_Graph (Absenv_v) (Ir_v) (Stubfunc_v) (Uaf_v) let list_funcs = ref [] let malloc = ref [] let free = ref [] let parsed_func = Hashtbl.create 100 let counter = let ctr = ref (-1) in fun () -> incr ctr; !ctr;; let init program_file = let () = Printf.printf "Launch VSA on %s\n" program_file in let () = GraphIR.set_size (!max_func) in let () = match !max_ins with | Some d -> GraphIR.set_max_ins d | None -> () in let () = match !total_max_ins with | Some d -> GraphIR.set_total_max_ins d | None -> () in let () = if (!analyze_irreducible_loop) then GraphIR.set_irreducible_loop () in let () = match (!depth) with | None -> () | Some d -> GraphIR.set_depth d in let channel = try open_in_bin program_file with _ -> let () = Printf.printf "Reil.REIL file not found (have you used -reil ? )\n" in exit 0 in let buf = Piqirun.init_from_channel channel in let raw_program = parse_program buf in let () = close_in channel in let raw_heap_func = raw_program.heap_func in let () = list_funcs := raw_program.functions in let () = malloc := List.map (fun x -> Int64.to_int x) raw_heap_func.call_to_malloc in free := List.map (fun x -> Int64.to_int x) raw_heap_func.call_to_free let launch_analysis func_name = let () = Printf.printf "Launch the analysis on %s (%d)\n" func_name (counter ())in let dir = Printf.sprintf "%s/%s" (!dir_output) (func_name) in let _ = GraphIR.launch_value_analysis func_name (!list_funcs) (!malloc) (!free) (not (!no_clean_stack)) dir (!verbose) (!show_values) (!show_call) (!show_free) ((!flow_graph_gml) || (!flow_graph_dot) ) (!flow_graph_gml) (!flow_graph_dot) (!flow_graph_disjoint) parsed_func in let () = Printf.printf "--------------------------------\n" in flush Pervasives.stdout let launch_analysis_list funcs_name = List.iter (fun x -> launch_analysis x) funcs_name let end_analysis () = GraphIR.end_analysis () end ;; module AllFuncs: TAnalysis = functor (Absenv_v : AbsEnvGenerique) -> functor (Ir_v : IR) -> functor (Stubfunc_v : Stubfunc) -> functor (Uaf_v : UafGenerique)-> struct module GraphIR = My_Graph (Absenv_v) (Ir_v) (Stubfunc_v) (Uaf_v) let list_funcs = ref [] let malloc = ref [] let free = ref [] let parsed_func = Hashtbl.create 100 let counter = let ctr = ref (-1) in fun () -> incr ctr; !ctr;; let init program_file = let () = Printf.printf "Lauch VSA on %s\n" program_file in let () = GraphIR.set_size (!max_func) in let () = match !max_ins with | Some d -> GraphIR.set_max_ins d | None -> () in let () = match !total_max_ins with | Some d -> GraphIR.set_total_max_ins d | None -> () in let () = if (!analyze_irreducible_loop) then GraphIR.set_irreducible_loop () in let () = match (!depth) with | None -> GraphIR.set_depth 4 (* default depth *) | Some d -> GraphIR.set_depth d in let channel = try open_in_bin program_file with _ -> let () = Printf.printf "Reil.REIL file not found (have you used -reil ? )\n" in exit 0 in let buf = Piqirun.init_from_channel channel in let raw_program = parse_program buf in let () = close_in channel in let raw_heap_func = raw_program.heap_func in let () = list_funcs := raw_program.functions in let () = malloc := List.map (fun x -> Int64.to_int x) raw_heap_func.call_to_malloc in free := List.map (fun x -> Int64.to_int x) raw_heap_func.call_to_free let launch_analysis func_name = let () = Printf.printf "Launch the analysis on %s (%d)\n" func_name (counter ())in let dir = Printf.sprintf "%s/%s" (!dir_output) (func_name) in let _ = GraphIR.launch_value_analysis func_name (!list_funcs) (!malloc) (!free) (not (!no_clean_stack)) dir (!verbose) (!show_values) (!show_call) (!show_free) ((!flow_graph_gml) || (!flow_graph_dot) ) (!flow_graph_gml) (!flow_graph_dot) (!flow_graph_disjoint) parsed_func in let () = Printf.printf "--------------------------------\n" in flush Pervasives.stdout let launch_analysis_list _funcs_name = let open Function_ in List.iter (fun x -> launch_analysis x.name) (!list_funcs) let end_analysis () = GraphIR.end_analysis () end ;; Callgraph analysis module SuperGraphAnalysis : TAnalysis = functor (Absenv_v : AbsEnvGenerique) -> functor (Ir_v : IR)-> functor (Stubfunc_v : Stubfunc) -> functor (Uaf_v : UafGenerique)-> struct module GraphIR = My_Graph (Absenv_v) (Ir_v) (Stubfunc_v) (Uaf_v) let list_funcs = ref [] let parsed_func = Hashtbl.create 100 let init program_file = let () = GraphIR.set_size (!max_func) in let () = match !max_ins with | Some d -> GraphIR.set_max_ins d | None -> () in let () = match !total_max_ins with | Some d -> GraphIR.set_total_max_ins d | None -> () in let channel = open_in_bin program_file in let buf = Piqirun.init_from_channel channel in let raw_program = parse_program buf in let () = close_in channel in list_funcs := raw_program.functions let launch_analysis func_name = let dir = Printf.sprintf "%s/%s" (!dir_output) (func_name) in let _ = GraphIR.launch_supercallgraph_analysis func_name (!list_funcs) dir (!verbose) (!show_call) ((!flow_graph_gml) || (!flow_graph_dot) ) (!flow_graph_gml) (!flow_graph_dot) (!flow_graph_disjoint) parsed_func in flush Pervasives.stdout let launch_analysis_list funcs_name = List.iter (fun x -> launch_analysis x) funcs_name let end_analysis () = () end ;; Callgraph analysis module ExportFuncs : TAnalysis = functor (Absenv_v : AbsEnvGenerique) -> functor (Ir_v : IR)-> functor (Stubfunc_v : Stubfunc) -> functor (Uaf_v : UafGenerique)-> struct module GraphIR = My_Graph (Absenv_v) (Ir_v) (Stubfunc_v) (Uaf_v) let list_funcs = ref [] let init program_file = let channel = open_in_bin program_file in let buf = Piqirun.init_from_channel channel in let raw_program = parse_program buf in let () = close_in channel in list_funcs := raw_program.functions let launch_analysis func_name = let _ = GraphIR.export_func_unloop (!list_funcs) func_name in () let launch_analysis_list funcs_name = List.iter (fun x -> launch_analysis x) funcs_name let end_analysis () = () end ;; let launch_stub stub p f uaf to_list = let m_absenv = match (!absenv) with | "2" -> (module Absenv2.AbsEnv :Absenvgenerique.AbsEnvGenerique) | "3" -> (module Absenv3.AbsEnv :Absenvgenerique.AbsEnvGenerique) | "1-no-top" -> (module Absenvnotop.AbsEnv :Absenvgenerique.AbsEnvGenerique) | "2-no-top" -> (module Absenv2notop.AbsEnv :Absenvgenerique.AbsEnvGenerique) | "3-no-top" -> (module Absenv3notop.AbsEnv :Absenvgenerique.AbsEnvGenerique) | _ -> (module Absenv.AbsEnv :Absenvgenerique.AbsEnvGenerique) in let module Absenv = (val m_absenv : Absenvgenerique.AbsEnvGenerique) in let m_uaf = match uaf with | "alloc" -> (module Uafgroupbyalloc.UafGroupByAlloc : Uafgenerique.UafGenerique) | "free" -> (module Uafgroupbyfree.UafGroupByFree : Uafgenerique.UafGenerique) | "use" -> (module Uafgroupbyuse.UafGroupByUse : Uafgenerique.UafGenerique) | _ -> failwith "Unknow groupby model ? " in let module Uaf = (val m_uaf : Uafgenerique.UafGenerique) in let m_stub = match stub with | "optipng" -> (module Stubfunc.StubOptiPNG : Stubfunc.Stubfunc) | "jasper" -> (module Stubfunc.StubJasper : Stubfunc.Stubfunc) | "gnome-nettool" -> (module Stubfunc.StubGnomeNettool : Stubfunc.Stubfunc) | "tiff2pdf" -> (module Stubfunc.StubTiff2pdfLibtiff : Stubfunc.Stubfunc) | _ -> (module Stubfunc.StubNoFunc : Stubfunc.Stubfunc) in let module Stub = (val m_stub : Stubfunc.Stubfunc) in let module Analysis = GuebAnalysis(Absenv)(Reil.REIL)(Stub)(Uaf) in let () = Analysis.init p in let () = match to_list with | false -> Analysis.launch_analysis (List.hd f) | true -> Analysis.launch_analysis_list f in Analysis.end_analysis ();; let read_lines_file filename = let lines = ref [] in let () = Printf.printf "begin\n" in let chan = open_in filename in let () = try while true; do let new_line = input_line chan in lines := (String.trim new_line) :: !lines done; with End_of_file -> close_in chan in List.rev !lines ;; let () = let speclist = [("-v", Arg.Set verbose, "Enable verbose mode"); ("-show-call", Arg.Set show_call, "Show calls"); ("-show-free", Arg.Set show_free, "Show freed variables"); ("-show-values", Arg.Set show_values, "Show values computed (hugeee print)"); ( " -print - graph " , Arg . Set print_graph , " Print the graph ( for type 2 , experimental ) " ) ; ( " -merge - output " , Arg . Set print_graph , " Merge output values ( experimental ) " ) ; ("-merge-output", Arg.Set print_graph, "Merge output values (experimental)");*) ("-flow-graph-dot", Arg.Set flow_graph_dot, "Export flow graph (Dot)"); ("-flow-graph-gml", Arg.Set flow_graph_gml, "Export flow graph (Gml)"); ("-flow-graph-call-disjoint", Arg.Set flow_graph_disjoint, "Export as separate functions"); ("-reil", Arg.String (fun x -> program:=x), "Name of the Reil.REIL file (protobuf), default : reil"); ("-func", Arg.String (fun x -> func:=x), "Name of the entry point function, default : main"); ("-funcs-file", Arg.String (fun x -> funcs_file:=x), "Name of the files containing all the functions name"); ("-stub", Arg.String (fun x -> stub_name:=x), "Name of the stub module"); ("-type", Arg.Int (fun x -> type_analysis:=x), "\n\t0 : uaf detection (default)\n\t1 : compute callgraph size \n\t2 : uaf detection on a set of functions\n\t3 : compute callgraph size on a set of functions"); ("-output-dir", Arg.String (fun x -> dir_output:=x), "Output directory. Default results"); ("-groupby", Arg.String (fun x -> group_by:=x), "Group UaF by (experimental):\n\talloc (default)\n\tfree"); ("-no-clean-stack", Arg.Set no_clean_stack, "Do not clean stack values after return"); (* ("-unroll-irreducible", Arg.Set analyze_irreducible_loop, "Unroll irreducible loops");*) ("-depth", Arg.Int (fun x -> depth:=Some x), "Max depth of functions analyzed. Default unlimited"); ("-size", Arg.Int (fun x -> max_func:=x), "Max number of funcs to analyze. Default 400"); ("-size-ins", Arg.Int (fun x -> max_ins:=Some x), "Max number of ins to analyze. Default unlimited"); ("-total-ins", Arg.Int (fun x -> total_max_ins:=Some x), "Max number of ins to analyze in total (all entry points). Default unlimited"); ("-absenv", Arg.String (fun x -> absenv:= x), "Memory model selection: (experimental)\n\t 1 -> default (HA/HF)\n\t 2 -> Pointer based (more precise)\n\t 3 -> Pointer based + use-after-return detection"); ] in let _ = Arg.parse speclist print_endline "GUEB: Experimental static analyzer detecting heap and stack use-after-free on binary code.\nGUEB is still under intensive development, for any questions, please contact josselin.feist[@]imag.fr\n" in let module Uaf = Uafgroupbyalloc.UafGroupByAlloc in (* not used in SGanalysis *) match(!type_analysis) with | 0 -> launch_stub (!stub_name) (!program) [(!func)] (!group_by) false | 1 -> let module SGanalysis = SuperGraphAnalysis(Absenv.AbsEnv)(Reil.REIL)(StubNoFunc)(Uaf) in SGanalysis.init (!program) ; SGanalysis.launch_analysis (!func) ; SGanalysis.end_analysis () ; | 2 -> let funcs=read_lines_file (!funcs_file) in launch_stub (!stub_name) (!program) funcs (!group_by) true | 3 -> let funcs=read_lines_file (!funcs_file) in let module SGanalysis = SuperGraphAnalysis(Absenv.AbsEnv)(Reil.REIL)(StubNoFunc)(Uaf) in SGanalysis.init (!program) ; SGanalysis.launch_analysis_list funcs ; SGanalysis.end_analysis () ; | 4 -> let module SGanalysis = ExportFuncs(Absenv.AbsEnv)(Reil.REIL)(StubNoFunc)(Uaf) in SGanalysis.init (!program) ; SGanalysis.launch_analysis (!func) ; SGanalysis.end_analysis () ; | 5 -> let funcs=read_lines_file (!funcs_file) in let module SGanalysis = ExportFuncs(Absenv.AbsEnv)(Reil.REIL)(StubNoFunc)(Uaf) in SGanalysis.init (!program) ; SGanalysis.launch_analysis_list funcs ; SGanalysis.end_analysis () ; | 6 -> let module SGanalysis = AllFuncs(Absenv.AbsEnv)(Reil.REIL)(StubNoFunc)(Uaf) in SGanalysis.init (!program) ; SGanalysis.launch_analysis_list [] ; SGanalysis.end_analysis () ; | _ -> Printf.printf "Bad analysis type\n"
null
https://raw.githubusercontent.com/montyly/gueb/45f496a5a1e8e908e562928762ece304c2408c3a/src/gueb.ml
ocaml
global vars let merge_output = ref false Main analysis default depth ("-unroll-irreducible", Arg.Set analyze_irreducible_loop, "Unroll irreducible loops"); not used in SGanalysis
open Absenvgenerique open Stubfunc open Ir open Uafgenerique open Graph open Program_piqi open Program open Heap_functions let verbose = ref false let show_call = ref false let show_free = ref false let show_values = ref false /let details_values = ref false let program = ref "reil" let func = ref "main" let funcs_file = ref "" let stub_name = ref "" let type_analysis = ref 0 let dir_output = ref "results" let print_graph = ref false let flow_graph_dot = ref false let flow_graph_gml = ref false let flow_graph_disjoint = ref false let max_func = ref 400 let max_ins = ref None let total_max_ins = ref None let group_by = ref "alloc" let no_clean_stack = ref false let analyze_irreducible_loop = ref false let depth = ref None let absenv = ref "" Signature module type TAnalysis = functor (Absenv_v : AbsEnvGenerique)-> functor (Ir_v : IR) -> functor (Stubfunc_v : Stubfunc) -> functor (Uaf_v : UafGenerique) -> sig val init : string -> unit val launch_analysis : string -> unit val launch_analysis_list : string list -> unit val end_analysis : unit -> unit end ;; module GuebAnalysis: TAnalysis = functor (Absenv_v : AbsEnvGenerique) -> functor (Ir_v : IR) -> functor (Stubfunc_v : Stubfunc) -> functor (Uaf_v : UafGenerique)-> struct module GraphIR = My_Graph (Absenv_v) (Ir_v) (Stubfunc_v) (Uaf_v) let list_funcs = ref [] let malloc = ref [] let free = ref [] let parsed_func = Hashtbl.create 100 let counter = let ctr = ref (-1) in fun () -> incr ctr; !ctr;; let init program_file = let () = Printf.printf "Launch VSA on %s\n" program_file in let () = GraphIR.set_size (!max_func) in let () = match !max_ins with | Some d -> GraphIR.set_max_ins d | None -> () in let () = match !total_max_ins with | Some d -> GraphIR.set_total_max_ins d | None -> () in let () = if (!analyze_irreducible_loop) then GraphIR.set_irreducible_loop () in let () = match (!depth) with | None -> () | Some d -> GraphIR.set_depth d in let channel = try open_in_bin program_file with _ -> let () = Printf.printf "Reil.REIL file not found (have you used -reil ? )\n" in exit 0 in let buf = Piqirun.init_from_channel channel in let raw_program = parse_program buf in let () = close_in channel in let raw_heap_func = raw_program.heap_func in let () = list_funcs := raw_program.functions in let () = malloc := List.map (fun x -> Int64.to_int x) raw_heap_func.call_to_malloc in free := List.map (fun x -> Int64.to_int x) raw_heap_func.call_to_free let launch_analysis func_name = let () = Printf.printf "Launch the analysis on %s (%d)\n" func_name (counter ())in let dir = Printf.sprintf "%s/%s" (!dir_output) (func_name) in let _ = GraphIR.launch_value_analysis func_name (!list_funcs) (!malloc) (!free) (not (!no_clean_stack)) dir (!verbose) (!show_values) (!show_call) (!show_free) ((!flow_graph_gml) || (!flow_graph_dot) ) (!flow_graph_gml) (!flow_graph_dot) (!flow_graph_disjoint) parsed_func in let () = Printf.printf "--------------------------------\n" in flush Pervasives.stdout let launch_analysis_list funcs_name = List.iter (fun x -> launch_analysis x) funcs_name let end_analysis () = GraphIR.end_analysis () end ;; module AllFuncs: TAnalysis = functor (Absenv_v : AbsEnvGenerique) -> functor (Ir_v : IR) -> functor (Stubfunc_v : Stubfunc) -> functor (Uaf_v : UafGenerique)-> struct module GraphIR = My_Graph (Absenv_v) (Ir_v) (Stubfunc_v) (Uaf_v) let list_funcs = ref [] let malloc = ref [] let free = ref [] let parsed_func = Hashtbl.create 100 let counter = let ctr = ref (-1) in fun () -> incr ctr; !ctr;; let init program_file = let () = Printf.printf "Lauch VSA on %s\n" program_file in let () = GraphIR.set_size (!max_func) in let () = match !max_ins with | Some d -> GraphIR.set_max_ins d | None -> () in let () = match !total_max_ins with | Some d -> GraphIR.set_total_max_ins d | None -> () in let () = if (!analyze_irreducible_loop) then GraphIR.set_irreducible_loop () in let () = match (!depth) with | Some d -> GraphIR.set_depth d in let channel = try open_in_bin program_file with _ -> let () = Printf.printf "Reil.REIL file not found (have you used -reil ? )\n" in exit 0 in let buf = Piqirun.init_from_channel channel in let raw_program = parse_program buf in let () = close_in channel in let raw_heap_func = raw_program.heap_func in let () = list_funcs := raw_program.functions in let () = malloc := List.map (fun x -> Int64.to_int x) raw_heap_func.call_to_malloc in free := List.map (fun x -> Int64.to_int x) raw_heap_func.call_to_free let launch_analysis func_name = let () = Printf.printf "Launch the analysis on %s (%d)\n" func_name (counter ())in let dir = Printf.sprintf "%s/%s" (!dir_output) (func_name) in let _ = GraphIR.launch_value_analysis func_name (!list_funcs) (!malloc) (!free) (not (!no_clean_stack)) dir (!verbose) (!show_values) (!show_call) (!show_free) ((!flow_graph_gml) || (!flow_graph_dot) ) (!flow_graph_gml) (!flow_graph_dot) (!flow_graph_disjoint) parsed_func in let () = Printf.printf "--------------------------------\n" in flush Pervasives.stdout let launch_analysis_list _funcs_name = let open Function_ in List.iter (fun x -> launch_analysis x.name) (!list_funcs) let end_analysis () = GraphIR.end_analysis () end ;; Callgraph analysis module SuperGraphAnalysis : TAnalysis = functor (Absenv_v : AbsEnvGenerique) -> functor (Ir_v : IR)-> functor (Stubfunc_v : Stubfunc) -> functor (Uaf_v : UafGenerique)-> struct module GraphIR = My_Graph (Absenv_v) (Ir_v) (Stubfunc_v) (Uaf_v) let list_funcs = ref [] let parsed_func = Hashtbl.create 100 let init program_file = let () = GraphIR.set_size (!max_func) in let () = match !max_ins with | Some d -> GraphIR.set_max_ins d | None -> () in let () = match !total_max_ins with | Some d -> GraphIR.set_total_max_ins d | None -> () in let channel = open_in_bin program_file in let buf = Piqirun.init_from_channel channel in let raw_program = parse_program buf in let () = close_in channel in list_funcs := raw_program.functions let launch_analysis func_name = let dir = Printf.sprintf "%s/%s" (!dir_output) (func_name) in let _ = GraphIR.launch_supercallgraph_analysis func_name (!list_funcs) dir (!verbose) (!show_call) ((!flow_graph_gml) || (!flow_graph_dot) ) (!flow_graph_gml) (!flow_graph_dot) (!flow_graph_disjoint) parsed_func in flush Pervasives.stdout let launch_analysis_list funcs_name = List.iter (fun x -> launch_analysis x) funcs_name let end_analysis () = () end ;; Callgraph analysis module ExportFuncs : TAnalysis = functor (Absenv_v : AbsEnvGenerique) -> functor (Ir_v : IR)-> functor (Stubfunc_v : Stubfunc) -> functor (Uaf_v : UafGenerique)-> struct module GraphIR = My_Graph (Absenv_v) (Ir_v) (Stubfunc_v) (Uaf_v) let list_funcs = ref [] let init program_file = let channel = open_in_bin program_file in let buf = Piqirun.init_from_channel channel in let raw_program = parse_program buf in let () = close_in channel in list_funcs := raw_program.functions let launch_analysis func_name = let _ = GraphIR.export_func_unloop (!list_funcs) func_name in () let launch_analysis_list funcs_name = List.iter (fun x -> launch_analysis x) funcs_name let end_analysis () = () end ;; let launch_stub stub p f uaf to_list = let m_absenv = match (!absenv) with | "2" -> (module Absenv2.AbsEnv :Absenvgenerique.AbsEnvGenerique) | "3" -> (module Absenv3.AbsEnv :Absenvgenerique.AbsEnvGenerique) | "1-no-top" -> (module Absenvnotop.AbsEnv :Absenvgenerique.AbsEnvGenerique) | "2-no-top" -> (module Absenv2notop.AbsEnv :Absenvgenerique.AbsEnvGenerique) | "3-no-top" -> (module Absenv3notop.AbsEnv :Absenvgenerique.AbsEnvGenerique) | _ -> (module Absenv.AbsEnv :Absenvgenerique.AbsEnvGenerique) in let module Absenv = (val m_absenv : Absenvgenerique.AbsEnvGenerique) in let m_uaf = match uaf with | "alloc" -> (module Uafgroupbyalloc.UafGroupByAlloc : Uafgenerique.UafGenerique) | "free" -> (module Uafgroupbyfree.UafGroupByFree : Uafgenerique.UafGenerique) | "use" -> (module Uafgroupbyuse.UafGroupByUse : Uafgenerique.UafGenerique) | _ -> failwith "Unknow groupby model ? " in let module Uaf = (val m_uaf : Uafgenerique.UafGenerique) in let m_stub = match stub with | "optipng" -> (module Stubfunc.StubOptiPNG : Stubfunc.Stubfunc) | "jasper" -> (module Stubfunc.StubJasper : Stubfunc.Stubfunc) | "gnome-nettool" -> (module Stubfunc.StubGnomeNettool : Stubfunc.Stubfunc) | "tiff2pdf" -> (module Stubfunc.StubTiff2pdfLibtiff : Stubfunc.Stubfunc) | _ -> (module Stubfunc.StubNoFunc : Stubfunc.Stubfunc) in let module Stub = (val m_stub : Stubfunc.Stubfunc) in let module Analysis = GuebAnalysis(Absenv)(Reil.REIL)(Stub)(Uaf) in let () = Analysis.init p in let () = match to_list with | false -> Analysis.launch_analysis (List.hd f) | true -> Analysis.launch_analysis_list f in Analysis.end_analysis ();; let read_lines_file filename = let lines = ref [] in let () = Printf.printf "begin\n" in let chan = open_in filename in let () = try while true; do let new_line = input_line chan in lines := (String.trim new_line) :: !lines done; with End_of_file -> close_in chan in List.rev !lines ;; let () = let speclist = [("-v", Arg.Set verbose, "Enable verbose mode"); ("-show-call", Arg.Set show_call, "Show calls"); ("-show-free", Arg.Set show_free, "Show freed variables"); ("-show-values", Arg.Set show_values, "Show values computed (hugeee print)"); ( " -print - graph " , Arg . Set print_graph , " Print the graph ( for type 2 , experimental ) " ) ; ( " -merge - output " , Arg . Set print_graph , " Merge output values ( experimental ) " ) ; ("-merge-output", Arg.Set print_graph, "Merge output values (experimental)");*) ("-flow-graph-dot", Arg.Set flow_graph_dot, "Export flow graph (Dot)"); ("-flow-graph-gml", Arg.Set flow_graph_gml, "Export flow graph (Gml)"); ("-flow-graph-call-disjoint", Arg.Set flow_graph_disjoint, "Export as separate functions"); ("-reil", Arg.String (fun x -> program:=x), "Name of the Reil.REIL file (protobuf), default : reil"); ("-func", Arg.String (fun x -> func:=x), "Name of the entry point function, default : main"); ("-funcs-file", Arg.String (fun x -> funcs_file:=x), "Name of the files containing all the functions name"); ("-stub", Arg.String (fun x -> stub_name:=x), "Name of the stub module"); ("-type", Arg.Int (fun x -> type_analysis:=x), "\n\t0 : uaf detection (default)\n\t1 : compute callgraph size \n\t2 : uaf detection on a set of functions\n\t3 : compute callgraph size on a set of functions"); ("-output-dir", Arg.String (fun x -> dir_output:=x), "Output directory. Default results"); ("-groupby", Arg.String (fun x -> group_by:=x), "Group UaF by (experimental):\n\talloc (default)\n\tfree"); ("-no-clean-stack", Arg.Set no_clean_stack, "Do not clean stack values after return"); ("-depth", Arg.Int (fun x -> depth:=Some x), "Max depth of functions analyzed. Default unlimited"); ("-size", Arg.Int (fun x -> max_func:=x), "Max number of funcs to analyze. Default 400"); ("-size-ins", Arg.Int (fun x -> max_ins:=Some x), "Max number of ins to analyze. Default unlimited"); ("-total-ins", Arg.Int (fun x -> total_max_ins:=Some x), "Max number of ins to analyze in total (all entry points). Default unlimited"); ("-absenv", Arg.String (fun x -> absenv:= x), "Memory model selection: (experimental)\n\t 1 -> default (HA/HF)\n\t 2 -> Pointer based (more precise)\n\t 3 -> Pointer based + use-after-return detection"); ] in let _ = Arg.parse speclist print_endline "GUEB: Experimental static analyzer detecting heap and stack use-after-free on binary code.\nGUEB is still under intensive development, for any questions, please contact josselin.feist[@]imag.fr\n" in match(!type_analysis) with | 0 -> launch_stub (!stub_name) (!program) [(!func)] (!group_by) false | 1 -> let module SGanalysis = SuperGraphAnalysis(Absenv.AbsEnv)(Reil.REIL)(StubNoFunc)(Uaf) in SGanalysis.init (!program) ; SGanalysis.launch_analysis (!func) ; SGanalysis.end_analysis () ; | 2 -> let funcs=read_lines_file (!funcs_file) in launch_stub (!stub_name) (!program) funcs (!group_by) true | 3 -> let funcs=read_lines_file (!funcs_file) in let module SGanalysis = SuperGraphAnalysis(Absenv.AbsEnv)(Reil.REIL)(StubNoFunc)(Uaf) in SGanalysis.init (!program) ; SGanalysis.launch_analysis_list funcs ; SGanalysis.end_analysis () ; | 4 -> let module SGanalysis = ExportFuncs(Absenv.AbsEnv)(Reil.REIL)(StubNoFunc)(Uaf) in SGanalysis.init (!program) ; SGanalysis.launch_analysis (!func) ; SGanalysis.end_analysis () ; | 5 -> let funcs=read_lines_file (!funcs_file) in let module SGanalysis = ExportFuncs(Absenv.AbsEnv)(Reil.REIL)(StubNoFunc)(Uaf) in SGanalysis.init (!program) ; SGanalysis.launch_analysis_list funcs ; SGanalysis.end_analysis () ; | 6 -> let module SGanalysis = AllFuncs(Absenv.AbsEnv)(Reil.REIL)(StubNoFunc)(Uaf) in SGanalysis.init (!program) ; SGanalysis.launch_analysis_list [] ; SGanalysis.end_analysis () ; | _ -> Printf.printf "Bad analysis type\n"
fd64463dc9406b604b2142977bfb70581b6fb8845ccbc7c20723fd682ed23d17
webyrd/quines
mk.scm
miniKanren with = /= , symbolo , , and noo ( A new goal ) ( noo ;;; 'clasure x). not-in is gone; there are fewer uses of 'sym; and no uses of ' num ( except when creating numbero . ) (define remp (lambda (p ls) (cond ((null? ls) '()) ((p (car ls)) (remp p (cdr ls))) (else (cons (car ls) (remp p (cdr ls))))))) (define (exists p ls) (cond ((null? ls) #f) ((p (car ls)) #t) (else (exists p (cdr ls))))) (define sorter (lambda (ls) (list-sort lex<=? ls))) (define datum->string (lambda (x) (with-output-to-string (lambda () (display x))))) (define-syntax test-check (syntax-rules () ((_ title tested-expression expected-result) (begin (printf "Testing ~s\n" title) (let* ((expected expected-result) (produced tested-expression)) (or (equal? expected produced) (errorf 'test-check "Failed: ~a~%Expected: ~a~%Computed: ~a~%" 'tested-expression expected produced))))))) (define a->s (lambda (a) (car a))) (define a->c* (lambda (a) (cadr a))) (define a->t (lambda (a) (caddr a))) (define-syntax lambdag@ (syntax-rules (:) ((_ (a) e) (lambda (a) e)) ((_ (a : s c* t) e) (lambda (a) (let ((s (a->s a)) (c* (a->c* a)) (t (a->t a))) e))))) (define mzero (lambda () #f)) (define unit (lambdag@ (a) a)) (define choice (lambda (a f) (cons a f))) (define-syntax lambdaf@ (syntax-rules () ((_ () e) (lambda () e)))) (define-syntax inc (syntax-rules () ((_ e) (lambdaf@ () e)))) (define empty-f (lambdaf@ () (mzero))) (define-syntax case-inf (syntax-rules () ((_ e (() e0) ((f^) e1) ((a^) e2) ((a f) e3)) (let ((a-inf e)) (cond ((not a-inf) e0) ((procedure? a-inf) (let ((f^ a-inf)) e1)) ((not (and (pair? a-inf) (procedure? (cdr a-inf)))) (let ((a^ a-inf)) e2)) (else (let ((a (car a-inf)) (f (cdr a-inf))) e3))))))) (define take (lambda (n f) (cond ((and n (zero? n)) '()) (else (case-inf (f) (() '()) ((f) (take n f)) ((a) (cons a '())) ((a f) (cons a (take (and n (- n 1)) f)))))))) (define empty-a '(() () ())) (define-syntax run (syntax-rules () ((_ n (x) g0 g ...) (take n (lambdaf@ () ((fresh (x) g0 g ... (lambdag@ (final-a) (choice ((reify x) final-a) empty-f))) empty-a)))))) (define-syntax run* (syntax-rules () ((_ (x) g ...) (run #f (x) g ...)))) (define-syntax fresh (syntax-rules () ((_ (x ...) g0 g ...) (lambdag@ (a) (inc (let ((x (var 'x)) ...) (bind* (g0 a) g ...))))))) (define-syntax bind* (syntax-rules () ((_ e) e) ((_ e g0 g ...) (bind* (bind e g0) g ...)))) (define bind (lambda (a-inf g) (case-inf a-inf (() (mzero)) ((f) (inc (bind (f) g))) ((a) (g a)) ((a f) (mplus (g a) (lambdaf@ () (bind (f) g))))))) (define mplus (lambda (a-inf f) (case-inf a-inf (() (f)) ((f^) (inc (mplus (f) f^))) ((a) (choice a f)) ((a f^) (choice a (lambdaf@ () (mplus (f) f^))))))) (define-syntax conde (syntax-rules () ((_ (g0 g ...) (g1 g^ ...) ...) (lambdag@ (a) (inc (mplus* (bind* (g0 a) g ...) (bind* (g1 a) g^ ...) ...)))))) (define-syntax mplus* (syntax-rules () ((_ e) e) ((_ e0 e ...) (mplus e0 (lambdaf@ () (mplus* e ...)))))) (define pr-t->tag (lambda (pr-t) (car (rhs pr-t)))) (define pr-t->pred (lambda (pr-t) (cdr (rhs pr-t)))) (define noo (lambda (tag u) (let ((pred (lambda (x) (not (eq? x tag))))) (lambdag@ (a : s c* t) (noo-aux tag u pred a s c* t))))) (define noo-aux (lambda (tag u pred a s c* t) (let ((u (if (var? u) (walk u s) u))) (cond ((pair? u) (cond ((pred u) (let ((a (noo-aux tag (car u) pred a s c* t))) (and a ((lambdag@ (a : s c* t) (noo-aux tag (cdr u) pred a s c* t)) a)))) (else (mzero)))) ((not (var? u)) (cond ((pred u) (unit a)) (else (mzero)))) ((ext-t u tag pred s t) => (lambda (t0) (cond ((not (eq? t0 t)) (let ((t^ (list (car t0)))) (let ((c* (subsume t^ c*))) (unit (subsume-t s c* t0))))) (else (unit a))))) (else (mzero)))))) (define make-flat-tag (lambda (tag pred) (lambda (u) (lambdag@ (a : s c* t) (let ((u (if (var? u) (walk u s) u))) (cond ((not (var? u)) (cond ((pred u) (unit a)) (else (mzero)))) ((ext-t u tag pred s t) => (lambda (t0) (cond ((not (eq? t0 t)) (let ((t^ (list (car t0)))) (let ((c* (subsume t^ c*))) (unit (subsume-t s c* t0))))) (else (unit a))))) (else (mzero)))))))) (define deep-tag? (lambda (tag) (not (or (eq? tag 'sym) (eq? tag 'num))))) ;;; We can extend t with a deep tag provided ;;; It is not in a singleton c of c* with the same ;;; tag. That would mean lifting an innocent ;;; constraint to an overarching constraint, would be wrong . So , no change to c * or t. ;;; in that case. (define ext-t (lambda (x tag pred s t^) (let ((x (walk x s))) (let loop ((t t^)) (cond ((null? t) (cons `(,x . (,tag . ,pred)) t^)) ((not (eq? (walk (lhs (car t)) s) x)) (loop (cdr t))) ((eq? (pr-t->tag (car t)) tag) t^) ((works-together? (pr-t->tag (car t)) tag) (loop (cdr t))) (else #f)))))) (define works-together? (lambda (t1 t2) (or (deep-tag? t1) (deep-tag? t2)))) (define subsume-t (lambda (s c* t) (let loop ((x* (rem-dups (map lhs t))) (c* c*) (t t)) (cond ((null? x*) `(,s ,c* ,t)) (else (let ((c*/t (subsume-c*/t (car x*) s c* t))) (loop (cdr x*) (car c*/t) (cdr c*/t)))))))) (define rem-dups (lambda (vars) (cond ((null? vars) '()) ((memq (car vars) (cdr vars)) (rem-dups (cdr vars))) (else (cons (car vars) (rem-dups (cdr vars))))))) (define have-flat-tag? (lambda (pred x) (lambda (pr-t) (let ((tag (pr-t->tag pr-t))) (and (not (deep-tag? tag)) (eq? (lhs pr-t) x) (pred tag)))))) (define subsume-c*/t (lambda (x s c* t) (cond ((exists (have-flat-tag? (lambda (u) (eq? u 'sym)) x) t) (subsumed-from-t-to-c* x s c* t '())) ((exists (have-flat-tag? (lambda (u) (not (eq? u 'sym))) x) t) `(,c* . ,(drop-from-t x t))) (else `(,c* . ,t))))) (define drop-from-t (lambda (x t) (remp (lambda (pr-t) (and (eq? (lhs pr-t) x) (deep-tag? (pr-t->tag pr-t)))) t))) (define subsumed-from-t-to-c* (lambda (x s c* t t^) (cond ((null? t) `(,c* . ,t^)) (else (let ((pr-t (car t))) (let ((tag (pr-t->tag pr-t)) (y (lhs pr-t))) (cond ((and (eq? y x) (deep-tag? tag)) (subsumed-from-t-to-c* x s (new-c* x tag c* s) (cdr t) t^)) (else (subsumed-from-t-to-c* x s c* (cdr t) (cons (car t) t^)))))))))) (define new-c* (lambda (x tag c* s) (cond ((exists (lambda (c) (and (null? (cdr c)) (eq? (walk (lhs (car c)) s) x) (eq? (rhs (car c)) tag))) c*) c*) (else (cons `((,x . ,tag)) c*))))) ;;; End reading here. (define subsume (lambda (t c*) (remp (lambda (c) (exists (subsumed-pr? t) c)) c*))) (define subsumed-pr? (lambda (t) (lambda (pr-c) (let ((u (rhs pr-c))) (and (not (var? u)) (let ((x (lhs pr-c))) (let ((pr-t (assq x t))) (and pr-t (let ((tag (pr-t->tag pr-t))) (cond ((and (deep-tag? tag) (eq? tag u))) ((not ((pr-t->pred pr-t) u))) (else #f))))))))))) (define booleano (lambda (x) (conde ((== #f x)) ((== #t x))))) (define symbolo (make-flat-tag 'sym symbol?)) (define numbero (make-flat-tag 'num number?)) (define =/= (lambda (u v) (lambdag@ (a : s c* t) (cond ((unify u v s) => (lambda (s0) (cond ((eq? s0 s) (mzero)) (else (let ((p* (list (prefix-s s0 s)))) (let ((p* (subsume t p*))) (let ((c* (append p* c*))) (unit `(,s ,c* ,t))))))))) (else (unit a)))))) (define prefix-s (lambda (s0 s) (cond ((eq? s0 s) '()) (else (cons (car s0) (prefix-s (cdr s0) s)))))) (define == (lambda (u v) (lambdag@ (a : s c* t) (cond ((unify u v s) => (lambda (s0) (cond ((eq? s0 s) (unit a)) ((verify-c* c* s0) => (lambda (c*) (cond ((verify-t t s0) => (lambda (t) (let ((c* (subsume t c*))) (unit (subsume-t s0 c* t))))) (else (mzero))))) (else (mzero))))) (else (mzero)))))) (define verify-c* (lambda (c* s) (cond ((null? c*) '()) ((verify-c* (cdr c*) s) => (lambda (c0*) (let ((c (car c*))) (cond ((verify-c*-aux c c0* s)) (else (mzero)))))) (else #f)))) (define verify-c*-aux (lambda (c c0* s) (cond ((unify* c s) => (lambda (s0) (and (not (eq? s0 s)) (cons (prefix-s s0 s) c0*)))) (else c0*)))) (define verify-t (lambda (t s) (cond ((null? t) '()) ((verify-t (cdr t) s) => (letrec ((rec (lambda (u) (let ((u (if (var? u) (walk u s) u))) (let ((tag (pr-t->tag (car t))) (pred (pr-t->pred (car t)))) (lambda (t0) (cond ((var? u) (ext-t u tag pred s t0)) ((pair? u) (if (deep-tag? tag) (cond (((rec (car u)) t0) => (rec (cdr u))) (else #f)) (and (pred u) t0))) (else (and (pred u) t0))))))))) (rec (lhs (car t))))) (else #f)))) (define succeed (== #f #f)) (define fail (== #f #t)) (define var (lambda (dummy) (vector dummy))) (define var? (lambda (x) (vector? x))) (define lhs (lambda (pr) (car pr))) (define rhs (lambda (pr) (cdr pr))) (define walk (lambda (x s) (let ((a (assq x s))) (cond (a (let ((u (rhs a))) (if (var? u) (walk u s) u))) (else x))))) (define walk* (lambda (v s) (let ((v (if (var? v) (walk v s) v))) (cond ((var? v) v) ((pair? v) (cons (walk* (car v) s) (walk* (cdr v) s))) (else v))))) (define unify (lambda (u v s) (let ((u (if (var? u) (walk u s) u)) (v (if (var? v) (walk v s) v))) (cond ((and (pair? u) (pair? v)) (let ((s (unify (car u) (car v) s))) (and s (unify (cdr u) (cdr v) s)))) (else (unify-nonpair u v s)))))) (define unify-nonpair (lambda (u v s) (cond ((eq? u v) s) ((var? u) (and (or (not (pair? v)) (valid? u v s)) (cons `(,u . ,v) s))) ((var? v) (and (or (not (pair? u)) (valid? v u s)) (cons `(,v . ,u) s))) ((equal? u v) s) (else #f)))) (define valid? (lambda (x v s) (not (occurs-check x v s)))) (define occurs-check (lambda (x v s) (let ((v (if (var? v) (walk v s) v))) (cond ((var? v) (eq? v x)) ((pair? v) (or (occurs-check x (car v) s) (occurs-check x (cdr v) s))) (else #f))))) (define reify-s (lambda (v) (let reify-s ((v v) (r '())) (let ((v (if (var? v) (walk v r) v))) (cond ((var? v) (let ((n (length r))) (let ((name (reify-name n))) (cons `(,v . ,name) r)))) ((pair? v) (let ((r (reify-s (car v) r))) (reify-s (cdr v) r))) (else r)))))) (define reify-name (lambda (n) (string->symbol (string-append "_" "." (number->string n))))) (define reify (lambda (x) (lambdag@ (a : s c* t) (let ((v (walk* x s))) (let ((r (reify-s v))) (reify-aux r v (let ((c* (remp (lambda (c) (anyvar? c r)) c*))) (rem-subsumed c*)) (remp (lambda (pr) (var? (walk (lhs pr) r))) t))))))) (define reify-aux (lambda (r v c* t) (let ((v (walk* v r)) (c* (walk* c* r)) (t (walk* t r))) (let ((c* (sorter (map sorter c*))) (p* (sorter (map sort-t-vars (partition* t))))) (cond ((and (null? c*) (null? p*)) v) ((null? c*) `(,v . ,p*)) (else `(,v (=/= . ,c*) . ,p*))))))) (define sort-t-vars (lambda (pr-t) (let ((tag (car pr-t)) (x* (sorter (cdr pr-t)))) (let ((reified-tag (tag->reified-tag tag))) `(,reified-tag . ,x*))))) (define tag->reified-tag (lambda (tag) (if (deep-tag? tag) (string->symbol (string-append "no-" (symbol->string tag))) tag))) (define lex<=? (lambda (x y) (string<=? (datum->string x) (datum->string y)))) (define anyvar? (lambda (c r) (cond ((pair? c) (or (anyvar? (car c) r) (anyvar? (cdr c) r))) (else (and (var? c) (var? (walk c r))))))) (define rem-subsumed (lambda (c*) (let rem-subsumed ((c* c*) (c^* '())) (cond ((null? c*) c^*) ((or (subsumed? (car c*) (cdr c*)) (subsumed? (car c*) c^*)) (rem-subsumed (cdr c*) c^*)) (else (rem-subsumed (cdr c*) (cons (car c*) c^*))))))) (define unify* (lambda (c s) (unify (map lhs c) (map rhs c) s))) (define subsumed? (lambda (c c*) (cond ((null? c*) #f) (else (let ((c^ (unify* (car c*) c))) (or (and c^ (eq? c^ c)) (subsumed? c (cdr c*)))))))) (define part (lambda (tag t x* y*) (cond ((null? t) (cons `(,tag . ,x*) (partition* y*))) ((eq? (pr-t->tag (car t)) tag) (let ((x (lhs (car t)))) (let ((x* (cond ((memq x x*) x*) (else (cons x x*))))) (part tag (cdr t) x* y*)))) (else (let ((y* (cons (car t) y*))) (part tag (cdr t) x* y*)))))) (define partition* (lambda (t) (cond ((null? t) '()) (else (part (pr-t->tag (car t)) t '() '()))))) (define-syntax project (syntax-rules () ((_ (x ...) g g* ...) (lambdag@ (a : s c* t) (let ((x (walk* x s)) ...) ((fresh () g g* ...) a)))))) (define-syntax conda (syntax-rules () ((_ (g0 g ...) (g1 g^ ...) ...) (lambdag@ (a) (inc (ifa ((g0 a) g ...) ((g1 a) g^ ...) ...)))))) (define-syntax ifa (syntax-rules () ((_) (mzero)) ((_ (e g ...) b ...) (let loop ((a-inf e)) (case-inf a-inf (() (ifa b ...)) ((f) (inc (loop (f)))) ((a) (bind* a-inf g ...)) ((a f) (bind* a-inf g ...))))))) (define-syntax condu (syntax-rules () ((_ (g0 g ...) (g1 g^ ...) ...) (lambdag@ (a) (inc (ifu ((g0 a) g ...) ((g1 a) g^ ...) ...)))))) (define-syntax ifu (syntax-rules () ((_) (mzero)) ((_ (e g ...) b ...) (let loop ((a-inf e)) (case-inf a-inf (() (ifu b ...)) ((f) (inc (loop (f)))) ((a) (bind* a-inf g ...)) ((a f) (bind* (unit a) g ...))))))) (define onceo (lambda (g) (condu (g))))
null
https://raw.githubusercontent.com/webyrd/quines/35436bd5b6edc63827058e0b1bf7b85d30cbde7d/mk.scm
scheme
'clasure x). not-in is gone; there are fewer uses of 'sym; and We can extend t with a deep tag provided It is not in a singleton c of c* with the same tag. That would mean lifting an innocent constraint to an overarching constraint, in that case. End reading here.
miniKanren with = /= , symbolo , , and noo ( A new goal ) ( noo no uses of ' num ( except when creating numbero . ) (define remp (lambda (p ls) (cond ((null? ls) '()) ((p (car ls)) (remp p (cdr ls))) (else (cons (car ls) (remp p (cdr ls))))))) (define (exists p ls) (cond ((null? ls) #f) ((p (car ls)) #t) (else (exists p (cdr ls))))) (define sorter (lambda (ls) (list-sort lex<=? ls))) (define datum->string (lambda (x) (with-output-to-string (lambda () (display x))))) (define-syntax test-check (syntax-rules () ((_ title tested-expression expected-result) (begin (printf "Testing ~s\n" title) (let* ((expected expected-result) (produced tested-expression)) (or (equal? expected produced) (errorf 'test-check "Failed: ~a~%Expected: ~a~%Computed: ~a~%" 'tested-expression expected produced))))))) (define a->s (lambda (a) (car a))) (define a->c* (lambda (a) (cadr a))) (define a->t (lambda (a) (caddr a))) (define-syntax lambdag@ (syntax-rules (:) ((_ (a) e) (lambda (a) e)) ((_ (a : s c* t) e) (lambda (a) (let ((s (a->s a)) (c* (a->c* a)) (t (a->t a))) e))))) (define mzero (lambda () #f)) (define unit (lambdag@ (a) a)) (define choice (lambda (a f) (cons a f))) (define-syntax lambdaf@ (syntax-rules () ((_ () e) (lambda () e)))) (define-syntax inc (syntax-rules () ((_ e) (lambdaf@ () e)))) (define empty-f (lambdaf@ () (mzero))) (define-syntax case-inf (syntax-rules () ((_ e (() e0) ((f^) e1) ((a^) e2) ((a f) e3)) (let ((a-inf e)) (cond ((not a-inf) e0) ((procedure? a-inf) (let ((f^ a-inf)) e1)) ((not (and (pair? a-inf) (procedure? (cdr a-inf)))) (let ((a^ a-inf)) e2)) (else (let ((a (car a-inf)) (f (cdr a-inf))) e3))))))) (define take (lambda (n f) (cond ((and n (zero? n)) '()) (else (case-inf (f) (() '()) ((f) (take n f)) ((a) (cons a '())) ((a f) (cons a (take (and n (- n 1)) f)))))))) (define empty-a '(() () ())) (define-syntax run (syntax-rules () ((_ n (x) g0 g ...) (take n (lambdaf@ () ((fresh (x) g0 g ... (lambdag@ (final-a) (choice ((reify x) final-a) empty-f))) empty-a)))))) (define-syntax run* (syntax-rules () ((_ (x) g ...) (run #f (x) g ...)))) (define-syntax fresh (syntax-rules () ((_ (x ...) g0 g ...) (lambdag@ (a) (inc (let ((x (var 'x)) ...) (bind* (g0 a) g ...))))))) (define-syntax bind* (syntax-rules () ((_ e) e) ((_ e g0 g ...) (bind* (bind e g0) g ...)))) (define bind (lambda (a-inf g) (case-inf a-inf (() (mzero)) ((f) (inc (bind (f) g))) ((a) (g a)) ((a f) (mplus (g a) (lambdaf@ () (bind (f) g))))))) (define mplus (lambda (a-inf f) (case-inf a-inf (() (f)) ((f^) (inc (mplus (f) f^))) ((a) (choice a f)) ((a f^) (choice a (lambdaf@ () (mplus (f) f^))))))) (define-syntax conde (syntax-rules () ((_ (g0 g ...) (g1 g^ ...) ...) (lambdag@ (a) (inc (mplus* (bind* (g0 a) g ...) (bind* (g1 a) g^ ...) ...)))))) (define-syntax mplus* (syntax-rules () ((_ e) e) ((_ e0 e ...) (mplus e0 (lambdaf@ () (mplus* e ...)))))) (define pr-t->tag (lambda (pr-t) (car (rhs pr-t)))) (define pr-t->pred (lambda (pr-t) (cdr (rhs pr-t)))) (define noo (lambda (tag u) (let ((pred (lambda (x) (not (eq? x tag))))) (lambdag@ (a : s c* t) (noo-aux tag u pred a s c* t))))) (define noo-aux (lambda (tag u pred a s c* t) (let ((u (if (var? u) (walk u s) u))) (cond ((pair? u) (cond ((pred u) (let ((a (noo-aux tag (car u) pred a s c* t))) (and a ((lambdag@ (a : s c* t) (noo-aux tag (cdr u) pred a s c* t)) a)))) (else (mzero)))) ((not (var? u)) (cond ((pred u) (unit a)) (else (mzero)))) ((ext-t u tag pred s t) => (lambda (t0) (cond ((not (eq? t0 t)) (let ((t^ (list (car t0)))) (let ((c* (subsume t^ c*))) (unit (subsume-t s c* t0))))) (else (unit a))))) (else (mzero)))))) (define make-flat-tag (lambda (tag pred) (lambda (u) (lambdag@ (a : s c* t) (let ((u (if (var? u) (walk u s) u))) (cond ((not (var? u)) (cond ((pred u) (unit a)) (else (mzero)))) ((ext-t u tag pred s t) => (lambda (t0) (cond ((not (eq? t0 t)) (let ((t^ (list (car t0)))) (let ((c* (subsume t^ c*))) (unit (subsume-t s c* t0))))) (else (unit a))))) (else (mzero)))))))) (define deep-tag? (lambda (tag) (not (or (eq? tag 'sym) (eq? tag 'num))))) would be wrong . So , no change to c * or t. (define ext-t (lambda (x tag pred s t^) (let ((x (walk x s))) (let loop ((t t^)) (cond ((null? t) (cons `(,x . (,tag . ,pred)) t^)) ((not (eq? (walk (lhs (car t)) s) x)) (loop (cdr t))) ((eq? (pr-t->tag (car t)) tag) t^) ((works-together? (pr-t->tag (car t)) tag) (loop (cdr t))) (else #f)))))) (define works-together? (lambda (t1 t2) (or (deep-tag? t1) (deep-tag? t2)))) (define subsume-t (lambda (s c* t) (let loop ((x* (rem-dups (map lhs t))) (c* c*) (t t)) (cond ((null? x*) `(,s ,c* ,t)) (else (let ((c*/t (subsume-c*/t (car x*) s c* t))) (loop (cdr x*) (car c*/t) (cdr c*/t)))))))) (define rem-dups (lambda (vars) (cond ((null? vars) '()) ((memq (car vars) (cdr vars)) (rem-dups (cdr vars))) (else (cons (car vars) (rem-dups (cdr vars))))))) (define have-flat-tag? (lambda (pred x) (lambda (pr-t) (let ((tag (pr-t->tag pr-t))) (and (not (deep-tag? tag)) (eq? (lhs pr-t) x) (pred tag)))))) (define subsume-c*/t (lambda (x s c* t) (cond ((exists (have-flat-tag? (lambda (u) (eq? u 'sym)) x) t) (subsumed-from-t-to-c* x s c* t '())) ((exists (have-flat-tag? (lambda (u) (not (eq? u 'sym))) x) t) `(,c* . ,(drop-from-t x t))) (else `(,c* . ,t))))) (define drop-from-t (lambda (x t) (remp (lambda (pr-t) (and (eq? (lhs pr-t) x) (deep-tag? (pr-t->tag pr-t)))) t))) (define subsumed-from-t-to-c* (lambda (x s c* t t^) (cond ((null? t) `(,c* . ,t^)) (else (let ((pr-t (car t))) (let ((tag (pr-t->tag pr-t)) (y (lhs pr-t))) (cond ((and (eq? y x) (deep-tag? tag)) (subsumed-from-t-to-c* x s (new-c* x tag c* s) (cdr t) t^)) (else (subsumed-from-t-to-c* x s c* (cdr t) (cons (car t) t^)))))))))) (define new-c* (lambda (x tag c* s) (cond ((exists (lambda (c) (and (null? (cdr c)) (eq? (walk (lhs (car c)) s) x) (eq? (rhs (car c)) tag))) c*) c*) (else (cons `((,x . ,tag)) c*))))) (define subsume (lambda (t c*) (remp (lambda (c) (exists (subsumed-pr? t) c)) c*))) (define subsumed-pr? (lambda (t) (lambda (pr-c) (let ((u (rhs pr-c))) (and (not (var? u)) (let ((x (lhs pr-c))) (let ((pr-t (assq x t))) (and pr-t (let ((tag (pr-t->tag pr-t))) (cond ((and (deep-tag? tag) (eq? tag u))) ((not ((pr-t->pred pr-t) u))) (else #f))))))))))) (define booleano (lambda (x) (conde ((== #f x)) ((== #t x))))) (define symbolo (make-flat-tag 'sym symbol?)) (define numbero (make-flat-tag 'num number?)) (define =/= (lambda (u v) (lambdag@ (a : s c* t) (cond ((unify u v s) => (lambda (s0) (cond ((eq? s0 s) (mzero)) (else (let ((p* (list (prefix-s s0 s)))) (let ((p* (subsume t p*))) (let ((c* (append p* c*))) (unit `(,s ,c* ,t))))))))) (else (unit a)))))) (define prefix-s (lambda (s0 s) (cond ((eq? s0 s) '()) (else (cons (car s0) (prefix-s (cdr s0) s)))))) (define == (lambda (u v) (lambdag@ (a : s c* t) (cond ((unify u v s) => (lambda (s0) (cond ((eq? s0 s) (unit a)) ((verify-c* c* s0) => (lambda (c*) (cond ((verify-t t s0) => (lambda (t) (let ((c* (subsume t c*))) (unit (subsume-t s0 c* t))))) (else (mzero))))) (else (mzero))))) (else (mzero)))))) (define verify-c* (lambda (c* s) (cond ((null? c*) '()) ((verify-c* (cdr c*) s) => (lambda (c0*) (let ((c (car c*))) (cond ((verify-c*-aux c c0* s)) (else (mzero)))))) (else #f)))) (define verify-c*-aux (lambda (c c0* s) (cond ((unify* c s) => (lambda (s0) (and (not (eq? s0 s)) (cons (prefix-s s0 s) c0*)))) (else c0*)))) (define verify-t (lambda (t s) (cond ((null? t) '()) ((verify-t (cdr t) s) => (letrec ((rec (lambda (u) (let ((u (if (var? u) (walk u s) u))) (let ((tag (pr-t->tag (car t))) (pred (pr-t->pred (car t)))) (lambda (t0) (cond ((var? u) (ext-t u tag pred s t0)) ((pair? u) (if (deep-tag? tag) (cond (((rec (car u)) t0) => (rec (cdr u))) (else #f)) (and (pred u) t0))) (else (and (pred u) t0))))))))) (rec (lhs (car t))))) (else #f)))) (define succeed (== #f #f)) (define fail (== #f #t)) (define var (lambda (dummy) (vector dummy))) (define var? (lambda (x) (vector? x))) (define lhs (lambda (pr) (car pr))) (define rhs (lambda (pr) (cdr pr))) (define walk (lambda (x s) (let ((a (assq x s))) (cond (a (let ((u (rhs a))) (if (var? u) (walk u s) u))) (else x))))) (define walk* (lambda (v s) (let ((v (if (var? v) (walk v s) v))) (cond ((var? v) v) ((pair? v) (cons (walk* (car v) s) (walk* (cdr v) s))) (else v))))) (define unify (lambda (u v s) (let ((u (if (var? u) (walk u s) u)) (v (if (var? v) (walk v s) v))) (cond ((and (pair? u) (pair? v)) (let ((s (unify (car u) (car v) s))) (and s (unify (cdr u) (cdr v) s)))) (else (unify-nonpair u v s)))))) (define unify-nonpair (lambda (u v s) (cond ((eq? u v) s) ((var? u) (and (or (not (pair? v)) (valid? u v s)) (cons `(,u . ,v) s))) ((var? v) (and (or (not (pair? u)) (valid? v u s)) (cons `(,v . ,u) s))) ((equal? u v) s) (else #f)))) (define valid? (lambda (x v s) (not (occurs-check x v s)))) (define occurs-check (lambda (x v s) (let ((v (if (var? v) (walk v s) v))) (cond ((var? v) (eq? v x)) ((pair? v) (or (occurs-check x (car v) s) (occurs-check x (cdr v) s))) (else #f))))) (define reify-s (lambda (v) (let reify-s ((v v) (r '())) (let ((v (if (var? v) (walk v r) v))) (cond ((var? v) (let ((n (length r))) (let ((name (reify-name n))) (cons `(,v . ,name) r)))) ((pair? v) (let ((r (reify-s (car v) r))) (reify-s (cdr v) r))) (else r)))))) (define reify-name (lambda (n) (string->symbol (string-append "_" "." (number->string n))))) (define reify (lambda (x) (lambdag@ (a : s c* t) (let ((v (walk* x s))) (let ((r (reify-s v))) (reify-aux r v (let ((c* (remp (lambda (c) (anyvar? c r)) c*))) (rem-subsumed c*)) (remp (lambda (pr) (var? (walk (lhs pr) r))) t))))))) (define reify-aux (lambda (r v c* t) (let ((v (walk* v r)) (c* (walk* c* r)) (t (walk* t r))) (let ((c* (sorter (map sorter c*))) (p* (sorter (map sort-t-vars (partition* t))))) (cond ((and (null? c*) (null? p*)) v) ((null? c*) `(,v . ,p*)) (else `(,v (=/= . ,c*) . ,p*))))))) (define sort-t-vars (lambda (pr-t) (let ((tag (car pr-t)) (x* (sorter (cdr pr-t)))) (let ((reified-tag (tag->reified-tag tag))) `(,reified-tag . ,x*))))) (define tag->reified-tag (lambda (tag) (if (deep-tag? tag) (string->symbol (string-append "no-" (symbol->string tag))) tag))) (define lex<=? (lambda (x y) (string<=? (datum->string x) (datum->string y)))) (define anyvar? (lambda (c r) (cond ((pair? c) (or (anyvar? (car c) r) (anyvar? (cdr c) r))) (else (and (var? c) (var? (walk c r))))))) (define rem-subsumed (lambda (c*) (let rem-subsumed ((c* c*) (c^* '())) (cond ((null? c*) c^*) ((or (subsumed? (car c*) (cdr c*)) (subsumed? (car c*) c^*)) (rem-subsumed (cdr c*) c^*)) (else (rem-subsumed (cdr c*) (cons (car c*) c^*))))))) (define unify* (lambda (c s) (unify (map lhs c) (map rhs c) s))) (define subsumed? (lambda (c c*) (cond ((null? c*) #f) (else (let ((c^ (unify* (car c*) c))) (or (and c^ (eq? c^ c)) (subsumed? c (cdr c*)))))))) (define part (lambda (tag t x* y*) (cond ((null? t) (cons `(,tag . ,x*) (partition* y*))) ((eq? (pr-t->tag (car t)) tag) (let ((x (lhs (car t)))) (let ((x* (cond ((memq x x*) x*) (else (cons x x*))))) (part tag (cdr t) x* y*)))) (else (let ((y* (cons (car t) y*))) (part tag (cdr t) x* y*)))))) (define partition* (lambda (t) (cond ((null? t) '()) (else (part (pr-t->tag (car t)) t '() '()))))) (define-syntax project (syntax-rules () ((_ (x ...) g g* ...) (lambdag@ (a : s c* t) (let ((x (walk* x s)) ...) ((fresh () g g* ...) a)))))) (define-syntax conda (syntax-rules () ((_ (g0 g ...) (g1 g^ ...) ...) (lambdag@ (a) (inc (ifa ((g0 a) g ...) ((g1 a) g^ ...) ...)))))) (define-syntax ifa (syntax-rules () ((_) (mzero)) ((_ (e g ...) b ...) (let loop ((a-inf e)) (case-inf a-inf (() (ifa b ...)) ((f) (inc (loop (f)))) ((a) (bind* a-inf g ...)) ((a f) (bind* a-inf g ...))))))) (define-syntax condu (syntax-rules () ((_ (g0 g ...) (g1 g^ ...) ...) (lambdag@ (a) (inc (ifu ((g0 a) g ...) ((g1 a) g^ ...) ...)))))) (define-syntax ifu (syntax-rules () ((_) (mzero)) ((_ (e g ...) b ...) (let loop ((a-inf e)) (case-inf a-inf (() (ifu b ...)) ((f) (inc (loop (f)))) ((a) (bind* a-inf g ...)) ((a f) (bind* (unit a) g ...))))))) (define onceo (lambda (g) (condu (g))))
13e6a07f117896e52547c0918fb2b732df592689a151897338b64f140e08f825
dalaing/little-languages
Gen.hs
| Copyright : ( c ) , 2016 License : : Stability : experimental Portability : non - portable Copyright : (c) Dave Laing, 2016 License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} module Component.Type.Note.Gen ( genTypeInput ) where import Component.Type.Gen (GenTypeInput(..)) genTypeInput :: GenTypeInput ty genTypeInput = mempty
null
https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/old/modular/common-lang/src/Component/Type/Note/Gen.hs
haskell
| Copyright : ( c ) , 2016 License : : Stability : experimental Portability : non - portable Copyright : (c) Dave Laing, 2016 License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} module Component.Type.Note.Gen ( genTypeInput ) where import Component.Type.Gen (GenTypeInput(..)) genTypeInput :: GenTypeInput ty genTypeInput = mempty
ee11f7a330a910dd09c4ddb61bbe29817f0478b46c690c4138c562c0e576c667
repl-acement/repl-acement
editor.cljs
(ns replacement.ui.views.editor (:require [re-frame.core :refer [subscribe dispatch]] [re-com.core :refer [h-box v-box box button gap line scroller border label input-text md-circle-icon-button md-icon-button input-textarea h-split v-split popover-anchor-wrapper popover-content-wrapper title flex-child-style p slider]] [re-com.splits :refer [hv-split-args-desc]] [reagent.core :as reagent] [reagent.dom :as rdom] [replacement.specs.user :as user] [replacement.ui.events :as events] [replacement.ui.subs :as subs] [replacement.ui.views.other-editor :as other-editor] [replacement.ui.views.add-lib :as add-lib] [replacement.ui.views.show-team-data :as team] [replacement.ui.views.eval :as eval-view] [replacement.ui.views.status :as status])) (defonce default-style {:font-family "Menlo, Lucida Console, Monaco, monospace" :border-radius "3px" :border "1px solid lightgrey" :padding "5px 5px 5px 5px"}) (defonce eval-panel-style (merge (flex-child-style "1") default-style)) (defonce edit-style (assoc default-style :border "2px solid lightgrey")) (defonce edit-panel-style (merge (flex-child-style "1") edit-style)) (defonce status-style (merge (dissoc default-style :border) {:font-size "10px" :font-weight "lighter" :color "lightgrey"})) (defn notify-edits [new-value] (dispatch [::events/current-form new-value])) (defn- key-binding [key-map [button event]] (assoc {} (get key-map button) #(dispatch [event]))) (defn extra-key-bindings [key-map event-map] (apply merge (map (partial key-binding key-map) event-map))) (def event-bindings {:enter ::events/eval :right ::events/history-next :down ::events/history-next :left ::events/history-prev :up ::events/history-prev}) (defn edit-panel [user] (let [key-bindings (subscribe [::subs/key-bindings])] (fn [] (let [editor-name (::user/name user) extra-keys (extra-key-bindings @key-bindings event-bindings)] [v-box :size "auto" :children [[gap :size "5px"] [h-box :children [[button :label (str "Eval") :tooltip (str "Shortcut: " (some-> (:enter @key-bindings) name)) :class "btn-success" :on-click #(dispatch [::events/eval])] [gap :size "5px"]]]]])))) (defn others-panel [other-users] (let [visible-count (count other-users)] (if (and visible-count (> visible-count 0)) [other-editor/other-panels other-users] [other-editor/waiting-panel]))) (defn button-row [] [h-box :height "20px" :style other-editor/other-editors-style :justify :between :children [[box :align :center :justify :start :child [md-icon-button :size :smaller :md-icon-name "zmdi-power" :tooltip "Logout" :on-click #(dispatch [::events/logout])]] [h-box :align :center :children [[add-lib/add-lib-panel] [md-icon-button :size :smaller :md-icon-name "zmdi-file-plus" :tooltip "Add a dependency" :on-click #(dispatch [::events/show-add-lib-panel true])]]] [h-box :align :center :children [[team/team-data-panel] [md-icon-button :size :smaller :md-icon-name "zmdi-account-add" :tooltip "REPL session invite link" :on-click #(dispatch [::events/show-team-data true])]]] [box :align :center :justify :start :child [md-icon-button :size :smaller :md-icon-name "zmdi-accounts-outline" ;; Toggle: zmdi-accounts / zmdi-accounts-outline :tooltip "Hide / Show other editors" :on-click #(dispatch [::events/toggle-others])]]]]) (defn editor-repl [user] [h-split :margin "5px" :splitter-size "5px" :panel-1 [edit-panel user] :panel-2 [v-box :style eval-panel-style :children [[eval-view/eval-panel user]]]]) ;; BUG - when other users login or logout ;; all evals and current input is lost (defn main-panels [user] (let [other-users @(subscribe [::subs/other-users])] [v-box :style {:position "absolute" :top "0px" :bottom "0px" :width "100%"} :children [[button-row] (if-not (seq other-users) [editor-repl user] [v-split :initial-split 20 :splitter-size "5px" :panel-1 [others-panel other-users] :panel-2 [editor-repl user]]) [status/status-bar user]]]))
null
https://raw.githubusercontent.com/repl-acement/repl-acement/43b17c24a5295464d2777628c211dd07313516c7/repl-ui/replacement/ui/views/editor.cljs
clojure
Toggle: zmdi-accounts / zmdi-accounts-outline BUG - when other users login or logout all evals and current input is lost
(ns replacement.ui.views.editor (:require [re-frame.core :refer [subscribe dispatch]] [re-com.core :refer [h-box v-box box button gap line scroller border label input-text md-circle-icon-button md-icon-button input-textarea h-split v-split popover-anchor-wrapper popover-content-wrapper title flex-child-style p slider]] [re-com.splits :refer [hv-split-args-desc]] [reagent.core :as reagent] [reagent.dom :as rdom] [replacement.specs.user :as user] [replacement.ui.events :as events] [replacement.ui.subs :as subs] [replacement.ui.views.other-editor :as other-editor] [replacement.ui.views.add-lib :as add-lib] [replacement.ui.views.show-team-data :as team] [replacement.ui.views.eval :as eval-view] [replacement.ui.views.status :as status])) (defonce default-style {:font-family "Menlo, Lucida Console, Monaco, monospace" :border-radius "3px" :border "1px solid lightgrey" :padding "5px 5px 5px 5px"}) (defonce eval-panel-style (merge (flex-child-style "1") default-style)) (defonce edit-style (assoc default-style :border "2px solid lightgrey")) (defonce edit-panel-style (merge (flex-child-style "1") edit-style)) (defonce status-style (merge (dissoc default-style :border) {:font-size "10px" :font-weight "lighter" :color "lightgrey"})) (defn notify-edits [new-value] (dispatch [::events/current-form new-value])) (defn- key-binding [key-map [button event]] (assoc {} (get key-map button) #(dispatch [event]))) (defn extra-key-bindings [key-map event-map] (apply merge (map (partial key-binding key-map) event-map))) (def event-bindings {:enter ::events/eval :right ::events/history-next :down ::events/history-next :left ::events/history-prev :up ::events/history-prev}) (defn edit-panel [user] (let [key-bindings (subscribe [::subs/key-bindings])] (fn [] (let [editor-name (::user/name user) extra-keys (extra-key-bindings @key-bindings event-bindings)] [v-box :size "auto" :children [[gap :size "5px"] [h-box :children [[button :label (str "Eval") :tooltip (str "Shortcut: " (some-> (:enter @key-bindings) name)) :class "btn-success" :on-click #(dispatch [::events/eval])] [gap :size "5px"]]]]])))) (defn others-panel [other-users] (let [visible-count (count other-users)] (if (and visible-count (> visible-count 0)) [other-editor/other-panels other-users] [other-editor/waiting-panel]))) (defn button-row [] [h-box :height "20px" :style other-editor/other-editors-style :justify :between :children [[box :align :center :justify :start :child [md-icon-button :size :smaller :md-icon-name "zmdi-power" :tooltip "Logout" :on-click #(dispatch [::events/logout])]] [h-box :align :center :children [[add-lib/add-lib-panel] [md-icon-button :size :smaller :md-icon-name "zmdi-file-plus" :tooltip "Add a dependency" :on-click #(dispatch [::events/show-add-lib-panel true])]]] [h-box :align :center :children [[team/team-data-panel] [md-icon-button :size :smaller :md-icon-name "zmdi-account-add" :tooltip "REPL session invite link" :on-click #(dispatch [::events/show-team-data true])]]] [box :align :center :justify :start :child :tooltip "Hide / Show other editors" :on-click #(dispatch [::events/toggle-others])]]]]) (defn editor-repl [user] [h-split :margin "5px" :splitter-size "5px" :panel-1 [edit-panel user] :panel-2 [v-box :style eval-panel-style :children [[eval-view/eval-panel user]]]]) (defn main-panels [user] (let [other-users @(subscribe [::subs/other-users])] [v-box :style {:position "absolute" :top "0px" :bottom "0px" :width "100%"} :children [[button-row] (if-not (seq other-users) [editor-repl user] [v-split :initial-split 20 :splitter-size "5px" :panel-1 [others-panel other-users] :panel-2 [editor-repl user]]) [status/status-bar user]]]))
01667d06714b239d816cdc02c13466457062bf7897cdc83d4e1ee89e3e500fbd
commercialhaskell/stack
ConstructPlan.hs
# LANGUAGE NoImplicitPrelude # {-# LANGUAGE LambdaCase #-} # LANGUAGE OverloadedStrings # # LANGUAGE ViewPatterns # | Construct a @Plan@ for how to build module Stack.Build.ConstructPlan ( constructPlan ) where import Control.Monad.RWS.Strict hiding ( (<>) ) import qualified Data.List as L import qualified Data.Map.Merge.Strict as Map import qualified Data.Map.Strict as Map import Data.Monoid.Map ( MonoidMap(..) ) import qualified Data.Set as Set import qualified Data.Text as T import Distribution.Types.BuildType ( BuildType (Configure) ) import Distribution.Types.PackageName ( mkPackageName ) import Generics.Deriving.Monoid ( memptydefault, mappenddefault ) import Path ( parent ) import RIO.Process ( HasProcessContext (..), findExecutable ) import RIO.State ( State, execState ) import Stack.Build.Cache ( tryGetFlagCache ) import Stack.Build.Haddock ( shouldHaddockDeps ) import Stack.Build.Source ( loadLocalPackage ) import Stack.Constants ( compilerOptionsCabalFlag ) import Stack.Package ( applyForceCustomBuild ) import Stack.Prelude hiding ( loadPackage ) import Stack.SourceMap ( getPLIVersion, mkProjectPackage ) import Stack.Types.Build ( BaseConfigOpts (..), BadDependency (..) , BuildException (..), BuildPrettyException (..) , CachePkgSrc (..), ConfigCache (..), ConfigureOpts (..) , ConstructPlanException (..), IsMutable (..), ParentMap , Plan (..), Task (..), TaskConfigOpts (..), TaskType (..) , configureOpts, installLocationIsMutable, isStackOpt , taskIsTarget, taskLocation, taskTargetIsMutable , toCachePkgSrc ) import Stack.Types.Compiler ( WhichCompiler (..) ) import Stack.Types.Config ( BuildConfig (..), BuildOpts (..), BuildOptsCLI (..) , BuildSubset (..), CompilerPaths (..), Config (..) , Curator (..), DumpPackage (..), EnvConfig, EnvSettings (..) , HasBuildConfig (..), HasCompiler (..), HasConfig (..) , HasEnvConfig (..), HasGHCVariant, HasPlatform , HasRunner (..), HasSourceMap (..), minimalEnvSettings , stackRootL, stackYamlL ) import Stack.Types.Dependency ( DepValue (DepValue), DepType (AsLibrary) ) import Stack.Types.GhcPkgId ( GhcPkgId ) import Stack.Types.NamedComponent ( exeComponents, renderComponent ) import Stack.Types.Package ( ExeName (..), InstallLocation (..), Installed (..) , InstalledMap, LocalPackage (..), Package (..) , PackageLibraries (..), PackageSource (..), installedVersion , packageIdentifier, psVersion, runMemoizedWith ) import Stack.Types.SourceMap ( CommonPackage (..), DepPackage (..), FromSnapshot (..) , GlobalPackage (..), SMTargets (..), SourceMap (..) ) import Stack.Types.Version ( latestApplicableVersion, versionRangeText, withinRange ) import System.Environment ( lookupEnv ) import System.IO ( putStrLn ) data PackageInfo = PIOnlyInstalled InstallLocation Installed -- ^ This indicates that the package is already installed, and that we -- shouldn't build it from source. This is only the case for global -- packages. | PIOnlySource PackageSource -- ^ This indicates that the package isn't installed, and we know where to -- find its source. | PIBoth PackageSource Installed -- ^ This indicates that the package is installed and we know where to find -- its source. We may want to reinstall from source. deriving Show combineSourceInstalled :: PackageSource -> (InstallLocation, Installed) -> PackageInfo combineSourceInstalled ps (location, installed) = assert (psVersion ps == installedVersion installed) $ case location of -- Always trust something in the snapshot Snap -> PIOnlyInstalled location installed Local -> PIBoth ps installed type CombinedMap = Map PackageName PackageInfo combineMap :: Map PackageName PackageSource -> InstalledMap -> CombinedMap combineMap = Map.merge (Map.mapMissing (\_ s -> PIOnlySource s)) (Map.mapMissing (\_ i -> uncurry PIOnlyInstalled i)) (Map.zipWithMatched (\_ s i -> combineSourceInstalled s i)) data AddDepRes = ADRToInstall Task | ADRFound InstallLocation Installed deriving Show data W = W { wFinals :: !(Map PackageName (Either ConstructPlanException Task)) , wInstall :: !(Map Text InstallLocation) -- ^ executable to be installed, and location where the binary is placed , wDirty :: !(Map PackageName Text) -- ^ why a local package is considered dirty , wWarnings :: !([Text] -> [Text]) -- ^ Warnings , wParents :: !ParentMap -- ^ Which packages a given package depends on, along with the package's -- version } deriving Generic instance Semigroup W where (<>) = mappenddefault instance Monoid W where mempty = memptydefault mappend = (<>) TODO replace with more efficient WS stack on top of StackT Ctx W (Map PackageName (Either ConstructPlanException AddDepRes)) IO data Ctx = Ctx { baseConfigOpts :: !BaseConfigOpts , loadPackage :: !( PackageLocationImmutable -> Map FlagName Bool -> [Text] -> [Text] -> M Package ) , combinedMap :: !CombinedMap , ctxEnvConfig :: !EnvConfig , callStack :: ![PackageName] , wanted :: !(Set PackageName) , localNames :: !(Set PackageName) , mcurator :: !(Maybe Curator) , pathEnvVar :: !Text } instance HasPlatform Ctx instance HasGHCVariant Ctx instance HasLogFunc Ctx where logFuncL = configL.logFuncL instance HasRunner Ctx where runnerL = configL.runnerL instance HasStylesUpdate Ctx where stylesUpdateL = runnerL.stylesUpdateL instance HasTerm Ctx where useColorL = runnerL.useColorL termWidthL = runnerL.termWidthL instance HasConfig Ctx instance HasPantryConfig Ctx where pantryConfigL = configL.pantryConfigL instance HasProcessContext Ctx where processContextL = configL.processContextL instance HasBuildConfig Ctx instance HasSourceMap Ctx where sourceMapL = envConfigL.sourceMapL instance HasCompiler Ctx where compilerPathsL = envConfigL.compilerPathsL instance HasEnvConfig Ctx where envConfigL = lens ctxEnvConfig (\x y -> x { ctxEnvConfig = y }) | Computes a build plan . This means figuring out which build ' Task 's to take , and the interdependencies among the build ' Task 's . In particular : -- 1 ) It determines which packages need to be built , based on the transitive -- deps of the current targets. For local packages, this is indicated by the -- 'lpWanted' boolean. For extra packages to build, this comes from the -- @extraToBuild0@ argument of type @Set PackageName@. These are usually -- packages that have been specified on the command line. -- 2 ) It will only rebuild an upstream package if it is n't present in the -- 'InstalledMap', or if some of its dependencies have changed. -- 3 ) It will only rebuild a local package if its files are dirty or some of its -- dependencies have changed. constructPlan :: forall env. HasEnvConfig env => BaseConfigOpts -> [DumpPackage] -- ^ locally registered -> ( PackageLocationImmutable -> Map FlagName Bool -> [Text] -> [Text] -> RIO EnvConfig Package ) -- ^ load upstream package -> SourceMap -> InstalledMap -> Bool -> RIO env Plan constructPlan baseConfigOpts0 localDumpPkgs loadPackage0 sourceMap installedMap initialBuildSteps = do logDebug "Constructing the build plan" when hasBaseInDeps $ prettyWarn $ fillSep [ flow "You are trying to upgrade or downgrade the" , style Current "base" , flow "package, which is almost certainly not what you really \ \want. Please, consider using another GHC version if you \ \need a certain version of" , style Current "base" <> "," , flow "or removing" , style Current "base" , flow "as an" , style Shell "extra-deps" <> "." , flow "For further information, see" , style Url "" <> "." ] <> line econfig <- view envConfigL globalCabalVersion <- view $ compilerPathsL.to cpCabalVersion sources <- getSources globalCabalVersion mcur <- view $ buildConfigL.to bcCurator let onTarget = void . addDep let inner = mapM_ onTarget $ Map.keys (smtTargets $ smTargets sourceMap) pathEnvVar' <- liftIO $ maybe mempty T.pack <$> lookupEnv "PATH" let ctx = mkCtx econfig globalCabalVersion sources mcur pathEnvVar' ((), m, W efinals installExes dirtyReason warnings parents) <- liftIO $ runRWST inner ctx Map.empty mapM_ (prettyWarn . fromString . T.unpack . textDisplay) (warnings []) let toEither (_, Left e) = Left e toEither (k, Right v) = Right (k, v) (errlibs, adrs) = partitionEithers $ map toEither $ Map.toList m (errfinals, finals) = partitionEithers $ map toEither $ Map.toList efinals errs = errlibs ++ errfinals if null errs then do let toTask (_, ADRFound _ _) = Nothing toTask (name, ADRToInstall task) = Just (name, task) tasks = Map.fromList $ mapMaybe toTask adrs takeSubset = case boptsCLIBuildSubset $ bcoBuildOptsCLI baseConfigOpts0 of BSAll -> pure BSOnlySnapshot -> pure . stripLocals BSOnlyDependencies -> pure . stripNonDeps (Map.keysSet $ smDeps sourceMap) BSOnlyLocals -> errorOnSnapshot takeSubset Plan { planTasks = tasks , planFinals = Map.fromList finals , planUnregisterLocal = mkUnregisterLocal tasks dirtyReason localDumpPkgs initialBuildSteps , planInstallExes = if boptsInstallExes (bcoBuildOpts baseConfigOpts0) || boptsInstallCompilerTool (bcoBuildOpts baseConfigOpts0) then installExes else Map.empty } else do planDebug $ show errs stackYaml <- view stackYamlL stackRoot <- view stackRootL prettyThrowM $ ConstructPlanFailed errs stackYaml stackRoot parents (wanted ctx) prunedGlobalDeps where hasBaseInDeps = Map.member (mkPackageName "base") (smDeps sourceMap) mkCtx econfig globalCabalVersion sources mcur pathEnvVar' = Ctx { baseConfigOpts = baseConfigOpts0 , loadPackage = \w x y z -> runRIO econfig $ applyForceCustomBuild globalCabalVersion <$> loadPackage0 w x y z , combinedMap = combineMap sources installedMap , ctxEnvConfig = econfig , callStack = [] , wanted = Map.keysSet (smtTargets $ smTargets sourceMap) , localNames = Map.keysSet (smProject sourceMap) , mcurator = mcur , pathEnvVar = pathEnvVar' } prunedGlobalDeps = flip Map.mapMaybe (smGlobal sourceMap) $ \case ReplacedGlobalPackage deps -> let pruned = filter (not . inSourceMap) deps in if null pruned then Nothing else Just pruned GlobalPackage _ -> Nothing inSourceMap pname = pname `Map.member` smDeps sourceMap || pname `Map.member` smProject sourceMap getSources globalCabalVersion = do let loadLocalPackage' pp = do lp <- loadLocalPackage pp pure lp { lpPackage = applyForceCustomBuild globalCabalVersion $ lpPackage lp } pPackages <- for (smProject sourceMap) $ \pp -> do lp <- loadLocalPackage' pp pure $ PSFilePath lp bopts <- view $ configL.to configBuild deps <- for (smDeps sourceMap) $ \dp -> case dpLocation dp of PLImmutable loc -> pure $ PSRemote loc (getPLIVersion loc) (dpFromSnapshot dp) (dpCommon dp) PLMutable dir -> do pp <- mkProjectPackage YesPrintWarnings dir (shouldHaddockDeps bopts) lp <- loadLocalPackage' pp pure $ PSFilePath lp pure $ pPackages <> deps -- | Throw an exception if there are any snapshot packages in the plan. errorOnSnapshot :: Plan -> RIO env Plan errorOnSnapshot plan@(Plan tasks _finals _unregister installExes) = do let snapTasks = Map.keys $ Map.filter (\t -> taskLocation t == Snap) tasks let snapExes = Map.keys $ Map.filter (== Snap) installExes unless (null snapTasks && null snapExes) $ throwIO $ NotOnlyLocal snapTasks snapExes pure plan data NotOnlyLocal = NotOnlyLocal [PackageName] [Text] deriving (Show, Typeable) instance Exception NotOnlyLocal where displayException (NotOnlyLocal packages exes) = concat [ "Error: [S-1727]\n" , "Specified only-locals, but I need to build snapshot contents:\n" , if null packages then "" else concat [ "Packages: " , L.intercalate ", " (map packageNameString packages) , "\n" ] , if null exes then "" else concat [ "Executables: " , L.intercalate ", " (map T.unpack exes) , "\n" ] ] -- | State to be maintained during the calculation of local packages -- to unregister. data UnregisterState = UnregisterState { usToUnregister :: !(Map GhcPkgId (PackageIdentifier, Text)) , usKeep :: ![DumpPackage] , usAnyAdded :: !Bool } -- | Determine which packages to unregister based on the given tasks and -- already registered local packages. mkUnregisterLocal :: Map PackageName Task -- ^ Tasks -> Map PackageName Text -- ^ Reasons why packages are dirty and must be rebuilt -> [DumpPackage] -- ^ Local package database dump -> Bool ^ If true , we 're doing a special initialBuildSteps build - do n't -- unregister target packages. -> Map GhcPkgId (PackageIdentifier, Text) mkUnregisterLocal tasks dirtyReason localDumpPkgs initialBuildSteps = -- We'll take multiple passes through the local packages. This will allow us -- to detect that a package should be unregistered, as well as all packages -- directly or transitively depending on it. loop Map.empty localDumpPkgs where loop :: Map GhcPkgId (PackageIdentifier, Text) -- ^ Current local packages to unregister. -> [DumpPackage] -- ^ Current local packages to keep. -> Map GhcPkgId (PackageIdentifier, Text) -- ^ Revised local packages to unregister. loop toUnregister keep -- If any new packages were added to the unregister Map, we need to loop -- through the remaining packages again to detect if a transitive dependency -- is being unregistered. | usAnyAdded us = loop (usToUnregister us) (usKeep us) -- Nothing added, so we've already caught them all. Return the Map we've -- already calculated. | otherwise = usToUnregister us where -- Run the unregister checking function on all packages we currently think -- we'll be keeping. us = execState (mapM_ go keep) initialUnregisterState initialUnregisterState = UnregisterState { usToUnregister = toUnregister , usKeep = [] , usAnyAdded = False } go :: DumpPackage -> State UnregisterState () go dp = do us <- get case maybeUnregisterReason (usToUnregister us) ident mParentLibId deps of -- Not unregistering, add it to the keep list. Nothing -> put us { usKeep = dp : usKeep us } -- Unregistering, add it to the unregister Map; and indicate that a -- package was in fact added to the unregister Map, so we loop again. Just reason -> put us { usToUnregister = Map.insert gid (ident, reason) (usToUnregister us) , usAnyAdded = True } where gid = dpGhcPkgId dp ident = dpPackageIdent dp mParentLibId = dpParentLibIdent dp deps = dpDepends dp maybeUnregisterReason :: Map GhcPkgId (PackageIdentifier, Text) -- ^ Current local packages to unregister. -> PackageIdentifier -- ^ Package identifier. -> Maybe PackageIdentifier -- ^ If package for sub library, package identifier of the parent. -> [GhcPkgId] -- ^ Dependencies of the package. -> Maybe Text -- ^ If to be unregistered, the reason for doing so. maybeUnregisterReason toUnregister ident mParentLibId deps -- If the package is not for a sub library, then it is directly relevant. If -- it is, then the relevant package is the parent. If we are planning on -- running a task on the relevant package, then the package must be -- unregistered, unless it is a target and an initial-build-steps build is -- being done. | Just task <- Map.lookup relevantPkgName tasks = if initialBuildSteps && taskIsTarget task && taskProvides task == relevantPkgId then Nothing else Just $ fromMaybe "" $ Map.lookup relevantPkgName dirtyReason -- Check if a dependency is going to be unregistered | (dep, _):_ <- mapMaybe (`Map.lookup` toUnregister) deps = Just $ "Dependency being unregistered: " <> T.pack (packageIdentifierString dep) -- None of the above, keep it! | otherwise = Nothing where -- If the package is not for a sub library, then the relevant package -- identifier is that of the package. If it is, then the relevant package -- identifier is that of the parent. relevantPkgId :: PackageIdentifier relevantPkgId = fromMaybe ident mParentLibId -- If the package is not for a sub library, then the relevant package name -- is that of the package. If it is, then the relevant package name is -- that of the parent. relevantPkgName :: PackageName relevantPkgName = maybe (pkgName ident) pkgName mParentLibId | Given a ' LocalPackage ' and its ' lpTestBench ' , adds a ' Task ' for running its -- tests and benchmarks. -- -- If @isAllInOne@ is 'True', then this means that the build step will also -- build the tests. Otherwise, this indicates that there's a cyclic dependency -- and an additional build step needs to be done. -- This will also add all the needed to build the tests / benchmarks . If -- @isAllInOne@ is 'True' (the common case), then all of these should have -- already been taken care of as part of the build step. addFinal :: LocalPackage -> Package -> Bool -> Bool -> M () addFinal lp package isAllInOne buildHaddocks = do depsRes <- addPackageDeps package res <- case depsRes of Left e -> pure $ Left e Right (missing, present, _minLoc) -> do ctx <- ask pure $ Right Task { taskProvides = PackageIdentifier (packageName package) (packageVersion package) , taskConfigOpts = TaskConfigOpts missing $ \missing' -> let allDeps = Map.union present missing' in configureOpts (view envConfigL ctx) (baseConfigOpts ctx) allDeps True -- local Mutable package , taskBuildHaddock = buildHaddocks , taskPresent = present , taskType = TTLocalMutable lp , taskAllInOne = isAllInOne , taskCachePkgSrc = CacheSrcLocal (toFilePath (parent (lpCabalFile lp))) , taskAnyMissing = not $ Set.null missing , taskBuildTypeConfig = packageBuildTypeConfig package } tell mempty { wFinals = Map.singleton (packageName package) res } -- | Given a 'PackageName', adds all of the build tasks to build the package, if -- needed. -- -- 'constructPlan' invokes this on all the target packages, setting -- @treatAsDep'@ to False, because those packages are direct build targets. -- 'addPackageDeps' invokes this while recursing into the dependencies of a -- package. As such, it sets @treatAsDep'@ to True, forcing this package to be -- marked as a dependency, even if it is directly wanted. This makes sense - if we left out packages that are , it would break the --only - dependencies -- build plan. addDep :: PackageName -> M (Either ConstructPlanException AddDepRes) addDep name = do ctx <- ask m <- get case Map.lookup name m of Just res -> do planDebug $ "addDep: Using cached result for " ++ show name ++ ": " ++ show res pure res Nothing -> do res <- if name `elem` callStack ctx then do planDebug $ "addDep: Detected cycle " <> show name <> ": " <> show (callStack ctx) pure $ Left $ DependencyCycleDetected $ name : callStack ctx else local (\ctx' -> ctx' { callStack = name : callStack ctx' }) $ do let mpackageInfo = Map.lookup name $ combinedMap ctx planDebug $ "addDep: Package info for " <> show name <> ": " <> show mpackageInfo case mpackageInfo of TODO look up in the package index and see if there 's a -- recommendation available Nothing -> pure $ Left $ UnknownPackage name Just (PIOnlyInstalled loc installed) -> do -- FIXME Slightly hacky, no flags since they likely won't affect -- executable names. This code does not feel right. let version = installedVersion installed askPkgLoc = liftRIO $ do mrev <- getLatestHackageRevision YesRequireHackageIndex name version case mrev of Nothing -> do this could happen for GHC boot libraries missing from -- Hackage prettyWarnL $ flow "No latest package revision found for" : style Current (fromString $ packageNameString name) <> "," : flow "dependency callstack:" : mkNarrativeList Nothing False ( map (fromString . packageNameString) (callStack ctx) :: [StyleDoc] ) pure Nothing Just (_rev, cfKey, treeKey) -> pure . Just $ PLIHackage (PackageIdentifier name version) cfKey treeKey tellExecutablesUpstream name askPkgLoc loc Map.empty pure $ Right $ ADRFound loc installed Just (PIOnlySource ps) -> do tellExecutables name ps installPackage name ps Nothing Just (PIBoth ps installed) -> do tellExecutables name ps installPackage name ps (Just installed) updateLibMap name res pure res FIXME what 's the purpose of this ? Add a ! tellExecutables :: PackageName -> PackageSource -> M () tellExecutables _name (PSFilePath lp) | lpWanted lp = tellExecutablesPackage Local $ lpPackage lp | otherwise = pure () -- Ignores ghcOptions because they don't matter for enumerating executables. tellExecutables name (PSRemote pkgloc _version _fromSnapshot cp) = tellExecutablesUpstream name (pure $ Just pkgloc) Snap (cpFlags cp) tellExecutablesUpstream :: PackageName -> M (Maybe PackageLocationImmutable) -> InstallLocation -> Map FlagName Bool -> M () tellExecutablesUpstream name retrievePkgLoc loc flags = do ctx <- ask when (name `Set.member` wanted ctx) $ do mPkgLoc <- retrievePkgLoc forM_ mPkgLoc $ \pkgLoc -> do p <- loadPackage ctx pkgLoc flags [] [] tellExecutablesPackage loc p tellExecutablesPackage :: InstallLocation -> Package -> M () tellExecutablesPackage loc p = do cm <- asks combinedMap -- Determine which components are enabled so we know which ones to copy let myComps = case Map.lookup (packageName p) cm of Nothing -> assert False Set.empty Just (PIOnlyInstalled _ _) -> Set.empty Just (PIOnlySource ps) -> goSource ps Just (PIBoth ps _) -> goSource ps goSource (PSFilePath lp) | lpWanted lp = exeComponents (lpComponents lp) | otherwise = Set.empty goSource PSRemote{} = Set.empty tell mempty { wInstall = Map.fromList $ map (, loc) $ Set.toList $ filterComps myComps $ packageExes p } where filterComps myComps x | Set.null myComps = x | otherwise = Set.intersection x myComps | Given a ' PackageSource ' and perhaps an ' Installed ' value , adds build ' Task 's for the package and its dependencies . installPackage :: PackageName -> PackageSource -> Maybe Installed -> M (Either ConstructPlanException AddDepRes) installPackage name ps minstalled = do ctx <- ask case ps of PSRemote pkgLoc _version _fromSnapshot cp -> do planDebug $ "installPackage: Doing all-in-one build for upstream package " <> show name package <- loadPackage ctx pkgLoc (cpFlags cp) (cpGhcOptions cp) (cpCabalConfigOpts cp) resolveDepsAndInstall True (cpHaddocks cp) ps package minstalled PSFilePath lp -> do case lpTestBench lp of Nothing -> do planDebug $ "installPackage: No test / bench component for " <> show name <> " so doing an all-in-one build." resolveDepsAndInstall True (lpBuildHaddocks lp) ps (lpPackage lp) minstalled Just tb -> do -- Attempt to find a plan which performs an all-in-one build. Ignore -- the writer action + reset the state if it fails. s <- get res <- pass $ do res <- addPackageDeps tb let writerFunc w = case res of Left _ -> mempty _ -> w pure (res, writerFunc) case res of Right deps -> do planDebug $ "installPackage: For " <> show name <> ", successfully added package deps" in curator builds we ca n't do all - in - one build as -- test/benchmark failure could prevent library from being -- available to its dependencies but when it's already available -- it's OK to do that splitRequired <- expectedTestOrBenchFailures <$> asks mcurator let isAllInOne = not splitRequired adr <- installPackageGivenDeps isAllInOne (lpBuildHaddocks lp) ps tb minstalled deps let finalAllInOne = case adr of ADRToInstall _ | splitRequired -> False _ -> True FIXME : this redundantly adds the ( but they 'll all just -- get looked up in the map) addFinal lp tb finalAllInOne False pure $ Right adr Left _ -> do -- Reset the state to how it was before attempting to find an -- all-in-one build plan. planDebug $ "installPackage: Before trying cyclic plan, resetting lib \ \result map to " <> show s put s -- Otherwise, fall back on building the tests / benchmarks in a -- separate step. res' <- resolveDepsAndInstall False (lpBuildHaddocks lp) ps (lpPackage lp) minstalled when (isRight res') $ do Insert it into the map so that it 's available for addFinal . updateLibMap name res' addFinal lp tb False False pure res' where expectedTestOrBenchFailures maybeCurator = fromMaybe False $ do curator <- maybeCurator pure $ Set.member name (curatorExpectTestFailure curator) || Set.member name (curatorExpectBenchmarkFailure curator) resolveDepsAndInstall :: Bool -> Bool -> PackageSource -> Package -> Maybe Installed -> M (Either ConstructPlanException AddDepRes) resolveDepsAndInstall isAllInOne buildHaddocks ps package minstalled = do res <- addPackageDeps package case res of Left err -> pure $ Left err Right deps -> Right <$> installPackageGivenDeps isAllInOne buildHaddocks ps package minstalled deps -- | Checks if we need to install the given 'Package', given the results -- of 'addPackageDeps'. If dependencies are missing, the package is dirty, or -- it's not installed, then it needs to be installed. installPackageGivenDeps :: Bool -> Bool -> PackageSource -> Package -> Maybe Installed -> ( Set PackageIdentifier , Map PackageIdentifier GhcPkgId , IsMutable ) -> M AddDepRes installPackageGivenDeps isAllInOne buildHaddocks ps package minstalled (missing, present, minMutable) = do let name = packageName package ctx <- ask mRightVersionInstalled <- case (minstalled, Set.null missing) of (Just installed, True) -> do shouldInstall <- checkDirtiness ps installed package present buildHaddocks pure $ if shouldInstall then Nothing else Just installed (Just _, False) -> do let t = T.intercalate ", " $ map (T.pack . packageNameString . pkgName) (Set.toList missing) tell mempty { wDirty = Map.singleton name $ "missing dependencies: " <> addEllipsis t } pure Nothing (Nothing, _) -> pure Nothing let loc = psLocation ps mutable = installLocationIsMutable loc <> minMutable pure $ case mRightVersionInstalled of Just installed -> ADRFound loc installed Nothing -> ADRToInstall Task { taskProvides = PackageIdentifier (packageName package) (packageVersion package) , taskConfigOpts = TaskConfigOpts missing $ \missing' -> let allDeps = Map.union present missing' in configureOpts (view envConfigL ctx) (baseConfigOpts ctx) allDeps (psLocal ps) mutable package , taskBuildHaddock = buildHaddocks , taskPresent = present , taskType = case ps of PSFilePath lp -> TTLocalMutable lp PSRemote pkgLoc _version _fromSnapshot _cp -> TTRemotePackage mutable package pkgLoc , taskAllInOne = isAllInOne , taskCachePkgSrc = toCachePkgSrc ps , taskAnyMissing = not $ Set.null missing , taskBuildTypeConfig = packageBuildTypeConfig package } -- | Is the build type of the package Configure packageBuildTypeConfig :: Package -> Bool packageBuildTypeConfig pkg = packageBuildType pkg == Configure -- Update response in the lib map. If it is an error, and there's already an -- error about cyclic dependencies, prefer the cyclic error. updateLibMap :: PackageName -> Either ConstructPlanException AddDepRes -> M () updateLibMap name val = modify $ \mp -> case (Map.lookup name mp, val) of (Just (Left DependencyCycleDetected{}), Left _) -> mp _ -> Map.insert name val mp addEllipsis :: Text -> Text addEllipsis t | T.length t < 100 = t | otherwise = T.take 97 t <> "..." -- | Given a package, recurses into all of its dependencies. The results indicate which packages are missing , meaning that their ' GhcPkgId 's will be figured out during the build , after they 've been built . The 2nd part of the -- tuple result indicates the packages that are already installed which will be -- used. -- The 3rd part of the tuple is an ' InstallLocation ' . If it is ' Local ' , then the -- parent package must be installed locally. Otherwise, if it is 'Snap', then it -- can either be installed locally or in the snapshot. addPackageDeps :: Package -> M ( Either ConstructPlanException ( Set PackageIdentifier , Map PackageIdentifier GhcPkgId , IsMutable ) ) addPackageDeps package = do ctx <- ask checkAndWarnForUnknownTools package let deps' = packageDeps package deps <- forM (Map.toList deps') $ \(depname, DepValue range depType) -> do eres <- addDep depname let getLatestApplicableVersionAndRev :: M (Maybe (Version, BlobKey)) getLatestApplicableVersionAndRev = do vsAndRevs <- runRIO ctx $ getHackagePackageVersions YesRequireHackageIndex UsePreferredVersions depname pure $ do lappVer <- latestApplicableVersion range $ Map.keysSet vsAndRevs revs <- Map.lookup lappVer vsAndRevs (cabalHash, _) <- Map.maxView revs Just (lappVer, cabalHash) case eres of Left e -> do addParent depname range Nothing let bd = case e of UnknownPackage name -> assert (name == depname) NotInBuildPlan DependencyCycleDetected names -> BDDependencyCycleDetected names -- ultimately we won't show any information on this to the user, -- we'll allow the dependency failures alone to display to avoid -- spamming the user too much DependencyPlanFailures _ _ -> Couldn'tResolveItsDependencies (packageVersion package) mlatestApplicable <- getLatestApplicableVersionAndRev pure $ Left (depname, (range, mlatestApplicable, bd)) Right adr | depType == AsLibrary && not (adrHasLibrary adr) -> pure $ Left (depname, (range, Nothing, HasNoLibrary)) Right adr -> do addParent depname range Nothing inRange <- if adrVersion adr `withinRange` range then pure True else do let warn_ reason = tell mempty { wWarnings = (msg:) } where msg = T.concat [ "WARNING: Ignoring " , T.pack $ packageNameString $ packageName package , "'s bounds on " , T.pack $ packageNameString depname , " (" , versionRangeText range , "); using " , T.pack $ packageIdentifierString $ PackageIdentifier depname (adrVersion adr) , ".\nReason: " , reason , "." ] allowNewer <- view $ configL.to configAllowNewer allowNewerDeps <- view $ configL.to configAllowNewerDeps let inSnapshotCheck = do -- We ignore dependency information for packages in a snapshot x <- inSnapshot (packageName package) (packageVersion package) y <- inSnapshot depname (adrVersion adr) if x && y then do warn_ "trusting snapshot over Cabal file dependency information" pure True else pure False if allowNewer then do warn_ "allow-newer enabled" case allowNewerDeps of Nothing -> pure True Just boundsIgnoredDeps -> pure $ packageName package `elem` boundsIgnoredDeps else do when (isJust allowNewerDeps) $ warn_ "allow-newer-deps are specified but allow-newer isn't enabled" inSnapshotCheck if inRange then case adr of ADRToInstall task -> pure $ Right ( Set.singleton $ taskProvides task , Map.empty, taskTargetIsMutable task ) ADRFound loc (Executable _) -> pure $ Right ( Set.empty, Map.empty , installLocationIsMutable loc ) ADRFound loc (Library ident gid _) -> pure $ Right ( Set.empty, Map.singleton ident gid , installLocationIsMutable loc ) else do mlatestApplicable <- getLatestApplicableVersionAndRev pure $ Left ( depname , ( range , mlatestApplicable , DependencyMismatch $ adrVersion adr ) ) case partitionEithers deps of Note that the Monoid for ' InstallLocation ' means that if any -- is 'Local', the result is 'Local', indicating that the parent -- package must be installed locally. Otherwise the result is -- 'Snap', indicating that the parent can either be installed -- locally or in the snapshot. ([], pairs) -> pure $ Right $ mconcat pairs (errs, _) -> pure $ Left $ DependencyPlanFailures package (Map.fromList errs) where adrVersion (ADRToInstall task) = pkgVersion $ taskProvides task adrVersion (ADRFound _ installed) = installedVersion installed -- Update the parents map, for later use in plan construction errors -- - see 'getShortestDepsPath'. addParent depname range mversion = tell mempty { wParents = MonoidMap $ Map.singleton depname val } where val = (First mversion, [(packageIdentifier package, range)]) adrHasLibrary :: AddDepRes -> Bool adrHasLibrary (ADRToInstall task) = taskHasLibrary task adrHasLibrary (ADRFound _ Library{}) = True adrHasLibrary (ADRFound _ Executable{}) = False taskHasLibrary :: Task -> Bool taskHasLibrary task = case taskType task of TTLocalMutable lp -> packageHasLibrary $ lpPackage lp TTRemotePackage _ p _ -> packageHasLibrary p -- make sure we consider internal libraries as libraries too packageHasLibrary :: Package -> Bool packageHasLibrary p = not (Set.null (packageInternalLibraries p)) || case packageLibraries p of HasLibraries _ -> True NoLibraries -> False checkDirtiness :: PackageSource -> Installed -> Package -> Map PackageIdentifier GhcPkgId -> Bool -> M Bool checkDirtiness ps installed package present buildHaddocks = do ctx <- ask moldOpts <- runRIO ctx $ tryGetFlagCache installed let configOpts = configureOpts (view envConfigL ctx) (baseConfigOpts ctx) present (psLocal ps) (installLocationIsMutable $ psLocation ps) -- should be Local i.e. mutable always package wantConfigCache = ConfigCache { configCacheOpts = configOpts , configCacheDeps = Set.fromList $ Map.elems present , configCacheComponents = case ps of PSFilePath lp -> Set.map (encodeUtf8 . renderComponent) $ lpComponents lp PSRemote{} -> Set.empty , configCacheHaddock = buildHaddocks , configCachePkgSrc = toCachePkgSrc ps , configCachePathEnvVar = pathEnvVar ctx } config = view configL ctx mreason <- case moldOpts of Nothing -> pure $ Just "old configure information not found" Just oldOpts | Just reason <- describeConfigDiff config oldOpts wantConfigCache -> pure $ Just reason | True <- psForceDirty ps -> pure $ Just "--force-dirty specified" | otherwise -> do dirty <- psDirty ps pure $ case dirty of Just files -> Just $ "local file changes: " <> addEllipsis (T.pack $ unwords $ Set.toList files) Nothing -> Nothing case mreason of Nothing -> pure False Just reason -> do tell mempty { wDirty = Map.singleton (packageName package) reason } pure True describeConfigDiff :: Config -> ConfigCache -> ConfigCache -> Maybe Text describeConfigDiff config old new | configCachePkgSrc old /= configCachePkgSrc new = Just $ "switching from " <> pkgSrcName (configCachePkgSrc old) <> " to " <> pkgSrcName (configCachePkgSrc new) | not (configCacheDeps new `Set.isSubsetOf` configCacheDeps old) = Just "dependencies changed" | not $ Set.null newComponents = Just $ "components added: " `T.append` T.intercalate ", " (map (decodeUtf8With lenientDecode) (Set.toList newComponents)) | not (configCacheHaddock old) && configCacheHaddock new = Just "rebuilding with haddocks" | oldOpts /= newOpts = Just $ T.pack $ concat [ "flags changed from " , show oldOpts , " to " , show newOpts ] | otherwise = Nothing where stripGhcOptions = go where go [] = [] go ("--ghc-option":x:xs) = go' Ghc x xs go ("--ghc-options":x:xs) = go' Ghc x xs go ((T.stripPrefix "--ghc-option=" -> Just x):xs) = go' Ghc x xs go ((T.stripPrefix "--ghc-options=" -> Just x):xs) = go' Ghc x xs go (x:xs) = x : go xs go' wc x xs = checkKeepers wc x $ go xs checkKeepers wc x xs = case filter isKeeper $ T.words x of [] -> xs keepers -> T.pack (compilerOptionsCabalFlag wc) : T.unwords keepers : xs GHC options which affect build results and therefore should always force -- a rebuild -- For the most part , we only care about options generated by Stack itself isKeeper = (== "-fhpc") -- more to be added later userOpts = filter (not . isStackOpt) . (if configRebuildGhcOptions config then id else stripGhcOptions) . map T.pack . (\(ConfigureOpts x y) -> x ++ y) . configCacheOpts (oldOpts, newOpts) = removeMatching (userOpts old) (userOpts new) removeMatching (x:xs) (y:ys) | x == y = removeMatching xs ys removeMatching xs ys = (xs, ys) newComponents = configCacheComponents new `Set.difference` configCacheComponents old pkgSrcName (CacheSrcLocal fp) = T.pack fp pkgSrcName CacheSrcUpstream = "upstream source" psForceDirty :: PackageSource -> Bool psForceDirty (PSFilePath lp) = lpForceDirty lp psForceDirty PSRemote{} = False psDirty :: (MonadIO m, HasEnvConfig env, MonadReader env m) => PackageSource -> m (Maybe (Set FilePath)) psDirty (PSFilePath lp) = runMemoizedWith $ lpDirtyFiles lp psDirty PSRemote {} = pure Nothing -- files never change in a remote package psLocal :: PackageSource -> Bool psLocal (PSFilePath _ ) = True psLocal PSRemote{} = False psLocation :: PackageSource -> InstallLocation psLocation (PSFilePath _) = Local psLocation PSRemote{} = Snap -- | Get all of the dependencies for a given package, including build -- tool dependencies. checkAndWarnForUnknownTools :: Package -> M () checkAndWarnForUnknownTools p = do -- Check whether the tool is on the PATH before warning about it. warnings <- fmap catMaybes $ forM (Set.toList $ packageUnknownTools p) $ \name@(ExeName toolName) -> do let settings = minimalEnvSettings { esIncludeLocals = True } config <- view configL menv <- liftIO $ configProcessContextSettings config settings mfound <- runRIO menv $ findExecutable $ T.unpack toolName case mfound of Left _ -> pure $ Just $ ToolWarning name (packageName p) Right _ -> pure Nothing tell mempty { wWarnings = (map toolWarningText warnings ++) } pure () -- | Warn about tools in the snapshot definition. States the tool name -- expected and the package name using it. data ToolWarning = ToolWarning ExeName PackageName deriving Show toolWarningText :: ToolWarning -> Text toolWarningText (ToolWarning (ExeName toolName) pkgName') = "No packages found in snapshot which provide a " <> T.pack (show toolName) <> " executable, which is a build-tool dependency of " <> T.pack (packageNameString pkgName') | Strip out anything from the @Plan@ intended for the local database stripLocals :: Plan -> Plan stripLocals plan = plan { planTasks = Map.filter checkTask $ planTasks plan , planFinals = Map.empty , planUnregisterLocal = Map.empty , planInstallExes = Map.filter (/= Local) $ planInstallExes plan } where checkTask task = taskLocation task == Snap stripNonDeps :: Set PackageName -> Plan -> Plan stripNonDeps deps plan = plan { planTasks = Map.filter checkTask $ planTasks plan , planFinals = Map.empty , planInstallExes = Map.empty -- TODO maybe don't disable this? } where checkTask task = taskProvides task `Set.member` missingForDeps providesDep task = pkgName (taskProvides task) `Set.member` deps missing = Map.fromList $ map (taskProvides &&& tcoMissing . taskConfigOpts) $ Map.elems (planTasks plan) missingForDeps = flip execState mempty $ for_ (Map.elems $ planTasks plan) $ \task -> when (providesDep task) $ collectMissing mempty (taskProvides task) collectMissing dependents pid = do when (pid `elem` dependents) $ impureThrow $ TaskCycleBug pid modify' (<> Set.singleton pid) mapM_ (collectMissing (pid:dependents)) (fromMaybe mempty $ Map.lookup pid missing) -- | Is the given package/version combo defined in the snapshot or in the global -- database? inSnapshot :: PackageName -> Version -> M Bool inSnapshot name version = do ctx <- ask pure $ fromMaybe False $ do ps <- Map.lookup name (combinedMap ctx) case ps of PIOnlySource (PSRemote _ srcVersion FromSnapshot _) -> pure $ srcVersion == version PIBoth (PSRemote _ srcVersion FromSnapshot _) _ -> pure $ srcVersion == version -- OnlyInstalled occurs for global database PIOnlyInstalled loc (Library pid _gid _lic) -> assert (loc == Snap) $ assert (pkgVersion pid == version) $ Just True _ -> pure False -- TODO: Consider intersecting version ranges for multiple deps on a package . This is why VersionRange is in the parent map . Switch this to ' True ' to enable some debugging putStrLn in this module planDebug :: MonadIO m => String -> m () planDebug = if False then liftIO . putStrLn else \_ -> pure ()
null
https://raw.githubusercontent.com/commercialhaskell/stack/7e35041ed27ebc9f3076d201a1c3f42dd04111db/src/Stack/Build/ConstructPlan.hs
haskell
# LANGUAGE LambdaCase # ^ This indicates that the package is already installed, and that we shouldn't build it from source. This is only the case for global packages. ^ This indicates that the package isn't installed, and we know where to find its source. ^ This indicates that the package is installed and we know where to find its source. We may want to reinstall from source. Always trust something in the snapshot ^ executable to be installed, and location where the binary is placed ^ why a local package is considered dirty ^ Warnings ^ Which packages a given package depends on, along with the package's version deps of the current targets. For local packages, this is indicated by the 'lpWanted' boolean. For extra packages to build, this comes from the @extraToBuild0@ argument of type @Set PackageName@. These are usually packages that have been specified on the command line. 'InstalledMap', or if some of its dependencies have changed. dependencies have changed. ^ locally registered ^ load upstream package | Throw an exception if there are any snapshot packages in the plan. | State to be maintained during the calculation of local packages to unregister. | Determine which packages to unregister based on the given tasks and already registered local packages. ^ Tasks ^ Reasons why packages are dirty and must be rebuilt ^ Local package database dump unregister target packages. We'll take multiple passes through the local packages. This will allow us to detect that a package should be unregistered, as well as all packages directly or transitively depending on it. ^ Current local packages to unregister. ^ Current local packages to keep. ^ Revised local packages to unregister. If any new packages were added to the unregister Map, we need to loop through the remaining packages again to detect if a transitive dependency is being unregistered. Nothing added, so we've already caught them all. Return the Map we've already calculated. Run the unregister checking function on all packages we currently think we'll be keeping. Not unregistering, add it to the keep list. Unregistering, add it to the unregister Map; and indicate that a package was in fact added to the unregister Map, so we loop again. ^ Current local packages to unregister. ^ Package identifier. ^ If package for sub library, package identifier of the parent. ^ Dependencies of the package. ^ If to be unregistered, the reason for doing so. If the package is not for a sub library, then it is directly relevant. If it is, then the relevant package is the parent. If we are planning on running a task on the relevant package, then the package must be unregistered, unless it is a target and an initial-build-steps build is being done. Check if a dependency is going to be unregistered None of the above, keep it! If the package is not for a sub library, then the relevant package identifier is that of the package. If it is, then the relevant package identifier is that of the parent. If the package is not for a sub library, then the relevant package name is that of the package. If it is, then the relevant package name is that of the parent. tests and benchmarks. If @isAllInOne@ is 'True', then this means that the build step will also build the tests. Otherwise, this indicates that there's a cyclic dependency and an additional build step needs to be done. @isAllInOne@ is 'True' (the common case), then all of these should have already been taken care of as part of the build step. local | Given a 'PackageName', adds all of the build tasks to build the package, if needed. 'constructPlan' invokes this on all the target packages, setting @treatAsDep'@ to False, because those packages are direct build targets. 'addPackageDeps' invokes this while recursing into the dependencies of a package. As such, it sets @treatAsDep'@ to True, forcing this package to be marked as a dependency, even if it is directly wanted. This makes sense - if only - dependencies build plan. recommendation available FIXME Slightly hacky, no flags since they likely won't affect executable names. This code does not feel right. Hackage Ignores ghcOptions because they don't matter for enumerating executables. Determine which components are enabled so we know which ones to copy Attempt to find a plan which performs an all-in-one build. Ignore the writer action + reset the state if it fails. test/benchmark failure could prevent library from being available to its dependencies but when it's already available it's OK to do that get looked up in the map) Reset the state to how it was before attempting to find an all-in-one build plan. Otherwise, fall back on building the tests / benchmarks in a separate step. | Checks if we need to install the given 'Package', given the results of 'addPackageDeps'. If dependencies are missing, the package is dirty, or it's not installed, then it needs to be installed. | Is the build type of the package Configure Update response in the lib map. If it is an error, and there's already an error about cyclic dependencies, prefer the cyclic error. | Given a package, recurses into all of its dependencies. The results tuple result indicates the packages that are already installed which will be used. parent package must be installed locally. Otherwise, if it is 'Snap', then it can either be installed locally or in the snapshot. ultimately we won't show any information on this to the user, we'll allow the dependency failures alone to display to avoid spamming the user too much We ignore dependency information for packages in a snapshot is 'Local', the result is 'Local', indicating that the parent package must be installed locally. Otherwise the result is 'Snap', indicating that the parent can either be installed locally or in the snapshot. Update the parents map, for later use in plan construction errors - see 'getShortestDepsPath'. make sure we consider internal libraries as libraries too should be Local i.e. mutable always a rebuild more to be added later files never change in a remote package | Get all of the dependencies for a given package, including build tool dependencies. Check whether the tool is on the PATH before warning about it. | Warn about tools in the snapshot definition. States the tool name expected and the package name using it. TODO maybe don't disable this? | Is the given package/version combo defined in the snapshot or in the global database? OnlyInstalled occurs for global database TODO: Consider intersecting version ranges for multiple deps on a
# LANGUAGE NoImplicitPrelude # # LANGUAGE OverloadedStrings # # LANGUAGE ViewPatterns # | Construct a @Plan@ for how to build module Stack.Build.ConstructPlan ( constructPlan ) where import Control.Monad.RWS.Strict hiding ( (<>) ) import qualified Data.List as L import qualified Data.Map.Merge.Strict as Map import qualified Data.Map.Strict as Map import Data.Monoid.Map ( MonoidMap(..) ) import qualified Data.Set as Set import qualified Data.Text as T import Distribution.Types.BuildType ( BuildType (Configure) ) import Distribution.Types.PackageName ( mkPackageName ) import Generics.Deriving.Monoid ( memptydefault, mappenddefault ) import Path ( parent ) import RIO.Process ( HasProcessContext (..), findExecutable ) import RIO.State ( State, execState ) import Stack.Build.Cache ( tryGetFlagCache ) import Stack.Build.Haddock ( shouldHaddockDeps ) import Stack.Build.Source ( loadLocalPackage ) import Stack.Constants ( compilerOptionsCabalFlag ) import Stack.Package ( applyForceCustomBuild ) import Stack.Prelude hiding ( loadPackage ) import Stack.SourceMap ( getPLIVersion, mkProjectPackage ) import Stack.Types.Build ( BaseConfigOpts (..), BadDependency (..) , BuildException (..), BuildPrettyException (..) , CachePkgSrc (..), ConfigCache (..), ConfigureOpts (..) , ConstructPlanException (..), IsMutable (..), ParentMap , Plan (..), Task (..), TaskConfigOpts (..), TaskType (..) , configureOpts, installLocationIsMutable, isStackOpt , taskIsTarget, taskLocation, taskTargetIsMutable , toCachePkgSrc ) import Stack.Types.Compiler ( WhichCompiler (..) ) import Stack.Types.Config ( BuildConfig (..), BuildOpts (..), BuildOptsCLI (..) , BuildSubset (..), CompilerPaths (..), Config (..) , Curator (..), DumpPackage (..), EnvConfig, EnvSettings (..) , HasBuildConfig (..), HasCompiler (..), HasConfig (..) , HasEnvConfig (..), HasGHCVariant, HasPlatform , HasRunner (..), HasSourceMap (..), minimalEnvSettings , stackRootL, stackYamlL ) import Stack.Types.Dependency ( DepValue (DepValue), DepType (AsLibrary) ) import Stack.Types.GhcPkgId ( GhcPkgId ) import Stack.Types.NamedComponent ( exeComponents, renderComponent ) import Stack.Types.Package ( ExeName (..), InstallLocation (..), Installed (..) , InstalledMap, LocalPackage (..), Package (..) , PackageLibraries (..), PackageSource (..), installedVersion , packageIdentifier, psVersion, runMemoizedWith ) import Stack.Types.SourceMap ( CommonPackage (..), DepPackage (..), FromSnapshot (..) , GlobalPackage (..), SMTargets (..), SourceMap (..) ) import Stack.Types.Version ( latestApplicableVersion, versionRangeText, withinRange ) import System.Environment ( lookupEnv ) import System.IO ( putStrLn ) data PackageInfo = PIOnlyInstalled InstallLocation Installed | PIOnlySource PackageSource | PIBoth PackageSource Installed deriving Show combineSourceInstalled :: PackageSource -> (InstallLocation, Installed) -> PackageInfo combineSourceInstalled ps (location, installed) = assert (psVersion ps == installedVersion installed) $ case location of Snap -> PIOnlyInstalled location installed Local -> PIBoth ps installed type CombinedMap = Map PackageName PackageInfo combineMap :: Map PackageName PackageSource -> InstalledMap -> CombinedMap combineMap = Map.merge (Map.mapMissing (\_ s -> PIOnlySource s)) (Map.mapMissing (\_ i -> uncurry PIOnlyInstalled i)) (Map.zipWithMatched (\_ s i -> combineSourceInstalled s i)) data AddDepRes = ADRToInstall Task | ADRFound InstallLocation Installed deriving Show data W = W { wFinals :: !(Map PackageName (Either ConstructPlanException Task)) , wInstall :: !(Map Text InstallLocation) , wDirty :: !(Map PackageName Text) , wWarnings :: !([Text] -> [Text]) , wParents :: !ParentMap } deriving Generic instance Semigroup W where (<>) = mappenddefault instance Monoid W where mempty = memptydefault mappend = (<>) TODO replace with more efficient WS stack on top of StackT Ctx W (Map PackageName (Either ConstructPlanException AddDepRes)) IO data Ctx = Ctx { baseConfigOpts :: !BaseConfigOpts , loadPackage :: !( PackageLocationImmutable -> Map FlagName Bool -> [Text] -> [Text] -> M Package ) , combinedMap :: !CombinedMap , ctxEnvConfig :: !EnvConfig , callStack :: ![PackageName] , wanted :: !(Set PackageName) , localNames :: !(Set PackageName) , mcurator :: !(Maybe Curator) , pathEnvVar :: !Text } instance HasPlatform Ctx instance HasGHCVariant Ctx instance HasLogFunc Ctx where logFuncL = configL.logFuncL instance HasRunner Ctx where runnerL = configL.runnerL instance HasStylesUpdate Ctx where stylesUpdateL = runnerL.stylesUpdateL instance HasTerm Ctx where useColorL = runnerL.useColorL termWidthL = runnerL.termWidthL instance HasConfig Ctx instance HasPantryConfig Ctx where pantryConfigL = configL.pantryConfigL instance HasProcessContext Ctx where processContextL = configL.processContextL instance HasBuildConfig Ctx instance HasSourceMap Ctx where sourceMapL = envConfigL.sourceMapL instance HasCompiler Ctx where compilerPathsL = envConfigL.compilerPathsL instance HasEnvConfig Ctx where envConfigL = lens ctxEnvConfig (\x y -> x { ctxEnvConfig = y }) | Computes a build plan . This means figuring out which build ' Task 's to take , and the interdependencies among the build ' Task 's . In particular : 1 ) It determines which packages need to be built , based on the transitive 2 ) It will only rebuild an upstream package if it is n't present in the 3 ) It will only rebuild a local package if its files are dirty or some of its constructPlan :: forall env. HasEnvConfig env => BaseConfigOpts -> ( PackageLocationImmutable -> Map FlagName Bool -> [Text] -> [Text] -> RIO EnvConfig Package ) -> SourceMap -> InstalledMap -> Bool -> RIO env Plan constructPlan baseConfigOpts0 localDumpPkgs loadPackage0 sourceMap installedMap initialBuildSteps = do logDebug "Constructing the build plan" when hasBaseInDeps $ prettyWarn $ fillSep [ flow "You are trying to upgrade or downgrade the" , style Current "base" , flow "package, which is almost certainly not what you really \ \want. Please, consider using another GHC version if you \ \need a certain version of" , style Current "base" <> "," , flow "or removing" , style Current "base" , flow "as an" , style Shell "extra-deps" <> "." , flow "For further information, see" , style Url "" <> "." ] <> line econfig <- view envConfigL globalCabalVersion <- view $ compilerPathsL.to cpCabalVersion sources <- getSources globalCabalVersion mcur <- view $ buildConfigL.to bcCurator let onTarget = void . addDep let inner = mapM_ onTarget $ Map.keys (smtTargets $ smTargets sourceMap) pathEnvVar' <- liftIO $ maybe mempty T.pack <$> lookupEnv "PATH" let ctx = mkCtx econfig globalCabalVersion sources mcur pathEnvVar' ((), m, W efinals installExes dirtyReason warnings parents) <- liftIO $ runRWST inner ctx Map.empty mapM_ (prettyWarn . fromString . T.unpack . textDisplay) (warnings []) let toEither (_, Left e) = Left e toEither (k, Right v) = Right (k, v) (errlibs, adrs) = partitionEithers $ map toEither $ Map.toList m (errfinals, finals) = partitionEithers $ map toEither $ Map.toList efinals errs = errlibs ++ errfinals if null errs then do let toTask (_, ADRFound _ _) = Nothing toTask (name, ADRToInstall task) = Just (name, task) tasks = Map.fromList $ mapMaybe toTask adrs takeSubset = case boptsCLIBuildSubset $ bcoBuildOptsCLI baseConfigOpts0 of BSAll -> pure BSOnlySnapshot -> pure . stripLocals BSOnlyDependencies -> pure . stripNonDeps (Map.keysSet $ smDeps sourceMap) BSOnlyLocals -> errorOnSnapshot takeSubset Plan { planTasks = tasks , planFinals = Map.fromList finals , planUnregisterLocal = mkUnregisterLocal tasks dirtyReason localDumpPkgs initialBuildSteps , planInstallExes = if boptsInstallExes (bcoBuildOpts baseConfigOpts0) || boptsInstallCompilerTool (bcoBuildOpts baseConfigOpts0) then installExes else Map.empty } else do planDebug $ show errs stackYaml <- view stackYamlL stackRoot <- view stackRootL prettyThrowM $ ConstructPlanFailed errs stackYaml stackRoot parents (wanted ctx) prunedGlobalDeps where hasBaseInDeps = Map.member (mkPackageName "base") (smDeps sourceMap) mkCtx econfig globalCabalVersion sources mcur pathEnvVar' = Ctx { baseConfigOpts = baseConfigOpts0 , loadPackage = \w x y z -> runRIO econfig $ applyForceCustomBuild globalCabalVersion <$> loadPackage0 w x y z , combinedMap = combineMap sources installedMap , ctxEnvConfig = econfig , callStack = [] , wanted = Map.keysSet (smtTargets $ smTargets sourceMap) , localNames = Map.keysSet (smProject sourceMap) , mcurator = mcur , pathEnvVar = pathEnvVar' } prunedGlobalDeps = flip Map.mapMaybe (smGlobal sourceMap) $ \case ReplacedGlobalPackage deps -> let pruned = filter (not . inSourceMap) deps in if null pruned then Nothing else Just pruned GlobalPackage _ -> Nothing inSourceMap pname = pname `Map.member` smDeps sourceMap || pname `Map.member` smProject sourceMap getSources globalCabalVersion = do let loadLocalPackage' pp = do lp <- loadLocalPackage pp pure lp { lpPackage = applyForceCustomBuild globalCabalVersion $ lpPackage lp } pPackages <- for (smProject sourceMap) $ \pp -> do lp <- loadLocalPackage' pp pure $ PSFilePath lp bopts <- view $ configL.to configBuild deps <- for (smDeps sourceMap) $ \dp -> case dpLocation dp of PLImmutable loc -> pure $ PSRemote loc (getPLIVersion loc) (dpFromSnapshot dp) (dpCommon dp) PLMutable dir -> do pp <- mkProjectPackage YesPrintWarnings dir (shouldHaddockDeps bopts) lp <- loadLocalPackage' pp pure $ PSFilePath lp pure $ pPackages <> deps errorOnSnapshot :: Plan -> RIO env Plan errorOnSnapshot plan@(Plan tasks _finals _unregister installExes) = do let snapTasks = Map.keys $ Map.filter (\t -> taskLocation t == Snap) tasks let snapExes = Map.keys $ Map.filter (== Snap) installExes unless (null snapTasks && null snapExes) $ throwIO $ NotOnlyLocal snapTasks snapExes pure plan data NotOnlyLocal = NotOnlyLocal [PackageName] [Text] deriving (Show, Typeable) instance Exception NotOnlyLocal where displayException (NotOnlyLocal packages exes) = concat [ "Error: [S-1727]\n" , "Specified only-locals, but I need to build snapshot contents:\n" , if null packages then "" else concat [ "Packages: " , L.intercalate ", " (map packageNameString packages) , "\n" ] , if null exes then "" else concat [ "Executables: " , L.intercalate ", " (map T.unpack exes) , "\n" ] ] data UnregisterState = UnregisterState { usToUnregister :: !(Map GhcPkgId (PackageIdentifier, Text)) , usKeep :: ![DumpPackage] , usAnyAdded :: !Bool } mkUnregisterLocal :: Map PackageName Task -> Map PackageName Text -> [DumpPackage] -> Bool ^ If true , we 're doing a special initialBuildSteps build - do n't -> Map GhcPkgId (PackageIdentifier, Text) mkUnregisterLocal tasks dirtyReason localDumpPkgs initialBuildSteps = loop Map.empty localDumpPkgs where loop :: Map GhcPkgId (PackageIdentifier, Text) -> [DumpPackage] -> Map GhcPkgId (PackageIdentifier, Text) loop toUnregister keep | usAnyAdded us = loop (usToUnregister us) (usKeep us) | otherwise = usToUnregister us where us = execState (mapM_ go keep) initialUnregisterState initialUnregisterState = UnregisterState { usToUnregister = toUnregister , usKeep = [] , usAnyAdded = False } go :: DumpPackage -> State UnregisterState () go dp = do us <- get case maybeUnregisterReason (usToUnregister us) ident mParentLibId deps of Nothing -> put us { usKeep = dp : usKeep us } Just reason -> put us { usToUnregister = Map.insert gid (ident, reason) (usToUnregister us) , usAnyAdded = True } where gid = dpGhcPkgId dp ident = dpPackageIdent dp mParentLibId = dpParentLibIdent dp deps = dpDepends dp maybeUnregisterReason :: Map GhcPkgId (PackageIdentifier, Text) -> PackageIdentifier -> Maybe PackageIdentifier -> [GhcPkgId] -> Maybe Text maybeUnregisterReason toUnregister ident mParentLibId deps | Just task <- Map.lookup relevantPkgName tasks = if initialBuildSteps && taskIsTarget task && taskProvides task == relevantPkgId then Nothing else Just $ fromMaybe "" $ Map.lookup relevantPkgName dirtyReason | (dep, _):_ <- mapMaybe (`Map.lookup` toUnregister) deps = Just $ "Dependency being unregistered: " <> T.pack (packageIdentifierString dep) | otherwise = Nothing where relevantPkgId :: PackageIdentifier relevantPkgId = fromMaybe ident mParentLibId relevantPkgName :: PackageName relevantPkgName = maybe (pkgName ident) pkgName mParentLibId | Given a ' LocalPackage ' and its ' lpTestBench ' , adds a ' Task ' for running its This will also add all the needed to build the tests / benchmarks . If addFinal :: LocalPackage -> Package -> Bool -> Bool -> M () addFinal lp package isAllInOne buildHaddocks = do depsRes <- addPackageDeps package res <- case depsRes of Left e -> pure $ Left e Right (missing, present, _minLoc) -> do ctx <- ask pure $ Right Task { taskProvides = PackageIdentifier (packageName package) (packageVersion package) , taskConfigOpts = TaskConfigOpts missing $ \missing' -> let allDeps = Map.union present missing' in configureOpts (view envConfigL ctx) (baseConfigOpts ctx) allDeps Mutable package , taskBuildHaddock = buildHaddocks , taskPresent = present , taskType = TTLocalMutable lp , taskAllInOne = isAllInOne , taskCachePkgSrc = CacheSrcLocal (toFilePath (parent (lpCabalFile lp))) , taskAnyMissing = not $ Set.null missing , taskBuildTypeConfig = packageBuildTypeConfig package } tell mempty { wFinals = Map.singleton (packageName package) res } addDep :: PackageName -> M (Either ConstructPlanException AddDepRes) addDep name = do ctx <- ask m <- get case Map.lookup name m of Just res -> do planDebug $ "addDep: Using cached result for " ++ show name ++ ": " ++ show res pure res Nothing -> do res <- if name `elem` callStack ctx then do planDebug $ "addDep: Detected cycle " <> show name <> ": " <> show (callStack ctx) pure $ Left $ DependencyCycleDetected $ name : callStack ctx else local (\ctx' -> ctx' { callStack = name : callStack ctx' }) $ do let mpackageInfo = Map.lookup name $ combinedMap ctx planDebug $ "addDep: Package info for " <> show name <> ": " <> show mpackageInfo case mpackageInfo of TODO look up in the package index and see if there 's a Nothing -> pure $ Left $ UnknownPackage name Just (PIOnlyInstalled loc installed) -> do let version = installedVersion installed askPkgLoc = liftRIO $ do mrev <- getLatestHackageRevision YesRequireHackageIndex name version case mrev of Nothing -> do this could happen for GHC boot libraries missing from prettyWarnL $ flow "No latest package revision found for" : style Current (fromString $ packageNameString name) <> "," : flow "dependency callstack:" : mkNarrativeList Nothing False ( map (fromString . packageNameString) (callStack ctx) :: [StyleDoc] ) pure Nothing Just (_rev, cfKey, treeKey) -> pure . Just $ PLIHackage (PackageIdentifier name version) cfKey treeKey tellExecutablesUpstream name askPkgLoc loc Map.empty pure $ Right $ ADRFound loc installed Just (PIOnlySource ps) -> do tellExecutables name ps installPackage name ps Nothing Just (PIBoth ps installed) -> do tellExecutables name ps installPackage name ps (Just installed) updateLibMap name res pure res FIXME what 's the purpose of this ? Add a ! tellExecutables :: PackageName -> PackageSource -> M () tellExecutables _name (PSFilePath lp) | lpWanted lp = tellExecutablesPackage Local $ lpPackage lp | otherwise = pure () tellExecutables name (PSRemote pkgloc _version _fromSnapshot cp) = tellExecutablesUpstream name (pure $ Just pkgloc) Snap (cpFlags cp) tellExecutablesUpstream :: PackageName -> M (Maybe PackageLocationImmutable) -> InstallLocation -> Map FlagName Bool -> M () tellExecutablesUpstream name retrievePkgLoc loc flags = do ctx <- ask when (name `Set.member` wanted ctx) $ do mPkgLoc <- retrievePkgLoc forM_ mPkgLoc $ \pkgLoc -> do p <- loadPackage ctx pkgLoc flags [] [] tellExecutablesPackage loc p tellExecutablesPackage :: InstallLocation -> Package -> M () tellExecutablesPackage loc p = do cm <- asks combinedMap let myComps = case Map.lookup (packageName p) cm of Nothing -> assert False Set.empty Just (PIOnlyInstalled _ _) -> Set.empty Just (PIOnlySource ps) -> goSource ps Just (PIBoth ps _) -> goSource ps goSource (PSFilePath lp) | lpWanted lp = exeComponents (lpComponents lp) | otherwise = Set.empty goSource PSRemote{} = Set.empty tell mempty { wInstall = Map.fromList $ map (, loc) $ Set.toList $ filterComps myComps $ packageExes p } where filterComps myComps x | Set.null myComps = x | otherwise = Set.intersection x myComps | Given a ' PackageSource ' and perhaps an ' Installed ' value , adds build ' Task 's for the package and its dependencies . installPackage :: PackageName -> PackageSource -> Maybe Installed -> M (Either ConstructPlanException AddDepRes) installPackage name ps minstalled = do ctx <- ask case ps of PSRemote pkgLoc _version _fromSnapshot cp -> do planDebug $ "installPackage: Doing all-in-one build for upstream package " <> show name package <- loadPackage ctx pkgLoc (cpFlags cp) (cpGhcOptions cp) (cpCabalConfigOpts cp) resolveDepsAndInstall True (cpHaddocks cp) ps package minstalled PSFilePath lp -> do case lpTestBench lp of Nothing -> do planDebug $ "installPackage: No test / bench component for " <> show name <> " so doing an all-in-one build." resolveDepsAndInstall True (lpBuildHaddocks lp) ps (lpPackage lp) minstalled Just tb -> do s <- get res <- pass $ do res <- addPackageDeps tb let writerFunc w = case res of Left _ -> mempty _ -> w pure (res, writerFunc) case res of Right deps -> do planDebug $ "installPackage: For " <> show name <> ", successfully added package deps" in curator builds we ca n't do all - in - one build as splitRequired <- expectedTestOrBenchFailures <$> asks mcurator let isAllInOne = not splitRequired adr <- installPackageGivenDeps isAllInOne (lpBuildHaddocks lp) ps tb minstalled deps let finalAllInOne = case adr of ADRToInstall _ | splitRequired -> False _ -> True FIXME : this redundantly adds the ( but they 'll all just addFinal lp tb finalAllInOne False pure $ Right adr Left _ -> do planDebug $ "installPackage: Before trying cyclic plan, resetting lib \ \result map to " <> show s put s res' <- resolveDepsAndInstall False (lpBuildHaddocks lp) ps (lpPackage lp) minstalled when (isRight res') $ do Insert it into the map so that it 's available for addFinal . updateLibMap name res' addFinal lp tb False False pure res' where expectedTestOrBenchFailures maybeCurator = fromMaybe False $ do curator <- maybeCurator pure $ Set.member name (curatorExpectTestFailure curator) || Set.member name (curatorExpectBenchmarkFailure curator) resolveDepsAndInstall :: Bool -> Bool -> PackageSource -> Package -> Maybe Installed -> M (Either ConstructPlanException AddDepRes) resolveDepsAndInstall isAllInOne buildHaddocks ps package minstalled = do res <- addPackageDeps package case res of Left err -> pure $ Left err Right deps -> Right <$> installPackageGivenDeps isAllInOne buildHaddocks ps package minstalled deps installPackageGivenDeps :: Bool -> Bool -> PackageSource -> Package -> Maybe Installed -> ( Set PackageIdentifier , Map PackageIdentifier GhcPkgId , IsMutable ) -> M AddDepRes installPackageGivenDeps isAllInOne buildHaddocks ps package minstalled (missing, present, minMutable) = do let name = packageName package ctx <- ask mRightVersionInstalled <- case (minstalled, Set.null missing) of (Just installed, True) -> do shouldInstall <- checkDirtiness ps installed package present buildHaddocks pure $ if shouldInstall then Nothing else Just installed (Just _, False) -> do let t = T.intercalate ", " $ map (T.pack . packageNameString . pkgName) (Set.toList missing) tell mempty { wDirty = Map.singleton name $ "missing dependencies: " <> addEllipsis t } pure Nothing (Nothing, _) -> pure Nothing let loc = psLocation ps mutable = installLocationIsMutable loc <> minMutable pure $ case mRightVersionInstalled of Just installed -> ADRFound loc installed Nothing -> ADRToInstall Task { taskProvides = PackageIdentifier (packageName package) (packageVersion package) , taskConfigOpts = TaskConfigOpts missing $ \missing' -> let allDeps = Map.union present missing' in configureOpts (view envConfigL ctx) (baseConfigOpts ctx) allDeps (psLocal ps) mutable package , taskBuildHaddock = buildHaddocks , taskPresent = present , taskType = case ps of PSFilePath lp -> TTLocalMutable lp PSRemote pkgLoc _version _fromSnapshot _cp -> TTRemotePackage mutable package pkgLoc , taskAllInOne = isAllInOne , taskCachePkgSrc = toCachePkgSrc ps , taskAnyMissing = not $ Set.null missing , taskBuildTypeConfig = packageBuildTypeConfig package } packageBuildTypeConfig :: Package -> Bool packageBuildTypeConfig pkg = packageBuildType pkg == Configure updateLibMap :: PackageName -> Either ConstructPlanException AddDepRes -> M () updateLibMap name val = modify $ \mp -> case (Map.lookup name mp, val) of (Just (Left DependencyCycleDetected{}), Left _) -> mp _ -> Map.insert name val mp addEllipsis :: Text -> Text addEllipsis t | T.length t < 100 = t | otherwise = T.take 97 t <> "..." indicate which packages are missing , meaning that their ' GhcPkgId 's will be figured out during the build , after they 've been built . The 2nd part of the The 3rd part of the tuple is an ' InstallLocation ' . If it is ' Local ' , then the addPackageDeps :: Package -> M ( Either ConstructPlanException ( Set PackageIdentifier , Map PackageIdentifier GhcPkgId , IsMutable ) ) addPackageDeps package = do ctx <- ask checkAndWarnForUnknownTools package let deps' = packageDeps package deps <- forM (Map.toList deps') $ \(depname, DepValue range depType) -> do eres <- addDep depname let getLatestApplicableVersionAndRev :: M (Maybe (Version, BlobKey)) getLatestApplicableVersionAndRev = do vsAndRevs <- runRIO ctx $ getHackagePackageVersions YesRequireHackageIndex UsePreferredVersions depname pure $ do lappVer <- latestApplicableVersion range $ Map.keysSet vsAndRevs revs <- Map.lookup lappVer vsAndRevs (cabalHash, _) <- Map.maxView revs Just (lappVer, cabalHash) case eres of Left e -> do addParent depname range Nothing let bd = case e of UnknownPackage name -> assert (name == depname) NotInBuildPlan DependencyCycleDetected names -> BDDependencyCycleDetected names DependencyPlanFailures _ _ -> Couldn'tResolveItsDependencies (packageVersion package) mlatestApplicable <- getLatestApplicableVersionAndRev pure $ Left (depname, (range, mlatestApplicable, bd)) Right adr | depType == AsLibrary && not (adrHasLibrary adr) -> pure $ Left (depname, (range, Nothing, HasNoLibrary)) Right adr -> do addParent depname range Nothing inRange <- if adrVersion adr `withinRange` range then pure True else do let warn_ reason = tell mempty { wWarnings = (msg:) } where msg = T.concat [ "WARNING: Ignoring " , T.pack $ packageNameString $ packageName package , "'s bounds on " , T.pack $ packageNameString depname , " (" , versionRangeText range , "); using " , T.pack $ packageIdentifierString $ PackageIdentifier depname (adrVersion adr) , ".\nReason: " , reason , "." ] allowNewer <- view $ configL.to configAllowNewer allowNewerDeps <- view $ configL.to configAllowNewerDeps let inSnapshotCheck = do x <- inSnapshot (packageName package) (packageVersion package) y <- inSnapshot depname (adrVersion adr) if x && y then do warn_ "trusting snapshot over Cabal file dependency information" pure True else pure False if allowNewer then do warn_ "allow-newer enabled" case allowNewerDeps of Nothing -> pure True Just boundsIgnoredDeps -> pure $ packageName package `elem` boundsIgnoredDeps else do when (isJust allowNewerDeps) $ warn_ "allow-newer-deps are specified but allow-newer isn't enabled" inSnapshotCheck if inRange then case adr of ADRToInstall task -> pure $ Right ( Set.singleton $ taskProvides task , Map.empty, taskTargetIsMutable task ) ADRFound loc (Executable _) -> pure $ Right ( Set.empty, Map.empty , installLocationIsMutable loc ) ADRFound loc (Library ident gid _) -> pure $ Right ( Set.empty, Map.singleton ident gid , installLocationIsMutable loc ) else do mlatestApplicable <- getLatestApplicableVersionAndRev pure $ Left ( depname , ( range , mlatestApplicable , DependencyMismatch $ adrVersion adr ) ) case partitionEithers deps of Note that the Monoid for ' InstallLocation ' means that if any ([], pairs) -> pure $ Right $ mconcat pairs (errs, _) -> pure $ Left $ DependencyPlanFailures package (Map.fromList errs) where adrVersion (ADRToInstall task) = pkgVersion $ taskProvides task adrVersion (ADRFound _ installed) = installedVersion installed addParent depname range mversion = tell mempty { wParents = MonoidMap $ Map.singleton depname val } where val = (First mversion, [(packageIdentifier package, range)]) adrHasLibrary :: AddDepRes -> Bool adrHasLibrary (ADRToInstall task) = taskHasLibrary task adrHasLibrary (ADRFound _ Library{}) = True adrHasLibrary (ADRFound _ Executable{}) = False taskHasLibrary :: Task -> Bool taskHasLibrary task = case taskType task of TTLocalMutable lp -> packageHasLibrary $ lpPackage lp TTRemotePackage _ p _ -> packageHasLibrary p packageHasLibrary :: Package -> Bool packageHasLibrary p = not (Set.null (packageInternalLibraries p)) || case packageLibraries p of HasLibraries _ -> True NoLibraries -> False checkDirtiness :: PackageSource -> Installed -> Package -> Map PackageIdentifier GhcPkgId -> Bool -> M Bool checkDirtiness ps installed package present buildHaddocks = do ctx <- ask moldOpts <- runRIO ctx $ tryGetFlagCache installed let configOpts = configureOpts (view envConfigL ctx) (baseConfigOpts ctx) present (psLocal ps) package wantConfigCache = ConfigCache { configCacheOpts = configOpts , configCacheDeps = Set.fromList $ Map.elems present , configCacheComponents = case ps of PSFilePath lp -> Set.map (encodeUtf8 . renderComponent) $ lpComponents lp PSRemote{} -> Set.empty , configCacheHaddock = buildHaddocks , configCachePkgSrc = toCachePkgSrc ps , configCachePathEnvVar = pathEnvVar ctx } config = view configL ctx mreason <- case moldOpts of Nothing -> pure $ Just "old configure information not found" Just oldOpts | Just reason <- describeConfigDiff config oldOpts wantConfigCache -> pure $ Just reason | True <- psForceDirty ps -> pure $ Just "--force-dirty specified" | otherwise -> do dirty <- psDirty ps pure $ case dirty of Just files -> Just $ "local file changes: " <> addEllipsis (T.pack $ unwords $ Set.toList files) Nothing -> Nothing case mreason of Nothing -> pure False Just reason -> do tell mempty { wDirty = Map.singleton (packageName package) reason } pure True describeConfigDiff :: Config -> ConfigCache -> ConfigCache -> Maybe Text describeConfigDiff config old new | configCachePkgSrc old /= configCachePkgSrc new = Just $ "switching from " <> pkgSrcName (configCachePkgSrc old) <> " to " <> pkgSrcName (configCachePkgSrc new) | not (configCacheDeps new `Set.isSubsetOf` configCacheDeps old) = Just "dependencies changed" | not $ Set.null newComponents = Just $ "components added: " `T.append` T.intercalate ", " (map (decodeUtf8With lenientDecode) (Set.toList newComponents)) | not (configCacheHaddock old) && configCacheHaddock new = Just "rebuilding with haddocks" | oldOpts /= newOpts = Just $ T.pack $ concat [ "flags changed from " , show oldOpts , " to " , show newOpts ] | otherwise = Nothing where stripGhcOptions = go where go [] = [] go ("--ghc-option":x:xs) = go' Ghc x xs go ("--ghc-options":x:xs) = go' Ghc x xs go ((T.stripPrefix "--ghc-option=" -> Just x):xs) = go' Ghc x xs go ((T.stripPrefix "--ghc-options=" -> Just x):xs) = go' Ghc x xs go (x:xs) = x : go xs go' wc x xs = checkKeepers wc x $ go xs checkKeepers wc x xs = case filter isKeeper $ T.words x of [] -> xs keepers -> T.pack (compilerOptionsCabalFlag wc) : T.unwords keepers : xs GHC options which affect build results and therefore should always force For the most part , we only care about options generated by Stack itself userOpts = filter (not . isStackOpt) . (if configRebuildGhcOptions config then id else stripGhcOptions) . map T.pack . (\(ConfigureOpts x y) -> x ++ y) . configCacheOpts (oldOpts, newOpts) = removeMatching (userOpts old) (userOpts new) removeMatching (x:xs) (y:ys) | x == y = removeMatching xs ys removeMatching xs ys = (xs, ys) newComponents = configCacheComponents new `Set.difference` configCacheComponents old pkgSrcName (CacheSrcLocal fp) = T.pack fp pkgSrcName CacheSrcUpstream = "upstream source" psForceDirty :: PackageSource -> Bool psForceDirty (PSFilePath lp) = lpForceDirty lp psForceDirty PSRemote{} = False psDirty :: (MonadIO m, HasEnvConfig env, MonadReader env m) => PackageSource -> m (Maybe (Set FilePath)) psDirty (PSFilePath lp) = runMemoizedWith $ lpDirtyFiles lp psLocal :: PackageSource -> Bool psLocal (PSFilePath _ ) = True psLocal PSRemote{} = False psLocation :: PackageSource -> InstallLocation psLocation (PSFilePath _) = Local psLocation PSRemote{} = Snap checkAndWarnForUnknownTools :: Package -> M () checkAndWarnForUnknownTools p = do warnings <- fmap catMaybes $ forM (Set.toList $ packageUnknownTools p) $ \name@(ExeName toolName) -> do let settings = minimalEnvSettings { esIncludeLocals = True } config <- view configL menv <- liftIO $ configProcessContextSettings config settings mfound <- runRIO menv $ findExecutable $ T.unpack toolName case mfound of Left _ -> pure $ Just $ ToolWarning name (packageName p) Right _ -> pure Nothing tell mempty { wWarnings = (map toolWarningText warnings ++) } pure () data ToolWarning = ToolWarning ExeName PackageName deriving Show toolWarningText :: ToolWarning -> Text toolWarningText (ToolWarning (ExeName toolName) pkgName') = "No packages found in snapshot which provide a " <> T.pack (show toolName) <> " executable, which is a build-tool dependency of " <> T.pack (packageNameString pkgName') | Strip out anything from the @Plan@ intended for the local database stripLocals :: Plan -> Plan stripLocals plan = plan { planTasks = Map.filter checkTask $ planTasks plan , planFinals = Map.empty , planUnregisterLocal = Map.empty , planInstallExes = Map.filter (/= Local) $ planInstallExes plan } where checkTask task = taskLocation task == Snap stripNonDeps :: Set PackageName -> Plan -> Plan stripNonDeps deps plan = plan { planTasks = Map.filter checkTask $ planTasks plan , planFinals = Map.empty } where checkTask task = taskProvides task `Set.member` missingForDeps providesDep task = pkgName (taskProvides task) `Set.member` deps missing = Map.fromList $ map (taskProvides &&& tcoMissing . taskConfigOpts) $ Map.elems (planTasks plan) missingForDeps = flip execState mempty $ for_ (Map.elems $ planTasks plan) $ \task -> when (providesDep task) $ collectMissing mempty (taskProvides task) collectMissing dependents pid = do when (pid `elem` dependents) $ impureThrow $ TaskCycleBug pid modify' (<> Set.singleton pid) mapM_ (collectMissing (pid:dependents)) (fromMaybe mempty $ Map.lookup pid missing) inSnapshot :: PackageName -> Version -> M Bool inSnapshot name version = do ctx <- ask pure $ fromMaybe False $ do ps <- Map.lookup name (combinedMap ctx) case ps of PIOnlySource (PSRemote _ srcVersion FromSnapshot _) -> pure $ srcVersion == version PIBoth (PSRemote _ srcVersion FromSnapshot _) _ -> pure $ srcVersion == version PIOnlyInstalled loc (Library pid _gid _lic) -> assert (loc == Snap) $ assert (pkgVersion pid == version) $ Just True _ -> pure False package . This is why VersionRange is in the parent map . Switch this to ' True ' to enable some debugging putStrLn in this module planDebug :: MonadIO m => String -> m () planDebug = if False then liftIO . putStrLn else \_ -> pure ()
547bee41c74af46c9a38de2477c13ab7a2c7610293d39f24591edd3e4a6c5173
mpickering/gitlab-triage
SetupMode.hs
{-# LANGUAGE OverloadedStrings #-} module SetupMode where import Brick hiding (continue, halt) import Brick.Forms import qualified Graphics.Vty as V import qualified Brick.Main as M import qualified Brick.Types as T import qualified Brick.Widgets.Border as B import qualified Brick.Widgets.Center as C import Brick.Types ( Widget ) import Control.Monad.IO.Class (liftIO) import Control.Applicative.Combinators () import Config import Model import SetupForm import Common drawSetup :: Form UserConfig e Name -> FilePath -> [Widget Name] drawSetup form cfg = [ui, background] where background = fill '@' formBox = C.center . joinBorders . B.border . hLimitPercent 75 . vLimit 5 $ renderForm form ui = formBox <=> fileFooter <=> setupFooter fileFooter = txt "Config will be written to: " <+> str cfg setupFooter = vLimit 1 $ txt "esc - quit; tab - next field; enter - submit" setupHandler :: SetupForm -> FilePath -> Handler AppState setupHandler f cfg _ e = do f' <- handleFormEvent e f let s' = AppState (Setup f' cfg) case e of T.VtyEvent (V.EvKey V.KEnter []) -> if allFieldsValid f' then do let c = formState f' liftIO $ writeConfig c liftIO (initialise c) >>= M.continue else M.continue s' T.VtyEvent (V.EvKey V.KEsc []) -> M.halt s' _ -> M.continue s'
null
https://raw.githubusercontent.com/mpickering/gitlab-triage/3586b1d62b7775282bd95775f1114084cd29ae4f/main/SetupMode.hs
haskell
# LANGUAGE OverloadedStrings #
module SetupMode where import Brick hiding (continue, halt) import Brick.Forms import qualified Graphics.Vty as V import qualified Brick.Main as M import qualified Brick.Types as T import qualified Brick.Widgets.Border as B import qualified Brick.Widgets.Center as C import Brick.Types ( Widget ) import Control.Monad.IO.Class (liftIO) import Control.Applicative.Combinators () import Config import Model import SetupForm import Common drawSetup :: Form UserConfig e Name -> FilePath -> [Widget Name] drawSetup form cfg = [ui, background] where background = fill '@' formBox = C.center . joinBorders . B.border . hLimitPercent 75 . vLimit 5 $ renderForm form ui = formBox <=> fileFooter <=> setupFooter fileFooter = txt "Config will be written to: " <+> str cfg setupFooter = vLimit 1 $ txt "esc - quit; tab - next field; enter - submit" setupHandler :: SetupForm -> FilePath -> Handler AppState setupHandler f cfg _ e = do f' <- handleFormEvent e f let s' = AppState (Setup f' cfg) case e of T.VtyEvent (V.EvKey V.KEnter []) -> if allFieldsValid f' then do let c = formState f' liftIO $ writeConfig c liftIO (initialise c) >>= M.continue else M.continue s' T.VtyEvent (V.EvKey V.KEsc []) -> M.halt s' _ -> M.continue s'
eb7be5c4c19cb034706a7042ee43fcb3bff000c7f407aae021ba33d06c9f5454
c4-project/c4f
import.ml
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) (** Common imports *) module Accessor = Accessor_base include Accessor.O module Src = C4f_fir_gen module Q = Base_quickcheck module Fir = C4f_fir module Fir_test = C4f_fir_test module Utils = C4f_utils
null
https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/fir_gen/test/import.ml
ocaml
* Common imports
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) module Accessor = Accessor_base include Accessor.O module Src = C4f_fir_gen module Q = Base_quickcheck module Fir = C4f_fir module Fir_test = C4f_fir_test module Utils = C4f_utils
4883e1fb4c7a52176d500ac6a56010b6436e44d6494e65950172ed48e613dd45
tsoding/aoc-2019
Main.hs
module Main where import Data.List import Text.Printf isValid1 :: Int -> Bool isValid1 x = isIncreasing && containsDouble where s = show x isIncreasing = s == sort s containsDouble = length (nub s) < length s isValid2 :: Int -> Bool isValid2 x = isIncreasing && containsDoubleGroup where s = show x isIncreasing = s == sort s containsDoubleGroup = not $ null $ filter (== 2) $ map length $ group s solve :: (Int, Int) -> (Int -> Bool) -> Int solve (low, high) isValid = length $ filter isValid [low .. high] main :: IO () main = do let input = (245182, 790572) printf "Part 1: %d\n" $ solve input isValid1 printf "Part 2: %d\n" $ solve input isValid2
null
https://raw.githubusercontent.com/tsoding/aoc-2019/bd186aa96558676a4380a465351b877dbaae261d/04/Main.hs
haskell
module Main where import Data.List import Text.Printf isValid1 :: Int -> Bool isValid1 x = isIncreasing && containsDouble where s = show x isIncreasing = s == sort s containsDouble = length (nub s) < length s isValid2 :: Int -> Bool isValid2 x = isIncreasing && containsDoubleGroup where s = show x isIncreasing = s == sort s containsDoubleGroup = not $ null $ filter (== 2) $ map length $ group s solve :: (Int, Int) -> (Int -> Bool) -> Int solve (low, high) isValid = length $ filter isValid [low .. high] main :: IO () main = do let input = (245182, 790572) printf "Part 1: %d\n" $ solve input isValid1 printf "Part 2: %d\n" $ solve input isValid2
3cf04054e62f97dd19307ebf34e1b0923a20275b0b4e6c802a04b119537c3d2d
racket/htdp
test-abbrev.rkt
#lang racket (require (for-syntax scheme/mpair)) (provide t) t : eli 's convenient short - cut syntactic form for defining tests . ;; here's an example of how you might use it: ( let * ( [ defs1 ` ( ( define ( a x ) ( + x 5 ) ) ( define b a ) ) ] [defs2 (append defs1 `((define c a)))]) (t 'top-ref4 m:intermediate ,@defs1 (define c b) (c 3) :: ,@defs1 (define c {b}) -> ,@defs1 (define c {a}) :: ,@defs2 ({c} 3) -> ,@defs2 ({a} 3) :: ,@defs2 {(a 3)} -> ,@defs2 {(+ 3 5)} -> ,@defs2 {8})) (define-syntax (t stx) (define (maybe-mlist->list r) (if (mpair? r) (mlist->list r) r)) (define (split l) (let loop ([l l] [r '()]) (cond [(null? l) (reverse (map maybe-mlist->list r))] [(symbol? (car l)) (loop (cdr l) (cons (car l) r))] [(or (null? r) (not (mpair? (car r)))) (loop (cdr l) (cons (mlist (car l)) r))] [else (mappend! (car r) (mlist (car l))) (loop (cdr l) r)]))) (define (process-hilites s) (syntax-case s () [(x) (eq? #\{ (syntax-property s 'paren-shape)) (with-syntax ([x (process-hilites #'x)]) #'(hilite x))] [(x . y) (let* ([x0 #'x] [y0 #'y] [x1 (process-hilites #'x)] [y1 (process-hilites #'y)]) (if (and (eq? x0 x1) (eq? y0 y1)) s (with-syntax ([x x1] [y y1]) #'(x . y))))] [_else s])) (define (process stx) (split (map (lambda (s) (if (and (identifier? s) (memq (syntax-e s) '(:: -> error:))) (syntax-e s) (process-hilites s))) (syntax->list stx)))) (define (parse l) (syntax-case l (::) [(fst :: rest ...) (cons #'fst (let loop ([rest #'(rest ...)]) (syntax-case rest (:: -> error:) [(error: (err)) (list #'(error err))] [() (list #'(finished-stepping))] [(x -> y) (list #'(before-after x y) #'(finished-stepping))] [(x -> error: (err)) (list #'(before-error x err))] [(x -> y :: . rest) (cons #'(before-after x y) (loop #'rest))] [(x -> y -> . rest) (cons #'(before-after x y) (loop #'(y -> . rest)))])))])) (syntax-case stx (::) [(_ name ll-models . rest) (with-syntax ([(exprs arg ...) (parse (process #'rest))]) (quasisyntax/loc stx (list name ll-models ;printf "exprs = ~s\n args = ~s\n" (exprs->string `exprs) `(arg ...) '())))])) ( - > ( listof sexp ) string ? ) (define (exprs->string exprs) (apply string-append (cdr (apply append (map (lambda (x) (list " " (format "~s" x))) exprs)))))
null
https://raw.githubusercontent.com/racket/htdp/aa78794fa1788358d6abd11dad54b3c9f4f5a80b/htdp-test/tests/stepper/test-abbrev.rkt
racket
here's an example of how you might use it: printf "exprs = ~s\n args = ~s\n"
#lang racket (require (for-syntax scheme/mpair)) (provide t) t : eli 's convenient short - cut syntactic form for defining tests . ( let * ( [ defs1 ` ( ( define ( a x ) ( + x 5 ) ) ( define b a ) ) ] [defs2 (append defs1 `((define c a)))]) (t 'top-ref4 m:intermediate ,@defs1 (define c b) (c 3) :: ,@defs1 (define c {b}) -> ,@defs1 (define c {a}) :: ,@defs2 ({c} 3) -> ,@defs2 ({a} 3) :: ,@defs2 {(a 3)} -> ,@defs2 {(+ 3 5)} -> ,@defs2 {8})) (define-syntax (t stx) (define (maybe-mlist->list r) (if (mpair? r) (mlist->list r) r)) (define (split l) (let loop ([l l] [r '()]) (cond [(null? l) (reverse (map maybe-mlist->list r))] [(symbol? (car l)) (loop (cdr l) (cons (car l) r))] [(or (null? r) (not (mpair? (car r)))) (loop (cdr l) (cons (mlist (car l)) r))] [else (mappend! (car r) (mlist (car l))) (loop (cdr l) r)]))) (define (process-hilites s) (syntax-case s () [(x) (eq? #\{ (syntax-property s 'paren-shape)) (with-syntax ([x (process-hilites #'x)]) #'(hilite x))] [(x . y) (let* ([x0 #'x] [y0 #'y] [x1 (process-hilites #'x)] [y1 (process-hilites #'y)]) (if (and (eq? x0 x1) (eq? y0 y1)) s (with-syntax ([x x1] [y y1]) #'(x . y))))] [_else s])) (define (process stx) (split (map (lambda (s) (if (and (identifier? s) (memq (syntax-e s) '(:: -> error:))) (syntax-e s) (process-hilites s))) (syntax->list stx)))) (define (parse l) (syntax-case l (::) [(fst :: rest ...) (cons #'fst (let loop ([rest #'(rest ...)]) (syntax-case rest (:: -> error:) [(error: (err)) (list #'(error err))] [() (list #'(finished-stepping))] [(x -> y) (list #'(before-after x y) #'(finished-stepping))] [(x -> error: (err)) (list #'(before-error x err))] [(x -> y :: . rest) (cons #'(before-after x y) (loop #'rest))] [(x -> y -> . rest) (cons #'(before-after x y) (loop #'(y -> . rest)))])))])) (syntax-case stx (::) [(_ name ll-models . rest) (with-syntax ([(exprs arg ...) (parse (process #'rest))]) (quasisyntax/loc stx (list name ll-models (exprs->string `exprs) `(arg ...) '())))])) ( - > ( listof sexp ) string ? ) (define (exprs->string exprs) (apply string-append (cdr (apply append (map (lambda (x) (list " " (format "~s" x))) exprs)))))
8fcd6d595a0cfdd34370f1cb1476c0c99d0a5fba056314f9c78f49018a95a71d
bendlas/davstore
app.clj
(ns davstore.app (:require [clojure.java.io :as io] [clojure.pprint :refer [pprint]] [clojure.tools.logging :as log] [datomic.api :refer [delete-database]] [davstore.blob :as blob] [davstore.dav :as dav] [davstore.store :as store] [net.cgrand.moustache :refer [app uri-segments path-info-segments uri]] [ring.middleware.head :refer [wrap-head]] [ring.util.response :refer [response header status content-type not-found]])) ;; Middlewares (defn wrap-store [h blob-path db-uri root-uuid root-uri] (let [store (blob/make-store blob-path) dstore (assoc (store/init-store! db-uri store root-uuid true) :root-dir root-uri)] (fn [req] (h (assoc req ::store (store/open-db dstore) ::bstore store))))) (defn wrap-root [h] (fn [req] (let [uri-segs (uri-segments req) path-segs (path-info-segments req) n (- (count uri-segs) (count path-segs))] (h (assoc req :root-path (take n uri-segs)))))) ;; Handlers (def blob-handler "Unused for WebDAV, but useful if you want to serve stable, infinitely cacheable names, say for a CDN." (app [] {:post (fn [{body :body store ::bstore :as req}] (let [{:keys [tempfile sha-1] :as res} (blob/store-temp store body) created (blob/merge-temp store res) uri (dav/pjoin (:uri req) sha-1)] (-> (response sha-1) (header "location" uri) (header "etag" (str \" sha-1 \")) (status (if created 201 302)))))} [sha-1] {:get (fn [req] (if-let [f (blob/get-file (::bstore req) sha-1)] (-> (response f) (content-type "application/octet-stream") (header "etag" (str \" sha-1 \"))) (not-found "Blob not found")))})) (def file-handler (app wrap-root wrap-head dav/wrap-errors [& path] {:options (dav/options path) :propfind (dav/propfind path) :get (dav/read path) :mkcol (dav/mkcol path) :copy (dav/copy path) :move (dav/move path) :delete (dav/delete path) :put (dav/put path) :proppatch (dav/proppatch path) :lock (dav/lock path) :unlock (dav/unlock path)})) (def blob-dir "/tmp/davstore-app") (def db-uri "datomic:mem-app") (def root-id #uuid "7178245f-5e6c-30fb-8175-c265b9fe6cb8") (defn wrap-log [h] (fn [req] (let [bos (java.io.ByteArrayOutputStream.) _ (when-let [body (:body req)] (io/copy body bos)) bs (.toByteArray bos) _ (log/debug (:request-method req) (:uri req) "\nHEADERS:" (with-out-str (pprint (:headers req))) "BODY:" (str \' (String. bs "UTF-8") \')) resp (h (assoc req :body (java.io.ByteArrayInputStream. bs)))] (log/debug " => RESPONSE" (with-out-str (pprint resp))) resp))) (defn wrap-log-light [h] (fn [req] (try (let [resp (h req)] (log/debug (.toUpperCase (name (:request-method req))) (:uri req) " => " (:status resp)) resp) (catch Exception e (log/error e (.toUpperCase (name (:request-method req))) (:uri req) " => " 500))))) (defn wrap-access-control [h allow-origin] (let [hdr {"access-control-allow-origin" allow-origin "access-control-allow-credentials" "true" "access-control-allow-methods" "OPTIONS,GET,PUT,DELETE,PROPFIND,REPORT,MOVE,COPY,PROPPATCH,MKCOL" "access-control-allow-headers" "Content-Type,Depth,Cache-Control,X-Requested-With,If-Modified-Since,If-Match,If,X-File-Name,X-File-Size,Destination,Overwrite,Authorization" "dav" "2"}] (fn [req] (if (= :options (:request-method req)) {:status 204 :headers hdr} (update-in (h req) [:headers] #(merge hdr %)))))) Quick and embedded dav server (require '[ring.adapter.jetty :as rj]) (declare davstore) (defonce server (agent nil)) (defn start-server! [] (def davstore (app (wrap-store blob-dir db-uri root-id "/files") wrap-log-light (wrap-access-control ":8080") ["blob" &] blob-handler ["files" &] file-handler ["debug"] (fn [req] {:status 400 :debug req}))) (send server (fn [s] (assert (not s)) (rj/run-jetty #'davstore {:port 8082 :join? false})))) (defn stop-server! [] (send server (fn [s] (.stop s) nil))) (defn get-handler-store ([] (get-handler-store davstore)) ([h] (::store (:debug (h {:request-method :debug :uri "/debug"})))))
null
https://raw.githubusercontent.com/bendlas/davstore/f8af4849c04c0404ebd0d6b000ef3b2bcd641d0b/src/davstore/app.clj
clojure
Middlewares Handlers
(ns davstore.app (:require [clojure.java.io :as io] [clojure.pprint :refer [pprint]] [clojure.tools.logging :as log] [datomic.api :refer [delete-database]] [davstore.blob :as blob] [davstore.dav :as dav] [davstore.store :as store] [net.cgrand.moustache :refer [app uri-segments path-info-segments uri]] [ring.middleware.head :refer [wrap-head]] [ring.util.response :refer [response header status content-type not-found]])) (defn wrap-store [h blob-path db-uri root-uuid root-uri] (let [store (blob/make-store blob-path) dstore (assoc (store/init-store! db-uri store root-uuid true) :root-dir root-uri)] (fn [req] (h (assoc req ::store (store/open-db dstore) ::bstore store))))) (defn wrap-root [h] (fn [req] (let [uri-segs (uri-segments req) path-segs (path-info-segments req) n (- (count uri-segs) (count path-segs))] (h (assoc req :root-path (take n uri-segs)))))) (def blob-handler "Unused for WebDAV, but useful if you want to serve stable, infinitely cacheable names, say for a CDN." (app [] {:post (fn [{body :body store ::bstore :as req}] (let [{:keys [tempfile sha-1] :as res} (blob/store-temp store body) created (blob/merge-temp store res) uri (dav/pjoin (:uri req) sha-1)] (-> (response sha-1) (header "location" uri) (header "etag" (str \" sha-1 \")) (status (if created 201 302)))))} [sha-1] {:get (fn [req] (if-let [f (blob/get-file (::bstore req) sha-1)] (-> (response f) (content-type "application/octet-stream") (header "etag" (str \" sha-1 \"))) (not-found "Blob not found")))})) (def file-handler (app wrap-root wrap-head dav/wrap-errors [& path] {:options (dav/options path) :propfind (dav/propfind path) :get (dav/read path) :mkcol (dav/mkcol path) :copy (dav/copy path) :move (dav/move path) :delete (dav/delete path) :put (dav/put path) :proppatch (dav/proppatch path) :lock (dav/lock path) :unlock (dav/unlock path)})) (def blob-dir "/tmp/davstore-app") (def db-uri "datomic:mem-app") (def root-id #uuid "7178245f-5e6c-30fb-8175-c265b9fe6cb8") (defn wrap-log [h] (fn [req] (let [bos (java.io.ByteArrayOutputStream.) _ (when-let [body (:body req)] (io/copy body bos)) bs (.toByteArray bos) _ (log/debug (:request-method req) (:uri req) "\nHEADERS:" (with-out-str (pprint (:headers req))) "BODY:" (str \' (String. bs "UTF-8") \')) resp (h (assoc req :body (java.io.ByteArrayInputStream. bs)))] (log/debug " => RESPONSE" (with-out-str (pprint resp))) resp))) (defn wrap-log-light [h] (fn [req] (try (let [resp (h req)] (log/debug (.toUpperCase (name (:request-method req))) (:uri req) " => " (:status resp)) resp) (catch Exception e (log/error e (.toUpperCase (name (:request-method req))) (:uri req) " => " 500))))) (defn wrap-access-control [h allow-origin] (let [hdr {"access-control-allow-origin" allow-origin "access-control-allow-credentials" "true" "access-control-allow-methods" "OPTIONS,GET,PUT,DELETE,PROPFIND,REPORT,MOVE,COPY,PROPPATCH,MKCOL" "access-control-allow-headers" "Content-Type,Depth,Cache-Control,X-Requested-With,If-Modified-Since,If-Match,If,X-File-Name,X-File-Size,Destination,Overwrite,Authorization" "dav" "2"}] (fn [req] (if (= :options (:request-method req)) {:status 204 :headers hdr} (update-in (h req) [:headers] #(merge hdr %)))))) Quick and embedded dav server (require '[ring.adapter.jetty :as rj]) (declare davstore) (defonce server (agent nil)) (defn start-server! [] (def davstore (app (wrap-store blob-dir db-uri root-id "/files") wrap-log-light (wrap-access-control ":8080") ["blob" &] blob-handler ["files" &] file-handler ["debug"] (fn [req] {:status 400 :debug req}))) (send server (fn [s] (assert (not s)) (rj/run-jetty #'davstore {:port 8082 :join? false})))) (defn stop-server! [] (send server (fn [s] (.stop s) nil))) (defn get-handler-store ([] (get-handler-store davstore)) ([h] (::store (:debug (h {:request-method :debug :uri "/debug"})))))
1f7de930c5fead456961e41c160b08ef6748d6c4c77e6f59882ae4846ed0bf33
kaoskorobase/mescaline
ProbabilisticSuffixTree.hs
module Data.ProbabilisticSuffixTree ( Tree(..) , NodeMap , Node(..) , empty , construct , toTree , printTree ) where import qualified Data.Map as M import qualified Data.ProbabilisticSuffixTree.Context as C import qualified Data.Tree as T data Tree a = Tree { nodes :: NodeMap a } deriving (Eq, Show) type NodeMap a = M.Map a (Node a) data Node a = Node { symbol :: a , count :: !Int , probability :: !Double , children :: NodeMap a } deriving (Eq, Show) empty :: Tree a empty = Tree M.empty -- This function could also do some tree pruning and pmf smoothing. fromContext :: C.NodeMap a -> Tree a fromContext ns = Tree (M.mapWithKey (fromContextNode (C.counts ns)) (C.nodes ns)) fromContextNode :: Int -> a -> C.Node a -> Node a fromContextNode ss a n = Node a c (fromIntegral c / fromIntegral ss) (M.mapWithKey (fromContextNode (C.counts ns)) (C.nodes ns)) where c = C.count n ns = C.children n construct :: Ord a => [a] -> Tree a construct = fromContext . C.construct toTree :: Tree a -> T.Tree (Maybe (a, Int, Double)) toTree (Tree ns) = T.Node Nothing (map toTreeNode (M.elems ns)) toTreeNode :: Node a -> T.Tree (Maybe (a, Int, Double)) toTreeNode n = T.Node (Just (symbol n, count n, probability n)) (map toTreeNode (M.elems (children n))) printTree :: Show a => Tree a -> IO () printTree = putStrLn . T.drawTree . fmap show . toTree
null
https://raw.githubusercontent.com/kaoskorobase/mescaline/13554fc4826d0c977d0010c0b4fb74ba12ced6b9/lib/mescaline/Data/ProbabilisticSuffixTree.hs
haskell
This function could also do some tree pruning and pmf smoothing.
module Data.ProbabilisticSuffixTree ( Tree(..) , NodeMap , Node(..) , empty , construct , toTree , printTree ) where import qualified Data.Map as M import qualified Data.ProbabilisticSuffixTree.Context as C import qualified Data.Tree as T data Tree a = Tree { nodes :: NodeMap a } deriving (Eq, Show) type NodeMap a = M.Map a (Node a) data Node a = Node { symbol :: a , count :: !Int , probability :: !Double , children :: NodeMap a } deriving (Eq, Show) empty :: Tree a empty = Tree M.empty fromContext :: C.NodeMap a -> Tree a fromContext ns = Tree (M.mapWithKey (fromContextNode (C.counts ns)) (C.nodes ns)) fromContextNode :: Int -> a -> C.Node a -> Node a fromContextNode ss a n = Node a c (fromIntegral c / fromIntegral ss) (M.mapWithKey (fromContextNode (C.counts ns)) (C.nodes ns)) where c = C.count n ns = C.children n construct :: Ord a => [a] -> Tree a construct = fromContext . C.construct toTree :: Tree a -> T.Tree (Maybe (a, Int, Double)) toTree (Tree ns) = T.Node Nothing (map toTreeNode (M.elems ns)) toTreeNode :: Node a -> T.Tree (Maybe (a, Int, Double)) toTreeNode n = T.Node (Just (symbol n, count n, probability n)) (map toTreeNode (M.elems (children n))) printTree :: Show a => Tree a -> IO () printTree = putStrLn . T.drawTree . fmap show . toTree
86943d83e053be0e715dde52eb8d9124981b13c0e6e3c8c6b07e6e5f833b8fc9
UnixJunkie/fragger
amino_acid.ml
Copyright ( C ) 2013 , Zhang Initiative Research Unit , * Advance Science Institute , Riken * 2 - 1 Hirosawa , Wako , Saitama 351 - 0198 , Japan * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License , 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 . * Advance Science Institute, Riken * 2-1 Hirosawa, Wako, Saitama 351-0198, Japan * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License, 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. *) open Core type aa_three = | ALA | ARG | ASN | ASP | CYS | GLU | GLN | GLY | HIS | ILE | LEU | LYS | MET | PHE | PRO | SER | THR | TRP | TYR | VAL type aa_one = | A | R | N | D | C | E | Q | G | H | I | L | K | M | F | P | S | T | W | Y | V let three_to_one = function | ALA -> A | ARG -> R | ASN -> N | ASP -> D | CYS -> C | GLU -> E | GLN -> Q | GLY -> G | HIS -> H | ILE -> I | LEU -> L | LYS -> K | MET -> M | PHE -> F | PRO -> P | SER -> S | THR -> T | TRP -> W | TYR -> Y | VAL -> V let one_to_three = function | A -> ALA | R -> ARG | N -> ASN | D -> ASP | C -> CYS | E -> GLU | Q -> GLN | G -> GLY | H -> HIS | I -> ILE | L -> LEU | K -> LYS | M -> MET | F -> PHE | P -> PRO | S -> SER | T -> THR | W -> TRP | Y -> TYR | V -> VAL exception Unknown_aa_three of string let aa_three_of_string = function | "ALA" -> ALA | "ARG" -> ARG | "ASN" -> ASN | "ASP" -> ASP | "CYS" -> CYS | "GLU" -> GLU | "GLN" -> GLN | "GLY" -> GLY | "HIS" -> HIS | "ILE" -> ILE | "LEU" -> LEU | "LYS" -> LYS | "MET" -> MET | "PHE" -> PHE | "PRO" -> PRO | "SER" -> SER | "THR" -> THR | "TRP" -> TRP | "TYR" -> TYR | "VAL" -> VAL | "A" -> ALA | "R" -> ARG | "N" -> ASN | "D" -> ASP | "C" -> CYS | "E" -> GLU | "Q" -> GLN | "G" -> GLY | "H" -> HIS | "I" -> ILE | "L" -> LEU | "K" -> LYS | "M" -> MET | "F" -> PHE | "P" -> PRO | "S" -> SER | "T" -> THR | "W" -> TRP | "Y" -> TYR | "V" -> VAL | unk -> raise (Unknown_aa_three unk) exception Unknown_aa_one of string let aa_one_of_string = function | "ALA" -> A | "ARG" -> R | "ASN" -> N | "ASP" -> D | "CYS" -> C | "GLU" -> E | "GLN" -> Q | "GLY" -> G | "HIS" -> H | "ILE" -> I | "LEU" -> L | "LYS" -> K | "MET" -> M | "PHE" -> F | "PRO" -> P | "SER" -> S | "THR" -> T | "TRP" -> W | "TYR" -> Y | "VAL" -> V | "A" -> A | "R" -> R | "N" -> N | "D" -> D | "C" -> C | "E" -> E | "Q" -> Q | "G" -> G | "H" -> H | "I" -> I | "L" -> L | "K" -> K | "M" -> M | "F" -> F | "P" -> P | "S" -> S | "T" -> T | "W" -> W | "Y" -> Y | "V" -> V | unk -> raise (Unknown_aa_one unk) let string_of_aa_three = function | ALA -> "ALA" | ARG -> "ARG" | ASN -> "ASN" | ASP -> "ASP" | CYS -> "CYS" | GLU -> "GLU" | GLN -> "GLN" | GLY -> "GLY" | HIS -> "HIS" | ILE -> "ILE" | LEU -> "LEU" | LYS -> "LYS" | MET -> "MET" | PHE -> "PHE" | PRO -> "PRO" | SER -> "SER" | THR -> "THR" | TRP -> "TRP" | TYR -> "TYR" | VAL -> "VAL" let string_of_aa_one = function | A -> "A" | R -> "R" | N -> "N" | D -> "D" | C -> "C" | E -> "E" | Q -> "Q" | G -> "G" | H -> "H" | I -> "I" | L -> "L" | K -> "K" | M -> "M" | F -> "F" | P -> "P" | S -> "S" | T -> "T" | W -> "W" | Y -> "Y" | V -> "V" let char_of_aa_one = function | A -> 'A' | R -> 'R' | N -> 'N' | D -> 'D' | C -> 'C' | E -> 'E' | Q -> 'Q' | G -> 'G' | H -> 'H' | I -> 'I' | L -> 'L' | K -> 'K' | M -> 'M' | F -> 'F' | P -> 'P' | S -> 'S' | T -> 'T' | W -> 'W' | Y -> 'Y' | V -> 'V'
null
https://raw.githubusercontent.com/UnixJunkie/fragger/7cbee359cfb6ddb3acfdf72501921b0728dd3e9f/src/amino_acid.ml
ocaml
Copyright ( C ) 2013 , Zhang Initiative Research Unit , * Advance Science Institute , Riken * 2 - 1 Hirosawa , Wako , Saitama 351 - 0198 , Japan * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License , 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 . * Advance Science Institute, Riken * 2-1 Hirosawa, Wako, Saitama 351-0198, Japan * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License, 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. *) open Core type aa_three = | ALA | ARG | ASN | ASP | CYS | GLU | GLN | GLY | HIS | ILE | LEU | LYS | MET | PHE | PRO | SER | THR | TRP | TYR | VAL type aa_one = | A | R | N | D | C | E | Q | G | H | I | L | K | M | F | P | S | T | W | Y | V let three_to_one = function | ALA -> A | ARG -> R | ASN -> N | ASP -> D | CYS -> C | GLU -> E | GLN -> Q | GLY -> G | HIS -> H | ILE -> I | LEU -> L | LYS -> K | MET -> M | PHE -> F | PRO -> P | SER -> S | THR -> T | TRP -> W | TYR -> Y | VAL -> V let one_to_three = function | A -> ALA | R -> ARG | N -> ASN | D -> ASP | C -> CYS | E -> GLU | Q -> GLN | G -> GLY | H -> HIS | I -> ILE | L -> LEU | K -> LYS | M -> MET | F -> PHE | P -> PRO | S -> SER | T -> THR | W -> TRP | Y -> TYR | V -> VAL exception Unknown_aa_three of string let aa_three_of_string = function | "ALA" -> ALA | "ARG" -> ARG | "ASN" -> ASN | "ASP" -> ASP | "CYS" -> CYS | "GLU" -> GLU | "GLN" -> GLN | "GLY" -> GLY | "HIS" -> HIS | "ILE" -> ILE | "LEU" -> LEU | "LYS" -> LYS | "MET" -> MET | "PHE" -> PHE | "PRO" -> PRO | "SER" -> SER | "THR" -> THR | "TRP" -> TRP | "TYR" -> TYR | "VAL" -> VAL | "A" -> ALA | "R" -> ARG | "N" -> ASN | "D" -> ASP | "C" -> CYS | "E" -> GLU | "Q" -> GLN | "G" -> GLY | "H" -> HIS | "I" -> ILE | "L" -> LEU | "K" -> LYS | "M" -> MET | "F" -> PHE | "P" -> PRO | "S" -> SER | "T" -> THR | "W" -> TRP | "Y" -> TYR | "V" -> VAL | unk -> raise (Unknown_aa_three unk) exception Unknown_aa_one of string let aa_one_of_string = function | "ALA" -> A | "ARG" -> R | "ASN" -> N | "ASP" -> D | "CYS" -> C | "GLU" -> E | "GLN" -> Q | "GLY" -> G | "HIS" -> H | "ILE" -> I | "LEU" -> L | "LYS" -> K | "MET" -> M | "PHE" -> F | "PRO" -> P | "SER" -> S | "THR" -> T | "TRP" -> W | "TYR" -> Y | "VAL" -> V | "A" -> A | "R" -> R | "N" -> N | "D" -> D | "C" -> C | "E" -> E | "Q" -> Q | "G" -> G | "H" -> H | "I" -> I | "L" -> L | "K" -> K | "M" -> M | "F" -> F | "P" -> P | "S" -> S | "T" -> T | "W" -> W | "Y" -> Y | "V" -> V | unk -> raise (Unknown_aa_one unk) let string_of_aa_three = function | ALA -> "ALA" | ARG -> "ARG" | ASN -> "ASN" | ASP -> "ASP" | CYS -> "CYS" | GLU -> "GLU" | GLN -> "GLN" | GLY -> "GLY" | HIS -> "HIS" | ILE -> "ILE" | LEU -> "LEU" | LYS -> "LYS" | MET -> "MET" | PHE -> "PHE" | PRO -> "PRO" | SER -> "SER" | THR -> "THR" | TRP -> "TRP" | TYR -> "TYR" | VAL -> "VAL" let string_of_aa_one = function | A -> "A" | R -> "R" | N -> "N" | D -> "D" | C -> "C" | E -> "E" | Q -> "Q" | G -> "G" | H -> "H" | I -> "I" | L -> "L" | K -> "K" | M -> "M" | F -> "F" | P -> "P" | S -> "S" | T -> "T" | W -> "W" | Y -> "Y" | V -> "V" let char_of_aa_one = function | A -> 'A' | R -> 'R' | N -> 'N' | D -> 'D' | C -> 'C' | E -> 'E' | Q -> 'Q' | G -> 'G' | H -> 'H' | I -> 'I' | L -> 'L' | K -> 'K' | M -> 'M' | F -> 'F' | P -> 'P' | S -> 'S' | T -> 'T' | W -> 'W' | Y -> 'Y' | V -> 'V'
78ad8d6284a58d19874bc8051f7eb31d715120ff4abe506cfe740adda529ac96
iijlab/postgresql-pure
Data.hs
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE CPP # {-# LANGUAGE DataKinds #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE DerivingStrategies #-} # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternSynonyms #-} # LANGUAGE TypeFamilies # {-# LANGUAGE UndecidableInstances #-} module Database.PostgreSQL.Pure.Internal.Data ( Connection (..) , Config (..) , ColumnInfo (..) , Response (..) , AuthenticationResponse (..) , AuthenticationMD5Password (..) , BackendKeyData (..) , CommandComplete (..) , DataRow (..) , DataRowRaw (..) , Error (..) , Notice (..) , ParameterStatus (..) , ReadyForQuery (..) , RowDescription (..) , ParameterDescription (..) , Debug (..) , ExecuteResult (..) , DescribeResult (..) , AttributeNumber , TypeModifier , FormatCode (..) , BindParameterFormatCodes (..) , BindResultFormatCodes (..) , TypeLength (..) , CommandTag (..) , ErrorFields (..) , TransactionState (..) , Buffer (..) , Carry , Salt , Address (..) , BackendParameters , Pid , BackendKey , Oid (..) , Raw (Null, Value) , SqlIdentifier (..) , TimeOfDayWithTimeZone (..) , Query (..) , PreparedStatement (..) , PreparedStatementProcedure (..) , PreparedStatementName (..) , Portal (..) , PortalProcedure (..) , PortalName (..) , Executed (..) , ExecutedProcedure (..) , CloseProcedure (..) , MessageResult , StringDecoder , StringEncoder , FromField (..) , FromRecord (..) , GFromRecord (..) , ToField (..) , ToRecord (..) , GToRecord (..) , Pretty (..) ) where import Database.PostgreSQL.Pure.Oid (Oid (Oid)) import Control.Applicative ((<|>)) import qualified Data.Attoparsec.ByteString as AP import qualified Data.ByteString as BS import qualified Data.ByteString.Builder as BSB import qualified Data.ByteString.Short as BSS import qualified Data.ByteString.UTF8 as BSU import Data.Char (chr, isPrint, toLower) import Data.Default.Class (Default (def)) import Data.Int (Int16, Int32) import Data.Kind (Type) import Data.List (intercalate) import Data.Map.Strict (Map) import Data.String (IsString) import Data.Time (TimeOfDay, TimeZone) import Data.Word (Word8) import Foreign (ForeignPtr) import GHC.Generics (Generic (Rep)) import qualified GHC.Generics as Generics import Hexdump (prettyHex, simpleHex) import Network.Socket (Socket) import qualified Network.Socket as NS import Text.Read (Read (readPrec)) import qualified Text.Read as R import qualified Text.Read.Lex as R #if !MIN_VERSION_base(4,13,0) import Control.Monad.Fail (MonadFail) #endif -- | A configuration of a connection. -- -- Default configuration is 'def', which is following. -- -- >>> address def AddressResolved 127.0.0.1:5432 -- >>> user def -- "postgres" -- >>> password def -- "" -- >>> database def -- "" -- >>> sendingBufferSize def 4096 -- >>> receptionBufferSize def 4096 data Config = Config { address :: Address -- ^ Server address. , user :: String -- ^ User name. , password :: String -- ^ Password of user. , database :: String -- ^ Database name. , sendingBufferSize :: Int -- ^ The size of sending buffer in byte. , receptionBufferSize :: Int -- ^ The size of receiving buffer in byte. } deriving (Show, Eq) instance Default Config where def = Config { address = AddressResolved $ NS.SockAddrInet 5432 $ NS.tupleToHostAddress (127, 0, 0, 1) , user = "postgres" , password = "" , database = "" , sendingBufferSize = 2 ^ (12 :: Int) , receptionBufferSize = 2 ^ (12 :: Int) } -- | IP address. data Address ^ Address which is DNS resolved . ^ Address which is not DNS resolved . deriving (Show, Eq) -- | Set of server parameters. type BackendParameters = Map BSS.ShortByteString BSS.ShortByteString -- | PostgreSQL connection. data Connection = Connection { socket :: Socket , pid :: Pid -- ^ The process ID of the server. , backendKey :: BackendKey , parameters :: BackendParameters -- ^ Set of server parameters. , sendingBuffer :: Buffer , receptionBuffer :: Buffer , config :: Config -- ^ Configuration of this connection. } data Buffer = Buffer (ForeignPtr Word8) Int type Salt = BS.ByteString -- | Transaction state of a server. data TransactionState = Idle -- ^ Not in a transaction block. | Block -- ^ In a transaction block. | Failed -- ^ Transaction failed. deriving (Show, Read, Eq, Enum) -- | Proccess ID type Pid = Int32 type BackendKey = Int32 type AttributeNumber = Int16 data TypeLength = VariableLength | FixedLength Int16 deriving (Show, Read, Eq, Ord) type TypeModifier = Int32 -- | Format code of parameters of results. data FormatCode = TextFormat | BinaryFormat deriving (Show, Read, Eq, Enum) data BindParameterFormatCodes = BindParameterFormatCodesAllDefault | BindParameterFormatCodesAll FormatCode | BindParameterFormatCodesEach [FormatCode] deriving (Show, Read, Eq) data BindResultFormatCodes = BindResultFormatCodesNothing | BindResultFormatCodesAllDefault | BindResultFormatCodesEach [FormatCode] deriving (Show, Read, Eq) -- | Command tag, which means which SQL command is completed. data CommandTag = InsertTag Oid Int | DeleteTag Int | UpdateTag Int | SelectTag Int | MoveTag Int | FetchTag Int since PostgreSQL 8.2 | CreateTableTag | DropTableTag | BeginTag | CommitTag | RollbackTag | SetTag deriving (Show, Read, Eq) data Response = AuthenticationResponse AuthenticationResponse | BackendKeyDataResponse BackendKeyData | CommandCompleteResponse CommandComplete | DataRowResponse DataRowRaw | ErrorResponse Error | NoticeResponse Notice | ParameterStatusResponse ParameterStatus | ReadyForQueryResponse ReadyForQuery | RowDescriptionResponse RowDescription | ParseCompleteResponse | BindCompleteResponse | EmptyQueryResponse | NoDataResponse | ParameterDescriptionResponse ParameterDescription | DebugResponse Debug -- XXX temporal implimentation data AuthenticationResponse = AuthenticationOkResponse | AuthenticationCleartextPasswordResponse | AuthenticationMD5PasswordResponse AuthenticationMD5Password deriving (Show, Read, Eq) newtype AuthenticationMD5Password = AuthenticationMD5Password Salt deriving (Show, Read, Eq) data BackendKeyData = BackendKeyData Pid BackendKey deriving (Show, Read, Eq) newtype CommandComplete = CommandComplete CommandTag deriving (Show, Read, Eq) newtype DataRow r = DataRow r deriving (Show, Read, Eq) newtype DataRowRaw = DataRowRaw [Raw] deriving (Show, Read, Eq) newtype Error = Error ErrorFields deriving (Show, Read, Eq) newtype Notice = Notice ErrorFields deriving (Show, Read, Eq) data ParameterStatus = ParameterStatus BSS.ShortByteString BSS.ShortByteString deriving (Show, Read, Eq) newtype ReadyForQuery = ReadyForQuery TransactionState deriving (Show, Read, Eq) newtype RowDescription = RowDescription [ColumnInfo] deriving (Show, Read, Eq) newtype ParameterDescription = ParameterDescription [Oid] deriving (Show, Read, Eq) newtype Debug = Debug BS.ByteString deriving (Show, Read, Eq) -- XXX temporal implimentation -- | Result of a “Execute” message. data ExecuteResult = ExecuteComplete CommandTag -- ^ All records gotten. | ExecuteEmptyQuery -- ^ No records. | ExecuteSuspended -- ^ Records are left yet. deriving (Show, Read, Eq) data DescribeResult = DescribePreparedStatementResult [Oid] [ColumnInfo] | DescribePortalResult [ColumnInfo] deriving (Show, Read, Eq) -- -error-fields.html newtype ErrorFields = ErrorFields [(Char, BSS.ShortByteString)] deriving (Show, Read, Eq) data TypeInfo = Basic Oid BS.ByteString deriving (Show, Read, Eq) -- | Metadata of a column. data ColumnInfo = ColumnInfo { name :: BS.ByteString , tableOid :: Oid , attributeNumber :: AttributeNumber , typeOid :: Oid , typeLength :: TypeLength , typeModifier :: TypeModifier , formatCode :: FormatCode } deriving (Show, Read, Eq) type Carry = BS.ByteString -- | Data without encoding nor decoding of a field. newtype Raw = Raw (Maybe BS.ByteString) deriving (Eq, Ord) instance Show Raw where show Null = "NULL" show (Value a) = show (BS.unpack a) instance Read Raw where readPrec = R.parens ( ( do R.lift $ R.expect $ R.Ident "NULL" pure Null ) <|> (Value . BS.pack <$> readPrec) ) -- | @NULL@. pattern Null :: Raw pattern Null = Raw Nothing -- | Not @NULL@. pattern Value :: BS.ByteString -> Raw pattern Value a = Raw (Just a) {-# COMPLETE Null, Value #-} -- | SQL query. -- -- This 'Data.String.fromString' counts only ASCII, becouse it is the same with 'BS.ByteString'. newtype Query = Query BS.ByteString deriving (Show, Read, Eq, Ord, IsString) -- | To convert a type which means that it is not processed by the server to a respective type which means that it is processed by the server. type family MessageResult m :: Type -- | This represents a prepared statement which is already processed by a server. data PreparedStatement = PreparedStatement { name :: PreparedStatementName , parameterOids :: [Oid] , resultInfos :: [ColumnInfo] } instance Show PreparedStatement where show (PreparedStatement name parameterOids resultInfos) = "PreparedStatement " <> show name <> " " <> show parameterOids <> " " <> show resultInfos instance Eq PreparedStatement where (PreparedStatement name0 parameterOids0 resultInfos0) == (PreparedStatement name1 parameterOids1 resultInfos1) = (name0, parameterOids0, resultInfos0) == (name1, parameterOids1, resultInfos1) -- | This represents a prepared statement which is not yet processed by a server. data PreparedStatementProcedure = PreparedStatementProcedure { name :: PreparedStatementName , parameterLength :: Word , resultLength :: Word , parameterOids :: Maybe [Oid] , builder :: BSB.Builder , parser :: AP.Parser (MessageResult PreparedStatementProcedure) } type instance MessageResult PreparedStatementProcedure = PreparedStatement instance Show PreparedStatementProcedure where show (PreparedStatementProcedure name parameterLength resultLength oids _ _) = mconcat ["PreparedStatementProcedure ", show name, " ", show parameterLength, " ", show resultLength, " ", show oids, " _ _"] -- | Name of a prepared statement. newtype PreparedStatementName = PreparedStatementName BS.ByteString deriving stock (Eq, Ord) deriving newtype (Show, Read, IsString) -- | This represents a portal which is already processed by a server. data Portal = Portal { name :: PortalName , infos :: [ColumnInfo] , preparedStatement :: PreparedStatement } instance Show Portal where show (Portal name infos ps) = "Portal " <> show name <> " " <> show infos <> " (" <> show ps <> ")" instance Eq Portal where (Portal name0 infos0 ps0) == (Portal name1 infos1 ps1) = (name0, infos0, ps0) == (name1, infos1, ps1) -- | This represents a portal which is not yet processed by a server. data PortalProcedure = PortalProcedure { name :: PortalName , format :: FormatCode , builder :: BSB.Builder , parser :: AP.Parser (MessageResult PortalProcedure) } type instance MessageResult PortalProcedure = (PreparedStatement, Portal) instance Show PortalProcedure where show (PortalProcedure name format _ _) = "PortalProcedure " <> show name <> " " <> show format <> " _ _" -- | Name of a portal. newtype PortalName = PortalName BS.ByteString deriving stock (Eq, Ord) deriving newtype (Show, Read, IsString) -- | This represents a result of a “Execute” message which is already processed by a server. data Executed r = Executed { result :: ExecuteResult , records :: [r] , portal :: Portal } instance Show r => Show (Executed r) where show (Executed r rs p) = "Executed " <> show r <> " " <> show rs <> " (" <> show p <> ")" instance Eq r => Eq (Executed r) where (Executed r0 rs0 p0) == (Executed r1 rs1 p1) = (r0, rs0, p0) == (r1, rs1, p1) -- | This represents a result of a “Execute” message which is not yet processed by a server. data ExecutedProcedure r = ExecutedProcedure { builder :: BSB.Builder , parser :: AP.Parser (MessageResult (ExecutedProcedure r)) } type instance MessageResult (ExecutedProcedure r) = (PreparedStatement, Portal, Executed r, Maybe ErrorFields) instance Show (ExecutedProcedure r) where show (ExecutedProcedure _ _) = "ExecutedProcedure _ _" -- | This represents a result of a “Close” message which is not yet processed by a server. data CloseProcedure = CloseProcedure { builder :: BSB.Builder , parser :: AP.Parser (MessageResult CloseProcedure) } type instance MessageResult CloseProcedure = () instance Show CloseProcedure where show (CloseProcedure _ _) = "CloseProcedure _ _" -- | Decoder of strings which may fail. type StringDecoder = BS.ByteString -> Either String String -- | Encoder of strings which may fail. type StringEncoder = String -> Either String BS.ByteString | This means that a field can be decoded as class FromField a where -- | Decoder of a field. fromField :: MonadFail m => StringDecoder -> ColumnInfo -> Maybe BS.ByteString -> m a | This means that a record can be parsed as class FromRecord a where -- | Decoder of a record. fromRecord :: StringDecoder -> [ColumnInfo] -> AP.Parser a default fromRecord :: (Generic a, GFromRecord (Rep a)) => StringDecoder -> [ColumnInfo] -> AP.Parser a fromRecord decode infos = do (rep, infos') <- gFromRecord decode infos case infos' of [] -> pure $ Generics.to rep is -> fail $ "length mismatch: too many: actual: " <> show (length is) class GFromRecord f where gFromRecord :: StringDecoder -> [ColumnInfo] -> AP.Parser ((f p), [ColumnInfo]) -- | This means that @a@ can be encoded to a field. class ToField a where -- | Encoder of a field. toField :: MonadFail m => BackendParameters -> StringEncoder -> Maybe Oid -> FormatCode -> a -> m (Maybe BS.ByteString) -- | This means that @a@ can be encoded to a record. class ToRecord a where -- | Encoder of a field. toRecord :: MonadFail m => BackendParameters -> StringEncoder -> Maybe [Oid] -> [FormatCode] -> a -> m [Maybe BS.ByteString] default toRecord :: (MonadFail m, Generic a, GToRecord (Rep a)) => BackendParameters -> StringEncoder -> Maybe [Oid] -> [FormatCode] -> a -> m [Maybe BS.ByteString] toRecord backendParams encode Nothing fs v = do (record, os, fs') <- gToRecord backendParams encode Nothing fs $ Generics.from v case (os, fs') of (Nothing, []) -> pure record (Nothing, _) -> fail "There are too many format codes" (_, _) -> error "can't reach here" toRecord backendParams encode os fs v = do (record, os', fs') <- gToRecord backendParams encode os fs $ Generics.from v case (os', fs') of (Just [], []) -> pure record (Just _, []) -> fail "There are too many OIDs" (Just _, _) -> fail "There are too many format codes" (_, _) -> error "can't reach here" class GToRecord f where gToRecord :: (MonadFail m) => BackendParameters -> StringEncoder -> Maybe [Oid] -> [FormatCode] -> f p -> m ([Maybe BS.ByteString], Maybe [Oid], [FormatCode]) -- | Type of PostgreSQL @sql_identifier@ type. newtype SqlIdentifier = SqlIdentifier BS.ByteString deriving (Show, Read, Eq) data TimeOfDayWithTimeZone = TimeOfDayWithTimeZone { timeOfDay :: TimeOfDay, timeZone :: TimeZone } deriving (Show, Read, Eq, Ord) class Pretty a where pretty :: a -> String instance Pretty Response where pretty (AuthenticationResponse r) = pretty r pretty (CommandCompleteResponse r) = pretty r pretty (DataRowResponse r) = pretty r pretty (ErrorResponse r) = pretty r pretty (NoticeResponse r) = pretty r pretty (ParameterStatusResponse r) = pretty r pretty (BackendKeyDataResponse r) = pretty r pretty (ReadyForQueryResponse r) = pretty r pretty (RowDescriptionResponse r) = pretty r pretty ParseCompleteResponse = "parse complete" pretty BindCompleteResponse = "bind complete" pretty (ParameterDescriptionResponse r) = pretty r pretty EmptyQueryResponse = "empty query" pretty NoDataResponse = "no data" pretty (DebugResponse r) = pretty r instance Pretty AuthenticationResponse where pretty AuthenticationOkResponse = "authentication ok" pretty AuthenticationCleartextPasswordResponse = "authentication using cleartext" pretty (AuthenticationMD5PasswordResponse r) = pretty r instance Pretty AuthenticationMD5Password where pretty (AuthenticationMD5Password salt) = "authentication MD5 password:\n\tsalt: " <> simpleHex salt instance Pretty CommandComplete where pretty (CommandComplete (InsertTag oid rows)) = "command complete:\n\ttag: insert \n\t\toid: " <> show oid <> "\n\t\trows: " <> show rows pretty (CommandComplete (DeleteTag rows)) = "command complete:\n\ttag: delete\n\t\trows: " <> show rows pretty (CommandComplete (UpdateTag rows)) = "command complete:\n\ttag: update\n\t\trows: " <> show rows pretty (CommandComplete (SelectTag rows)) = "command complete:\n\ttag: select\n\t\trows: " <> show rows pretty (CommandComplete (MoveTag rows)) = "command complete:\n\ttag: move\n\t\trows: " <> show rows pretty (CommandComplete (FetchTag rows)) = "command complete:\n\ttag: fetch\n\t\trows: " <> show rows pretty (CommandComplete (CopyTag rows)) = "command complete:\n\ttag: copy\n\t\trows: " <> show rows pretty (CommandComplete CreateTableTag) = "command complete:\n\ttag: create table" pretty (CommandComplete DropTableTag) = "command complete:\n\ttag: drop table" pretty (CommandComplete BeginTag) = "command complete:\n\ttag: begin" pretty (CommandComplete CommitTag) = "command complete:\n\ttag: commit" pretty (CommandComplete RollbackTag) = "command complete:\n\ttag: rollback" pretty (CommandComplete SetTag) = "command complete:\n\ttag: set" instance Show r => Pretty (DataRow r) where pretty (DataRow record) = "data:\n" <> show record instance Pretty DataRowRaw where pretty (DataRowRaw values) = "data:\n" <> intercalate "\n" (go <$> zip [0 :: Int ..] values) where go (idx, v) = "\t" <> show idx <> pretty v instance Pretty Error where pretty (Error fields) = "error response:\n" <> indent (pretty fields) instance Pretty Notice where pretty (Notice fields) = "notice response:\n" <> indent (pretty fields) instance Pretty ErrorFields where pretty (ErrorFields errs) = let lookups = foldr go ("", "", "") :: [(Char, BSS.ShortByteString)] -> (BSS.ShortByteString, BSS.ShortByteString, BSS.ShortByteString) go ('S', largeS') (_, largeC', largeM') = (largeS', largeC', largeM') go ('C', largeC') (largeS', _, largeM') = (largeS', largeC', largeM') go ('M', largeM') (largeS', largeC', _) = (largeS', largeC', largeM') go _ a = a (largeS, largeC, largeM) = lookups errs pp (code, message) = code : ": " <> shortByteStringToString message in shortByteStringToString (largeS <> " (" <> largeC <> "): " <> largeM) <> ('\n' : intercalate "\n" (pp <$> errs)) instance Pretty TransactionState where pretty Idle = "idle" pretty Block = "block" pretty Failed = "failed" instance Pretty ParameterStatus where pretty (ParameterStatus key value) = "parameter:\n\t" <> shortByteStringToString key <> ": " <> shortByteStringToString value instance Pretty BackendKeyData where pretty (BackendKeyData pid bk) = "cancellation key:\n\tpid: " <> show pid <> "\n\tbackend key: " <> show bk instance Pretty ReadyForQuery where pretty (ReadyForQuery ts) = "ready for query:\n\ttransaction state: " <> (toLower <$> show ts) instance Pretty RowDescription where This uses decoder of UTF-8 although this should read client_encoding parameter , because this is used for debugging . pretty (RowDescription infos) = "row description:\n" <> intercalate "\n" (go <$> infos) where go (ColumnInfo name tableOid attrNum typeOid len typeMod format) = "\t" <> BSU.toString name <> ":" <> "\n\t\ttable object ID: " <> show tableOid <> "\n\t\tcolumn attribute number: " <> show attrNum <> "\n\t\tdata type object ID: " <> show typeOid <> "\n\t\tdata type length: " <> pretty len <> "\n\t\ttype modifier: " <> show typeMod <> "\n\t\tformat: " <> pretty format instance Pretty ParameterDescription where pretty (ParameterDescription oids) = "parameter description: " <> show oids instance Pretty Debug where pretty (Debug bs) = "Debug:\n" <> prettyHex bs instance Pretty TypeLength where pretty VariableLength = "variable" pretty (FixedLength l) = show l instance Pretty FormatCode where pretty TextFormat = "text" pretty BinaryFormat = "binary" instance Pretty Raw where pretty Null = "NULL" pretty (Value r) = "Value [" <> simpleHex r <> "] " <> show (printableString r) This uses decoder of UTF-8 although this should read client_encoding parameter , because this is used for debugging . printableString :: BS.ByteString -> String printableString bytes = let replacePrintable c | isPrint c = c | otherwise = '.' in replacePrintable <$> BSU.toString bytes shortByteStringToString :: BSS.ShortByteString -> String shortByteStringToString = ((chr . fromIntegral) <$>) . BSS.unpack indent :: String -> String indent = unlines . (('\t' :) <$>) . lines
null
https://raw.githubusercontent.com/iijlab/postgresql-pure/2a640f102f3e3540aedbcf4cfb5d1ed10310f773/src/Database/PostgreSQL/Pure/Internal/Data.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE DefaultSignatures # # LANGUAGE DerivingStrategies # # LANGUAGE OverloadedStrings # # LANGUAGE PatternSynonyms # # LANGUAGE UndecidableInstances # | A configuration of a connection. Default configuration is 'def', which is following. >>> address def >>> user def "postgres" >>> password def "" >>> database def "" >>> sendingBufferSize def >>> receptionBufferSize def ^ Server address. ^ User name. ^ Password of user. ^ Database name. ^ The size of sending buffer in byte. ^ The size of receiving buffer in byte. | IP address. | Set of server parameters. | PostgreSQL connection. ^ The process ID of the server. ^ Set of server parameters. ^ Configuration of this connection. | Transaction state of a server. ^ Not in a transaction block. ^ In a transaction block. ^ Transaction failed. | Proccess ID | Format code of parameters of results. | Command tag, which means which SQL command is completed. XXX temporal implimentation XXX temporal implimentation | Result of a “Execute” message. ^ All records gotten. ^ No records. ^ Records are left yet. -error-fields.html | Metadata of a column. | Data without encoding nor decoding of a field. | @NULL@. | Not @NULL@. # COMPLETE Null, Value # | SQL query. This 'Data.String.fromString' counts only ASCII, becouse it is the same with 'BS.ByteString'. | To convert a type which means that it is not processed by the server to a respective type which means that it is processed by the server. | This represents a prepared statement which is already processed by a server. | This represents a prepared statement which is not yet processed by a server. | Name of a prepared statement. | This represents a portal which is already processed by a server. | This represents a portal which is not yet processed by a server. | Name of a portal. | This represents a result of a “Execute” message which is already processed by a server. | This represents a result of a “Execute” message which is not yet processed by a server. | This represents a result of a “Close” message which is not yet processed by a server. | Decoder of strings which may fail. | Encoder of strings which may fail. | Decoder of a field. | Decoder of a record. | This means that @a@ can be encoded to a field. | Encoder of a field. | This means that @a@ can be encoded to a record. | Encoder of a field. | Type of PostgreSQL @sql_identifier@ type.
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE CPP # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE NamedFieldPuns # # LANGUAGE TypeFamilies # module Database.PostgreSQL.Pure.Internal.Data ( Connection (..) , Config (..) , ColumnInfo (..) , Response (..) , AuthenticationResponse (..) , AuthenticationMD5Password (..) , BackendKeyData (..) , CommandComplete (..) , DataRow (..) , DataRowRaw (..) , Error (..) , Notice (..) , ParameterStatus (..) , ReadyForQuery (..) , RowDescription (..) , ParameterDescription (..) , Debug (..) , ExecuteResult (..) , DescribeResult (..) , AttributeNumber , TypeModifier , FormatCode (..) , BindParameterFormatCodes (..) , BindResultFormatCodes (..) , TypeLength (..) , CommandTag (..) , ErrorFields (..) , TransactionState (..) , Buffer (..) , Carry , Salt , Address (..) , BackendParameters , Pid , BackendKey , Oid (..) , Raw (Null, Value) , SqlIdentifier (..) , TimeOfDayWithTimeZone (..) , Query (..) , PreparedStatement (..) , PreparedStatementProcedure (..) , PreparedStatementName (..) , Portal (..) , PortalProcedure (..) , PortalName (..) , Executed (..) , ExecutedProcedure (..) , CloseProcedure (..) , MessageResult , StringDecoder , StringEncoder , FromField (..) , FromRecord (..) , GFromRecord (..) , ToField (..) , ToRecord (..) , GToRecord (..) , Pretty (..) ) where import Database.PostgreSQL.Pure.Oid (Oid (Oid)) import Control.Applicative ((<|>)) import qualified Data.Attoparsec.ByteString as AP import qualified Data.ByteString as BS import qualified Data.ByteString.Builder as BSB import qualified Data.ByteString.Short as BSS import qualified Data.ByteString.UTF8 as BSU import Data.Char (chr, isPrint, toLower) import Data.Default.Class (Default (def)) import Data.Int (Int16, Int32) import Data.Kind (Type) import Data.List (intercalate) import Data.Map.Strict (Map) import Data.String (IsString) import Data.Time (TimeOfDay, TimeZone) import Data.Word (Word8) import Foreign (ForeignPtr) import GHC.Generics (Generic (Rep)) import qualified GHC.Generics as Generics import Hexdump (prettyHex, simpleHex) import Network.Socket (Socket) import qualified Network.Socket as NS import Text.Read (Read (readPrec)) import qualified Text.Read as R import qualified Text.Read.Lex as R #if !MIN_VERSION_base(4,13,0) import Control.Monad.Fail (MonadFail) #endif AddressResolved 127.0.0.1:5432 4096 4096 data Config = Config } deriving (Show, Eq) instance Default Config where def = Config { address = AddressResolved $ NS.SockAddrInet 5432 $ NS.tupleToHostAddress (127, 0, 0, 1) , user = "postgres" , password = "" , database = "" , sendingBufferSize = 2 ^ (12 :: Int) , receptionBufferSize = 2 ^ (12 :: Int) } data Address ^ Address which is DNS resolved . ^ Address which is not DNS resolved . deriving (Show, Eq) type BackendParameters = Map BSS.ShortByteString BSS.ShortByteString data Connection = Connection { socket :: Socket , backendKey :: BackendKey , sendingBuffer :: Buffer , receptionBuffer :: Buffer } data Buffer = Buffer (ForeignPtr Word8) Int type Salt = BS.ByteString data TransactionState deriving (Show, Read, Eq, Enum) type Pid = Int32 type BackendKey = Int32 type AttributeNumber = Int16 data TypeLength = VariableLength | FixedLength Int16 deriving (Show, Read, Eq, Ord) type TypeModifier = Int32 data FormatCode = TextFormat | BinaryFormat deriving (Show, Read, Eq, Enum) data BindParameterFormatCodes = BindParameterFormatCodesAllDefault | BindParameterFormatCodesAll FormatCode | BindParameterFormatCodesEach [FormatCode] deriving (Show, Read, Eq) data BindResultFormatCodes = BindResultFormatCodesNothing | BindResultFormatCodesAllDefault | BindResultFormatCodesEach [FormatCode] deriving (Show, Read, Eq) data CommandTag = InsertTag Oid Int | DeleteTag Int | UpdateTag Int | SelectTag Int | MoveTag Int | FetchTag Int since PostgreSQL 8.2 | CreateTableTag | DropTableTag | BeginTag | CommitTag | RollbackTag | SetTag deriving (Show, Read, Eq) data Response = AuthenticationResponse AuthenticationResponse | BackendKeyDataResponse BackendKeyData | CommandCompleteResponse CommandComplete | DataRowResponse DataRowRaw | ErrorResponse Error | NoticeResponse Notice | ParameterStatusResponse ParameterStatus | ReadyForQueryResponse ReadyForQuery | RowDescriptionResponse RowDescription | ParseCompleteResponse | BindCompleteResponse | EmptyQueryResponse | NoDataResponse | ParameterDescriptionResponse ParameterDescription data AuthenticationResponse = AuthenticationOkResponse | AuthenticationCleartextPasswordResponse | AuthenticationMD5PasswordResponse AuthenticationMD5Password deriving (Show, Read, Eq) newtype AuthenticationMD5Password = AuthenticationMD5Password Salt deriving (Show, Read, Eq) data BackendKeyData = BackendKeyData Pid BackendKey deriving (Show, Read, Eq) newtype CommandComplete = CommandComplete CommandTag deriving (Show, Read, Eq) newtype DataRow r = DataRow r deriving (Show, Read, Eq) newtype DataRowRaw = DataRowRaw [Raw] deriving (Show, Read, Eq) newtype Error = Error ErrorFields deriving (Show, Read, Eq) newtype Notice = Notice ErrorFields deriving (Show, Read, Eq) data ParameterStatus = ParameterStatus BSS.ShortByteString BSS.ShortByteString deriving (Show, Read, Eq) newtype ReadyForQuery = ReadyForQuery TransactionState deriving (Show, Read, Eq) newtype RowDescription = RowDescription [ColumnInfo] deriving (Show, Read, Eq) newtype ParameterDescription = ParameterDescription [Oid] deriving (Show, Read, Eq) data ExecuteResult deriving (Show, Read, Eq) data DescribeResult = DescribePreparedStatementResult [Oid] [ColumnInfo] | DescribePortalResult [ColumnInfo] deriving (Show, Read, Eq) newtype ErrorFields = ErrorFields [(Char, BSS.ShortByteString)] deriving (Show, Read, Eq) data TypeInfo = Basic Oid BS.ByteString deriving (Show, Read, Eq) data ColumnInfo = ColumnInfo { name :: BS.ByteString , tableOid :: Oid , attributeNumber :: AttributeNumber , typeOid :: Oid , typeLength :: TypeLength , typeModifier :: TypeModifier , formatCode :: FormatCode } deriving (Show, Read, Eq) type Carry = BS.ByteString newtype Raw = Raw (Maybe BS.ByteString) deriving (Eq, Ord) instance Show Raw where show Null = "NULL" show (Value a) = show (BS.unpack a) instance Read Raw where readPrec = R.parens ( ( do R.lift $ R.expect $ R.Ident "NULL" pure Null ) <|> (Value . BS.pack <$> readPrec) ) pattern Null :: Raw pattern Null = Raw Nothing pattern Value :: BS.ByteString -> Raw pattern Value a = Raw (Just a) newtype Query = Query BS.ByteString deriving (Show, Read, Eq, Ord, IsString) type family MessageResult m :: Type data PreparedStatement = PreparedStatement { name :: PreparedStatementName , parameterOids :: [Oid] , resultInfos :: [ColumnInfo] } instance Show PreparedStatement where show (PreparedStatement name parameterOids resultInfos) = "PreparedStatement " <> show name <> " " <> show parameterOids <> " " <> show resultInfos instance Eq PreparedStatement where (PreparedStatement name0 parameterOids0 resultInfos0) == (PreparedStatement name1 parameterOids1 resultInfos1) = (name0, parameterOids0, resultInfos0) == (name1, parameterOids1, resultInfos1) data PreparedStatementProcedure = PreparedStatementProcedure { name :: PreparedStatementName , parameterLength :: Word , resultLength :: Word , parameterOids :: Maybe [Oid] , builder :: BSB.Builder , parser :: AP.Parser (MessageResult PreparedStatementProcedure) } type instance MessageResult PreparedStatementProcedure = PreparedStatement instance Show PreparedStatementProcedure where show (PreparedStatementProcedure name parameterLength resultLength oids _ _) = mconcat ["PreparedStatementProcedure ", show name, " ", show parameterLength, " ", show resultLength, " ", show oids, " _ _"] newtype PreparedStatementName = PreparedStatementName BS.ByteString deriving stock (Eq, Ord) deriving newtype (Show, Read, IsString) data Portal = Portal { name :: PortalName , infos :: [ColumnInfo] , preparedStatement :: PreparedStatement } instance Show Portal where show (Portal name infos ps) = "Portal " <> show name <> " " <> show infos <> " (" <> show ps <> ")" instance Eq Portal where (Portal name0 infos0 ps0) == (Portal name1 infos1 ps1) = (name0, infos0, ps0) == (name1, infos1, ps1) data PortalProcedure = PortalProcedure { name :: PortalName , format :: FormatCode , builder :: BSB.Builder , parser :: AP.Parser (MessageResult PortalProcedure) } type instance MessageResult PortalProcedure = (PreparedStatement, Portal) instance Show PortalProcedure where show (PortalProcedure name format _ _) = "PortalProcedure " <> show name <> " " <> show format <> " _ _" newtype PortalName = PortalName BS.ByteString deriving stock (Eq, Ord) deriving newtype (Show, Read, IsString) data Executed r = Executed { result :: ExecuteResult , records :: [r] , portal :: Portal } instance Show r => Show (Executed r) where show (Executed r rs p) = "Executed " <> show r <> " " <> show rs <> " (" <> show p <> ")" instance Eq r => Eq (Executed r) where (Executed r0 rs0 p0) == (Executed r1 rs1 p1) = (r0, rs0, p0) == (r1, rs1, p1) data ExecutedProcedure r = ExecutedProcedure { builder :: BSB.Builder , parser :: AP.Parser (MessageResult (ExecutedProcedure r)) } type instance MessageResult (ExecutedProcedure r) = (PreparedStatement, Portal, Executed r, Maybe ErrorFields) instance Show (ExecutedProcedure r) where show (ExecutedProcedure _ _) = "ExecutedProcedure _ _" data CloseProcedure = CloseProcedure { builder :: BSB.Builder , parser :: AP.Parser (MessageResult CloseProcedure) } type instance MessageResult CloseProcedure = () instance Show CloseProcedure where show (CloseProcedure _ _) = "CloseProcedure _ _" type StringDecoder = BS.ByteString -> Either String String type StringEncoder = String -> Either String BS.ByteString | This means that a field can be decoded as class FromField a where fromField :: MonadFail m => StringDecoder -> ColumnInfo -> Maybe BS.ByteString -> m a | This means that a record can be parsed as class FromRecord a where fromRecord :: StringDecoder -> [ColumnInfo] -> AP.Parser a default fromRecord :: (Generic a, GFromRecord (Rep a)) => StringDecoder -> [ColumnInfo] -> AP.Parser a fromRecord decode infos = do (rep, infos') <- gFromRecord decode infos case infos' of [] -> pure $ Generics.to rep is -> fail $ "length mismatch: too many: actual: " <> show (length is) class GFromRecord f where gFromRecord :: StringDecoder -> [ColumnInfo] -> AP.Parser ((f p), [ColumnInfo]) class ToField a where toField :: MonadFail m => BackendParameters -> StringEncoder -> Maybe Oid -> FormatCode -> a -> m (Maybe BS.ByteString) class ToRecord a where toRecord :: MonadFail m => BackendParameters -> StringEncoder -> Maybe [Oid] -> [FormatCode] -> a -> m [Maybe BS.ByteString] default toRecord :: (MonadFail m, Generic a, GToRecord (Rep a)) => BackendParameters -> StringEncoder -> Maybe [Oid] -> [FormatCode] -> a -> m [Maybe BS.ByteString] toRecord backendParams encode Nothing fs v = do (record, os, fs') <- gToRecord backendParams encode Nothing fs $ Generics.from v case (os, fs') of (Nothing, []) -> pure record (Nothing, _) -> fail "There are too many format codes" (_, _) -> error "can't reach here" toRecord backendParams encode os fs v = do (record, os', fs') <- gToRecord backendParams encode os fs $ Generics.from v case (os', fs') of (Just [], []) -> pure record (Just _, []) -> fail "There are too many OIDs" (Just _, _) -> fail "There are too many format codes" (_, _) -> error "can't reach here" class GToRecord f where gToRecord :: (MonadFail m) => BackendParameters -> StringEncoder -> Maybe [Oid] -> [FormatCode] -> f p -> m ([Maybe BS.ByteString], Maybe [Oid], [FormatCode]) newtype SqlIdentifier = SqlIdentifier BS.ByteString deriving (Show, Read, Eq) data TimeOfDayWithTimeZone = TimeOfDayWithTimeZone { timeOfDay :: TimeOfDay, timeZone :: TimeZone } deriving (Show, Read, Eq, Ord) class Pretty a where pretty :: a -> String instance Pretty Response where pretty (AuthenticationResponse r) = pretty r pretty (CommandCompleteResponse r) = pretty r pretty (DataRowResponse r) = pretty r pretty (ErrorResponse r) = pretty r pretty (NoticeResponse r) = pretty r pretty (ParameterStatusResponse r) = pretty r pretty (BackendKeyDataResponse r) = pretty r pretty (ReadyForQueryResponse r) = pretty r pretty (RowDescriptionResponse r) = pretty r pretty ParseCompleteResponse = "parse complete" pretty BindCompleteResponse = "bind complete" pretty (ParameterDescriptionResponse r) = pretty r pretty EmptyQueryResponse = "empty query" pretty NoDataResponse = "no data" pretty (DebugResponse r) = pretty r instance Pretty AuthenticationResponse where pretty AuthenticationOkResponse = "authentication ok" pretty AuthenticationCleartextPasswordResponse = "authentication using cleartext" pretty (AuthenticationMD5PasswordResponse r) = pretty r instance Pretty AuthenticationMD5Password where pretty (AuthenticationMD5Password salt) = "authentication MD5 password:\n\tsalt: " <> simpleHex salt instance Pretty CommandComplete where pretty (CommandComplete (InsertTag oid rows)) = "command complete:\n\ttag: insert \n\t\toid: " <> show oid <> "\n\t\trows: " <> show rows pretty (CommandComplete (DeleteTag rows)) = "command complete:\n\ttag: delete\n\t\trows: " <> show rows pretty (CommandComplete (UpdateTag rows)) = "command complete:\n\ttag: update\n\t\trows: " <> show rows pretty (CommandComplete (SelectTag rows)) = "command complete:\n\ttag: select\n\t\trows: " <> show rows pretty (CommandComplete (MoveTag rows)) = "command complete:\n\ttag: move\n\t\trows: " <> show rows pretty (CommandComplete (FetchTag rows)) = "command complete:\n\ttag: fetch\n\t\trows: " <> show rows pretty (CommandComplete (CopyTag rows)) = "command complete:\n\ttag: copy\n\t\trows: " <> show rows pretty (CommandComplete CreateTableTag) = "command complete:\n\ttag: create table" pretty (CommandComplete DropTableTag) = "command complete:\n\ttag: drop table" pretty (CommandComplete BeginTag) = "command complete:\n\ttag: begin" pretty (CommandComplete CommitTag) = "command complete:\n\ttag: commit" pretty (CommandComplete RollbackTag) = "command complete:\n\ttag: rollback" pretty (CommandComplete SetTag) = "command complete:\n\ttag: set" instance Show r => Pretty (DataRow r) where pretty (DataRow record) = "data:\n" <> show record instance Pretty DataRowRaw where pretty (DataRowRaw values) = "data:\n" <> intercalate "\n" (go <$> zip [0 :: Int ..] values) where go (idx, v) = "\t" <> show idx <> pretty v instance Pretty Error where pretty (Error fields) = "error response:\n" <> indent (pretty fields) instance Pretty Notice where pretty (Notice fields) = "notice response:\n" <> indent (pretty fields) instance Pretty ErrorFields where pretty (ErrorFields errs) = let lookups = foldr go ("", "", "") :: [(Char, BSS.ShortByteString)] -> (BSS.ShortByteString, BSS.ShortByteString, BSS.ShortByteString) go ('S', largeS') (_, largeC', largeM') = (largeS', largeC', largeM') go ('C', largeC') (largeS', _, largeM') = (largeS', largeC', largeM') go ('M', largeM') (largeS', largeC', _) = (largeS', largeC', largeM') go _ a = a (largeS, largeC, largeM) = lookups errs pp (code, message) = code : ": " <> shortByteStringToString message in shortByteStringToString (largeS <> " (" <> largeC <> "): " <> largeM) <> ('\n' : intercalate "\n" (pp <$> errs)) instance Pretty TransactionState where pretty Idle = "idle" pretty Block = "block" pretty Failed = "failed" instance Pretty ParameterStatus where pretty (ParameterStatus key value) = "parameter:\n\t" <> shortByteStringToString key <> ": " <> shortByteStringToString value instance Pretty BackendKeyData where pretty (BackendKeyData pid bk) = "cancellation key:\n\tpid: " <> show pid <> "\n\tbackend key: " <> show bk instance Pretty ReadyForQuery where pretty (ReadyForQuery ts) = "ready for query:\n\ttransaction state: " <> (toLower <$> show ts) instance Pretty RowDescription where This uses decoder of UTF-8 although this should read client_encoding parameter , because this is used for debugging . pretty (RowDescription infos) = "row description:\n" <> intercalate "\n" (go <$> infos) where go (ColumnInfo name tableOid attrNum typeOid len typeMod format) = "\t" <> BSU.toString name <> ":" <> "\n\t\ttable object ID: " <> show tableOid <> "\n\t\tcolumn attribute number: " <> show attrNum <> "\n\t\tdata type object ID: " <> show typeOid <> "\n\t\tdata type length: " <> pretty len <> "\n\t\ttype modifier: " <> show typeMod <> "\n\t\tformat: " <> pretty format instance Pretty ParameterDescription where pretty (ParameterDescription oids) = "parameter description: " <> show oids instance Pretty Debug where pretty (Debug bs) = "Debug:\n" <> prettyHex bs instance Pretty TypeLength where pretty VariableLength = "variable" pretty (FixedLength l) = show l instance Pretty FormatCode where pretty TextFormat = "text" pretty BinaryFormat = "binary" instance Pretty Raw where pretty Null = "NULL" pretty (Value r) = "Value [" <> simpleHex r <> "] " <> show (printableString r) This uses decoder of UTF-8 although this should read client_encoding parameter , because this is used for debugging . printableString :: BS.ByteString -> String printableString bytes = let replacePrintable c | isPrint c = c | otherwise = '.' in replacePrintable <$> BSU.toString bytes shortByteStringToString :: BSS.ShortByteString -> String shortByteStringToString = ((chr . fromIntegral) <$>) . BSS.unpack indent :: String -> String indent = unlines . (('\t' :) <$>) . lines
d8f7e16f0219e34fce32041254bf14d6762af6884352c444ac8c6bdece895c7e
dgiot/dgiot
dgiot_json.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved . %% 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. %%-------------------------------------------------------------------- -module(dgiot_json). -compile(inline). -export([ encode/1 , encode/2 , safe_encode/1 , safe_encode/2 ]). -compile({inline, [ encode/1 , encode/2 ]}). -export([ decode/1 , decode/2 , safe_decode/1 , safe_decode/2 ]). -compile({inline, [ decode/1 , decode/2 ]}). -type(encode_options() :: jiffy:encode_options()). -type(decode_options() :: jiffy:decode_options()). -type(json_text() :: iolist() | binary()). -type(json_term() :: jiffy:jiffy_decode_result()). -export_type([json_text/0, json_term/0]). -export_type([decode_options/0, encode_options/0]). -spec(encode(json_term()) -> json_text()). encode(Term) -> encode(Term, [force_utf8]). -spec(encode(json_term(), encode_options()) -> json_text()). encode(Term, Opts) -> to_binary(jiffy:encode(to_ejson(Term), Opts)). -spec(safe_encode(json_term()) -> {ok, json_text()} | {error, Reason :: term()}). safe_encode(Term) -> safe_encode(Term, [force_utf8]). -spec(safe_encode(json_term(), encode_options()) -> {ok, json_text()} | {error, Reason :: term()}). safe_encode(Term, Opts) -> try encode(Term, Opts) of Json -> {ok, Json} catch error:Reason -> {error, Reason} end. -spec(decode(json_text()) -> json_term()). decode(Json) -> decode(Json, [return_maps]). -spec(decode(json_text(), decode_options()) -> json_term()). decode(Json, Opts) -> from_ejson(jiffy:decode(Json, Opts)). -spec(safe_decode(json_text()) -> {ok, json_term()} | {error, Reason :: term()}). safe_decode(Json) -> safe_decode(Json, []). -spec(safe_decode(json_text(), decode_options()) -> {ok, json_term()} | {error, Reason :: term()}). safe_decode(Json, Opts) -> try decode(Json, Opts) of Term -> {ok, Term} catch error:Reason -> {error, Reason} end. %%-------------------------------------------------------------------- %% Helpers %%-------------------------------------------------------------------- -compile({inline, [ to_ejson/1 , from_ejson/1 ]}). to_ejson([{}]) -> {[]}; to_ejson([{_, _}|_] = L) -> {[{K, to_ejson(V)} || {K, V} <- L ]}; to_ejson(L) when is_list(L) -> [to_ejson(E) || E <- L]; to_ejson(T) -> T. from_ejson(L) when is_list(L) -> [from_ejson(E) || E <- L]; from_ejson({[]}) -> [{}]; from_ejson({L}) -> [{Name, from_ejson(Value)} || {Name, Value} <- L]; from_ejson(T) -> T. to_binary(B) when is_binary(B) -> B; to_binary(L) when is_list(L) -> iolist_to_binary(L).
null
https://raw.githubusercontent.com/dgiot/dgiot/8a74ec56d478910204dea5459f13d05e86214354/apps/dgiot/src/utils/dgiot_json.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. -------------------------------------------------------------------- -------------------------------------------------------------------- Helpers --------------------------------------------------------------------
Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(dgiot_json). -compile(inline). -export([ encode/1 , encode/2 , safe_encode/1 , safe_encode/2 ]). -compile({inline, [ encode/1 , encode/2 ]}). -export([ decode/1 , decode/2 , safe_decode/1 , safe_decode/2 ]). -compile({inline, [ decode/1 , decode/2 ]}). -type(encode_options() :: jiffy:encode_options()). -type(decode_options() :: jiffy:decode_options()). -type(json_text() :: iolist() | binary()). -type(json_term() :: jiffy:jiffy_decode_result()). -export_type([json_text/0, json_term/0]). -export_type([decode_options/0, encode_options/0]). -spec(encode(json_term()) -> json_text()). encode(Term) -> encode(Term, [force_utf8]). -spec(encode(json_term(), encode_options()) -> json_text()). encode(Term, Opts) -> to_binary(jiffy:encode(to_ejson(Term), Opts)). -spec(safe_encode(json_term()) -> {ok, json_text()} | {error, Reason :: term()}). safe_encode(Term) -> safe_encode(Term, [force_utf8]). -spec(safe_encode(json_term(), encode_options()) -> {ok, json_text()} | {error, Reason :: term()}). safe_encode(Term, Opts) -> try encode(Term, Opts) of Json -> {ok, Json} catch error:Reason -> {error, Reason} end. -spec(decode(json_text()) -> json_term()). decode(Json) -> decode(Json, [return_maps]). -spec(decode(json_text(), decode_options()) -> json_term()). decode(Json, Opts) -> from_ejson(jiffy:decode(Json, Opts)). -spec(safe_decode(json_text()) -> {ok, json_term()} | {error, Reason :: term()}). safe_decode(Json) -> safe_decode(Json, []). -spec(safe_decode(json_text(), decode_options()) -> {ok, json_term()} | {error, Reason :: term()}). safe_decode(Json, Opts) -> try decode(Json, Opts) of Term -> {ok, Term} catch error:Reason -> {error, Reason} end. -compile({inline, [ to_ejson/1 , from_ejson/1 ]}). to_ejson([{}]) -> {[]}; to_ejson([{_, _}|_] = L) -> {[{K, to_ejson(V)} || {K, V} <- L ]}; to_ejson(L) when is_list(L) -> [to_ejson(E) || E <- L]; to_ejson(T) -> T. from_ejson(L) when is_list(L) -> [from_ejson(E) || E <- L]; from_ejson({[]}) -> [{}]; from_ejson({L}) -> [{Name, from_ejson(Value)} || {Name, Value} <- L]; from_ejson(T) -> T. to_binary(B) when is_binary(B) -> B; to_binary(L) when is_list(L) -> iolist_to_binary(L).
4c86cacda755e303dfff8db899c800859cf592a9fdbcb86606e059937b41ce96
inhabitedtype/ocaml-aws
describeGlobalClusters.ml
open Types open Aws type input = DescribeGlobalClustersMessage.t type output = GlobalClustersMessage.t type error = Errors_internal.t let service = "rds" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2014-10-31" ]; "Action", [ "DescribeGlobalClusters" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (DescribeGlobalClustersMessage.to_query req))))) in `POST, uri, [] let of_http body = try let xml = Ezxmlm.from_string body in let resp = Util.option_bind (Xml.member "DescribeGlobalClustersResponse" (snd xml)) (Xml.member "DescribeGlobalClustersResult") in try Util.or_error (Util.option_bind resp GlobalClustersMessage.parse) (let open Error in BadResponse { body; message = "Could not find well formed GlobalClustersMessage." }) with Xml.RequiredFieldMissing msg -> let open Error in `Error (BadResponse { body ; message = "Error parsing GlobalClustersMessage - missing field in body or children: " ^ msg }) with Failure msg -> `Error (let open Error in BadResponse { body; message = "Error parsing xml: " ^ msg }) let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/rds/lib/describeGlobalClusters.ml
ocaml
open Types open Aws type input = DescribeGlobalClustersMessage.t type output = GlobalClustersMessage.t type error = Errors_internal.t let service = "rds" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2014-10-31" ]; "Action", [ "DescribeGlobalClusters" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (DescribeGlobalClustersMessage.to_query req))))) in `POST, uri, [] let of_http body = try let xml = Ezxmlm.from_string body in let resp = Util.option_bind (Xml.member "DescribeGlobalClustersResponse" (snd xml)) (Xml.member "DescribeGlobalClustersResult") in try Util.or_error (Util.option_bind resp GlobalClustersMessage.parse) (let open Error in BadResponse { body; message = "Could not find well formed GlobalClustersMessage." }) with Xml.RequiredFieldMissing msg -> let open Error in `Error (BadResponse { body ; message = "Error parsing GlobalClustersMessage - missing field in body or children: " ^ msg }) with Failure msg -> `Error (let open Error in BadResponse { body; message = "Error parsing xml: " ^ msg }) let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
53a553ef2c8be042e60ea9fb601f2a446963b75c4eaed0279f4b63d50b68c5b9
quil-lang/quilc
options.lisp
;;;; options.lisp ;;;; Author : (in-package #:cl-quil) ;;; The variables below allow for general configuration of the ;;; compiler. For frontend specific configuration, see ;;; frontend-options.lisp. More configuration of the compressor ;;; specifically can be found in compressor-configuration.lisp. (defvar *recognize-swap-specially* t "Make SWAP-APPLICATION nodes specially for SWAP instructions.") (defvar *compress-carefully* nil "Flag that turns on/off a bunch of intermediate correctness checks during compression. WARNING: this can be *very* costly, since it involves computing explicit matrix presentations.") (defvar *check-math* t "Flag that turns on even more math correctness checks. This may slow things down considerably.") (defvar *enable-approximate-compilation* nil "When NIL, compression by replacing instructions sequences with approximate sequences is disabled. NOTE: When T, this permits the approximate compilation templates to emit inexact results, but does not actually enable any alternative code paths. When NIL, these results are still generated, but they are discarded.")
null
https://raw.githubusercontent.com/quil-lang/quilc/9bc75f650fe06c78c22ed52c4e749401d3129c8c/src/options.lisp
lisp
options.lisp The variables below allow for general configuration of the compiler. For frontend specific configuration, see frontend-options.lisp. More configuration of the compressor specifically can be found in compressor-configuration.lisp.
Author : (in-package #:cl-quil) (defvar *recognize-swap-specially* t "Make SWAP-APPLICATION nodes specially for SWAP instructions.") (defvar *compress-carefully* nil "Flag that turns on/off a bunch of intermediate correctness checks during compression. WARNING: this can be *very* costly, since it involves computing explicit matrix presentations.") (defvar *check-math* t "Flag that turns on even more math correctness checks. This may slow things down considerably.") (defvar *enable-approximate-compilation* nil "When NIL, compression by replacing instructions sequences with approximate sequences is disabled. NOTE: When T, this permits the approximate compilation templates to emit inexact results, but does not actually enable any alternative code paths. When NIL, these results are still generated, but they are discarded.")
85af051b8e577ba5d7f1fddebdd21f608515e8d38ac8a886a4d7226616461d90
sneeuwballen/zipperposition
Bool_clause.ml
This file is free software , part of Zipperposition . See file " license " for more details . * { 1 Boolean Clause } open Logtk type bool_lit = BBox.Lit.t type t = bool_lit list let compare = CCOrd.list BBox.Lit.compare let pp = BBox.pp_bclause let pp_zf = Util.pp_list ~sep:" || " BBox.pp_zf let pp_tstp = Util.pp_list ~sep:" | " BBox.pp_tstp let pp_in = function | Output_format.O_zf -> pp_zf | Output_format.O_tptp -> pp_tstp | Output_format.O_normal -> pp | Output_format.O_none -> CCFormat.silent let to_form ~ctx:_ c = List.map BBox.to_s_form c |> TypedSTerm.Form.or_ exception E_proof of t let proof_tc = Proof.Result.make_tc ~of_exn:(function | E_proof c -> Some c | _ -> None) ~to_exn:(fun c -> E_proof c) ~compare:compare ~flavor:(fun _ -> `Pure_bool) ~to_form ~pp_in () let mk_proof_res = Proof.Result.make proof_tc let proof_res_as_bc r = let module P = Proof in begin match r with | P.Res (_, E_proof p) -> Some p | _ -> None end
null
https://raw.githubusercontent.com/sneeuwballen/zipperposition/7f1455fbe2e7509907f927649c288141b1a3a247/src/prover/Bool_clause.ml
ocaml
This file is free software , part of Zipperposition . See file " license " for more details . * { 1 Boolean Clause } open Logtk type bool_lit = BBox.Lit.t type t = bool_lit list let compare = CCOrd.list BBox.Lit.compare let pp = BBox.pp_bclause let pp_zf = Util.pp_list ~sep:" || " BBox.pp_zf let pp_tstp = Util.pp_list ~sep:" | " BBox.pp_tstp let pp_in = function | Output_format.O_zf -> pp_zf | Output_format.O_tptp -> pp_tstp | Output_format.O_normal -> pp | Output_format.O_none -> CCFormat.silent let to_form ~ctx:_ c = List.map BBox.to_s_form c |> TypedSTerm.Form.or_ exception E_proof of t let proof_tc = Proof.Result.make_tc ~of_exn:(function | E_proof c -> Some c | _ -> None) ~to_exn:(fun c -> E_proof c) ~compare:compare ~flavor:(fun _ -> `Pure_bool) ~to_form ~pp_in () let mk_proof_res = Proof.Result.make proof_tc let proof_res_as_bc r = let module P = Proof in begin match r with | P.Res (_, E_proof p) -> Some p | _ -> None end
2461fa1dee2621d3076986eb589fd9bdd4bfb847e5749833a83cc9d1b3ccbe1c
duelinmarkers/clj-record
boot.clj
(ns clj-record.boot "Requiring this one namespace will require everything needed to use clj-record." (:require (clj-record core callbacks associations validation serialization)))
null
https://raw.githubusercontent.com/duelinmarkers/clj-record/2dd5b9a1fcb8828565acfdf9919330bf4b5dbfaa/src/clj_record/boot.clj
clojure
(ns clj-record.boot "Requiring this one namespace will require everything needed to use clj-record." (:require (clj-record core callbacks associations validation serialization)))
295b638f0d0e2b54607c577221f888f1584da1a45b59a9b4b2ac36f2ae00a457
spawnfest/eep49ers
specs_and_funs.erl
-module(specs_and_funs). -export([my_apply/3, two/1]). OTP-15519 , -spec my_apply(Fun, Arg, fun((A) -> A)) -> Result when Fun :: fun((Arg) -> Result), Arg :: any(), Result :: any(). my_apply(Fun, Arg, _) -> Fun(Arg). -spec two(fun((A) -> A)) -> fun((B) -> B). two(F) -> F(fun(X) -> X end).
null
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/syntax_tools/test/syntax_tools_SUITE_data/specs_and_funs.erl
erlang
-module(specs_and_funs). -export([my_apply/3, two/1]). OTP-15519 , -spec my_apply(Fun, Arg, fun((A) -> A)) -> Result when Fun :: fun((Arg) -> Result), Arg :: any(), Result :: any(). my_apply(Fun, Arg, _) -> Fun(Arg). -spec two(fun((A) -> A)) -> fun((B) -> B). two(F) -> F(fun(X) -> X end).
cff210ca6ec8d2c6d3629839ad6bb9824261e07d0db892c20b5f42b5b6371c4f
joinr/spork
xml.clj
;;minor wrapper/extensions around clojure.xml. ;;convenience functions. (ns spork.util.xml (:require [clojure [xml :as xml]])) (defn getbytes [instring] (clojure.java.io/input-stream (.getBytes instring))) (defn xparse "Parse an xml source. Just a shadow for parse." [s] (xml/parse s)) (defn str->xml "Parse a string as if it were an xml source." [s] (xparse (getbytes s))) (def xemit xml/emit) (def xemit-element xml/emit-element) (def xtag xml/tag) (def xcontent xml/content) (def xattrs xml/attrs) (defrecord xelm [tag attrs content]) (defn make-xelm ([tag attrs content] (cond (or (nil? content) (vector? content)) (xelm. tag attrs content) (or (map? content) (set? content) (not (seq? content))) (xelm. tag attrs [content]) :true (xelm. tag attrs (apply vector content)))) ([tag] (make-xelm tag nil nil)) ([tag attrs] (make-xelm tag attrs nil))) (defn spit-xml [x] (with-out-str (xemit x)))
null
https://raw.githubusercontent.com/joinr/spork/bb80eddadf90bf92745bf5315217e25a99fbf9d6/src/spork/util/xml.clj
clojure
minor wrapper/extensions around clojure.xml. convenience functions.
(ns spork.util.xml (:require [clojure [xml :as xml]])) (defn getbytes [instring] (clojure.java.io/input-stream (.getBytes instring))) (defn xparse "Parse an xml source. Just a shadow for parse." [s] (xml/parse s)) (defn str->xml "Parse a string as if it were an xml source." [s] (xparse (getbytes s))) (def xemit xml/emit) (def xemit-element xml/emit-element) (def xtag xml/tag) (def xcontent xml/content) (def xattrs xml/attrs) (defrecord xelm [tag attrs content]) (defn make-xelm ([tag attrs content] (cond (or (nil? content) (vector? content)) (xelm. tag attrs content) (or (map? content) (set? content) (not (seq? content))) (xelm. tag attrs [content]) :true (xelm. tag attrs (apply vector content)))) ([tag] (make-xelm tag nil nil)) ([tag attrs] (make-xelm tag attrs nil))) (defn spit-xml [x] (with-out-str (xemit x)))
3e31e906cffa67126a450d96f142f9277646f853dd35c5ac851fd3ca4179a08e
hbr/albatross
deque.mli
type _ t val is_empty: _ t -> bool val has_some: _ t -> bool val empty: _ t val push_front: 'a -> 'a t -> 'a t val push_rear: 'a -> 'a t -> 'a t val pop_front: 'a t -> ('a * 'a t) option val update_first: ('a -> 'a) -> 'a t -> 'a t val update_last: ('a -> 'a) -> 'a t -> 'a t val to_list: 'a t -> 'a list
null
https://raw.githubusercontent.com/hbr/albatross/8f28ef97951f92f30dc69cf94c0bbe20d64fba21/ocaml/fmlib/basic/deque.mli
ocaml
type _ t val is_empty: _ t -> bool val has_some: _ t -> bool val empty: _ t val push_front: 'a -> 'a t -> 'a t val push_rear: 'a -> 'a t -> 'a t val pop_front: 'a t -> ('a * 'a t) option val update_first: ('a -> 'a) -> 'a t -> 'a t val update_last: ('a -> 'a) -> 'a t -> 'a t val to_list: 'a t -> 'a list
ff9bff8c6fc49717b993b97447ee579f140cef97c6a7b68355bd7e8e0d75c6aa
paulcadman/the-little-typer
int-Nat.rkt
#lang pie Exercises on and ind - Nat from Chapters 6 and 7 of The Little Typer (claim + (-> Nat Nat Nat)) (define + (λ (a b) (rec-Nat a b (λ (a-k b+a-k) (add1 b+a-k))))) Exercise 7.0 ;; Define a function called zip that takes an argument of type ( ) and a second argument of type ( Vec B n ) and evaluates to a vlue of type ( ( Pair A B ) n ) , the result of zipping the first and second arguments . Exercise 7.1 ;; ;; Define a function called append that takes an argument of type (Vec E n) and an argument of type ( Vect E m ) and evaluates to a value of type ( ( + n m ) ) , the result of appending the elements of the second argument to the end of the first . (claim append (Π ([E U] [n Nat] [m Nat]) (-> (Vec E n) (Vec E m) (Vec E (+ n m))))) Exercise 7.2 ;; Define a function called drop - last - k that takes an argument of type ( E ? ) and evaluates to a value of type ( E ? ) , the result of dropping the last k elements from the first argument . ;; NB : The type of the function should guarantee that we ca n't drop more elements than there are in the first argument .
null
https://raw.githubusercontent.com/paulcadman/the-little-typer/0a5c6877a902f26fc7f100de593f44f6a986624c/exercises/int-Nat.rkt
racket
Define a function called append that takes an argument of type (Vec E n) and an
#lang pie Exercises on and ind - Nat from Chapters 6 and 7 of The Little Typer (claim + (-> Nat Nat Nat)) (define + (λ (a b) (rec-Nat a b (λ (a-k b+a-k) (add1 b+a-k))))) Exercise 7.0 Define a function called zip that takes an argument of type ( ) and a second argument of type ( Vec B n ) and evaluates to a vlue of type ( ( Pair A B ) n ) , the result of zipping the first and second arguments . Exercise 7.1 argument of type ( Vect E m ) and evaluates to a value of type ( ( + n m ) ) , the result of appending the elements of the second argument to the end of the first . (claim append (Π ([E U] [n Nat] [m Nat]) (-> (Vec E n) (Vec E m) (Vec E (+ n m))))) Exercise 7.2 Define a function called drop - last - k that takes an argument of type ( E ? ) and evaluates to a value of type ( E ? ) , the result of dropping the last k elements from the first argument . NB : The type of the function should guarantee that we ca n't drop more elements than there are in the first argument .
2a135344bd59a28c93985de348dc21b4eb130ebb5b74d6b1789b0faf8cb7bafe
ygrek/mldonkey
configwin_messages.ml
(**************************************************************************) Copyright 2003 , 2002 b8_bavard , , , b52_simon INRIA (* *) (* This file is part of mldonkey. *) (* *) 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. *) (* *) 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 mldonkey ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA (* *) (**************************************************************************) * Module containing the messages of Configwin . open Gettext let software = "Configwin";; let version = "0.94";; let _s x = _s "Configwin" x let _b x = _b "Configwin" x let mAdd = _s "Add";; let mRemove = _s "Remove";; let mUp = _s "Up";; let mEdit = _s "Edit";; let mOk = _s "Ok";; let mCancel = _s "Cancel";; let mApply = _s "Apply";; let mValue = _s "Value"
null
https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/gtk/configwin/configwin_messages.ml
ocaml
************************************************************************ This file is part of mldonkey. or (at your option) any later version. 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. ************************************************************************
Copyright 2003 , 2002 b8_bavard , , , b52_simon INRIA 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 , is distributed in the hope that it will be useful , You should have received a copy of the GNU General Public License along with mldonkey ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * Module containing the messages of Configwin . open Gettext let software = "Configwin";; let version = "0.94";; let _s x = _s "Configwin" x let _b x = _b "Configwin" x let mAdd = _s "Add";; let mRemove = _s "Remove";; let mUp = _s "Up";; let mEdit = _s "Edit";; let mOk = _s "Ok";; let mCancel = _s "Cancel";; let mApply = _s "Apply";; let mValue = _s "Value"
4db8c853938e9d417bb870e0531768ec69d2f044eecca6e37065db03d29d1a0a
vii/teepeedee2
frame.lisp
(in-package #:tpd2.webapp) (defmyclass (frame (:include simple-channel)) current-page (site (current-site)) variables (username (random-name)) timeout trace-info destroy-hooks) (defvar *frames* (make-hash-table :test #'equalp)) (my-defun frame exit () (loop for hook in (my destroy-hooks) do (funcall hook me)) (my 'channel-destroy) (remhash (my id) *frames*)) (my-defun frame reset-timeout () (timeout-set (my timeout) (* 5 60))) (my-defun frame 'initialize-instance :after (&key) (setf (gethash (my id) *frames*) me) (setf (my timeout) (make-timeout :func (lambda()(my exit)))) (my reset-timeout)) (defun find-frame (id) (gethash id *frames*)) (defun-speedy webapp-frame-available-p () (and (boundp '*webapp-frame*) *webapp-frame*)) (defun webapp-frame (&rest args-for-make-frame) (unless *webapp-frame* (setf *webapp-frame* (apply 'make-frame args-for-make-frame))) *webapp-frame*) (my-defun frame var (id &optional default) (getf (my variables) id default)) (my-defun frame (setf var) (val id) (setf (getf (my variables) id) val)) (defun webapp-frame-var (id &optional default) (frame-var (webapp-frame) id default)) (defun (setf webapp-frame-var) (val id &optional default) (declare (ignore default)) (setf (frame-var (webapp-frame) id) val)) (defun list-all-frames () (let (ret) (maphash (lambda(k v)(declare (ignore k))(push v ret)) *frames*) ret)) (defun frame-id (frame) (channel-id frame)) (my-defun frame change-username (new-name) (setf (my username) new-name) (my notify) new-name) (my-defun frame 'simple-channel-body-ml ())
null
https://raw.githubusercontent.com/vii/teepeedee2/a2ed78c51d782993591c3284562daeed3aba3d40/src/webapp/frame.lisp
lisp
(in-package #:tpd2.webapp) (defmyclass (frame (:include simple-channel)) current-page (site (current-site)) variables (username (random-name)) timeout trace-info destroy-hooks) (defvar *frames* (make-hash-table :test #'equalp)) (my-defun frame exit () (loop for hook in (my destroy-hooks) do (funcall hook me)) (my 'channel-destroy) (remhash (my id) *frames*)) (my-defun frame reset-timeout () (timeout-set (my timeout) (* 5 60))) (my-defun frame 'initialize-instance :after (&key) (setf (gethash (my id) *frames*) me) (setf (my timeout) (make-timeout :func (lambda()(my exit)))) (my reset-timeout)) (defun find-frame (id) (gethash id *frames*)) (defun-speedy webapp-frame-available-p () (and (boundp '*webapp-frame*) *webapp-frame*)) (defun webapp-frame (&rest args-for-make-frame) (unless *webapp-frame* (setf *webapp-frame* (apply 'make-frame args-for-make-frame))) *webapp-frame*) (my-defun frame var (id &optional default) (getf (my variables) id default)) (my-defun frame (setf var) (val id) (setf (getf (my variables) id) val)) (defun webapp-frame-var (id &optional default) (frame-var (webapp-frame) id default)) (defun (setf webapp-frame-var) (val id &optional default) (declare (ignore default)) (setf (frame-var (webapp-frame) id) val)) (defun list-all-frames () (let (ret) (maphash (lambda(k v)(declare (ignore k))(push v ret)) *frames*) ret)) (defun frame-id (frame) (channel-id frame)) (my-defun frame change-username (new-name) (setf (my username) new-name) (my notify) new-name) (my-defun frame 'simple-channel-body-ml ())
f7cb72024b34d9e366b2639fc1abadb8b9f011139a3fe1d4d9146c8853c07fa8
sjl/newseasons
settings-vagrant.clj
(ns newseasons.settings) (def redis-pass "devpass") (def postmark-api-key "POSTMARK_API_TEST")
null
https://raw.githubusercontent.com/sjl/newseasons/9f3bce450b413ee065abcf1b6b5b7dbdd8728481/src/newseasons/settings-vagrant.clj
clojure
(ns newseasons.settings) (def redis-pass "devpass") (def postmark-api-key "POSTMARK_API_TEST")
ba417fcee20d738320e900f160be85a2688017e76ed862aeb23329de85257885
danr/hipspec
Int.hs
module Int where fac :: Int -> Int fac 0 = 0 fac n = n * fac (n - 1)
null
https://raw.githubusercontent.com/danr/hipspec/a114db84abd5fee8ce0b026abc5380da11147aa9/tfp1/tests/should_fail/Int.hs
haskell
module Int where fac :: Int -> Int fac 0 = 0 fac n = n * fac (n - 1)
d89bc6878735ea080a5d057b2f08e2108e01f0ccc5964136877ad6e1aae91c93
poscat0x04/telegram-types
PollOption.hs
module Web.Telegram.Types.Internal.PollOption where import Common | Information about one answer option in a poll . data PollOption = PollOption | Option text , 1 - 100 characters text :: Text, -- | Number of users that voted for this option voterCount :: Int } deriving stock (Show, Eq) mkLabel ''PollOption deriveJSON snake ''PollOption
null
https://raw.githubusercontent.com/poscat0x04/telegram-types/c09ccc81cff10399538894cf2d1273022c797e18/src/Web/Telegram/Types/Internal/PollOption.hs
haskell
| Number of users that voted for this option
module Web.Telegram.Types.Internal.PollOption where import Common | Information about one answer option in a poll . data PollOption = PollOption | Option text , 1 - 100 characters text :: Text, voterCount :: Int } deriving stock (Show, Eq) mkLabel ''PollOption deriveJSON snake ''PollOption
0898af6777a81b4339356d74c45cd58d0c5dc7c6534f3dd5bc77a638cf928acc
squirrel-prover/squirrel-prover
bullets.mli
(** Management of bullets and braces in proof scripts. *) (** Bullet symbols. *) type bullet = string (** Path through a proof tree under construction. *) type path val pp : Format.formatter -> path -> unit val initial_path : path val empty_path : path val is_empty : path -> bool val tactic_allowed : path -> bool exception Decoration_not_allowed (** Multiple bullets or braces, bullet after brace, closing brace on unclosed goal or on goal without an open brace, or attempt to decorate empty path. *) exception Closing_brace_needed (** Raised if some operation is attempted when a closing brace is needed. *) exception Bullet_expected (** Raised if some operation is attempted when a bullet is expected. *) * Close current subgoal . val close_goal : path -> path * Expand current subgoal to some number of subgoals . Equivalent to [ close_goal ] when the number of subgoals is zero . Equivalent to [close_goal] when the number of subgoals is zero. *) val expand_goal : int -> path -> path val open_bullet : bullet -> path -> path val open_brace : path -> path val close_brace : path -> path
null
https://raw.githubusercontent.com/squirrel-prover/squirrel-prover/d25b6dab570ea0e99915059a67599fd3a38caa8b/src/bullets.mli
ocaml
* Management of bullets and braces in proof scripts. * Bullet symbols. * Path through a proof tree under construction. * Multiple bullets or braces, bullet after brace, closing brace on unclosed goal or on goal without an open brace, or attempt to decorate empty path. * Raised if some operation is attempted when a closing brace is needed. * Raised if some operation is attempted when a bullet is expected.
type bullet = string type path val pp : Format.formatter -> path -> unit val initial_path : path val empty_path : path val is_empty : path -> bool val tactic_allowed : path -> bool exception Decoration_not_allowed exception Closing_brace_needed exception Bullet_expected * Close current subgoal . val close_goal : path -> path * Expand current subgoal to some number of subgoals . Equivalent to [ close_goal ] when the number of subgoals is zero . Equivalent to [close_goal] when the number of subgoals is zero. *) val expand_goal : int -> path -> path val open_bullet : bullet -> path -> path val open_brace : path -> path val close_brace : path -> path
adfda2d4f11801cd89d364a793154c86456a181406c14acb12fb5d4bcad944c8
yetanalytics/dl4clj
default_gradient.clj
(ns ^{:doc "Default gradient implementation. Basically lookup table for ndarrays see: "} dl4clj.nn.gradient.default-gradient (:import [org.deeplearning4j.nn.gradient DefaultGradient]) (:require [nd4clj.linalg.factory.nd4j :refer [vec-or-matrix->indarray]] [dl4clj.utils :refer [obj-or-code?]])) (defn new-default-gradient [& {:keys [flattened-gradient as-code?] :or {as-code? true} :as opts}] (let [code (if flattened-gradient `(DefaultGradient. (vec-or-matrix->indarray ~flattened-gradient)) `(DefaultGradient.))] (obj-or-code? as-code? code)))
null
https://raw.githubusercontent.com/yetanalytics/dl4clj/9ef055b2a460f1a6246733713136b981fd322510/src/dl4clj/nn/gradient/default_gradient.clj
clojure
(ns ^{:doc "Default gradient implementation. Basically lookup table for ndarrays see: "} dl4clj.nn.gradient.default-gradient (:import [org.deeplearning4j.nn.gradient DefaultGradient]) (:require [nd4clj.linalg.factory.nd4j :refer [vec-or-matrix->indarray]] [dl4clj.utils :refer [obj-or-code?]])) (defn new-default-gradient [& {:keys [flattened-gradient as-code?] :or {as-code? true} :as opts}] (let [code (if flattened-gradient `(DefaultGradient. (vec-or-matrix->indarray ~flattened-gradient)) `(DefaultGradient.))] (obj-or-code? as-code? code)))
a2c867113e158239c85a79ba389b13df2b51681f9fe56b4b1bab3c50f4ac8abe
weyrick/roadsend-php
output-buffering.scm
;; ***** BEGIN LICENSE BLOCK ***** Roadsend PHP Compiler Runtime Libraries Copyright ( C ) 2007 Roadsend , 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 ; either version 2.1 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 . ;; You should have received a copy of the GNU Lesser 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 ;; ***** END LICENSE BLOCK ***** (module output-buffering (import (utils "utils.scm") (php-runtime "php-runtime.scm") (php-hash "php-hash.scm") (url-rewriter "url-rewriter.scm") (php-object "php-object.scm") (php-errors "php-errors.scm") (signatures "signatures.scm") (php-ini "php-ini.scm")) (load (php-macros "../php-macros.scm")) (export PHP_OUTPUT_HANDLER_START PHP_OUTPUT_HANDLER_CONT PHP_OUTPUT_HANDLER_END *output-buffer-implicit-flush?* *output-buffer-stack* *output-callback-stack* *output-rewrite-vars* (maybe-init-url-rewriter) (ob-reset!) (ob-start callback) (ob-pop-stacks) (ob-verify-stacks) (ob-flush-to-next from to callback) (ob-flush) (ob-flush-all) (ob-rewrite-urls output))) (define *output-buffer-implicit-flush?* #f) (defconstant PHP_OUTPUT_HANDLER_START 1) (defconstant PHP_OUTPUT_HANDLER_CONT (bit-lsh 1 1)) (defconstant PHP_OUTPUT_HANDLER_END (bit-lsh 1 2)) ;the top of this stack is the current output buffer, if the stack is ;empty output is unbuffered (define *output-buffer-stack* '()) ; this should mirror the output-buffer-stack: always the same length. ; either there will be a string representing the function to call, or ; a nil. (define *output-callback-stack* '()) ; for url rewriter (define *output-rewrite-vars* (make-hashtable)) ; called each page view (define (ob-reset!) (set! *output-buffer-stack* '()) (set! *output-callback-stack* '()) (unless (=fx (hashtable-size *output-rewrite-vars*) 0) (set! *output-rewrite-vars* (make-hashtable)))) (define (maybe-init-url-rewriter) (when (convert-to-boolean (get-ini-entry "session.use_trans_id")) defbuiltin is defined in ext / standard / php - output - control.scm (ob-start "_internal_url_rewriter"))) ; rewrite urls for transparent session ids (define (ob-build-get-vars) (let ((getvars "")) (hashtable-for-each *output-rewrite-vars* (lambda (k v) (set! getvars (mkstr getvars k "=" v "&")))) (substring getvars 0 (max 0 (- (string-length getvars) 1))))) (define (ob-build-post-vars) (let ((postvars "")) (hashtable-for-each *output-rewrite-vars* (lambda (k v) (set! postvars (string-append postvars (format "<input type=\"hidden\" name=\"~a\" value=\"~a\">~%" k v))))) postvars)) (define (ob-rewrite-urls output) (let ((getvars (ob-build-get-vars)) (postvars (ob-build-post-vars)) (tags-to-rewrite (get-ini-entry "url_rewriter.tags"))) ; list of tags to replace comes from tags-to-rewrite which defaults to " a = href , area , frame = src , input = src , form = fakeentry " per php ini (let ((a? #f) (area? #f) (frame? #f) (input? #f) (form? #f)) (let ((rg (regular-grammar () ("a=href" (set! a? #t)) ("area=href" (set! area? #t)) ("frame=src" (set! frame? #t)) ("input=src" (set! input? #t)) ("form=fakeentry" (set! form? #t)) ("," 'woo!)))) (get-tokens-from-string rg tags-to-rewrite) (debug-trace 4 "rewrite tags: a? " a? ", area? " area? ", frame? " frame? ", input? " input? ", form? " form?)) (rewrite-urls output getvars postvars a? area? frame? input? form?)))) (define (ob-start callback) (ob-verify-stacks) (set! *output-buffer-stack* (cons (open-output-string) *output-buffer-stack*)) (set! *output-callback-stack* (cons (if (eqv? callback 'unpassed) #f (if (php-hash? callback) (cons (container-value (php-hash-lookup-location callback #f 0)) (php-hash-lookup callback 1)) callback)) *output-callback-stack*)) ) (define (ob-pop-stacks) (ob-verify-stacks) (if (pair? *output-buffer-stack*) (begin (set! *output-buffer-stack* (cdr *output-buffer-stack*)) (set! *output-callback-stack* (cdr *output-callback-stack*)) #t) #f)) (define (ob-verify-stacks) (unless (= (length *output-callback-stack*) (length *output-buffer-stack*)) (php-error "verify-stacks: output buffer stacks currupted. callbacks: " *output-callback-stack* ", buffers " *output-buffer-stack*))) (define (ob-flush-to-next from to callback) "flush output from buffer from into buffer to, if to is #f, display the output" (let* ((len (length *output-buffer-stack*)) (output (close-output-port from)) XXX this is n't right yet see # 1156 (mode (cond ((= len 1) PHP_OUTPUT_HANDLER_START) ((eqv? to #f) PHP_OUTPUT_HANDLER_END) (else PHP_OUTPUT_HANDLER_END)))) (when callback ; a pair means we call a method (if (pair? callback) (set! output (mkstr (call-php-method (car callback) (cdr callback) output))) (let ((callback-sig (get-php-function-sig callback))) (if callback-sig (case (sig-length callback-sig) ((1) (set! output (mkstr (php-funcall callback output)))) ((2) (set! output (mkstr (php-funcall callback output mode)))) (else (php-error "output buffering callback has invalid number of arguments"))) (php-error "output buffering callback undefined: " callback))))) (if to (display output to) (begin (display output) )) #t)) (define (ob-flush) (let ((len (length *output-buffer-stack*))) (cond ((= len 1) (ob-flush-to-next (car *output-buffer-stack*) #f (car *output-callback-stack*))) ((> len 1) (ob-flush-to-next (car *output-buffer-stack*) (cadr *output-buffer-stack*) (car *output-callback-stack*))) (else #f)))) (define (ob-flush-all) (let loop () (ob-flush) (if (ob-pop-stacks) (loop))))
null
https://raw.githubusercontent.com/weyrick/roadsend-php/d6301a897b1a02d7a85bdb915bea91d0991eb158/runtime/output-buffering.scm
scheme
***** BEGIN LICENSE BLOCK ***** This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License either version 2.1 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 along with this program; if not, write to the Free Software ***** END LICENSE BLOCK ***** the top of this stack is the current output buffer, if the stack is empty output is unbuffered this should mirror the output-buffer-stack: always the same length. either there will be a string representing the function to call, or a nil. for url rewriter called each page view rewrite urls for transparent session ids list of tags to replace comes from tags-to-rewrite which defaults to a pair means we call a method
Roadsend PHP Compiler Runtime Libraries Copyright ( C ) 2007 Roadsend , Inc. of the License , or ( at your option ) any later version . GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA (module output-buffering (import (utils "utils.scm") (php-runtime "php-runtime.scm") (php-hash "php-hash.scm") (url-rewriter "url-rewriter.scm") (php-object "php-object.scm") (php-errors "php-errors.scm") (signatures "signatures.scm") (php-ini "php-ini.scm")) (load (php-macros "../php-macros.scm")) (export PHP_OUTPUT_HANDLER_START PHP_OUTPUT_HANDLER_CONT PHP_OUTPUT_HANDLER_END *output-buffer-implicit-flush?* *output-buffer-stack* *output-callback-stack* *output-rewrite-vars* (maybe-init-url-rewriter) (ob-reset!) (ob-start callback) (ob-pop-stacks) (ob-verify-stacks) (ob-flush-to-next from to callback) (ob-flush) (ob-flush-all) (ob-rewrite-urls output))) (define *output-buffer-implicit-flush?* #f) (defconstant PHP_OUTPUT_HANDLER_START 1) (defconstant PHP_OUTPUT_HANDLER_CONT (bit-lsh 1 1)) (defconstant PHP_OUTPUT_HANDLER_END (bit-lsh 1 2)) (define *output-buffer-stack* '()) (define *output-callback-stack* '()) (define *output-rewrite-vars* (make-hashtable)) (define (ob-reset!) (set! *output-buffer-stack* '()) (set! *output-callback-stack* '()) (unless (=fx (hashtable-size *output-rewrite-vars*) 0) (set! *output-rewrite-vars* (make-hashtable)))) (define (maybe-init-url-rewriter) (when (convert-to-boolean (get-ini-entry "session.use_trans_id")) defbuiltin is defined in ext / standard / php - output - control.scm (ob-start "_internal_url_rewriter"))) (define (ob-build-get-vars) (let ((getvars "")) (hashtable-for-each *output-rewrite-vars* (lambda (k v) (set! getvars (mkstr getvars k "=" v "&")))) (substring getvars 0 (max 0 (- (string-length getvars) 1))))) (define (ob-build-post-vars) (let ((postvars "")) (hashtable-for-each *output-rewrite-vars* (lambda (k v) (set! postvars (string-append postvars (format "<input type=\"hidden\" name=\"~a\" value=\"~a\">~%" k v))))) postvars)) (define (ob-rewrite-urls output) (let ((getvars (ob-build-get-vars)) (postvars (ob-build-post-vars)) (tags-to-rewrite (get-ini-entry "url_rewriter.tags"))) " a = href , area , frame = src , input = src , form = fakeentry " per php ini (let ((a? #f) (area? #f) (frame? #f) (input? #f) (form? #f)) (let ((rg (regular-grammar () ("a=href" (set! a? #t)) ("area=href" (set! area? #t)) ("frame=src" (set! frame? #t)) ("input=src" (set! input? #t)) ("form=fakeentry" (set! form? #t)) ("," 'woo!)))) (get-tokens-from-string rg tags-to-rewrite) (debug-trace 4 "rewrite tags: a? " a? ", area? " area? ", frame? " frame? ", input? " input? ", form? " form?)) (rewrite-urls output getvars postvars a? area? frame? input? form?)))) (define (ob-start callback) (ob-verify-stacks) (set! *output-buffer-stack* (cons (open-output-string) *output-buffer-stack*)) (set! *output-callback-stack* (cons (if (eqv? callback 'unpassed) #f (if (php-hash? callback) (cons (container-value (php-hash-lookup-location callback #f 0)) (php-hash-lookup callback 1)) callback)) *output-callback-stack*)) ) (define (ob-pop-stacks) (ob-verify-stacks) (if (pair? *output-buffer-stack*) (begin (set! *output-buffer-stack* (cdr *output-buffer-stack*)) (set! *output-callback-stack* (cdr *output-callback-stack*)) #t) #f)) (define (ob-verify-stacks) (unless (= (length *output-callback-stack*) (length *output-buffer-stack*)) (php-error "verify-stacks: output buffer stacks currupted. callbacks: " *output-callback-stack* ", buffers " *output-buffer-stack*))) (define (ob-flush-to-next from to callback) "flush output from buffer from into buffer to, if to is #f, display the output" (let* ((len (length *output-buffer-stack*)) (output (close-output-port from)) XXX this is n't right yet see # 1156 (mode (cond ((= len 1) PHP_OUTPUT_HANDLER_START) ((eqv? to #f) PHP_OUTPUT_HANDLER_END) (else PHP_OUTPUT_HANDLER_END)))) (when callback (if (pair? callback) (set! output (mkstr (call-php-method (car callback) (cdr callback) output))) (let ((callback-sig (get-php-function-sig callback))) (if callback-sig (case (sig-length callback-sig) ((1) (set! output (mkstr (php-funcall callback output)))) ((2) (set! output (mkstr (php-funcall callback output mode)))) (else (php-error "output buffering callback has invalid number of arguments"))) (php-error "output buffering callback undefined: " callback))))) (if to (display output to) (begin (display output) )) #t)) (define (ob-flush) (let ((len (length *output-buffer-stack*))) (cond ((= len 1) (ob-flush-to-next (car *output-buffer-stack*) #f (car *output-callback-stack*))) ((> len 1) (ob-flush-to-next (car *output-buffer-stack*) (cadr *output-buffer-stack*) (car *output-callback-stack*))) (else #f)))) (define (ob-flush-all) (let loop () (ob-flush) (if (ob-pop-stacks) (loop))))
7511b258a59fa1202d65ce5fce2fd6d77ac1ab422bf20199eb0dc15bcc2ca0e2
helins/wasm.cljc
read.cljc
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (ns helins.wasm.read "Reading data from a WASM module represented as a BinF view. In other words, decompilation. Unless one wants to design a custom module parsing environment, ultimately, one should use the `decompile` function from the `helins.wasm` namespace which does all the job for decompiling a whole WASM module. See README for namespace organization and naming scheme." {:author "Adam Helinski"} (:require [helins.binf :as binf] [helins.binf.int64 :as binf.int64] [helins.binf.leb128 :as binf.leb128] [helins.wasm.bin :as wasm.bin] [helins.wasm.count :as wasm.count] [helins.wasm.ir :as wasm.ir])) (declare code' custom' data' dataidx' elem' elemkind' elemidx' elemtype' export' exportdesc' expr' func' funcidx' global' globalidx' import' importdesc' instr' instr'+ labelidx' localidx' locals' mem' memidx' mut' opcode->f s32' s64' start' table' tableidx' typeidx' u32') ;;;;;;;;;; Private helpers (defn- -err Used for throwing when something from the BinF view is not understood . ([string view] (-err string view nil)) ([string view offset] (throw (ex-info string (cond-> {:wasm/view view} offset (assoc :wasm.err/offset offset)))))) ;;;;;;;;;; Conventions (defn vec' ([f view] (loop [i (u32' view) v []] (if (pos? i) (recur (dec i) (conj v (f view))) v))) ([ctx f view] (loop [ctx-2 ctx i (u32' view)] (if (pos? i) (recur (f ctx-2 view) (dec i)) ctx-2)))) Values / Byte (defn byte' [view] (binf/rr-u8 view)) ;;;;;;;;;; Values / Integers (defn i32' [view] (s32' view)) (defn i64' [view] (s64' view)) (defn s32' [view] (binf.leb128/rr-i32 view)) (defn s33' [view] (binf.leb128/rr-i64 view 33)) (defn s64' [view] (binf.leb128/rr-i64 view)) (defn u32' [view] (binf.leb128/rr-u32 view)) (defn u64' [view] (binf.leb128/rr-u64 view)) ;;;;;;;;;; Values / Floating-Point (defn f32' [view] (double (binf/rr-f32 view))) (defn f64' [view] (binf/rr-f64 view)) ;;;;;;;;;; Values / Names (defn name' [view] (binf/rr-buffer view (u32' view))) ;;;;;;;;;; Types / Reference Types (defn reftype' [view] (byte' view)) ;;;;;;;;;; Types / Value Types (defn valtype' [view] (byte' view)) ;;;;;;;;;; Types / Result Types (defn resulttype' [view] (not-empty (vec' valtype' view))) ;;;;;;;;;; Types / Function Types (defn funcref' [view] (let [b8-1 (byte' view)] (when (not= b8-1 wasm.bin/functype) (-err (str "Function type should start with 0x60, not: " b8-1) view wasm.count/byte'))) nil) (defn functype' [view] (funcref' view) [(resulttype' view) (resulttype' view)]) ;;;;;;;;;; Types / Limits (defn limits' [hmap view] (let [flag (byte' view)] (condp = flag wasm.bin/limits-min (wasm.ir/limits' hmap (u32' view)) wasm.bin/limits-minmax (wasm.ir/limits' hmap (u32' view) (u32' view)) (-err (str "Unknown limit type: " flag) view wasm.count/byte')))) ;;;;;;;;;; Types / Memory Types (defn memtype' [hmap view] (limits' hmap view)) ;;;;;;;;;; Types / Table types (defn tabletype' [hmap view] (let [reftype (reftype' view)] (wasm.ir/tabletype' (limits' hmap view) reftype))) ;;;;;;;;;; Types / Global types (defn globaltype' [hmap view] (wasm.ir/globaltype' hmap (valtype' view) (mut' view))) (defn mut' [view] (let [flag (byte' view)] (condp = flag wasm.bin/mut-const false wasm.bin/mut-var true (-err (str "Unknown mutability flag for global: " flag) view wasm.count/byte')))) Instructions / Control Instructions (defn blocktype' [view] (let [x (s33' view)] (if (< x (binf.int64/i* 0)) (let [x-2 (bit-and 0x7F (binf.int64/u8 x))] (if (= x-2 wasm.bin/blocktype-nil) nil [:wasm/valtype x-2])) [:wasm/typeidx (binf.int64/u32 x)]))) (defn block' [opvec ctx view] (conj opvec (blocktype' view) (instr'+ ctx view))) (defn loop' [opvec ctx view] (conj opvec (blocktype' view) (instr'+ ctx view))) (defn else' [ctx view] (instr'+ ctx view)) (defn if' [opvec ctx view] (let [opvec-2 (conj opvec (blocktype' view))] (loop [instr+ []] (let [opcode (byte' view)] (condp = opcode wasm.bin/else (conj opvec-2 instr+ (else' ctx view)) wasm.bin/end (conj opvec-2 instr+ []) (recur (conj instr+ (instr' ctx opcode view)))))))) (defn br' [opvec _ctx view] (conj opvec (labelidx' view))) (defn br_if' [opvec _ctx view] (br' opvec _ctx view)) (defn br_table' [opvec _ctx view] (conj opvec (vec' labelidx' view) (labelidx' view))) (defn call' [opvec _ctx view] (conj opvec (funcidx' view))) (defn call_indirect' [opvec _ctx view] (conj opvec (typeidx' view) (tableidx' view))) ;;;;;;;;; Instructions / Reference Instructions (defn ref-null' [opvec _ctx view] (conj opvec (reftype' view))) (defn ref-func' [opvec _ctx view] (conj opvec (funcidx' view))) Instructions / Parametric Instructions (defn select-t' [opvec _ctx view] (conj opvec (vec' valtype' view))) ;;;;;;;;;; Instructions / Variable Instructions (defn op-var-local "Used for local variable instructions." [opvec _ctx view] (conj opvec (localidx' view))) (defn op-var-global "Used for global variable instructions." [opvec _ctx view] (conj opvec (globalidx' view))) Instructions / Table Instructions (defn op-table "Table instruction involving a table index immediate." [opvec _ctx view] (conj opvec (tableidx' view))) (defn table-init' [opvec _ctx view] (conj opvec (elemidx' view) (tableidx' view))) (defn elem-drop' [opvec _ctx view] (conj opvec (elemidx' view))) (defn table-copy' [opvec _ctx view] (conj opvec (tableidx' view) (tableidx' view))) Instructions / Memory Instructions (defn memarg' [vect view] (conj vect (u32' view) (u32' view))) (defn op-memarg "Used for memory instructions that have a [[memarg']]." [opvec _ctx view] (memarg' opvec view)) (defn op-memory "Used for memory instructions that have a [[memidx']] as only immediate." [opvec _ctx view] (conj opvec (memidx' view))) (defn memory-init' [opvec _ctx view] (conj opvec (dataidx' view) (byte' view))) (defn data-drop' [opvec _ctx view] (conj opvec (dataidx' view))) (defn memory-copy' [opvec _ctx view] (conj opvec (byte' view) (byte' view))) (defn memory-fill' [opvec _ctx view] (conj opvec (byte' view))) Instructions / Numeric Instructions (defn op-constval "Used for numerical operations declaring a constant value." ([const] (partial op-constval const)) ([const opvec _ctx view] (conj opvec (const view)))) ;;;;;;;;;; Instructions / Expressions (def op-main->f "Map of **opcode** -> **reading function** for opcodes which: - Have any kind of immediate(s) - Is not 0xFC (the \"misc\" opcode that leads to a second-level opcode" {wasm.bin/block block' wasm.bin/loop- loop' wasm.bin/if- if' wasm.bin/br br' wasm.bin/br_if br_if' wasm.bin/br_table br_table' wasm.bin/call call' wasm.bin/call_indirect call_indirect' wasm.bin/ref-null ref-null' wasm.bin/ref-func ref-func' wasm.bin/select-t select-t' wasm.bin/local-get op-var-local wasm.bin/local-set op-var-local wasm.bin/local-tee op-var-local wasm.bin/global-get op-var-global wasm.bin/global-set op-var-global wasm.bin/table-get op-table wasm.bin/table-set op-table wasm.bin/i32-load op-memarg wasm.bin/i64-load op-memarg wasm.bin/f32-load op-memarg wasm.bin/f64-load op-memarg wasm.bin/i32-load8_s op-memarg wasm.bin/i32-load8_u op-memarg wasm.bin/i32-load16_s op-memarg wasm.bin/i32-load16_u op-memarg wasm.bin/i64-load8_s op-memarg wasm.bin/i64-load8_u op-memarg wasm.bin/i64-load16_s op-memarg wasm.bin/i64-load16_u op-memarg wasm.bin/i64-load32_s op-memarg wasm.bin/i64-load32_u op-memarg wasm.bin/i32-store op-memarg wasm.bin/i64-store op-memarg wasm.bin/f32-store op-memarg wasm.bin/f64-store op-memarg wasm.bin/i32-store8 op-memarg wasm.bin/i32-store16 op-memarg wasm.bin/i64-store8 op-memarg wasm.bin/i64-store16 op-memarg wasm.bin/i64-store32 op-memarg wasm.bin/memory-size op-memory wasm.bin/memory-grow op-memory wasm.bin/i32-const (op-constval i32') wasm.bin/i64-const (op-constval i64') wasm.bin/f32-const (op-constval f32') wasm.bin/f64-const (op-constval f64')}) (def op-misc->f "Map of **immediate** to \"misc\" opcode (0xFC)** -> **reading function**." {wasm.bin/memory-init memory-init' wasm.bin/data-drop data-drop' wasm.bin/memory-copy memory-copy' wasm.bin/memory-fill memory-fill' wasm.bin/table-init table-init' wasm.bin/elem-drop elem-drop' wasm.bin/table-copy table-copy' wasm.bin/table-grow op-table wasm.bin/table-size op-table wasm.bin/table-fill op-table}) (defn instr' ([ctx view] (instr' ctx (byte' view) view)) ([ctx opcode view] (let [opvec [opcode]] (if (= opcode wasm.bin/misc) (let [opcode-2 (u32' view) opvec-2 (conj opvec opcode-2)] (if-some [f-2 (op-misc->f opcode-2)] (f-2 opvec-2 ctx view) (do (when-not (contains? wasm.bin/opcode-misc->opsym opcode-2) (-err (str "Secondary opcode for miscellaneous opcode is not a recognized instruction: " opcode-2) view (wasm.count/u32' opcode-2))) opvec-2))) (if-some [f (op-main->f opcode)] (f opvec ctx view) (do (when-not (contains? wasm.bin/opcode-main->opsym opcode) (-err (str "This opcode is not a recognized instruction: " opcode) view wasm.count/byte')) opvec)))))) (defn instr'+ "Behaves same as [[expr']]." [ctx view] (expr' ctx view)) (defn expr' "For a vector of [[instr']]." [ctx view] (loop [instr+ []] (let [opcode (byte' view)] (if (= opcode wasm.bin/end) instr+ (recur (conj instr+ (instr' ctx opcode view))))))) ;;;;;;;;;; Modules / Indices (defn idx "For the time being at least, all WASM indices are represented as [[u32']] and hence, are read by this function." [view] (u32' view)) (def typeidx' idx) (def funcidx' idx) (def tableidx' idx) (def memidx' idx) (def globalidx' idx) (def elemidx' idx) (def dataidx' idx) (def localidx' idx) (def labelidx' idx) ;;;;;;;;;; Modules / Sections (defn section-id' [view] (byte' view)) (defn section' [view] (let [id (section-id' view)] (when-not (wasm.bin/section-id? id) (-err (str "Unknown section ID: " id) view wasm.count/section-id')) (let [n-byte (u32' view) start (binf/position view)] (binf/skip view n-byte) {:wasm.section/id id :wasm.section/view (binf/view view start n-byte)}))) ;;;;;;;;;; Modules / (Helpers) (defn func "For functions found in the funcsec and in imports. WASM specification does not have a special name for it since binary-wise it is simply a type index." [hmap view] (wasm.ir/func hmap (typeidx' view))) Modules / Custom Section (defn customsec' [ctx view] (custom' ctx view)) (defn custom' [ctx view] (update ctx :wasm/customsec (fnil conj []) {:wasm/name (name' view) :wasm/data (binf/view view (binf/position view) (binf/remaining view))})) Modules / Type Section (defn typesec' [ctx view] (vec' ctx (fn [ctx-2 view] (wasm.ir/assoc-type ctx-2 (wasm.ir/type-signature {} (functype' view)))) view)) ;;;;;;;;;; Modules / Import Section (defn importsec' [ctx view] (vec' ctx import' view)) (defn import' [ctx view] (importdesc' ctx view (wasm.ir/import' {} (name' view) (name' view)))) (defn importdesc-func "Helper for reading an imported function." [ctx view hmap] (wasm.ir/import-func ctx (func hmap view))) (defn importdesc-table "Helper for reading an imported table." [ctx view hmap] (wasm.ir/import-table ctx (tabletype' hmap view))) (defn importdesc-mem "Helper for reading an imported mem." [ctx view hmap] (wasm.ir/import-mem ctx (memtype' hmap view))) (defn importdesc-global "Helper for reading an imported global." [ctx view hmap] (wasm.ir/import-global ctx (globaltype' hmap view))) (defn importdesc' [ctx view hmap] (let [type (byte' view) f (condp = type wasm.bin/importdesc-func importdesc-func wasm.bin/importdesc-table importdesc-table wasm.bin/importdesc-mem importdesc-mem wasm.bin/importdesc-global importdesc-global (-err (str "Unknown type in import description: " type) view wasm.count/byte'))] (f ctx view hmap))) Modules / Function Section (defn funcsec' [ctx view] (vec' ctx (fn [ctx-2 view] (wasm.ir/assoc-func ctx-2 (func {} view))) view)) ;;;;;;;;;; Modules / Table Section (defn tablesec' [ctx view] (vec' ctx table' view)) (defn table' [ctx view] (wasm.ir/assoc-table ctx (tabletype' {} view))) ;;;;;;;;;; Modules / Memory Section (defn memsec' [ctx view] (vec' ctx mem' view)) (defn mem' [ctx view] (wasm.ir/assoc-mem ctx (memtype' {} view))) ;;;;;;;;;; Modules / Global section (defn globalsec' [ctx view] (vec' ctx global' view)) (defn global' [ctx view] (wasm.ir/assoc-global ctx (-> {} (globaltype' view) (assoc :wasm/expr (expr' ctx view))))) Modules / Export Section (defn exportsec' [ctx view] (vec' ctx export' view)) (defn export' [ctx view] (exportdesc' ctx view {:wasm/name (name' view)})) (defn exportdesc-any [ctx hmap k-space idx] (update-in ctx [:wasm/exportsec k-space idx] (fnil conj []) hmap)) (defn exportdesc-func "Helper for reading an exported func." [ctx view hmap] (exportdesc-any ctx hmap :wasm.export/func (funcidx' view))) (defn exportdesc-table "Helper for reading an exported table." [ctx view hmap] (exportdesc-any ctx hmap :wasm.export/table (tableidx' view))) (defn exportdesc-mem "Helper for reading an exported mem." [ctx view hmap] (exportdesc-any ctx hmap :wasm.export/mem (memidx' view))) (defn exportdesc-global "Helper for reading an exported global." [ctx view hmap] (exportdesc-any ctx hmap :wasm.export/global (globalidx' view))) (defn exportdesc' [ctx view hmap] (let [export-type (byte' view) f (condp = export-type wasm.bin/exportdesc-func exportdesc-func wasm.bin/exportdesc-table exportdesc-table wasm.bin/exportdesc-mem exportdesc-mem wasm.bin/exportdesc-global exportdesc-global (-err (str "Unknown type in export description: " type) view wasm.count/byte'))] (f ctx view hmap))) ;;;;;;;;;; Modules / Start Section (defn startsec' [ctx view] (wasm.ir/startsec' ctx (start' {} view))) (defn start' [hmap view] (wasm.ir/start' hmap (funcidx' view))) ;;;;;;;;;; Modules / Element Section (defn elemsec' [ctx view] (vec' ctx elem' view)) (defn elem' [ctx view] (wasm.ir/assoc-elem ctx (let [flag (byte' view) _ (when-not (<= 0x00 flag 0x07) (-err (str "Element segment flag is not in [0;7]: " flag) view wasm.count/byte')) hmap (if (even? flag) (-> (if (or (= flag 0x02) (= flag 0x06)) {:wasm/tableidx (tableidx' view)} {}) (assoc :wasm/offset (expr' ctx view) :wasm.elem/mode :active)) {:wasm.elem/mode (if (pos? (bit-and flag 2r010)) :declarative :passive)})] (if (pos? (bit-and flag 2r100)) (-> (if (= flag 0x04) hmap (assoc hmap :wasm/reftype (reftype' view))) (assoc :wasm.elem/resolve :expr :wasm.elem/vec (vec' (partial expr' ctx) view))) (-> (if (= flag 0x00) hmap (assoc hmap :wasm/elemkind (elemkind' view))) (assoc :wasm.elem/resolve :idx :wasm.elem/vec (vec' funcidx' view))))))) (defn elemkind' [view] (byte' view)) Modules / Code Section (defn codesec' "This function only finds functions and split them into individual BinF views. This allows for implementing, if needed one day, multithreaded reading on a function-per-function basis. For full decompilation, [[codesec'2]] is used later." [ctx view] (assoc-in ctx [:wasm/source :wasm.source/codesec] (reduce (fn [source-codesec _idx] (conj source-codesec (code' {} view))) [] (range (u32' view))))) (defn code' [hmap view] (let [n-byte (u32' view) start (binf/position view)] (binf/skip view n-byte) (assoc hmap :wasm.codesec/view (binf/view view start n-byte)))) (defn func' [hmap ctx view] (-> hmap (assoc :wasm/locals (locals' view) :wasm/expr (expr' ctx view)) (dissoc :wasm/code))) (defn locals' [view] (vec' (fn [view] [(u32' view) (valtype' view)]) view)) (defn codesec'2 "After applying [[codesec']], this function takes those function BinF views and actually reads them" [ctx] (let [idx-offset (or (ffirst (ctx :wasm/funcsec)) 0)] (update ctx :wasm/codesec (fn [codesec] (reduce-kv (fn [codesec-2 idx {:wasm.codesec/keys [view]}] (assoc codesec-2 (+ idx-offset idx) (func' {} ctx view))) codesec (get-in ctx [:wasm/source :wasm.source/codesec])))))) Modules / Data Section (defn datasec' [ctx view] (vec' ctx data' view)) (defn data' [ctx view] (-> ctx (update :wasm/dataidx inc) (assoc-in [:wasm/datasec (ctx :wasm/dataidx)] (let [flag (byte' view)] (when-not (<= 0x00 flag 0x02) (-err (str "Data segment flat is not in [0;2]: " flag) view wasm.count/byte')) (-> (if (= flag 0x01) {:wasm.data/mode :passive} (-> (if (= flag 0x02) {:wasm/memidx (memidx' view)} {}) (assoc :wasm/offset (expr' ctx view) :wasm.data/mode :active))) (assoc :wasm/buffer (binf/rr-buffer view (u32' view)))))))) Modules / Data Count Section (defn datacountsec' [ctx view] (wasm.ir/datacountsec' ctx (u32' view))) ;;;;;;;;;; Modules / Modules (defn magic' Checking for " \0asm " BOM ( reversed u32 because BinF view is little - endian as requested by the WASM specification ) . [view] (when (not= (binf/rr-u32 view) wasm.bin/magic) (-err "WASM file does not start with magic word" view 4))) (defn version' [view] (binf/rr-u32 view)) (defn section'+ "After applying [[module']], actually reads those sections as BinF views." [ctx] (reduce (fn [ctx-2 {:wasm.section/keys [id view]}] (if (= id wasm.bin/section-id-custom) (customsec' ctx-2 view) ((condp = id wasm.bin/section-id-type typesec' wasm.bin/section-id-import importsec' wasm.bin/section-id-func funcsec' wasm.bin/section-id-table tablesec' wasm.bin/section-id-mem memsec' wasm.bin/section-id-global globalsec' wasm.bin/section-id-export exportsec' wasm.bin/section-id-start startsec' wasm.bin/section-id-elem elemsec' wasm.bin/section-id-code codesec' wasm.bin/section-id-data datasec' wasm.bin/section-id-datacount datacountsec') ctx-2 view))) ctx (get-in ctx [:wasm/source :wasm.source/section+]))) (defn module' "Finds sections and split them into BinF views. Then, see [[section'+]]." [ctx view] (magic' view) (let [ctx-2 (assoc ctx :wasm/version (version' view))] (cond-> ctx-2 (pos? (binf/remaining view)) (assoc-in [:wasm/source :wasm.source/section+] (loop [section+ []] (if (pos? (binf/remaining view)) (recur (conj section+ (section' view))) section+))))))
null
https://raw.githubusercontent.com/helins/wasm.cljc/bef1393899089763e0114aefbaec6303838ec7a0/src/main/helins/wasm/read.cljc
clojure
Private helpers Conventions Values / Integers Values / Floating-Point Values / Names Types / Reference Types Types / Value Types Types / Result Types Types / Function Types Types / Limits Types / Memory Types Types / Table types Types / Global types Instructions / Reference Instructions Instructions / Variable Instructions Instructions / Expressions Modules / Indices Modules / Sections Modules / (Helpers) Modules / Import Section Modules / Table Section Modules / Memory Section Modules / Global section Modules / Start Section Modules / Element Section Modules / Modules
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (ns helins.wasm.read "Reading data from a WASM module represented as a BinF view. In other words, decompilation. Unless one wants to design a custom module parsing environment, ultimately, one should use the `decompile` function from the `helins.wasm` namespace which does all the job for decompiling a whole WASM module. See README for namespace organization and naming scheme." {:author "Adam Helinski"} (:require [helins.binf :as binf] [helins.binf.int64 :as binf.int64] [helins.binf.leb128 :as binf.leb128] [helins.wasm.bin :as wasm.bin] [helins.wasm.count :as wasm.count] [helins.wasm.ir :as wasm.ir])) (declare code' custom' data' dataidx' elem' elemkind' elemidx' elemtype' export' exportdesc' expr' func' funcidx' global' globalidx' import' importdesc' instr' instr'+ labelidx' localidx' locals' mem' memidx' mut' opcode->f s32' s64' start' table' tableidx' typeidx' u32') (defn- -err Used for throwing when something from the BinF view is not understood . ([string view] (-err string view nil)) ([string view offset] (throw (ex-info string (cond-> {:wasm/view view} offset (assoc :wasm.err/offset offset)))))) (defn vec' ([f view] (loop [i (u32' view) v []] (if (pos? i) (recur (dec i) (conj v (f view))) v))) ([ctx f view] (loop [ctx-2 ctx i (u32' view)] (if (pos? i) (recur (f ctx-2 view) (dec i)) ctx-2)))) Values / Byte (defn byte' [view] (binf/rr-u8 view)) (defn i32' [view] (s32' view)) (defn i64' [view] (s64' view)) (defn s32' [view] (binf.leb128/rr-i32 view)) (defn s33' [view] (binf.leb128/rr-i64 view 33)) (defn s64' [view] (binf.leb128/rr-i64 view)) (defn u32' [view] (binf.leb128/rr-u32 view)) (defn u64' [view] (binf.leb128/rr-u64 view)) (defn f32' [view] (double (binf/rr-f32 view))) (defn f64' [view] (binf/rr-f64 view)) (defn name' [view] (binf/rr-buffer view (u32' view))) (defn reftype' [view] (byte' view)) (defn valtype' [view] (byte' view)) (defn resulttype' [view] (not-empty (vec' valtype' view))) (defn funcref' [view] (let [b8-1 (byte' view)] (when (not= b8-1 wasm.bin/functype) (-err (str "Function type should start with 0x60, not: " b8-1) view wasm.count/byte'))) nil) (defn functype' [view] (funcref' view) [(resulttype' view) (resulttype' view)]) (defn limits' [hmap view] (let [flag (byte' view)] (condp = flag wasm.bin/limits-min (wasm.ir/limits' hmap (u32' view)) wasm.bin/limits-minmax (wasm.ir/limits' hmap (u32' view) (u32' view)) (-err (str "Unknown limit type: " flag) view wasm.count/byte')))) (defn memtype' [hmap view] (limits' hmap view)) (defn tabletype' [hmap view] (let [reftype (reftype' view)] (wasm.ir/tabletype' (limits' hmap view) reftype))) (defn globaltype' [hmap view] (wasm.ir/globaltype' hmap (valtype' view) (mut' view))) (defn mut' [view] (let [flag (byte' view)] (condp = flag wasm.bin/mut-const false wasm.bin/mut-var true (-err (str "Unknown mutability flag for global: " flag) view wasm.count/byte')))) Instructions / Control Instructions (defn blocktype' [view] (let [x (s33' view)] (if (< x (binf.int64/i* 0)) (let [x-2 (bit-and 0x7F (binf.int64/u8 x))] (if (= x-2 wasm.bin/blocktype-nil) nil [:wasm/valtype x-2])) [:wasm/typeidx (binf.int64/u32 x)]))) (defn block' [opvec ctx view] (conj opvec (blocktype' view) (instr'+ ctx view))) (defn loop' [opvec ctx view] (conj opvec (blocktype' view) (instr'+ ctx view))) (defn else' [ctx view] (instr'+ ctx view)) (defn if' [opvec ctx view] (let [opvec-2 (conj opvec (blocktype' view))] (loop [instr+ []] (let [opcode (byte' view)] (condp = opcode wasm.bin/else (conj opvec-2 instr+ (else' ctx view)) wasm.bin/end (conj opvec-2 instr+ []) (recur (conj instr+ (instr' ctx opcode view)))))))) (defn br' [opvec _ctx view] (conj opvec (labelidx' view))) (defn br_if' [opvec _ctx view] (br' opvec _ctx view)) (defn br_table' [opvec _ctx view] (conj opvec (vec' labelidx' view) (labelidx' view))) (defn call' [opvec _ctx view] (conj opvec (funcidx' view))) (defn call_indirect' [opvec _ctx view] (conj opvec (typeidx' view) (tableidx' view))) (defn ref-null' [opvec _ctx view] (conj opvec (reftype' view))) (defn ref-func' [opvec _ctx view] (conj opvec (funcidx' view))) Instructions / Parametric Instructions (defn select-t' [opvec _ctx view] (conj opvec (vec' valtype' view))) (defn op-var-local "Used for local variable instructions." [opvec _ctx view] (conj opvec (localidx' view))) (defn op-var-global "Used for global variable instructions." [opvec _ctx view] (conj opvec (globalidx' view))) Instructions / Table Instructions (defn op-table "Table instruction involving a table index immediate." [opvec _ctx view] (conj opvec (tableidx' view))) (defn table-init' [opvec _ctx view] (conj opvec (elemidx' view) (tableidx' view))) (defn elem-drop' [opvec _ctx view] (conj opvec (elemidx' view))) (defn table-copy' [opvec _ctx view] (conj opvec (tableidx' view) (tableidx' view))) Instructions / Memory Instructions (defn memarg' [vect view] (conj vect (u32' view) (u32' view))) (defn op-memarg "Used for memory instructions that have a [[memarg']]." [opvec _ctx view] (memarg' opvec view)) (defn op-memory "Used for memory instructions that have a [[memidx']] as only immediate." [opvec _ctx view] (conj opvec (memidx' view))) (defn memory-init' [opvec _ctx view] (conj opvec (dataidx' view) (byte' view))) (defn data-drop' [opvec _ctx view] (conj opvec (dataidx' view))) (defn memory-copy' [opvec _ctx view] (conj opvec (byte' view) (byte' view))) (defn memory-fill' [opvec _ctx view] (conj opvec (byte' view))) Instructions / Numeric Instructions (defn op-constval "Used for numerical operations declaring a constant value." ([const] (partial op-constval const)) ([const opvec _ctx view] (conj opvec (const view)))) (def op-main->f "Map of **opcode** -> **reading function** for opcodes which: - Have any kind of immediate(s) - Is not 0xFC (the \"misc\" opcode that leads to a second-level opcode" {wasm.bin/block block' wasm.bin/loop- loop' wasm.bin/if- if' wasm.bin/br br' wasm.bin/br_if br_if' wasm.bin/br_table br_table' wasm.bin/call call' wasm.bin/call_indirect call_indirect' wasm.bin/ref-null ref-null' wasm.bin/ref-func ref-func' wasm.bin/select-t select-t' wasm.bin/local-get op-var-local wasm.bin/local-set op-var-local wasm.bin/local-tee op-var-local wasm.bin/global-get op-var-global wasm.bin/global-set op-var-global wasm.bin/table-get op-table wasm.bin/table-set op-table wasm.bin/i32-load op-memarg wasm.bin/i64-load op-memarg wasm.bin/f32-load op-memarg wasm.bin/f64-load op-memarg wasm.bin/i32-load8_s op-memarg wasm.bin/i32-load8_u op-memarg wasm.bin/i32-load16_s op-memarg wasm.bin/i32-load16_u op-memarg wasm.bin/i64-load8_s op-memarg wasm.bin/i64-load8_u op-memarg wasm.bin/i64-load16_s op-memarg wasm.bin/i64-load16_u op-memarg wasm.bin/i64-load32_s op-memarg wasm.bin/i64-load32_u op-memarg wasm.bin/i32-store op-memarg wasm.bin/i64-store op-memarg wasm.bin/f32-store op-memarg wasm.bin/f64-store op-memarg wasm.bin/i32-store8 op-memarg wasm.bin/i32-store16 op-memarg wasm.bin/i64-store8 op-memarg wasm.bin/i64-store16 op-memarg wasm.bin/i64-store32 op-memarg wasm.bin/memory-size op-memory wasm.bin/memory-grow op-memory wasm.bin/i32-const (op-constval i32') wasm.bin/i64-const (op-constval i64') wasm.bin/f32-const (op-constval f32') wasm.bin/f64-const (op-constval f64')}) (def op-misc->f "Map of **immediate** to \"misc\" opcode (0xFC)** -> **reading function**." {wasm.bin/memory-init memory-init' wasm.bin/data-drop data-drop' wasm.bin/memory-copy memory-copy' wasm.bin/memory-fill memory-fill' wasm.bin/table-init table-init' wasm.bin/elem-drop elem-drop' wasm.bin/table-copy table-copy' wasm.bin/table-grow op-table wasm.bin/table-size op-table wasm.bin/table-fill op-table}) (defn instr' ([ctx view] (instr' ctx (byte' view) view)) ([ctx opcode view] (let [opvec [opcode]] (if (= opcode wasm.bin/misc) (let [opcode-2 (u32' view) opvec-2 (conj opvec opcode-2)] (if-some [f-2 (op-misc->f opcode-2)] (f-2 opvec-2 ctx view) (do (when-not (contains? wasm.bin/opcode-misc->opsym opcode-2) (-err (str "Secondary opcode for miscellaneous opcode is not a recognized instruction: " opcode-2) view (wasm.count/u32' opcode-2))) opvec-2))) (if-some [f (op-main->f opcode)] (f opvec ctx view) (do (when-not (contains? wasm.bin/opcode-main->opsym opcode) (-err (str "This opcode is not a recognized instruction: " opcode) view wasm.count/byte')) opvec)))))) (defn instr'+ "Behaves same as [[expr']]." [ctx view] (expr' ctx view)) (defn expr' "For a vector of [[instr']]." [ctx view] (loop [instr+ []] (let [opcode (byte' view)] (if (= opcode wasm.bin/end) instr+ (recur (conj instr+ (instr' ctx opcode view))))))) (defn idx "For the time being at least, all WASM indices are represented as [[u32']] and hence, are read by this function." [view] (u32' view)) (def typeidx' idx) (def funcidx' idx) (def tableidx' idx) (def memidx' idx) (def globalidx' idx) (def elemidx' idx) (def dataidx' idx) (def localidx' idx) (def labelidx' idx) (defn section-id' [view] (byte' view)) (defn section' [view] (let [id (section-id' view)] (when-not (wasm.bin/section-id? id) (-err (str "Unknown section ID: " id) view wasm.count/section-id')) (let [n-byte (u32' view) start (binf/position view)] (binf/skip view n-byte) {:wasm.section/id id :wasm.section/view (binf/view view start n-byte)}))) (defn func "For functions found in the funcsec and in imports. WASM specification does not have a special name for it since binary-wise it is simply a type index." [hmap view] (wasm.ir/func hmap (typeidx' view))) Modules / Custom Section (defn customsec' [ctx view] (custom' ctx view)) (defn custom' [ctx view] (update ctx :wasm/customsec (fnil conj []) {:wasm/name (name' view) :wasm/data (binf/view view (binf/position view) (binf/remaining view))})) Modules / Type Section (defn typesec' [ctx view] (vec' ctx (fn [ctx-2 view] (wasm.ir/assoc-type ctx-2 (wasm.ir/type-signature {} (functype' view)))) view)) (defn importsec' [ctx view] (vec' ctx import' view)) (defn import' [ctx view] (importdesc' ctx view (wasm.ir/import' {} (name' view) (name' view)))) (defn importdesc-func "Helper for reading an imported function." [ctx view hmap] (wasm.ir/import-func ctx (func hmap view))) (defn importdesc-table "Helper for reading an imported table." [ctx view hmap] (wasm.ir/import-table ctx (tabletype' hmap view))) (defn importdesc-mem "Helper for reading an imported mem." [ctx view hmap] (wasm.ir/import-mem ctx (memtype' hmap view))) (defn importdesc-global "Helper for reading an imported global." [ctx view hmap] (wasm.ir/import-global ctx (globaltype' hmap view))) (defn importdesc' [ctx view hmap] (let [type (byte' view) f (condp = type wasm.bin/importdesc-func importdesc-func wasm.bin/importdesc-table importdesc-table wasm.bin/importdesc-mem importdesc-mem wasm.bin/importdesc-global importdesc-global (-err (str "Unknown type in import description: " type) view wasm.count/byte'))] (f ctx view hmap))) Modules / Function Section (defn funcsec' [ctx view] (vec' ctx (fn [ctx-2 view] (wasm.ir/assoc-func ctx-2 (func {} view))) view)) (defn tablesec' [ctx view] (vec' ctx table' view)) (defn table' [ctx view] (wasm.ir/assoc-table ctx (tabletype' {} view))) (defn memsec' [ctx view] (vec' ctx mem' view)) (defn mem' [ctx view] (wasm.ir/assoc-mem ctx (memtype' {} view))) (defn globalsec' [ctx view] (vec' ctx global' view)) (defn global' [ctx view] (wasm.ir/assoc-global ctx (-> {} (globaltype' view) (assoc :wasm/expr (expr' ctx view))))) Modules / Export Section (defn exportsec' [ctx view] (vec' ctx export' view)) (defn export' [ctx view] (exportdesc' ctx view {:wasm/name (name' view)})) (defn exportdesc-any [ctx hmap k-space idx] (update-in ctx [:wasm/exportsec k-space idx] (fnil conj []) hmap)) (defn exportdesc-func "Helper for reading an exported func." [ctx view hmap] (exportdesc-any ctx hmap :wasm.export/func (funcidx' view))) (defn exportdesc-table "Helper for reading an exported table." [ctx view hmap] (exportdesc-any ctx hmap :wasm.export/table (tableidx' view))) (defn exportdesc-mem "Helper for reading an exported mem." [ctx view hmap] (exportdesc-any ctx hmap :wasm.export/mem (memidx' view))) (defn exportdesc-global "Helper for reading an exported global." [ctx view hmap] (exportdesc-any ctx hmap :wasm.export/global (globalidx' view))) (defn exportdesc' [ctx view hmap] (let [export-type (byte' view) f (condp = export-type wasm.bin/exportdesc-func exportdesc-func wasm.bin/exportdesc-table exportdesc-table wasm.bin/exportdesc-mem exportdesc-mem wasm.bin/exportdesc-global exportdesc-global (-err (str "Unknown type in export description: " type) view wasm.count/byte'))] (f ctx view hmap))) (defn startsec' [ctx view] (wasm.ir/startsec' ctx (start' {} view))) (defn start' [hmap view] (wasm.ir/start' hmap (funcidx' view))) (defn elemsec' [ctx view] (vec' ctx elem' view)) (defn elem' [ctx view] (wasm.ir/assoc-elem ctx (let [flag (byte' view) _ (when-not (<= 0x00 flag 0x07) (-err (str "Element segment flag is not in [0;7]: " flag) view wasm.count/byte')) hmap (if (even? flag) (-> (if (or (= flag 0x02) (= flag 0x06)) {:wasm/tableidx (tableidx' view)} {}) (assoc :wasm/offset (expr' ctx view) :wasm.elem/mode :active)) {:wasm.elem/mode (if (pos? (bit-and flag 2r010)) :declarative :passive)})] (if (pos? (bit-and flag 2r100)) (-> (if (= flag 0x04) hmap (assoc hmap :wasm/reftype (reftype' view))) (assoc :wasm.elem/resolve :expr :wasm.elem/vec (vec' (partial expr' ctx) view))) (-> (if (= flag 0x00) hmap (assoc hmap :wasm/elemkind (elemkind' view))) (assoc :wasm.elem/resolve :idx :wasm.elem/vec (vec' funcidx' view))))))) (defn elemkind' [view] (byte' view)) Modules / Code Section (defn codesec' "This function only finds functions and split them into individual BinF views. This allows for implementing, if needed one day, multithreaded reading on a function-per-function basis. For full decompilation, [[codesec'2]] is used later." [ctx view] (assoc-in ctx [:wasm/source :wasm.source/codesec] (reduce (fn [source-codesec _idx] (conj source-codesec (code' {} view))) [] (range (u32' view))))) (defn code' [hmap view] (let [n-byte (u32' view) start (binf/position view)] (binf/skip view n-byte) (assoc hmap :wasm.codesec/view (binf/view view start n-byte)))) (defn func' [hmap ctx view] (-> hmap (assoc :wasm/locals (locals' view) :wasm/expr (expr' ctx view)) (dissoc :wasm/code))) (defn locals' [view] (vec' (fn [view] [(u32' view) (valtype' view)]) view)) (defn codesec'2 "After applying [[codesec']], this function takes those function BinF views and actually reads them" [ctx] (let [idx-offset (or (ffirst (ctx :wasm/funcsec)) 0)] (update ctx :wasm/codesec (fn [codesec] (reduce-kv (fn [codesec-2 idx {:wasm.codesec/keys [view]}] (assoc codesec-2 (+ idx-offset idx) (func' {} ctx view))) codesec (get-in ctx [:wasm/source :wasm.source/codesec])))))) Modules / Data Section (defn datasec' [ctx view] (vec' ctx data' view)) (defn data' [ctx view] (-> ctx (update :wasm/dataidx inc) (assoc-in [:wasm/datasec (ctx :wasm/dataidx)] (let [flag (byte' view)] (when-not (<= 0x00 flag 0x02) (-err (str "Data segment flat is not in [0;2]: " flag) view wasm.count/byte')) (-> (if (= flag 0x01) {:wasm.data/mode :passive} (-> (if (= flag 0x02) {:wasm/memidx (memidx' view)} {}) (assoc :wasm/offset (expr' ctx view) :wasm.data/mode :active))) (assoc :wasm/buffer (binf/rr-buffer view (u32' view)))))))) Modules / Data Count Section (defn datacountsec' [ctx view] (wasm.ir/datacountsec' ctx (u32' view))) (defn magic' Checking for " \0asm " BOM ( reversed u32 because BinF view is little - endian as requested by the WASM specification ) . [view] (when (not= (binf/rr-u32 view) wasm.bin/magic) (-err "WASM file does not start with magic word" view 4))) (defn version' [view] (binf/rr-u32 view)) (defn section'+ "After applying [[module']], actually reads those sections as BinF views." [ctx] (reduce (fn [ctx-2 {:wasm.section/keys [id view]}] (if (= id wasm.bin/section-id-custom) (customsec' ctx-2 view) ((condp = id wasm.bin/section-id-type typesec' wasm.bin/section-id-import importsec' wasm.bin/section-id-func funcsec' wasm.bin/section-id-table tablesec' wasm.bin/section-id-mem memsec' wasm.bin/section-id-global globalsec' wasm.bin/section-id-export exportsec' wasm.bin/section-id-start startsec' wasm.bin/section-id-elem elemsec' wasm.bin/section-id-code codesec' wasm.bin/section-id-data datasec' wasm.bin/section-id-datacount datacountsec') ctx-2 view))) ctx (get-in ctx [:wasm/source :wasm.source/section+]))) (defn module' "Finds sections and split them into BinF views. Then, see [[section'+]]." [ctx view] (magic' view) (let [ctx-2 (assoc ctx :wasm/version (version' view))] (cond-> ctx-2 (pos? (binf/remaining view)) (assoc-in [:wasm/source :wasm.source/section+] (loop [section+ []] (if (pos? (binf/remaining view)) (recur (conj section+ (section' view))) section+))))))
1ec7bf3193ac3b56d17c992a758b8405b8f85b66bc61531468557f000492dc6c
swaywm/cl-wlroots
output-damage-grovel.lisp
(in-package #:wlr/types/output-damage) (pkg-config-cflags "wlroots") (cc-flags "-DWLR_USE_UNSTABLE") (include "wlr/types/wlr_output_damage.h") (cstruct output-damage "struct wlr_output_damage" (:output "output" :type (:struct output)) (:event-damage-frame "events.frame" :type (:struct wl_signal)) (:event-destroy "events.destroy" :type (:struct wl_signal)))
null
https://raw.githubusercontent.com/swaywm/cl-wlroots/f8a33979e45086ecd5c7deefd5ee067b941e0998/wlr/types/output-damage-grovel.lisp
lisp
(in-package #:wlr/types/output-damage) (pkg-config-cflags "wlroots") (cc-flags "-DWLR_USE_UNSTABLE") (include "wlr/types/wlr_output_damage.h") (cstruct output-damage "struct wlr_output_damage" (:output "output" :type (:struct output)) (:event-damage-frame "events.frame" :type (:struct wl_signal)) (:event-destroy "events.destroy" :type (:struct wl_signal)))
2ed0351b1f27c823d8935a848f748b41708a7fc45c2a42b26c8dc2baa720369c
effectfully-ou/sketches
HFT.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE QuantifiedConstraints # {-# LANGUAGE RankNTypes #-} # LANGUAGE UndecidableInstances # module HFT where import FT import Control.Applicative import System.Random newtype Subsystem constr a = Subsystem { unSubsystem :: forall m. constr m => m a } instance (forall f. constr f => Functor f) => Functor (Subsystem constr) where fmap f (Subsystem a) = Subsystem $ fmap f a x <$ (Subsystem a) = Subsystem $ x <$ a instance (forall f. constr f => Applicative f) => Applicative (Subsystem constr) where pure x = Subsystem $ pure x Subsystem f <*> Subsystem a = Subsystem $ f <*> a Subsystem f <* Subsystem a = Subsystem $ f <* a Subsystem f *> Subsystem a = Subsystem $ f *> a liftA2 f (Subsystem a) (Subsystem b) = Subsystem $ liftA2 f a b instance (forall m. constr m => Monad m) => Monad (Subsystem constr) where return = pure Subsystem a >>= f = Subsystem $ a >>= unSubsystem . f a >> b = a *> b fail err = Subsystem $ fail err subsystem :: (forall m. constr2 m => constr1 m) => Subsystem constr1 a -> Subsystem constr2 a subsystem (Subsystem a) = Subsystem a instance (forall m. constr m => MonadLogger m) => MonadLogger (Subsystem constr) where logMessage level msg = Subsystem $ logMessage level msg instance (forall m. constr m => MonadApp m) => MonadApp (Subsystem constr) where getRandomInt range = Subsystem $ getRandomInt range type Logger = Subsystem MonadLogger type App = Subsystem MonadApp runApp :: App a -> IO a runApp = unSubsystem logged :: Logger () logged = logMessage Info "a" printRandomFactorial' :: App () printRandomFactorial' = do n <- getRandomInt (1, 100) logInfo $ show $ product [1..n] logMessage Info "b" subsystem logged
null
https://raw.githubusercontent.com/effectfully-ou/sketches/7b512a529292e8c4bce80526b3f2b938f8cc8e60/hierarchical-free-monads-mostly-pointless/src/HFT.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE RankNTypes #
# LANGUAGE QuantifiedConstraints # # LANGUAGE UndecidableInstances # module HFT where import FT import Control.Applicative import System.Random newtype Subsystem constr a = Subsystem { unSubsystem :: forall m. constr m => m a } instance (forall f. constr f => Functor f) => Functor (Subsystem constr) where fmap f (Subsystem a) = Subsystem $ fmap f a x <$ (Subsystem a) = Subsystem $ x <$ a instance (forall f. constr f => Applicative f) => Applicative (Subsystem constr) where pure x = Subsystem $ pure x Subsystem f <*> Subsystem a = Subsystem $ f <*> a Subsystem f <* Subsystem a = Subsystem $ f <* a Subsystem f *> Subsystem a = Subsystem $ f *> a liftA2 f (Subsystem a) (Subsystem b) = Subsystem $ liftA2 f a b instance (forall m. constr m => Monad m) => Monad (Subsystem constr) where return = pure Subsystem a >>= f = Subsystem $ a >>= unSubsystem . f a >> b = a *> b fail err = Subsystem $ fail err subsystem :: (forall m. constr2 m => constr1 m) => Subsystem constr1 a -> Subsystem constr2 a subsystem (Subsystem a) = Subsystem a instance (forall m. constr m => MonadLogger m) => MonadLogger (Subsystem constr) where logMessage level msg = Subsystem $ logMessage level msg instance (forall m. constr m => MonadApp m) => MonadApp (Subsystem constr) where getRandomInt range = Subsystem $ getRandomInt range type Logger = Subsystem MonadLogger type App = Subsystem MonadApp runApp :: App a -> IO a runApp = unSubsystem logged :: Logger () logged = logMessage Info "a" printRandomFactorial' :: App () printRandomFactorial' = do n <- getRandomInt (1, 100) logInfo $ show $ product [1..n] logMessage Info "b" subsystem logged
ea5fedc9766b8b7fe4f88776716b03876ab7aabbbc9aed626a32026439192d29
bnoordhuis/chicken-core
srfi-4-tests.scm
;;;; srfi-4-tests.scm (use srfi-1 srfi-4) (define-syntax test1 (er-macro-transformer (lambda (x r c) (let* ((t (strip-syntax (cadr x))) (name (symbol->string (strip-syntax t)))) (define (conc op) (string->symbol (string-append name op))) `(let ((x (,(conc "vector") 100 101))) (print x) (assert (= 100 (,(conc "vector-ref") x 0))) (,(conc "vector-set!") x 1 99) (assert (= 99 (,(conc "vector-ref") x 1))) (assert (= 2 (,(conc "vector-length") x))) (assert (every = '(100 99) (,(conc "vector->list") x)))))))) (test1 u8) (test1 u16) (test1 u32) (test1 s8) (test1 s16) (test1 s32) (test1 f32) (test1 f64)
null
https://raw.githubusercontent.com/bnoordhuis/chicken-core/56d30e3be095b6abe1bddcfe10505fa726a43bb5/tests/srfi-4-tests.scm
scheme
srfi-4-tests.scm
(use srfi-1 srfi-4) (define-syntax test1 (er-macro-transformer (lambda (x r c) (let* ((t (strip-syntax (cadr x))) (name (symbol->string (strip-syntax t)))) (define (conc op) (string->symbol (string-append name op))) `(let ((x (,(conc "vector") 100 101))) (print x) (assert (= 100 (,(conc "vector-ref") x 0))) (,(conc "vector-set!") x 1 99) (assert (= 99 (,(conc "vector-ref") x 1))) (assert (= 2 (,(conc "vector-length") x))) (assert (every = '(100 99) (,(conc "vector->list") x)))))))) (test1 u8) (test1 u16) (test1 u32) (test1 s8) (test1 s16) (test1 s32) (test1 f32) (test1 f64)