_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
c24e257e7db2aec6e3a53a4e2ef974a4b285dab704ed426535012c9aaf88b19c
standard-fish/summer-competititon-2019
world-map.rkt
#lang racket (require json racket/draw math/base) (define (lat-lon->map-point coordinates) (match-define (list lon lat _ ...) coordinates) (define-values (x y) (values (degrees->radians lon) (asinh (tan (degrees->radians lat))))) (list (/ (+ 1 (/ x pi)) 2) (/ (- 1 (/ y pi)) 2))) (define (draw-polygon dc polygons) (define path (for/fold ([path #f]) ([polygon (in-list polygons)] #:unless (null? polygon)) (define sub-path (new dc-path%)) (send/apply sub-path move-to (lat-lon->map-point (car polygon))) (for ([point (in-list (cdr polygon))]) (send/apply sub-path line-to (lat-lon->map-point point))) (send sub-path close) (if path (begin (send path append sub-path) path) sub-path))) (and path (send dc draw-path path 0 0))) (define (make-geojson-bitmap gjdata width height) (define dc (new bitmap-dc% [bitmap (make-object bitmap% width height)])) (send* dc (set-scale width height) (set-smoothing 'smoothed) (set-pen (send the-pen-list find-or-create-pen "black" (* 0.5 (/ 1 width)) 'solid))) ;; Iterate over each feature (timezone) and render it (for ([feature (in-list (hash-ref gjdata 'features))]) (send dc set-brush (send the-brush-list find-or-create-brush "black" 'transparent)) (let* ([geometry (hash-ref feature 'geometry (lambda () (hash)))] [data (hash-ref geometry 'coordinates (lambda () null))]) (case (hash-ref geometry 'type #f) (("Polygon") (draw-polygon dc data)) (("MultiPolygon") (for ([polygon (in-list data)]) (draw-polygon dc polygon))) (else (printf "Skipping ~a geometry" (hash-ref geometry 'type #f)))))) (send dc get-bitmap)) (define world-data (call-with-input-file "./data/world-map.json" read-json)) (define bm (make-geojson-bitmap world-data 800 500)) (send bm save-file "world.png" 'png 100 #:unscaled? #t)
null
https://raw.githubusercontent.com/standard-fish/summer-competititon-2019/2e8d74f79b493e0307aa278b4500901c5d5157a8/entries/alex-hhh/world-map.rkt
racket
Iterate over each feature (timezone) and render it
#lang racket (require json racket/draw math/base) (define (lat-lon->map-point coordinates) (match-define (list lon lat _ ...) coordinates) (define-values (x y) (values (degrees->radians lon) (asinh (tan (degrees->radians lat))))) (list (/ (+ 1 (/ x pi)) 2) (/ (- 1 (/ y pi)) 2))) (define (draw-polygon dc polygons) (define path (for/fold ([path #f]) ([polygon (in-list polygons)] #:unless (null? polygon)) (define sub-path (new dc-path%)) (send/apply sub-path move-to (lat-lon->map-point (car polygon))) (for ([point (in-list (cdr polygon))]) (send/apply sub-path line-to (lat-lon->map-point point))) (send sub-path close) (if path (begin (send path append sub-path) path) sub-path))) (and path (send dc draw-path path 0 0))) (define (make-geojson-bitmap gjdata width height) (define dc (new bitmap-dc% [bitmap (make-object bitmap% width height)])) (send* dc (set-scale width height) (set-smoothing 'smoothed) (set-pen (send the-pen-list find-or-create-pen "black" (* 0.5 (/ 1 width)) 'solid))) (for ([feature (in-list (hash-ref gjdata 'features))]) (send dc set-brush (send the-brush-list find-or-create-brush "black" 'transparent)) (let* ([geometry (hash-ref feature 'geometry (lambda () (hash)))] [data (hash-ref geometry 'coordinates (lambda () null))]) (case (hash-ref geometry 'type #f) (("Polygon") (draw-polygon dc data)) (("MultiPolygon") (for ([polygon (in-list data)]) (draw-polygon dc polygon))) (else (printf "Skipping ~a geometry" (hash-ref geometry 'type #f)))))) (send dc get-bitmap)) (define world-data (call-with-input-file "./data/world-map.json" read-json)) (define bm (make-geojson-bitmap world-data 800 500)) (send bm save-file "world.png" 'png 100 #:unscaled? #t)
cca6e5cdb03eae64c5832d2343c5a216d8c17f444dae0059a889ff2d1cb9b0fd
andorp/bead
ServerSide.hs
module Bead.View.Fay.JSON.ServerSide ( decodeFromFay , encodeToFay , module Data.Data ) where import Data.Data import Data.Aeson (encode, decode) import Fay.Convert import Data.ByteString.Lazy.Char8 (pack, unpack) import Control.Monad ((<=<)) -- | Produce 'Just a' if the given string represents an 'a' JSON object decodeFromFay :: (Data a) => String -> Maybe a decodeFromFay = readFromFay <=< (decode . pack) -- | Produces 'Just String' representation if the given value is a JSON represatble encodeToFay :: (Show a, Data a) => a -> Maybe String encodeToFay = fmap (unpack . encode) . showToFay
null
https://raw.githubusercontent.com/andorp/bead/280dc9c3d5cfe1b9aac0f2f802c705ae65f02ac2/src/Bead/View/Fay/JSON/ServerSide.hs
haskell
| Produce 'Just a' if the given string represents an 'a' JSON object | Produces 'Just String' representation if the given value is a JSON represatble
module Bead.View.Fay.JSON.ServerSide ( decodeFromFay , encodeToFay , module Data.Data ) where import Data.Data import Data.Aeson (encode, decode) import Fay.Convert import Data.ByteString.Lazy.Char8 (pack, unpack) import Control.Monad ((<=<)) decodeFromFay :: (Data a) => String -> Maybe a decodeFromFay = readFromFay <=< (decode . pack) encodeToFay :: (Show a, Data a) => a -> Maybe String encodeToFay = fmap (unpack . encode) . showToFay
ebabc4ba205e37bad26310ce678a4dc5ff2cd1400f56038ad13bbd1c3994cec3
reborg/clojure-essential-reference
1.clj
(binding [*compile-files* true *compile-path* "."] < 1 >
null
https://raw.githubusercontent.com/reborg/clojure-essential-reference/9a3eb82024c8e5fbe17412af541c2cd30820c92e/DynamicVariablesintheStandardLibrary/*compiler-options*/1.clj
clojure
(binding [*compile-files* true *compile-path* "."] < 1 >
c6242a4fa42c2bfd8973a6ef87ca61b51c8a2146b2ebec4a23dbf851e50addbe
fujita-y/digamma
pnpoly.scm
;;; PNPOLY - Test if a point is contained in a 2D polygon. (define (pt-in-poly2 xp yp x y) (let loop ((c #f) (i (- (FLOATvector-length xp) 1)) (j 0)) (if (< i 0) c (if (or (and (or (FLOAT> (FLOATvector-ref yp i) y) (FLOAT>= y (FLOATvector-ref yp j))) (or (FLOAT> (FLOATvector-ref yp j) y) (FLOAT>= y (FLOATvector-ref yp i)))) (FLOAT>= x (FLOAT+ (FLOATvector-ref xp i) (FLOAT/ (FLOAT* (FLOAT- (FLOATvector-ref xp j) (FLOATvector-ref xp i)) (FLOAT- y (FLOATvector-ref yp i))) (FLOAT- (FLOATvector-ref yp j) (FLOATvector-ref yp i)))))) (loop c (- i 1) i) (loop (not c) (- i 1) i))))) (define (run) (let ((count 0) (xp (FLOATvector-const 0. 1. 1. 0. 0. 1. -.5 -1. -1. -2. -2.5 -2. -1.5 -.5 1. 1. 0. -.5 -1. -.5)) (yp (FLOATvector-const 0. 0. 1. 1. 2. 3. 2. 3. 0. -.5 -1. -1.5 -2. -2. -1.5 -1. -.5 -1. -1. -.5))) (if (pt-in-poly2 xp yp .5 .5) (set! count (+ count 1))) (if (pt-in-poly2 xp yp .5 1.5) (set! count (+ count 1))) (if (pt-in-poly2 xp yp -.5 1.5) (set! count (+ count 1))) (if (pt-in-poly2 xp yp .75 2.25) (set! count (+ count 1))) (if (pt-in-poly2 xp yp 0. 2.01) (set! count (+ count 1))) (if (pt-in-poly2 xp yp -.5 2.5) (set! count (+ count 1))) (if (pt-in-poly2 xp yp -1. -.5) (set! count (+ count 1))) (if (pt-in-poly2 xp yp -1.5 .5) (set! count (+ count 1))) (if (pt-in-poly2 xp yp -2.25 -1.) (set! count (+ count 1))) (if (pt-in-poly2 xp yp .5 -.25) (set! count (+ count 1))) (if (pt-in-poly2 xp yp .5 -1.25) (set! count (+ count 1))) (if (pt-in-poly2 xp yp -.5 -2.5) (set! count (+ count 1))) count)) (define (compile) (closure-compile pt-in-poly2) (closure-compile run) (closure-compile main)) (define (main . args) (run-benchmark "pnpoly" pnpoly-iters (lambda (result) (and (number? result) (= result 6))) (lambda () (lambda () (run)))))
null
https://raw.githubusercontent.com/fujita-y/digamma/5a31f9fd67737fd857ada643d5548155a2ed0e76/bench/gambit-benchmarks/pnpoly.scm
scheme
PNPOLY - Test if a point is contained in a 2D polygon.
(define (pt-in-poly2 xp yp x y) (let loop ((c #f) (i (- (FLOATvector-length xp) 1)) (j 0)) (if (< i 0) c (if (or (and (or (FLOAT> (FLOATvector-ref yp i) y) (FLOAT>= y (FLOATvector-ref yp j))) (or (FLOAT> (FLOATvector-ref yp j) y) (FLOAT>= y (FLOATvector-ref yp i)))) (FLOAT>= x (FLOAT+ (FLOATvector-ref xp i) (FLOAT/ (FLOAT* (FLOAT- (FLOATvector-ref xp j) (FLOATvector-ref xp i)) (FLOAT- y (FLOATvector-ref yp i))) (FLOAT- (FLOATvector-ref yp j) (FLOATvector-ref yp i)))))) (loop c (- i 1) i) (loop (not c) (- i 1) i))))) (define (run) (let ((count 0) (xp (FLOATvector-const 0. 1. 1. 0. 0. 1. -.5 -1. -1. -2. -2.5 -2. -1.5 -.5 1. 1. 0. -.5 -1. -.5)) (yp (FLOATvector-const 0. 0. 1. 1. 2. 3. 2. 3. 0. -.5 -1. -1.5 -2. -2. -1.5 -1. -.5 -1. -1. -.5))) (if (pt-in-poly2 xp yp .5 .5) (set! count (+ count 1))) (if (pt-in-poly2 xp yp .5 1.5) (set! count (+ count 1))) (if (pt-in-poly2 xp yp -.5 1.5) (set! count (+ count 1))) (if (pt-in-poly2 xp yp .75 2.25) (set! count (+ count 1))) (if (pt-in-poly2 xp yp 0. 2.01) (set! count (+ count 1))) (if (pt-in-poly2 xp yp -.5 2.5) (set! count (+ count 1))) (if (pt-in-poly2 xp yp -1. -.5) (set! count (+ count 1))) (if (pt-in-poly2 xp yp -1.5 .5) (set! count (+ count 1))) (if (pt-in-poly2 xp yp -2.25 -1.) (set! count (+ count 1))) (if (pt-in-poly2 xp yp .5 -.25) (set! count (+ count 1))) (if (pt-in-poly2 xp yp .5 -1.25) (set! count (+ count 1))) (if (pt-in-poly2 xp yp -.5 -2.5) (set! count (+ count 1))) count)) (define (compile) (closure-compile pt-in-poly2) (closure-compile run) (closure-compile main)) (define (main . args) (run-benchmark "pnpoly" pnpoly-iters (lambda (result) (and (number? result) (= result 6))) (lambda () (lambda () (run)))))
e8617a76aba96890295daca664bf5d8f15ae3af8f87a3a746bb881c9a78a3454
let-def/menhir
referenceInterpreter.mli
(**************************************************************************) (* *) Menhir (* *) , INRIA Rocquencourt , PPS , Université Paris Diderot (* *) Copyright 2005 - 2008 Institut National de Recherche en Informatique (* et en Automatique. All rights reserved. This file is distributed *) under the terms of the Q Public License version 1.0 , with the change (* described in file LICENSE. *) (* *) (**************************************************************************) open Grammar open Cst This reference interpreter animates the LR automaton . It uses the grammar and automaton descriptions , as provided by [ Grammar ] and [ Lr1 ] , as well as the generic LR engine in [ MenhirLib . Engine ] . grammar and automaton descriptions, as provided by [Grammar] and [Lr1], as well as the generic LR engine in [MenhirLib.Engine]. *) The first parameter to the interpreter is a Boolean flag that tells whether a trace should be produced on the standard error channel . whether a trace should be produced on the standard error channel. *) (* The interpreter requires a start symbol, a lexer, and a lexing buffer. It either succeeds and produces a concrete syntax tree, or fails. *) val interpret: bool -> Nonterminal.t -> (Lexing.lexbuf -> Terminal.t) -> Lexing.lexbuf -> cst option
null
https://raw.githubusercontent.com/let-def/menhir/e8ba7bef219acd355798072c42abbd11335ecf09/src/referenceInterpreter.mli
ocaml
************************************************************************ et en Automatique. All rights reserved. This file is distributed described in file LICENSE. ************************************************************************ The interpreter requires a start symbol, a lexer, and a lexing buffer. It either succeeds and produces a concrete syntax tree, or fails.
Menhir , INRIA Rocquencourt , PPS , Université Paris Diderot Copyright 2005 - 2008 Institut National de Recherche en Informatique under the terms of the Q Public License version 1.0 , with the change open Grammar open Cst This reference interpreter animates the LR automaton . It uses the grammar and automaton descriptions , as provided by [ Grammar ] and [ Lr1 ] , as well as the generic LR engine in [ MenhirLib . Engine ] . grammar and automaton descriptions, as provided by [Grammar] and [Lr1], as well as the generic LR engine in [MenhirLib.Engine]. *) The first parameter to the interpreter is a Boolean flag that tells whether a trace should be produced on the standard error channel . whether a trace should be produced on the standard error channel. *) val interpret: bool -> Nonterminal.t -> (Lexing.lexbuf -> Terminal.t) -> Lexing.lexbuf -> cst option
18bf8bf1dd76137db93f38b1de74b1d7ac5d6467f767fa33fa56a2ce88449fe0
tmfg/mmtis-national-access-point
confirm_email.cljs
(ns ote.app.controller.confirm-email (:require [ote.app.routes :as routes] [ote.communication :as comm] [tuck.core :as tuck :refer-macros [define-event]])) (define-event ConfirmSuccess [] {} (-> app (assoc-in [:confirm-email :loaded?] true) (assoc-in [:confirm-email :success?] true))) (define-event ConfirmFailure [] {} (-> app (assoc-in [:confirm-email :loaded?] true) (assoc-in [:confirm-email :success?] false))) (define-event InitConfirmEmailView [] {} (comm/post! "confirm-email" {:token (get-in app [:params :token])} {:on-success (tuck/send-async! ->ConfirmSuccess) :on-failure (tuck/send-async! ->ConfirmFailure)}) (assoc-in app [:confirm-email :loaded?] false)) (defmethod routes/on-navigate-event :confirm-email [_] (->InitConfirmEmailView))
null
https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/a86cc890ffa1fe4f773083be5d2556e87a93d975/ote/src/cljs/ote/app/controller/confirm_email.cljs
clojure
(ns ote.app.controller.confirm-email (:require [ote.app.routes :as routes] [ote.communication :as comm] [tuck.core :as tuck :refer-macros [define-event]])) (define-event ConfirmSuccess [] {} (-> app (assoc-in [:confirm-email :loaded?] true) (assoc-in [:confirm-email :success?] true))) (define-event ConfirmFailure [] {} (-> app (assoc-in [:confirm-email :loaded?] true) (assoc-in [:confirm-email :success?] false))) (define-event InitConfirmEmailView [] {} (comm/post! "confirm-email" {:token (get-in app [:params :token])} {:on-success (tuck/send-async! ->ConfirmSuccess) :on-failure (tuck/send-async! ->ConfirmFailure)}) (assoc-in app [:confirm-email :loaded?] false)) (defmethod routes/on-navigate-event :confirm-email [_] (->InitConfirmEmailView))
c0130c57d639b855860aa7986420988ff6e9202d03d1af65d4066f6548413d8a
GaloisInc/surveyor
ModelViewer.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeApplications # # LANGUAGE DataKinds # # LANGUAGE TypeFamilies # | A viewer for Crux models module Surveyor.Brick.Widget.ModelViewer ( renderModelViewer, ) where import qualified Brick as B import qualified Crux.Types as CT import qualified Data.Binary.IEEE754 as IEEE754 import qualified Data.BitVector.Sized as BV import qualified Data.Parameterized.Map as MapF import qualified Data.Text as T import qualified Lang.Crucible.Types as LCT import qualified Surveyor.Brick.Names as SBN import qualified Data.Text.Prettyprint.Doc as PP import qualified Data.Text.Prettyprint.Doc.Render.Text as PPT renderModelViewer :: CT.ModelView -> B.Widget SBN.Names renderModelViewer mv = B.txt (ppModel mv) ppModel :: CT.ModelView -> T.Text ppModel (CT.ModelView vals) = case ents of [] -> "[]" _ -> T.unlines $ (zipWith T.append pre ents) ++ ["]"] where ents = MapF.foldrWithKey (\k v rest -> ppVals k v ++ rest) [] vals pre = "[ " : repeat ", " ppVals :: LCT.BaseTypeRepr ty -> CT.Vals ty -> [T.Text] ppVals ty (CT.Vals xs) = let showEnt = case ty of LCT.BaseBVRepr n -> showEnt' show n LCT.BaseFloatRepr (LCT.FloatingPointPrecisionRepr eb sb) | LCT.natValue eb == 8, LCT.natValue sb == 24 -> showEnt' (show . IEEE754.wordToFloat . fromInteger . BV.asUnsigned) (LCT.knownNat @32) LCT.BaseFloatRepr (LCT.FloatingPointPrecisionRepr eb sb) | LCT.natValue eb == 11, LCT.natValue sb == 53 -> showEnt' (show . IEEE754.wordToDouble . fromInteger . BV.asUnsigned) (LCT.knownNat @64) LCT.BaseRealRepr -> showEnt' (show . fromRational @Double) (LCT.knownNat @64) _ -> error ("Type not implemented: " ++ show ty) in map showEnt xs where showEnt' :: Show b => (a -> String) -> b -> CT.Entry a -> T.Text showEnt' repr n e = PPT.renderStrict . PP.layoutCompact $ "name:" PP.<+> PP.pretty (CT.entryName e) PP.<+> "value:" PP.<+> PP.pretty (repr (CT.entryValue e)) PP.<+> "bits:" PP.<+> PP.pretty (show n)
null
https://raw.githubusercontent.com/GaloisInc/surveyor/96b6748d811bc2ab9ef330307a324bd00e04819f/surveyor-brick/src/Surveyor/Brick/Widget/ModelViewer.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeApplications # # LANGUAGE DataKinds # # LANGUAGE TypeFamilies # | A viewer for Crux models module Surveyor.Brick.Widget.ModelViewer ( renderModelViewer, ) where import qualified Brick as B import qualified Crux.Types as CT import qualified Data.Binary.IEEE754 as IEEE754 import qualified Data.BitVector.Sized as BV import qualified Data.Parameterized.Map as MapF import qualified Data.Text as T import qualified Lang.Crucible.Types as LCT import qualified Surveyor.Brick.Names as SBN import qualified Data.Text.Prettyprint.Doc as PP import qualified Data.Text.Prettyprint.Doc.Render.Text as PPT renderModelViewer :: CT.ModelView -> B.Widget SBN.Names renderModelViewer mv = B.txt (ppModel mv) ppModel :: CT.ModelView -> T.Text ppModel (CT.ModelView vals) = case ents of [] -> "[]" _ -> T.unlines $ (zipWith T.append pre ents) ++ ["]"] where ents = MapF.foldrWithKey (\k v rest -> ppVals k v ++ rest) [] vals pre = "[ " : repeat ", " ppVals :: LCT.BaseTypeRepr ty -> CT.Vals ty -> [T.Text] ppVals ty (CT.Vals xs) = let showEnt = case ty of LCT.BaseBVRepr n -> showEnt' show n LCT.BaseFloatRepr (LCT.FloatingPointPrecisionRepr eb sb) | LCT.natValue eb == 8, LCT.natValue sb == 24 -> showEnt' (show . IEEE754.wordToFloat . fromInteger . BV.asUnsigned) (LCT.knownNat @32) LCT.BaseFloatRepr (LCT.FloatingPointPrecisionRepr eb sb) | LCT.natValue eb == 11, LCT.natValue sb == 53 -> showEnt' (show . IEEE754.wordToDouble . fromInteger . BV.asUnsigned) (LCT.knownNat @64) LCT.BaseRealRepr -> showEnt' (show . fromRational @Double) (LCT.knownNat @64) _ -> error ("Type not implemented: " ++ show ty) in map showEnt xs where showEnt' :: Show b => (a -> String) -> b -> CT.Entry a -> T.Text showEnt' repr n e = PPT.renderStrict . PP.layoutCompact $ "name:" PP.<+> PP.pretty (CT.entryName e) PP.<+> "value:" PP.<+> PP.pretty (repr (CT.entryValue e)) PP.<+> "bits:" PP.<+> PP.pretty (show n)
1a0b8295b3a90d7a280933d51fe29594107b9aee576e088ccc001f7e89bcffb0
atolab/zenoh
tx_engine.ml
* Copyright ( c ) 2017 , 2020 ADLINK Technology Inc. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * -2.0 , or the Apache License , Version 2.0 * which is available at -2.0 . * * SPDX - License - Identifier : EPL-2.0 OR Apache-2.0 * * Contributors : * team , < > * Copyright (c) 2017, 2020 ADLINK Technology Inc. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * -2.0, or the Apache License, Version 2.0 * which is available at -2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 * * Contributors: * ADLINK zenoh team, <> *) open Apero module TransportEngine = struct module TxMap = Map.Make(String) let register _ _ = () let load _ = Result.fail `NotImplemented let resolve _ = Result.fail `NotImplemented end
null
https://raw.githubusercontent.com/atolab/zenoh/32e311aae6be93c001fd725b4d918b2fb4e9713d/src/zenoh-proto/tx_engine.ml
ocaml
* Copyright ( c ) 2017 , 2020 ADLINK Technology Inc. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * -2.0 , or the Apache License , Version 2.0 * which is available at -2.0 . * * SPDX - License - Identifier : EPL-2.0 OR Apache-2.0 * * Contributors : * team , < > * Copyright (c) 2017, 2020 ADLINK Technology Inc. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * -2.0, or the Apache License, Version 2.0 * which is available at -2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 * * Contributors: * ADLINK zenoh team, <> *) open Apero module TransportEngine = struct module TxMap = Map.Make(String) let register _ _ = () let load _ = Result.fail `NotImplemented let resolve _ = Result.fail `NotImplemented end
96baf1542e2e859ffa34744657f7f65ebf7640739467d43d11d0552d7e962953
brendanhay/gogol
Acknowledge.hs
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # -- | Module : . ShoppingContent . Content . Orderreturns . Acknowledge Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- Acks an order return in your Merchant Center account . -- /See:/ < API for Shopping Reference > for @content.orderreturns.acknowledge@. module Gogol.ShoppingContent.Content.Orderreturns.Acknowledge ( -- * Resource ContentOrderreturnsAcknowledgeResource, -- ** Constructing a Request ContentOrderreturnsAcknowledge (..), newContentOrderreturnsAcknowledge, ) where import qualified Gogol.Prelude as Core import Gogol.ShoppingContent.Types | A resource alias for @content.orderreturns.acknowledge@ method which the -- 'ContentOrderreturnsAcknowledge' request conforms to. type ContentOrderreturnsAcknowledgeResource = "content" Core.:> "v2.1" Core.:> Core.Capture "merchantId" Core.Word64 Core.:> "orderreturns" Core.:> Core.Capture "returnId" Core.Text Core.:> "acknowledge" Core.:> Core.QueryParam "$.xgafv" Xgafv Core.:> Core.QueryParam "access_token" Core.Text Core.:> Core.QueryParam "callback" Core.Text Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "upload_protocol" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.ReqBody '[Core.JSON] OrderreturnsAcknowledgeRequest Core.:> Core.Post '[Core.JSON] OrderreturnsAcknowledgeResponse | Acks an order return in your Merchant Center account . -- -- /See:/ 'newContentOrderreturnsAcknowledge' smart constructor. data ContentOrderreturnsAcknowledge = ContentOrderreturnsAcknowledge { -- | V1 error format. xgafv :: (Core.Maybe Xgafv), -- | OAuth access token. accessToken :: (Core.Maybe Core.Text), | JSONP callback :: (Core.Maybe Core.Text), -- | The ID of the account that manages the order. This cannot be a multi-client account. merchantId :: Core.Word64, -- | Multipart request metadata. payload :: OrderreturnsAcknowledgeRequest, -- | The ID of the return. returnId :: Core.Text, | Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) . uploadType :: (Core.Maybe Core.Text), -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). uploadProtocol :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) | Creates a value of ' ContentOrderreturnsAcknowledge ' with the minimum fields required to make a request . newContentOrderreturnsAcknowledge :: -- | The ID of the account that manages the order. This cannot be a multi-client account. See 'merchantId'. Core.Word64 -> -- | Multipart request metadata. See 'payload'. OrderreturnsAcknowledgeRequest -> -- | The ID of the return. See 'returnId'. Core.Text -> ContentOrderreturnsAcknowledge newContentOrderreturnsAcknowledge merchantId payload returnId = ContentOrderreturnsAcknowledge { xgafv = Core.Nothing, accessToken = Core.Nothing, callback = Core.Nothing, merchantId = merchantId, payload = payload, returnId = returnId, uploadType = Core.Nothing, uploadProtocol = Core.Nothing } instance Core.GoogleRequest ContentOrderreturnsAcknowledge where type Rs ContentOrderreturnsAcknowledge = OrderreturnsAcknowledgeResponse type Scopes ContentOrderreturnsAcknowledge = '[Content'FullControl] requestClient ContentOrderreturnsAcknowledge {..} = go merchantId returnId xgafv accessToken callback uploadType uploadProtocol (Core.Just Core.AltJSON) payload shoppingContentService where go = Core.buildClient ( Core.Proxy :: Core.Proxy ContentOrderreturnsAcknowledgeResource ) Core.mempty
null
https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-shopping-content/gen/Gogol/ShoppingContent/Content/Orderreturns/Acknowledge.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Stability : auto-generated * Resource ** Constructing a Request 'ContentOrderreturnsAcknowledge' request conforms to. /See:/ 'newContentOrderreturnsAcknowledge' smart constructor. | V1 error format. | OAuth access token. | The ID of the account that manages the order. This cannot be a multi-client account. | Multipart request metadata. | The ID of the return. | Upload protocol for media (e.g. \"raw\", \"multipart\"). | The ID of the account that manages the order. This cannot be a multi-client account. See 'merchantId'. | Multipart request metadata. See 'payload'. | The ID of the return. See 'returnId'.
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Module : . ShoppingContent . Content . Orderreturns . Acknowledge Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) Acks an order return in your Merchant Center account . /See:/ < API for Shopping Reference > for @content.orderreturns.acknowledge@. module Gogol.ShoppingContent.Content.Orderreturns.Acknowledge ContentOrderreturnsAcknowledgeResource, ContentOrderreturnsAcknowledge (..), newContentOrderreturnsAcknowledge, ) where import qualified Gogol.Prelude as Core import Gogol.ShoppingContent.Types | A resource alias for @content.orderreturns.acknowledge@ method which the type ContentOrderreturnsAcknowledgeResource = "content" Core.:> "v2.1" Core.:> Core.Capture "merchantId" Core.Word64 Core.:> "orderreturns" Core.:> Core.Capture "returnId" Core.Text Core.:> "acknowledge" Core.:> Core.QueryParam "$.xgafv" Xgafv Core.:> Core.QueryParam "access_token" Core.Text Core.:> Core.QueryParam "callback" Core.Text Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "upload_protocol" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.ReqBody '[Core.JSON] OrderreturnsAcknowledgeRequest Core.:> Core.Post '[Core.JSON] OrderreturnsAcknowledgeResponse | Acks an order return in your Merchant Center account . data ContentOrderreturnsAcknowledge = ContentOrderreturnsAcknowledge xgafv :: (Core.Maybe Xgafv), accessToken :: (Core.Maybe Core.Text), | JSONP callback :: (Core.Maybe Core.Text), merchantId :: Core.Word64, payload :: OrderreturnsAcknowledgeRequest, returnId :: Core.Text, | Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) . uploadType :: (Core.Maybe Core.Text), uploadProtocol :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) | Creates a value of ' ContentOrderreturnsAcknowledge ' with the minimum fields required to make a request . newContentOrderreturnsAcknowledge :: Core.Word64 -> OrderreturnsAcknowledgeRequest -> Core.Text -> ContentOrderreturnsAcknowledge newContentOrderreturnsAcknowledge merchantId payload returnId = ContentOrderreturnsAcknowledge { xgafv = Core.Nothing, accessToken = Core.Nothing, callback = Core.Nothing, merchantId = merchantId, payload = payload, returnId = returnId, uploadType = Core.Nothing, uploadProtocol = Core.Nothing } instance Core.GoogleRequest ContentOrderreturnsAcknowledge where type Rs ContentOrderreturnsAcknowledge = OrderreturnsAcknowledgeResponse type Scopes ContentOrderreturnsAcknowledge = '[Content'FullControl] requestClient ContentOrderreturnsAcknowledge {..} = go merchantId returnId xgafv accessToken callback uploadType uploadProtocol (Core.Just Core.AltJSON) payload shoppingContentService where go = Core.buildClient ( Core.Proxy :: Core.Proxy ContentOrderreturnsAcknowledgeResource ) Core.mempty
9e2e3d90bd79bab1660240165c4b80e4f74f186ad58662b756ab849637a41bb2
Opetushallitus/ataru
application_states.cljc
(ns ataru.application.application-states (:require [ataru.application.review-states :as review-states] [clojure.set :as set])) (defn get-review-state-label-by-name [states name lang] (->> states (filter #(= (first %) name)) first second lang)) (defn get-all-reviews-for-requirement "Adds default (incomplete) reviews where none have yet been created" [review-requirement-name application selected-hakukohde-oids] (let [application-hakukohteet (set (:hakukohde application)) hakukohde-filter (set selected-hakukohde-oids) has-hakukohteet? (not (empty? application-hakukohteet)) review-targets (cond (not-empty selected-hakukohde-oids) hakukohde-filter has-hakukohteet? application-hakukohteet :else #{"form"}) relevant-states (filter #(and (= (:requirement %) review-requirement-name) (= has-hakukohteet? (not= (:hakukohde %) "form")) (or (empty? hakukohde-filter) (contains? hakukohde-filter (:hakukohde %)))) (:application-hakukohde-reviews application)) unreviewed-targets (set/difference review-targets (set (map :hakukohde relevant-states))) default-state-name (-> (filter #(= (keyword review-requirement-name) (first %)) review-states/hakukohde-review-types) (first) (last) (ffirst) (name))] (into relevant-states (map (fn [oid] {:requirement review-requirement-name :state default-state-name :hakukohde oid}) unreviewed-targets)))) (defn get-all-reviews-for-all-requirements ([application selected-hakukohde-oids] (mapcat #(get-all-reviews-for-requirement % application selected-hakukohde-oids) review-states/hakukohde-review-type-names)) ([application] (get-all-reviews-for-all-requirements application nil))) (defn attachment-reviews-with-no-requirements [application] (let [reviews (:application-attachment-reviews application) no-reqs (set/difference (set (:hakukohde application)) (set (map :hakukohde reviews)))] (concat reviews (map (fn [oid] {:hakukohde oid :state review-states/no-attachment-requirements}) no-reqs))))
null
https://raw.githubusercontent.com/Opetushallitus/ataru/0f49a46d23e25ce0d1e35339632955a07ff4ad68/src/cljc/ataru/application/application_states.cljc
clojure
(ns ataru.application.application-states (:require [ataru.application.review-states :as review-states] [clojure.set :as set])) (defn get-review-state-label-by-name [states name lang] (->> states (filter #(= (first %) name)) first second lang)) (defn get-all-reviews-for-requirement "Adds default (incomplete) reviews where none have yet been created" [review-requirement-name application selected-hakukohde-oids] (let [application-hakukohteet (set (:hakukohde application)) hakukohde-filter (set selected-hakukohde-oids) has-hakukohteet? (not (empty? application-hakukohteet)) review-targets (cond (not-empty selected-hakukohde-oids) hakukohde-filter has-hakukohteet? application-hakukohteet :else #{"form"}) relevant-states (filter #(and (= (:requirement %) review-requirement-name) (= has-hakukohteet? (not= (:hakukohde %) "form")) (or (empty? hakukohde-filter) (contains? hakukohde-filter (:hakukohde %)))) (:application-hakukohde-reviews application)) unreviewed-targets (set/difference review-targets (set (map :hakukohde relevant-states))) default-state-name (-> (filter #(= (keyword review-requirement-name) (first %)) review-states/hakukohde-review-types) (first) (last) (ffirst) (name))] (into relevant-states (map (fn [oid] {:requirement review-requirement-name :state default-state-name :hakukohde oid}) unreviewed-targets)))) (defn get-all-reviews-for-all-requirements ([application selected-hakukohde-oids] (mapcat #(get-all-reviews-for-requirement % application selected-hakukohde-oids) review-states/hakukohde-review-type-names)) ([application] (get-all-reviews-for-all-requirements application nil))) (defn attachment-reviews-with-no-requirements [application] (let [reviews (:application-attachment-reviews application) no-reqs (set/difference (set (:hakukohde application)) (set (map :hakukohde reviews)))] (concat reviews (map (fn [oid] {:hakukohde oid :state review-states/no-attachment-requirements}) no-reqs))))
4dd255c122788ed2cc103dedbec92e43ad681e1017b779d25e761ef8ee3361db
maximedenes/native-coq
tries.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) module Make = functor (X : Set.OrderedType) -> functor (Y : Map.OrderedType) -> struct module T_dom = Fset.Make(X) module T_codom = Fmap.Make(Y) type t = Node of T_dom.t * t T_codom.t let codom_to_list m = T_codom.fold (fun x y l -> (x,y)::l) m [] let codom_rng m = T_codom.fold (fun _ y acc -> y::acc) m [] let codom_dom m = T_codom.fold (fun x _ acc -> x::acc) m [] let empty = Node (T_dom.empty, T_codom.empty) let map (Node (_,m)) lbl = T_codom.find lbl m let xtract (Node (hereset,_)) = T_dom.elements hereset let dom (Node (_,m)) = codom_dom m let in_dom (Node (_,m)) lbl = T_codom.mem lbl m let is_empty_node (Node(a,b)) = (T_dom.elements a = []) & (codom_to_list b = []) let assure_arc m lbl = if T_codom.mem lbl m then m else T_codom.add lbl (Node (T_dom.empty,T_codom.empty)) m let cleanse_arcs (Node (hereset,m)) = let l = codom_rng m in Node(hereset, if List.for_all is_empty_node l then T_codom.empty else m) let rec at_path f (Node (hereset,m)) = function | [] -> cleanse_arcs (Node(f hereset,m)) | h::t -> let m = assure_arc m h in cleanse_arcs (Node(hereset, T_codom.add h (at_path f (T_codom.find h m) t) m)) let add tm (path,v) = at_path (fun hereset -> T_dom.add v hereset) tm path let rmv tm (path,v) = at_path (fun hereset -> T_dom.remove v hereset) tm path let app f tlm = let rec apprec pfx (Node(hereset,m)) = let path = List.rev pfx in T_dom.iter (fun v -> f(path,v)) hereset; T_codom.iter (fun l tm -> apprec (l::pfx) tm) m in apprec [] tlm let to_list tlm = let rec torec pfx (Node(hereset,m)) = let path = List.rev pfx in List.flatten((List.map (fun v -> (path,v)) (T_dom.elements hereset)):: (List.map (fun (l,tm) -> torec (l::pfx) tm) (codom_to_list m))) in torec [] tlm end
null
https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/lib/tries.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 **********************************************************************
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * module Make = functor (X : Set.OrderedType) -> functor (Y : Map.OrderedType) -> struct module T_dom = Fset.Make(X) module T_codom = Fmap.Make(Y) type t = Node of T_dom.t * t T_codom.t let codom_to_list m = T_codom.fold (fun x y l -> (x,y)::l) m [] let codom_rng m = T_codom.fold (fun _ y acc -> y::acc) m [] let codom_dom m = T_codom.fold (fun x _ acc -> x::acc) m [] let empty = Node (T_dom.empty, T_codom.empty) let map (Node (_,m)) lbl = T_codom.find lbl m let xtract (Node (hereset,_)) = T_dom.elements hereset let dom (Node (_,m)) = codom_dom m let in_dom (Node (_,m)) lbl = T_codom.mem lbl m let is_empty_node (Node(a,b)) = (T_dom.elements a = []) & (codom_to_list b = []) let assure_arc m lbl = if T_codom.mem lbl m then m else T_codom.add lbl (Node (T_dom.empty,T_codom.empty)) m let cleanse_arcs (Node (hereset,m)) = let l = codom_rng m in Node(hereset, if List.for_all is_empty_node l then T_codom.empty else m) let rec at_path f (Node (hereset,m)) = function | [] -> cleanse_arcs (Node(f hereset,m)) | h::t -> let m = assure_arc m h in cleanse_arcs (Node(hereset, T_codom.add h (at_path f (T_codom.find h m) t) m)) let add tm (path,v) = at_path (fun hereset -> T_dom.add v hereset) tm path let rmv tm (path,v) = at_path (fun hereset -> T_dom.remove v hereset) tm path let app f tlm = let rec apprec pfx (Node(hereset,m)) = let path = List.rev pfx in T_dom.iter (fun v -> f(path,v)) hereset; T_codom.iter (fun l tm -> apprec (l::pfx) tm) m in apprec [] tlm let to_list tlm = let rec torec pfx (Node(hereset,m)) = let path = List.rev pfx in List.flatten((List.map (fun v -> (path,v)) (T_dom.elements hereset)):: (List.map (fun (l,tm) -> torec (l::pfx) tm) (codom_to_list m))) in torec [] tlm end
e2ef26e9620d12de6365a3c1d6035031da808f368ced504acd0d113f4af78608
Yuras/io-region
example6.hs
{-# LANGUAGE DeriveDataTypeable #-} -- example6 import Data.Typeable import Data.IORef import Control.Applicative import Control.Monad import Control.Exception (Exception, SomeException) import qualified Control.Exception as E import Control.Concurrent hiding (killThread, throwTo) import qualified Control.Concurrent as CC import System.IO.Unsafe (unsafePerformIO) import System.Timeout (timeout) # NOINLINE numHandles # numHandles :: IORef Int numHandles = unsafePerformIO $ newIORef 0 # NOINLINE dataWritten # dataWritten :: IORef [String] dataWritten = unsafePerformIO $ newIORef [] # NOINLINE asyncLock # asyncLock :: MVar () asyncLock = unsafePerformIO $ newMVar () test :: IO () -> IO () test action = do action `E.catch` \e -> do putStrLn $ "exception: " ++ show (e :: SomeException) readIORef numHandles >>= putStrLn . ("Number of open handles: " ++) . show readIORef dataWritten >>= putStrLn . ("Data writtern to file: " ++) . show data Handle = Handle (IORef (Maybe String)) openFile :: FilePath -> IO Handle openFile _ = do modifyIORef' numHandles succ Handle <$> newIORef Nothing hClose :: Handle -> IO () hClose h = hFlushFailing h `E.finally` modifyIORef numHandles pred hFlushFailing :: Handle -> IO () hFlushFailing _ = do threadDelay (20 * 1000 * 1000) error "hFlush failed" hFlush :: Handle -> IO () hFlush (Handle ref) = do val <- readIORef ref case val of Just str -> modifyIORef dataWritten (str :) _ -> return () writeIORef ref Nothing hPutStr :: Handle -> String -> IO () hPutStr h@(Handle ref) str = do hFlush h writeIORef ref (Just str) data Ex = Ex deriving (Show, Typeable) instance Exception Ex where -- disable async exceptions, but automatically interrupt any interruptible action -- -- pure mans implementation, requires support from RTS -- it is even is not safe interruptibleMask :: IO a -> IO a interruptibleMask action = withMVar asyncLock $ \_ -> do pid <- myThreadId E.bracket (forkIOWithUnmask $ \unmask -> unmask $ forever $ CC.throwTo pid Ex) (E.uninterruptibleMask_ . CC.killThread) (const action) killThread :: ThreadId -> IO () killThread pid = throwTo pid E.ThreadKilled throwTo :: Exception e => ThreadId -> e -> IO () throwTo pid e = withMVar asyncLock $ const (E.throwTo pid e) bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c bracket allocate release use = E.mask $ \restore -> do resource <- allocate result <- E.catch (restore $ use resource) $ \e -> do void (interruptibleMask $ release resource) `E.catch` \e' -> putStrLn ("Ignoring exception: " ++ show (e' :: SomeException)) E.throw (e :: SomeException) void (release resource) return result example :: IO () example = void $ timeout (2 * 1000 * 1000) $ bracket (openFile "path") hClose $ \h -> do hPutStr h "Hello" hPutStr h "World" threadDelay (2 * 1000 * 1000) main :: IO () main = do pid <- myThreadId void $ forkIO $ do threadDelay (1 * 1000 * 1000) killThread pid test example
null
https://raw.githubusercontent.com/Yuras/io-region/515738d486b422d238a81335b4490de093ce6cd9/misc/imask/example6.hs
haskell
# LANGUAGE DeriveDataTypeable # example6 disable async exceptions, but automatically interrupt any interruptible action pure mans implementation, requires support from RTS it is even is not safe
import Data.Typeable import Data.IORef import Control.Applicative import Control.Monad import Control.Exception (Exception, SomeException) import qualified Control.Exception as E import Control.Concurrent hiding (killThread, throwTo) import qualified Control.Concurrent as CC import System.IO.Unsafe (unsafePerformIO) import System.Timeout (timeout) # NOINLINE numHandles # numHandles :: IORef Int numHandles = unsafePerformIO $ newIORef 0 # NOINLINE dataWritten # dataWritten :: IORef [String] dataWritten = unsafePerformIO $ newIORef [] # NOINLINE asyncLock # asyncLock :: MVar () asyncLock = unsafePerformIO $ newMVar () test :: IO () -> IO () test action = do action `E.catch` \e -> do putStrLn $ "exception: " ++ show (e :: SomeException) readIORef numHandles >>= putStrLn . ("Number of open handles: " ++) . show readIORef dataWritten >>= putStrLn . ("Data writtern to file: " ++) . show data Handle = Handle (IORef (Maybe String)) openFile :: FilePath -> IO Handle openFile _ = do modifyIORef' numHandles succ Handle <$> newIORef Nothing hClose :: Handle -> IO () hClose h = hFlushFailing h `E.finally` modifyIORef numHandles pred hFlushFailing :: Handle -> IO () hFlushFailing _ = do threadDelay (20 * 1000 * 1000) error "hFlush failed" hFlush :: Handle -> IO () hFlush (Handle ref) = do val <- readIORef ref case val of Just str -> modifyIORef dataWritten (str :) _ -> return () writeIORef ref Nothing hPutStr :: Handle -> String -> IO () hPutStr h@(Handle ref) str = do hFlush h writeIORef ref (Just str) data Ex = Ex deriving (Show, Typeable) instance Exception Ex where interruptibleMask :: IO a -> IO a interruptibleMask action = withMVar asyncLock $ \_ -> do pid <- myThreadId E.bracket (forkIOWithUnmask $ \unmask -> unmask $ forever $ CC.throwTo pid Ex) (E.uninterruptibleMask_ . CC.killThread) (const action) killThread :: ThreadId -> IO () killThread pid = throwTo pid E.ThreadKilled throwTo :: Exception e => ThreadId -> e -> IO () throwTo pid e = withMVar asyncLock $ const (E.throwTo pid e) bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c bracket allocate release use = E.mask $ \restore -> do resource <- allocate result <- E.catch (restore $ use resource) $ \e -> do void (interruptibleMask $ release resource) `E.catch` \e' -> putStrLn ("Ignoring exception: " ++ show (e' :: SomeException)) E.throw (e :: SomeException) void (release resource) return result example :: IO () example = void $ timeout (2 * 1000 * 1000) $ bracket (openFile "path") hClose $ \h -> do hPutStr h "Hello" hPutStr h "World" threadDelay (2 * 1000 * 1000) main :: IO () main = do pid <- myThreadId void $ forkIO $ do threadDelay (1 * 1000 * 1000) killThread pid test example
9bac0b543da8a7d75c9c6937bb9a8dd8967792dd6266ae1be1fa8f1767df3001
facebook/pyre-check
Error.mli
* Copyright ( c ) Meta Platforms , Inc. and 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) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open Ast type kind = { code: int; name: string; messages: string list; } [@@deriving sexp, compare] type t [@@deriving sexp, compare] val code : t -> int val create : location:Location.WithModule.t -> kind:kind -> define:Statement.Define.t Node.t -> t module Instantiated : sig type t val code : t -> int val location : t -> Location.WithPath.t val description : t -> string val to_yojson : t -> Yojson.Safe.t end val instantiate : show_error_traces:bool -> lookup:(Reference.t -> string option) -> t -> Instantiated.t
null
https://raw.githubusercontent.com/facebook/pyre-check/10c375bea52db5d10b71cb5206fac7da9549eb0c/source/interprocedural/Error.mli
ocaml
* Copyright ( c ) Meta Platforms , Inc. and 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) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open Ast type kind = { code: int; name: string; messages: string list; } [@@deriving sexp, compare] type t [@@deriving sexp, compare] val code : t -> int val create : location:Location.WithModule.t -> kind:kind -> define:Statement.Define.t Node.t -> t module Instantiated : sig type t val code : t -> int val location : t -> Location.WithPath.t val description : t -> string val to_yojson : t -> Yojson.Safe.t end val instantiate : show_error_traces:bool -> lookup:(Reference.t -> string option) -> t -> Instantiated.t
16bfa597141a0c37b7a4d5fcbd22d3a4f7f06e8a218b1b9fbf5b13799dcf258a
ucsd-progsys/liquidhaskell
T743.hs
{-@ LIQUID "--expect-any-error" @-} module T743 where @ checkNat : : Nat - > Int @ checkNat :: Int -> Int checkNat x = x unsound :: Int unsound = checkNat (-1) data TestBS = TestBS Int deriving (Read)
null
https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/neg/T743.hs
haskell
@ LIQUID "--expect-any-error" @
module T743 where @ checkNat : : Nat - > Int @ checkNat :: Int -> Int checkNat x = x unsound :: Int unsound = checkNat (-1) data TestBS = TestBS Int deriving (Read)
ae11301a2a55b17ab95f73cbc0cf5dbf43dc9c5b174df71bab478eb2715478a3
guildhall/guile-haunt
html.scm
Haunt --- Static site generator for GNU Copyright © 2015 < > ;;; This file is part of Haunt . ;;; Haunt 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. ;;; Haunt 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 Haunt . If not , see < / > . ;;; Commentary: ;; SXML to HTML conversion . ;; ;;; Code: (define-module (haunt html) #:use-module (sxml simple) #:use-module (srfi srfi-26) #:use-module (ice-9 match) #:use-module (ice-9 format) #:use-module (ice-9 hash-table) #:export (sxml->html sxml->html-string)) (define %void-elements '(area base br col command embed hr img input keygen link meta param source track wbr)) (define (void-element? tag) "Return #t if TAG is a void element." (pair? (memq tag %void-elements))) (define %escape-chars (alist->hash-table '((#\" . "quot") (#\& . "amp") (#\' . "apos") (#\< . "lt") (#\> . "gt")))) (define (string->escaped-html s port) "Write the HTML escaped form of S to PORT." (define (escape c) (let ((escaped (hash-ref %escape-chars c))) (if escaped (format port "&~a;" escaped) (display c port)))) (string-for-each escape s)) (define (object->escaped-html obj port) "Write the HTML escaped form of OBJ to PORT." (string->escaped-html (call-with-output-string (cut display obj <>)) port)) (define (attribute-value->html value port) "Write the HTML escaped form of VALUE to PORT." (if (string? value) (string->escaped-html value port) (object->escaped-html value port))) (define (attribute->html attr value port) "Write ATTR and VALUE to PORT." (format port "~a=\"" attr) (attribute-value->html value port) (display #\" port)) (define (element->html tag attrs body port) "Write the HTML TAG to PORT, where TAG has the attributes in the list ATTRS and the child nodes in BODY." (format port "<~a" tag) (for-each (match-lambda ((attr value) (display #\space port) (attribute->html attr value port))) attrs) (if (and (null? body) (void-element? tag)) (display " />" port) (begin (display #\> port) (for-each (cut sxml->html <> port) body) (format port "</~a>" tag)))) (define (doctype->html doctype port) (format port "<!DOCTYPE ~a>" doctype)) (define* (sxml->html tree #:optional (port (current-output-port))) "Write the serialized HTML form of TREE to PORT." (match tree (() *unspecified*) (('doctype type) (doctype->html type port)) Unescaped , raw HTML output . (('raw html) (display html port)) (((? symbol? tag) ('@ attrs ...) body ...) (element->html tag attrs body port)) (((? symbol? tag) body ...) (element->html tag '() body port)) ((nodes ...) (for-each (cut sxml->html <> port) nodes)) ((? string? text) (string->escaped-html text port)) ;; Render arbitrary Scheme objects, too. (obj (object->escaped-html obj port)))) (define (sxml->html-string sxml) "Render SXML as an HTML string." (call-with-output-string (lambda (port) (sxml->html sxml port))))
null
https://raw.githubusercontent.com/guildhall/guile-haunt/c67e8e924c664ae4035862cc7b439cd7ec4bcef6/haunt/html.scm
scheme
you can redistribute it and/or modify it either version 3 of the License , or (at your option) any later version. 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. Commentary: Code: Render arbitrary Scheme objects, too.
Haunt --- Static site generator for GNU Copyright © 2015 < > This file is part of Haunt . under the terms of the GNU General Public License as published by Haunt is distributed in the hope that it will be useful , but You should have received a copy of the GNU General Public License along with Haunt . If not , see < / > . SXML to HTML conversion . (define-module (haunt html) #:use-module (sxml simple) #:use-module (srfi srfi-26) #:use-module (ice-9 match) #:use-module (ice-9 format) #:use-module (ice-9 hash-table) #:export (sxml->html sxml->html-string)) (define %void-elements '(area base br col command embed hr img input keygen link meta param source track wbr)) (define (void-element? tag) "Return #t if TAG is a void element." (pair? (memq tag %void-elements))) (define %escape-chars (alist->hash-table '((#\" . "quot") (#\& . "amp") (#\' . "apos") (#\< . "lt") (#\> . "gt")))) (define (string->escaped-html s port) "Write the HTML escaped form of S to PORT." (define (escape c) (let ((escaped (hash-ref %escape-chars c))) (if escaped (format port "&~a;" escaped) (display c port)))) (string-for-each escape s)) (define (object->escaped-html obj port) "Write the HTML escaped form of OBJ to PORT." (string->escaped-html (call-with-output-string (cut display obj <>)) port)) (define (attribute-value->html value port) "Write the HTML escaped form of VALUE to PORT." (if (string? value) (string->escaped-html value port) (object->escaped-html value port))) (define (attribute->html attr value port) "Write ATTR and VALUE to PORT." (format port "~a=\"" attr) (attribute-value->html value port) (display #\" port)) (define (element->html tag attrs body port) "Write the HTML TAG to PORT, where TAG has the attributes in the list ATTRS and the child nodes in BODY." (format port "<~a" tag) (for-each (match-lambda ((attr value) (display #\space port) (attribute->html attr value port))) attrs) (if (and (null? body) (void-element? tag)) (display " />" port) (begin (display #\> port) (for-each (cut sxml->html <> port) body) (format port "</~a>" tag)))) (define (doctype->html doctype port) (format port "<!DOCTYPE ~a>" doctype)) (define* (sxml->html tree #:optional (port (current-output-port))) "Write the serialized HTML form of TREE to PORT." (match tree (() *unspecified*) (('doctype type) (doctype->html type port)) Unescaped , raw HTML output . (('raw html) (display html port)) (((? symbol? tag) ('@ attrs ...) body ...) (element->html tag attrs body port)) (((? symbol? tag) body ...) (element->html tag '() body port)) ((nodes ...) (for-each (cut sxml->html <> port) nodes)) ((? string? text) (string->escaped-html text port)) (obj (object->escaped-html obj port)))) (define (sxml->html-string sxml) "Render SXML as an HTML string." (call-with-output-string (lambda (port) (sxml->html sxml port))))
cee1c742abe950816f034c7261736faf5635f452612e80063cb730ff68470581
sebhoss/finj
periodic_payment.clj
; Copyright © 2013 < > ; This work is free. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License , Version 2 , as published by . See / for more details . ; (ns finj.periodic-payment "Periodic payment pay a certain amount of money per period. Definitions: * amount - Amount of an individual payment * rate - Rate of interest * period - Payment periods" (:require [com.github.sebhoss.def :refer :all])) (defnk due-value "Calculates the due value of a sequence of periodic payments. Parameters: * amount - Payment per period * rate - Rate of interest * period - Number of payment periods Examples: * (due-value :amount 100 :rate 0.05 :period 5) => 515.0 * (due-value :amount 150 :rate 0.1 :period 8) => 1267.5 * (due-value :amount 180 :rate 0.15 :period 12) => 2335.5" [:amount :rate :period] {:pre [(number? amount) (number? rate) (number? period)]} (* amount (+ period (* rate (/ (inc period) 2))))) (defnk immediate-value "Calculates the due value of a sequence of periodic payments. Parameters: * amount - Payment per period * rate - Rate of interest * period - Number of payment periods Examples: * (immediate-value :amount 100 :rate 0.05 :period 5) => 509.99999999999994 * (immediate-value :amount 150 :rate 0.1 :period 8) => 1252.5 * (immediate-value :amount 180 :rate 0.15 :period 12) => 2308.5" [:amount :rate :period] {:pre [(number? amount) (number? rate) (number? period)]} (* amount (+ period (* rate (/ (dec period) 2)))))
null
https://raw.githubusercontent.com/sebhoss/finj/7c27cb506528642a6e8a673be1b9a49d68e533e5/src/main/clojure/finj/periodic_payment.clj
clojure
This work is free. You can redistribute it and/or modify it under the
Copyright © 2013 < > terms of the Do What The Fuck You Want To Public License , Version 2 , as published by . See / for more details . (ns finj.periodic-payment "Periodic payment pay a certain amount of money per period. Definitions: * amount - Amount of an individual payment * rate - Rate of interest * period - Payment periods" (:require [com.github.sebhoss.def :refer :all])) (defnk due-value "Calculates the due value of a sequence of periodic payments. Parameters: * amount - Payment per period * rate - Rate of interest * period - Number of payment periods Examples: * (due-value :amount 100 :rate 0.05 :period 5) => 515.0 * (due-value :amount 150 :rate 0.1 :period 8) => 1267.5 * (due-value :amount 180 :rate 0.15 :period 12) => 2335.5" [:amount :rate :period] {:pre [(number? amount) (number? rate) (number? period)]} (* amount (+ period (* rate (/ (inc period) 2))))) (defnk immediate-value "Calculates the due value of a sequence of periodic payments. Parameters: * amount - Payment per period * rate - Rate of interest * period - Number of payment periods Examples: * (immediate-value :amount 100 :rate 0.05 :period 5) => 509.99999999999994 * (immediate-value :amount 150 :rate 0.1 :period 8) => 1252.5 * (immediate-value :amount 180 :rate 0.15 :period 12) => 2308.5" [:amount :rate :period] {:pre [(number? amount) (number? rate) (number? period)]} (* amount (+ period (* rate (/ (dec period) 2)))))
cf57a9b9761ec08d150417c2673b039a7ab5527d669aa9f19bf895f96518ec22
jdreaver/amy
Pretty.hs
{-# LANGUAGE OverloadedStrings #-} module Amy.Syntax.Pretty ( prettyModule , prettyTypeDeclaration , prettyExpr , prettyType ) where import Data.Foldable (toList) import qualified Data.Map.Strict as Map import Amy.Pretty import Amy.Syntax.AST prettyModule :: Module -> Doc ann prettyModule (Module _ typeDecls externs bindings) = vcatTwoHardLines $ (prettyTypeDeclaration' <$> typeDecls) ++ (prettyExtern' <$> externs) ++ (prettyBinding' <$> concatMap toList bindings) prettyTypeDeclaration' :: TypeDeclaration -> Doc ann prettyTypeDeclaration' (TypeDeclaration info cons) = prettyTypeDeclaration (prettyTyConDefinition info) (prettyConstructor <$> cons) where prettyConstructor (DataConDefinition (Located _ conName) mArg) = prettyDataConstructor (prettyDataConName conName) (prettyType <$> mArg) prettyTyConDefinition :: TyConDefinition -> Doc ann prettyTyConDefinition (TyConDefinition (Located _ name) args) = prettyTyConName name <> args' where args' = if null args then mempty else space <> sep (prettyTyVarName . locatedValue <$> args) prettyExtern' :: Extern -> Doc ann prettyExtern' (Extern (Located _ name) ty) = prettyExtern (prettyIdent name) (prettyType ty) prettyBinding' :: Binding -> Doc ann prettyBinding' (Binding (Located _ name) ty args _ body) = tyDoc <> bindingDoc where tyDoc = case ty of TyUnknown -> mempty _ -> prettyBindingType (prettyIdent name) (prettyType ty) <> hardline bindingDoc = prettyBinding (prettyIdent name) (prettyIdent . locatedValue . typedValue <$> args) (prettyExpr body) prettyExpr :: Expr -> Doc ann prettyExpr (ELit (Located _ lit)) = pretty $ showLiteral lit prettyExpr (ERecord _ rows) = bracketed $ uncurry prettyRow <$> Map.toList rows where prettyRow (Located _ label) (Typed _ expr) = prettyRowLabel label <> ":" <+> prettyExpr expr prettyExpr (ERecordSelect expr (Located _ field) _) = prettyExpr expr <> "." <> prettyRowLabel field prettyExpr (EVar (Typed _ (Located _ ident))) = prettyIdent ident prettyExpr (ECon (Typed _ (Located _ dataCon))) = prettyDataConName dataCon prettyExpr (EIf (If pred' then' else' _)) = prettyIf (prettyExpr pred') (prettyExpr then') (prettyExpr else') prettyExpr (ECase (Case scrutinee matches _)) = prettyCase (prettyExpr scrutinee) Nothing (toList $ mkMatch <$> matches) where mkMatch (Match pat body) = (prettyPattern pat, prettyExpr body) prettyExpr (ELet (Let bindings body _)) = prettyLet (prettyBinding' <$> concatMap toList bindings) (prettyExpr body) prettyExpr (ELam (Lambda args body _ _)) = prettyLambda (prettyIdent . locatedValue . typedValue <$> toList args) (prettyExpr body) prettyExpr (EApp (App f arg _)) = prettyExpr f <+> prettyExpr arg prettyExpr (EParens expr) = parens $ prettyExpr expr prettyPattern :: Pattern -> Doc ann prettyPattern (PLit (Located _ lit)) = pretty $ showLiteral lit prettyPattern (PVar (Typed _ (Located _ var))) = prettyIdent var prettyPattern (PParens pat) = parens (prettyPattern pat) prettyPattern (PCons (PatCons (Located _ con) mArg _)) = prettyDataConName con <> maybe mempty prettyArg mArg where prettyArg = (space <>) . prettyArg' prettyArg' arg@PCons{} = parens (prettyPattern arg) prettyArg' arg = prettyPattern arg
null
https://raw.githubusercontent.com/jdreaver/amy/a0c73f6c02e7d923f1d85c0de89f78dc204dae2f/library/Amy/Syntax/Pretty.hs
haskell
# LANGUAGE OverloadedStrings #
module Amy.Syntax.Pretty ( prettyModule , prettyTypeDeclaration , prettyExpr , prettyType ) where import Data.Foldable (toList) import qualified Data.Map.Strict as Map import Amy.Pretty import Amy.Syntax.AST prettyModule :: Module -> Doc ann prettyModule (Module _ typeDecls externs bindings) = vcatTwoHardLines $ (prettyTypeDeclaration' <$> typeDecls) ++ (prettyExtern' <$> externs) ++ (prettyBinding' <$> concatMap toList bindings) prettyTypeDeclaration' :: TypeDeclaration -> Doc ann prettyTypeDeclaration' (TypeDeclaration info cons) = prettyTypeDeclaration (prettyTyConDefinition info) (prettyConstructor <$> cons) where prettyConstructor (DataConDefinition (Located _ conName) mArg) = prettyDataConstructor (prettyDataConName conName) (prettyType <$> mArg) prettyTyConDefinition :: TyConDefinition -> Doc ann prettyTyConDefinition (TyConDefinition (Located _ name) args) = prettyTyConName name <> args' where args' = if null args then mempty else space <> sep (prettyTyVarName . locatedValue <$> args) prettyExtern' :: Extern -> Doc ann prettyExtern' (Extern (Located _ name) ty) = prettyExtern (prettyIdent name) (prettyType ty) prettyBinding' :: Binding -> Doc ann prettyBinding' (Binding (Located _ name) ty args _ body) = tyDoc <> bindingDoc where tyDoc = case ty of TyUnknown -> mempty _ -> prettyBindingType (prettyIdent name) (prettyType ty) <> hardline bindingDoc = prettyBinding (prettyIdent name) (prettyIdent . locatedValue . typedValue <$> args) (prettyExpr body) prettyExpr :: Expr -> Doc ann prettyExpr (ELit (Located _ lit)) = pretty $ showLiteral lit prettyExpr (ERecord _ rows) = bracketed $ uncurry prettyRow <$> Map.toList rows where prettyRow (Located _ label) (Typed _ expr) = prettyRowLabel label <> ":" <+> prettyExpr expr prettyExpr (ERecordSelect expr (Located _ field) _) = prettyExpr expr <> "." <> prettyRowLabel field prettyExpr (EVar (Typed _ (Located _ ident))) = prettyIdent ident prettyExpr (ECon (Typed _ (Located _ dataCon))) = prettyDataConName dataCon prettyExpr (EIf (If pred' then' else' _)) = prettyIf (prettyExpr pred') (prettyExpr then') (prettyExpr else') prettyExpr (ECase (Case scrutinee matches _)) = prettyCase (prettyExpr scrutinee) Nothing (toList $ mkMatch <$> matches) where mkMatch (Match pat body) = (prettyPattern pat, prettyExpr body) prettyExpr (ELet (Let bindings body _)) = prettyLet (prettyBinding' <$> concatMap toList bindings) (prettyExpr body) prettyExpr (ELam (Lambda args body _ _)) = prettyLambda (prettyIdent . locatedValue . typedValue <$> toList args) (prettyExpr body) prettyExpr (EApp (App f arg _)) = prettyExpr f <+> prettyExpr arg prettyExpr (EParens expr) = parens $ prettyExpr expr prettyPattern :: Pattern -> Doc ann prettyPattern (PLit (Located _ lit)) = pretty $ showLiteral lit prettyPattern (PVar (Typed _ (Located _ var))) = prettyIdent var prettyPattern (PParens pat) = parens (prettyPattern pat) prettyPattern (PCons (PatCons (Located _ con) mArg _)) = prettyDataConName con <> maybe mempty prettyArg mArg where prettyArg = (space <>) . prettyArg' prettyArg' arg@PCons{} = parens (prettyPattern arg) prettyArg' arg = prettyPattern arg
c9e72de8a67ed34ab35b1a095f40e8f45e647e31ee40c2370e03a2e16a29fed7
jbreindel/battlecraft
bc_player_serv.erl
-module(bc_player_serv). -behavior(gen_server). %% api functions -export([start_link/6, spawn_entities/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %% state rec -record(state, {entity_sup, game, player, player_num, spawn_matrix, gold, map, entities}). %%==================================================================== %% API functions %%==================================================================== start_link(BcEntitySup, BcGame, BcPlayer, BcGoldFsm, BcMap, BcEntities) -> gen_server:start_link(?MODULE, [BcEntitySup, BcGame, BcPlayer, BcGoldFsm, BcMap, BcEntities], []). spawn_entities(BcPlayerServ, EntityType) -> gen_server:cast(BcPlayerServ, {spawn_entities, EntityType}). %%==================================================================== %% Gen_server functions %%==================================================================== -spec init(Args :: term()) -> Result when Result :: {ok, State} | {ok, State, Timeout} | {ok, State, hibernate} | {stop, Reason :: term()} | ignore, State :: term(), Timeout :: non_neg_integer() | infinity. init([BcEntitySup, BcGame, BcPlayer, BcGoldFsm, BcMap, BcEntities]) -> {ok, #state{entity_sup = BcEntitySup, game = BcGame, player = BcPlayer, player_num = undefined, spawn_matrix = undefined, gold = BcGoldFsm, map = BcMap, entities = BcEntities}}. -spec handle_call(Request :: term(), From :: {pid(), Tag :: term()}, State :: term()) -> Result when Result :: {reply, Reply, NewState} | {reply, Reply, NewState, Timeout} | {reply, Reply, NewState, hibernate} | {noreply, NewState} | {noreply, NewState, Timeout} | {noreply, NewState, hibernate} | {stop, Reason, Reply, NewState} | {stop, Reason, NewState}, Reply :: term(), NewState :: term(), Timeout :: non_neg_integer() | infinity, Reason :: term(). handle_call(Request, From, State) -> {reply, ok, State}. -spec handle_cast(Request :: term(), State :: term()) -> Result when Result :: {noreply, NewState} | {noreply, NewState, Timeout} | {noreply, NewState, hibernate} | {stop, Reason :: term(), NewState}, NewState :: term(), Timeout :: non_neg_integer() | infinity. handle_cast({spawn_entities, EntityTypeStr}, #state{entities = BcEntities} = State) -> EntityType = bc_entity_util:iolist_to_entity_type(EntityTypeStr), case bc_entities:entity_config(EntityType, BcEntities) of {ok, BcEntityConfig} -> case player_num(State) of {ok, undefined, _} -> {noreply, State}; {ok, PlayerNum, State1} -> case spawn_matrix(State1) of {ok, undefined, _} -> {noreply, State1}; {ok, BcMatrix, State2} -> Cost = bc_entity_config:cost(BcEntityConfig), case bc_gold_fsm:subtract(State2#state.gold, Cost) of {ok, _} -> spawn_entity_batch(BcEntityConfig, State2), {noreply, State2}; {error, _} -> {noreply, State2} end end; _ -> {noreply, State} end; error -> {noreply, State} end. -spec handle_info(Info :: timeout | term(), State :: term()) -> Result when Result :: {noreply, NewState} | {noreply, NewState, Timeout} | {noreply, NewState, hibernate} | {stop, Reason :: term(), NewState}, NewState :: term(), Timeout :: non_neg_integer() | infinity. handle_info(Info, State) -> {noreply, State}. -spec terminate(Reason, State :: term()) -> Any :: term() when Reason :: normal | shutdown | {shutdown, term()} | term(). terminate(Reason, State) -> io:format("BcPlayerServer terminates with ~p~n", [Reason]), ok. -spec code_change(OldVsn, State :: term(), Extra :: term()) -> Result when Result :: {ok, NewState :: term()} | {error, Reason :: term()}, OldVsn :: Vsn | {down, Vsn}, Vsn :: term(). code_change(OldVsn, State, Extra) -> {ok, State}. %%==================================================================== Internal functions %%==================================================================== base_num(BaseBcVertices, BcMap) -> BaseBcVertex = lists:nth(1, BaseBcVertices), TODO replace this with lists : member/2 case lists:any(fun(Base1BcVertex) -> bc_vertex:row(Base1BcVertex) =:= bc_vertex:row(BaseBcVertex) andalso bc_vertex:col(Base1BcVertex) =:= bc_vertex:col(BaseBcVertex) end, bc_map:base1_vertices(BcMap)) of true -> 1; false -> case lists:any(fun(Base2BcVertex) -> bc_vertex:row(Base2BcVertex) =:= bc_vertex:row(BaseBcVertex) andalso bc_vertex:col(Base2BcVertex) =:= bc_vertex:col(BaseBcVertex) end, bc_map:base2_vertices(BcMap)) of true -> 2; false -> case lists:any(fun(Base3BcVertex) -> bc_vertex:row(Base3BcVertex) =:= bc_vertex:row(BaseBcVertex) andalso bc_vertex:col(Base3BcVertex) =:= bc_vertex:col(BaseBcVertex) end, bc_map:base3_vertices(BcMap)) of true -> 3; false -> case lists:any(fun(Base4BcVertex) -> bc_vertex:row(Base4BcVertex) =:= bc_vertex:row(BaseBcVertex) andalso bc_vertex:col(Base4BcVertex) =:= bc_vertex:col(BaseBcVertex) end, bc_map:base4_vertices(BcMap)) of true -> 4; false -> undefined end end end end. player_num(#state{player = BcPlayer, player_num = PlayerNum, map = BcMap, entities = BcEntities} = State) -> case PlayerNum of undefined -> PlayerId = bc_player:id(BcPlayer), BaseBcEntities = bc_entities:query_type(base, BcEntities), case lists:filter(fun(BaseBcEntity) -> PlayerId =:= bc_entity:player_id(BaseBcEntity) end, BaseBcEntities) of [] -> {ok, undefined, State}; [PlayerBaseBcEntity] -> Uuid = bc_entity:uuid(PlayerBaseBcEntity), QueryResults = bc_map:query_ids(BcMap, Uuid), BcVertices = lists:map(fun(QueryRes) -> maps:get(vertex, QueryRes) end, QueryResults), Num = base_num(BcVertices, BcMap), {ok, Num, State#state{player_num = Num}} end; Num when is_integer(Num) -> {ok, Num, State} end. spawn_entity_batch(BcEntityConfig, #state{spawn_matrix = SpawnBcMatrix} = State) -> case spawn_vertices(0, State) of {ok, SpawnBcVertices} -> EntitySize = bc_entity_config:size(BcEntityConfig), SpawnCountFloat = length(SpawnBcVertices) / EntitySize, SpawnCount = erlang:trunc(SpawnCountFloat), case bc_matrix:dimensions(SpawnBcMatrix) of {RowCount, ColCount} when RowCount >= ColCount -> spawn_entities({0, RowCount}, SpawnCount, BcEntityConfig, State); {RowCount, ColCount} when RowCount < ColCount -> spawn_entities({0, ColCount}, SpawnCount, BcEntityConfig, State); _ -> {error, "Cannot spawn entities."} end; error -> {error, "Cannot spawn entities."} end. spawn_entities({Offset, MaxOffset}, _, _, _) when Offset > MaxOffset -> ok; spawn_entities(_, SpawnCount, _, _) when SpawnCount =< 0 -> ok; spawn_entities({Offset, MaxOffset}, SpawnCount, BcEntityConfig, #state{entities = BcEntities, map = BcMap, player_num = PlayerNum, spawn_matrix = BcMatrix} = State) -> case spawn_vertices(Offset, State) of {ok, SpawnBcVertices} -> SpawnedCount = do_spawn_entities(SpawnCount, 0, SpawnBcVertices, BcEntityConfig, State), spawn_entities({Offset + 1, MaxOffset}, SpawnCount - SpawnedCount, BcEntityConfig, State); error -> {error, "Cannot spawn entities"} end. do_spawn_entities(0, Acc, _, _, _) -> Acc; do_spawn_entities(_, Acc, [], _, _) -> Acc; do_spawn_entities(BatchCount, Acc, [SpawnBcVertex|SpawnBcVertices], BcEntityConfig, #state{entity_sup = BcEntitySup, entities = BcEntities, player = BcPlayer, map = BcMap, player_num = PlayerNum} = State) -> Uuid = uuid:get_v4(), BcCollision = bc_collision:init(Uuid, SpawnBcVertex), case bc_entity_util:spawn_entity(BcCollision, BcPlayer, BcEntitySup, BcEntityConfig, PlayerNum, BcMap, BcEntities) of {ok, BcEntity} -> do_spawn_entities(BatchCount - 1, Acc + 1, SpawnBcVertices, BcEntityConfig, State); _ -> do_spawn_entities(BatchCount, Acc, SpawnBcVertices, BcEntityConfig, State) end. spawn_vertices(Offset, #state{player_num = PlayerNum, spawn_matrix = SpawnBcMatrix} = State) -> case PlayerNum of 1 -> MinRow = bc_matrix:min_row(SpawnBcMatrix), bc_matrix:row(MinRow + Offset, SpawnBcMatrix); 2 -> MaxCol = bc_matrix:max_col(SpawnBcMatrix), bc_matrix:col(MaxCol - Offset, SpawnBcMatrix); 3 -> MaxRow = bc_matrix:max_row(SpawnBcMatrix), bc_matrix:row(MaxRow - Offset, SpawnBcMatrix); 4 -> MinCol = bc_matrix:min_col(SpawnBcMatrix), bc_matrix:col(MinCol + Offset, SpawnBcMatrix) end. spawn_matrix(#state{player_num = PlayerNum, spawn_matrix = SpawnBcMatrix, map = BcMap} = State) -> case SpawnBcMatrix of undefined -> BcVertices = bc_map:base_spawn_vertices(BcMap, PlayerNum), BcMatrix = bc_matrix:init(BcVertices), {ok, BcMatrix, State#state{spawn_matrix = BcMatrix}}; BcMatrix -> {ok, BcMatrix, State} end.
null
https://raw.githubusercontent.com/jbreindel/battlecraft/622131a1ad8c46f19cf9ffd6bf32ba4a74ef4137/apps/bc_game/src/bc_player_serv.erl
erlang
api functions gen_server callbacks state rec ==================================================================== API functions ==================================================================== ==================================================================== Gen_server functions ==================================================================== ==================================================================== ====================================================================
-module(bc_player_serv). -behavior(gen_server). -export([start_link/6, spawn_entities/2]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {entity_sup, game, player, player_num, spawn_matrix, gold, map, entities}). start_link(BcEntitySup, BcGame, BcPlayer, BcGoldFsm, BcMap, BcEntities) -> gen_server:start_link(?MODULE, [BcEntitySup, BcGame, BcPlayer, BcGoldFsm, BcMap, BcEntities], []). spawn_entities(BcPlayerServ, EntityType) -> gen_server:cast(BcPlayerServ, {spawn_entities, EntityType}). -spec init(Args :: term()) -> Result when Result :: {ok, State} | {ok, State, Timeout} | {ok, State, hibernate} | {stop, Reason :: term()} | ignore, State :: term(), Timeout :: non_neg_integer() | infinity. init([BcEntitySup, BcGame, BcPlayer, BcGoldFsm, BcMap, BcEntities]) -> {ok, #state{entity_sup = BcEntitySup, game = BcGame, player = BcPlayer, player_num = undefined, spawn_matrix = undefined, gold = BcGoldFsm, map = BcMap, entities = BcEntities}}. -spec handle_call(Request :: term(), From :: {pid(), Tag :: term()}, State :: term()) -> Result when Result :: {reply, Reply, NewState} | {reply, Reply, NewState, Timeout} | {reply, Reply, NewState, hibernate} | {noreply, NewState} | {noreply, NewState, Timeout} | {noreply, NewState, hibernate} | {stop, Reason, Reply, NewState} | {stop, Reason, NewState}, Reply :: term(), NewState :: term(), Timeout :: non_neg_integer() | infinity, Reason :: term(). handle_call(Request, From, State) -> {reply, ok, State}. -spec handle_cast(Request :: term(), State :: term()) -> Result when Result :: {noreply, NewState} | {noreply, NewState, Timeout} | {noreply, NewState, hibernate} | {stop, Reason :: term(), NewState}, NewState :: term(), Timeout :: non_neg_integer() | infinity. handle_cast({spawn_entities, EntityTypeStr}, #state{entities = BcEntities} = State) -> EntityType = bc_entity_util:iolist_to_entity_type(EntityTypeStr), case bc_entities:entity_config(EntityType, BcEntities) of {ok, BcEntityConfig} -> case player_num(State) of {ok, undefined, _} -> {noreply, State}; {ok, PlayerNum, State1} -> case spawn_matrix(State1) of {ok, undefined, _} -> {noreply, State1}; {ok, BcMatrix, State2} -> Cost = bc_entity_config:cost(BcEntityConfig), case bc_gold_fsm:subtract(State2#state.gold, Cost) of {ok, _} -> spawn_entity_batch(BcEntityConfig, State2), {noreply, State2}; {error, _} -> {noreply, State2} end end; _ -> {noreply, State} end; error -> {noreply, State} end. -spec handle_info(Info :: timeout | term(), State :: term()) -> Result when Result :: {noreply, NewState} | {noreply, NewState, Timeout} | {noreply, NewState, hibernate} | {stop, Reason :: term(), NewState}, NewState :: term(), Timeout :: non_neg_integer() | infinity. handle_info(Info, State) -> {noreply, State}. -spec terminate(Reason, State :: term()) -> Any :: term() when Reason :: normal | shutdown | {shutdown, term()} | term(). terminate(Reason, State) -> io:format("BcPlayerServer terminates with ~p~n", [Reason]), ok. -spec code_change(OldVsn, State :: term(), Extra :: term()) -> Result when Result :: {ok, NewState :: term()} | {error, Reason :: term()}, OldVsn :: Vsn | {down, Vsn}, Vsn :: term(). code_change(OldVsn, State, Extra) -> {ok, State}. Internal functions base_num(BaseBcVertices, BcMap) -> BaseBcVertex = lists:nth(1, BaseBcVertices), TODO replace this with lists : member/2 case lists:any(fun(Base1BcVertex) -> bc_vertex:row(Base1BcVertex) =:= bc_vertex:row(BaseBcVertex) andalso bc_vertex:col(Base1BcVertex) =:= bc_vertex:col(BaseBcVertex) end, bc_map:base1_vertices(BcMap)) of true -> 1; false -> case lists:any(fun(Base2BcVertex) -> bc_vertex:row(Base2BcVertex) =:= bc_vertex:row(BaseBcVertex) andalso bc_vertex:col(Base2BcVertex) =:= bc_vertex:col(BaseBcVertex) end, bc_map:base2_vertices(BcMap)) of true -> 2; false -> case lists:any(fun(Base3BcVertex) -> bc_vertex:row(Base3BcVertex) =:= bc_vertex:row(BaseBcVertex) andalso bc_vertex:col(Base3BcVertex) =:= bc_vertex:col(BaseBcVertex) end, bc_map:base3_vertices(BcMap)) of true -> 3; false -> case lists:any(fun(Base4BcVertex) -> bc_vertex:row(Base4BcVertex) =:= bc_vertex:row(BaseBcVertex) andalso bc_vertex:col(Base4BcVertex) =:= bc_vertex:col(BaseBcVertex) end, bc_map:base4_vertices(BcMap)) of true -> 4; false -> undefined end end end end. player_num(#state{player = BcPlayer, player_num = PlayerNum, map = BcMap, entities = BcEntities} = State) -> case PlayerNum of undefined -> PlayerId = bc_player:id(BcPlayer), BaseBcEntities = bc_entities:query_type(base, BcEntities), case lists:filter(fun(BaseBcEntity) -> PlayerId =:= bc_entity:player_id(BaseBcEntity) end, BaseBcEntities) of [] -> {ok, undefined, State}; [PlayerBaseBcEntity] -> Uuid = bc_entity:uuid(PlayerBaseBcEntity), QueryResults = bc_map:query_ids(BcMap, Uuid), BcVertices = lists:map(fun(QueryRes) -> maps:get(vertex, QueryRes) end, QueryResults), Num = base_num(BcVertices, BcMap), {ok, Num, State#state{player_num = Num}} end; Num when is_integer(Num) -> {ok, Num, State} end. spawn_entity_batch(BcEntityConfig, #state{spawn_matrix = SpawnBcMatrix} = State) -> case spawn_vertices(0, State) of {ok, SpawnBcVertices} -> EntitySize = bc_entity_config:size(BcEntityConfig), SpawnCountFloat = length(SpawnBcVertices) / EntitySize, SpawnCount = erlang:trunc(SpawnCountFloat), case bc_matrix:dimensions(SpawnBcMatrix) of {RowCount, ColCount} when RowCount >= ColCount -> spawn_entities({0, RowCount}, SpawnCount, BcEntityConfig, State); {RowCount, ColCount} when RowCount < ColCount -> spawn_entities({0, ColCount}, SpawnCount, BcEntityConfig, State); _ -> {error, "Cannot spawn entities."} end; error -> {error, "Cannot spawn entities."} end. spawn_entities({Offset, MaxOffset}, _, _, _) when Offset > MaxOffset -> ok; spawn_entities(_, SpawnCount, _, _) when SpawnCount =< 0 -> ok; spawn_entities({Offset, MaxOffset}, SpawnCount, BcEntityConfig, #state{entities = BcEntities, map = BcMap, player_num = PlayerNum, spawn_matrix = BcMatrix} = State) -> case spawn_vertices(Offset, State) of {ok, SpawnBcVertices} -> SpawnedCount = do_spawn_entities(SpawnCount, 0, SpawnBcVertices, BcEntityConfig, State), spawn_entities({Offset + 1, MaxOffset}, SpawnCount - SpawnedCount, BcEntityConfig, State); error -> {error, "Cannot spawn entities"} end. do_spawn_entities(0, Acc, _, _, _) -> Acc; do_spawn_entities(_, Acc, [], _, _) -> Acc; do_spawn_entities(BatchCount, Acc, [SpawnBcVertex|SpawnBcVertices], BcEntityConfig, #state{entity_sup = BcEntitySup, entities = BcEntities, player = BcPlayer, map = BcMap, player_num = PlayerNum} = State) -> Uuid = uuid:get_v4(), BcCollision = bc_collision:init(Uuid, SpawnBcVertex), case bc_entity_util:spawn_entity(BcCollision, BcPlayer, BcEntitySup, BcEntityConfig, PlayerNum, BcMap, BcEntities) of {ok, BcEntity} -> do_spawn_entities(BatchCount - 1, Acc + 1, SpawnBcVertices, BcEntityConfig, State); _ -> do_spawn_entities(BatchCount, Acc, SpawnBcVertices, BcEntityConfig, State) end. spawn_vertices(Offset, #state{player_num = PlayerNum, spawn_matrix = SpawnBcMatrix} = State) -> case PlayerNum of 1 -> MinRow = bc_matrix:min_row(SpawnBcMatrix), bc_matrix:row(MinRow + Offset, SpawnBcMatrix); 2 -> MaxCol = bc_matrix:max_col(SpawnBcMatrix), bc_matrix:col(MaxCol - Offset, SpawnBcMatrix); 3 -> MaxRow = bc_matrix:max_row(SpawnBcMatrix), bc_matrix:row(MaxRow - Offset, SpawnBcMatrix); 4 -> MinCol = bc_matrix:min_col(SpawnBcMatrix), bc_matrix:col(MinCol + Offset, SpawnBcMatrix) end. spawn_matrix(#state{player_num = PlayerNum, spawn_matrix = SpawnBcMatrix, map = BcMap} = State) -> case SpawnBcMatrix of undefined -> BcVertices = bc_map:base_spawn_vertices(BcMap, PlayerNum), BcMatrix = bc_matrix:init(BcVertices), {ok, BcMatrix, State#state{spawn_matrix = BcMatrix}}; BcMatrix -> {ok, BcMatrix, State} end.
c376650bf32003fecae19390910995812e195e6fa96ace482dceed6826b6e9e2
homebaseio/datalog-console
version.cljc
(ns datalog-console.lib.version {:no-doc true}) (def version "0.3.2")
null
https://raw.githubusercontent.com/homebaseio/datalog-console/64bc87e42285ed8e33ac9c9df5c8501796986260/src/main/datalog_console/lib/version.cljc
clojure
(ns datalog-console.lib.version {:no-doc true}) (def version "0.3.2")
1ce21dabb492b76f3e9df8a823b7241f88106e631f821ed26b70116a07ddade7
jumarko/clojure-experiments
069_merge_with_fn.clj
(ns clojure-experiments.four-clojure.069-merge-with-fn "Implement `merge-with` yourself. See . Solutions: ") (defn my-merge-with [f & ms] (let [merge-entry (fn [result k v] (if-let [[_result-k result-v] (find result k)] (assoc result k (f result-v v)) (assoc result k v))) merge-maps (fn [m1 m2] (reduce-kv merge-entry m1 m2))] (reduce merge-maps {} ms))) (my-merge-with * {:a 2, :b 3, :c 4} {:a 2} {:b 2} {:c 5}) = > should be : { : a 4 , : b 6 , : c 20 } (my-merge-with - {1 10, 2 20} {1 3, 2 10, 3 15}) = > should be : { 1 7 , 2 10 , 3 15 } (my-merge-with concat {:a [3], :b [6]} {:a [4 5], :c [8 9]} {:b [7]}) = > should be : { : a ( 3 4 5 ) , : b ( 6 7 ) , : c [ 8 9 ] } this should throw NPE ! #_(my-merge-with + {:a nil} {:a 2})
null
https://raw.githubusercontent.com/jumarko/clojure-experiments/f0f9c091959e7f54c3fb13d0585a793ebb09e4f9/src/clojure_experiments/four_clojure/069_merge_with_fn.clj
clojure
(ns clojure-experiments.four-clojure.069-merge-with-fn "Implement `merge-with` yourself. See . Solutions: ") (defn my-merge-with [f & ms] (let [merge-entry (fn [result k v] (if-let [[_result-k result-v] (find result k)] (assoc result k (f result-v v)) (assoc result k v))) merge-maps (fn [m1 m2] (reduce-kv merge-entry m1 m2))] (reduce merge-maps {} ms))) (my-merge-with * {:a 2, :b 3, :c 4} {:a 2} {:b 2} {:c 5}) = > should be : { : a 4 , : b 6 , : c 20 } (my-merge-with - {1 10, 2 20} {1 3, 2 10, 3 15}) = > should be : { 1 7 , 2 10 , 3 15 } (my-merge-with concat {:a [3], :b [6]} {:a [4 5], :c [8 9]} {:b [7]}) = > should be : { : a ( 3 4 5 ) , : b ( 6 7 ) , : c [ 8 9 ] } this should throw NPE ! #_(my-merge-with + {:a nil} {:a 2})
e9b51c8611b247958d542b01f25b9847afbcfbff862348c7e2612b2602529b02
ChaosEternal/guile-scsh
glob.scm
;;; Code for processing file names with a glob pattern. Copyright ( c ) 1994 by ( ) . Copyright ( c ) 1994 by ( ) . Copyright ( c ) 2013 by Chaos Eternal ( ) . ;;; ;;; See file COPYING. ;;; Chaos: this modification is pretty dirty. ;;; Usage: (glob pattern-list) ;;; pattern-list := a list of glob-pattern strings ;;; Return: list of file names (strings) ;;; The files "." and ".." are never returned by glob. Dot files will only be returned if the first character ;;; of a glob pattern is a ".". ;;; The empty pattern matches nothing. A pattern beginning with / starts at root ; otherwise , we start at cwd . ;;; A pattern ending with / matches only directories, e.g., "/usr/man/man?/" (define-module (scsh glob) :use-module (srfi srfi-8) :use-module (srfi srfi-1) :use-module (scsh errno) :use-module (scsh scsh-condition) :use-module (scsh scsh) :use-module (ice-9 regex) :use-module (scsh ssyntax) :export (glob glob* directory-files glob->regexp-list)) (define char->ascii char->integer) (define-syntax glob (syntax-rules () ((_ rest ...) (apply glob* `(rest ...))))) (define (glob* . pattern-list) Expand out braces , and apply GLOB - ONE - PATTERN to all the result patterns . (apply append (map glob-one-pattern (apply append (map glob-remove-braces (map stringify pattern-list)))))) (define (split-file-name fn) (string-split fn #\/)) (define (file-name-as-directory fn) (string-append fn "/")) (define (filter-dot-files dotfile?) (lambda (x) (if (or (equal? x ".") (equal? x "..")) #f (if dotfile? #t (if (eq? (string-ref x 0) #\.) #f #t))))) (define (directory-files dir dotfile?) (filter (filter-dot-files dotfile?) (port->list readdir (opendir dir)))) (define (glob-one-pattern pattern) (let ((plen (string-length pattern))) (if (zero? plen) '() (let ((directories-only? (char=? #\/ (string-ref pattern (- plen 1)))) (patterns (split-file-name pattern))) ; Must be non-null. (if (equal? "" (car patterns)) (really-glob "" (cdr patterns) directories-only?) ; root cwd (define (really-glob root-file patterns directories-only?) ;; This is the heart of the matcher. (let recur ((file root-file) (pats patterns) (sure? #f)) ; True if we are sure this file exists. (if (pair? pats) (let ((pat (car pats)) (pats (cdr pats)) (dir (file-name-as-directory file))) (receive (winners sure?) (glob-subpat dir pat) (apply append (map (lambda (f) (recur (string-append dir f) pats sure?)) winners)))) ;; All done. (if directories-only? (if (maybe-isdir? file) (list (file-name-as-directory file)) '()) (if (or sure? (file-exists? file)) (list file) '()))))) ;;; Return the elts of directory FNAME that match pattern PAT. ;;; If PAT contains no wildcards, we cheat and do not match the ;;; constant pattern against every file in FNAME/; we just ;;; immediately return FNAME/PAT. In this case, we indicate that we ;;; aren't actually sure the file exists by returning a true SURE? ;;; value. Not only does this vastly speed up the matcher, it also ;;; allows us to match the constant patterns "." and "..". (define (glob-subpat fname pat) ; PAT doesn't contain a slash. (cond ((string=? pat "") (values '() #t)) ((constant-glob? pat) (values (cons (glob-unquote pat) '()) #f)) ; Don't check filesys. (else (let* ((dots? (char=? #\. (string-ref pat 0))) ; Match dot files? (candidates (maybe-directory-files fname dots?)) (re (glob->regexp pat))) (values (filter (lambda (f) (string-match re f)) candidates) #t))))) ; These guys exist for sure. ;;; The initial special-case above isn't really for the fast-path; it's ;;; an obscure and unlikely case. But since we have to check pat[0] for an ;;; initial dot, we have to do the check anyway... ;;; Translate a brace-free glob pattern to a regular expression. (define (glob->regexp pat) (string-join (glob->regexp-list pat) "")) (define (re-repeat x y z) ".*" ) (define re-any ".") (define re-eos "$") (define re-bos "^") (define glob->regexp-list (let ((dot-star ".*")) ; ".*" or (* any) (lambda (pat) (let ((pat-len (string-length pat)) (str-cons (lambda (chars res) ; Reverse CHARS and cons the result string - re onto RES . (cons (list->string (reverse chars)) res) res)))) ;; We accumulate chars into CHARS, and coalesce into a single string ;; with STR-CONS when we run across a non-char. (let lp ((chars '()) (res (list re-bos)) (i 0)) (if (= i pat-len) (reverse (cons re-eos (str-cons chars res))) (let ((c (string-ref pat i)) (i (+ i 1))) (case c ((#\\) (if (< i pat-len) (lp (cons (string-ref pat i) (cons #\\ chars)) res (+ i 1)) (error "Ill-formed glob pattern -- ends in backslash" pat))) ((#\*) (lp '() (cons dot-star (str-cons chars res)) i)) ((#\?) (lp '() (cons re-any (str-cons chars res)) i)) ((#\.) (lp '() (cons "[.]" (str-cons chars res)) i)) ((#\[) (receive (re i) (parse-glob-bracket pat i) (lp '() (cons re (str-cons chars res)) i))) (else (lp (cons c chars) res i)))))))))) ;;; A glob bracket expression is [...] or [^...]. ;;; The body is a sequence of <char> and <char>-<char> ranges. A < char > is any character except right - bracket , carat , hypen or backslash , ;;; or a backslash followed by any character at all. (define (parse-glob-bracket pat i) (let ((pat-len (string-length pat))) (let lp ((elts '(#\[)) (i i)) (if (>= i pat-len) (error "Ill-formed glob pattern -- no terminating close-bracket" pat) (let ((c (string-ref pat i)) (i (+ 1 i))) (case c ((#\]) (values (list->string (reverse (cons #\] elts))) i)) ((#\\) (if (>= i pat-len) (error "Ill-formed glob patten -- ends in backslash" pat) (lp (cons (string-ref pat i) (cons #\\ elts)) (+ 1 i)))) (else (lp (cons c elts) i)))))))) ;;; Is the glob pattern free of *'s, ?'s and [...]'s? (define (constant-glob? pattern) (let ((patlen (string-length pattern))) (let lp ((i 0)) (or (= i patlen) (let ((next-i (+ i 1))) (case (string-ref pattern i) ((#\\) ; Escape char (if (= next-i patlen) (error "Ill-formed glob pattern -- ends in backslash" pattern) (lp (+ next-i 1)))) ((#\* #\? #\[) #f) (else (lp next-i)))))))) ;;; Make an effort to get the files in the putative directory PATH. ;;; If PATH isn't a directory, or some filesys error happens (such ;;; as a broken symlink, or a permissions problem), don't error out, ;;; just quietly return the empty list. (define (maybe-directory-files path dotfiles?) (with-errno-handler ((errno data) (else '())) ; On any error, return (). (directory-files (if (string=? path "") "." path) dotfiles?))) ;;; Make an effort to find out if the file is a directory. If there's any error , return # f. (define (maybe-isdir? path) (with-errno-handler ((errno data) On any error , return # f. (file-is-directory? path))) ;;; This section of code is responsible for processing the braces in glob ;;; patterns. I.e., "{foo,bar}/*.c" -> ("foo/*.c" "bar/*.c") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (append-suffix strs suffix) (map (lambda (s) (string-append s suffix)) strs)) (define (cross-append prefixes suffixes) (apply append (map (lambda (sfx) (append-suffix prefixes sfx)) suffixes))) ;;; Parse a glob pattern into an equivalent series of brace-free patterns. The pattern starts at START and is terminated by ( 1 ) end of string , ( 2 ) an unmatched close brace , or ( 3 ) a comma ( if COMMA - TERMINATES ? is set ) . Returns two values : ;;; - the list of patterns ;;; - the string index after the pattern terminates. This points at ;;; the comma or brace if they terminated the scan, since they are ;;; not part of the pattern. (define (parse-glob-braces pattern start comma-terminates?) (let ((pattern-len (string-length pattern)) (finish (lambda (prefixes pat) (append-suffix prefixes (list->string (reverse pat)))))) (let lp ((i start) (prefixes '("")) (pat '())) (if (= i pattern-len) (values (finish prefixes pat) i) (let ((c (string-ref pattern i))) (case c ((#\{) (let ((prefixes (append-suffix prefixes (list->string (reverse pat))))) (receive (pats i) (parse-comma-sequence pattern (+ i 1)) (lp i (cross-append prefixes pats) '())))) ((#\\) (let ((next-i (+ i 1))) (if (= next-i pattern-len) (error "Dangling escape char in glob pattern" pattern) (if (memv (string-ref pattern next-i) '(#\{ #\, #\} #\\)) (lp (+ next-i 1) prefixes (cons (string-ref pattern next-i) pat)) (lp (+ i 1) prefixes (cons (string-ref pattern i) pat)))))) ((#\,) (if comma-terminates? (values (finish prefixes pat) i) (lp (+ i 1) prefixes (cons c pat)))) ((#\}) (values (finish prefixes pat) i)) (else (lp (+ i 1) prefixes (cons c pat))))))))) ;;; Parse the internals of a {foo,bar,baz} brace list from a glob pattern. START is the index of the char following the open brace . Returns two values : ;;; - an equivalent list of brace-free glob patterns ;;; - the index of the char after the terminating brace (define (parse-comma-sequence pattern start) (let ((pattern-len (string-length pattern))) (let lp ((i start) (patterns '())) ; The list of comma-separated patterns read. (if (= i pattern-len) (error "Glob brace-expression pattern not terminated" pattern) (receive (pats i) (parse-glob-braces pattern i #t) (let ((patterns (append patterns pats))) (if (= i pattern-len) (error "Unterminated brace in glob pattern" pattern) (let ((c (string-ref pattern i))) (case c ((#\}) (values patterns (+ i 1))) ((#\,) (lp (+ i 1) patterns)) (else (error "glob parser internal error" pattern i))))))))))) (define (glob-remove-braces pattern) (receive (pats i) (parse-glob-braces pattern 0 #f) (if (= i (string-length pattern)) pats (error "Unmatched close brace in glob pattern" pattern i)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Convert a string into a glob pattern that matches that string exactly -- ;;; in other words, quote the \ * ? [] and {} chars with backslashes. (define (glob-quote string) (let lp ((i (- (string-length string) 1)) (result '())) (if (< i 0) (list->string result) (lp (- i 1) (let* ((c (string-ref string i)) (result (cons c result))) (if (memv c '(#\[ #\] #\* #\? #\{ #\} #\\)) (cons #\\ result) result)))))) (define (glob-unquote string) (let ((len (string-length string))) (let lp ((i 0) (result '())) (if (= i len) (list->string (reverse result)) (let* ((c (string-ref string i))) (if (char=? c #\\) (let ((next-i (+ i 1))) (if (= next-i len) (error "Dangling escape char in glob pattern" string) (let ((quoted (string-ref string next-i))) (lp (+ i 2) (cons quoted result))))) (lp (+ i 1) (cons c result))))))))
null
https://raw.githubusercontent.com/ChaosEternal/guile-scsh/1a76e006e193a6a8c9f93d23bacb9e51a1ff6c4c/scsh/glob.scm
scheme
Code for processing file names with a glob pattern. See file COPYING. Chaos: this modification is pretty dirty. Usage: (glob pattern-list) pattern-list := a list of glob-pattern strings Return: list of file names (strings) The files "." and ".." are never returned by glob. of a glob pattern is a ".". The empty pattern matches nothing. otherwise , we start at cwd . A pattern ending with / matches only directories, e.g., "/usr/man/man?/" Must be non-null. root This is the heart of the matcher. True if we are sure this file exists. All done. Return the elts of directory FNAME that match pattern PAT. If PAT contains no wildcards, we cheat and do not match the constant pattern against every file in FNAME/; we just immediately return FNAME/PAT. In this case, we indicate that we aren't actually sure the file exists by returning a true SURE? value. Not only does this vastly speed up the matcher, it also allows us to match the constant patterns "." and "..". PAT doesn't contain a slash. Don't check filesys. Match dot files? These guys exist for sure. The initial special-case above isn't really for the fast-path; it's an obscure and unlikely case. But since we have to check pat[0] for an initial dot, we have to do the check anyway... Translate a brace-free glob pattern to a regular expression. ".*" or (* any) Reverse CHARS and cons the We accumulate chars into CHARS, and coalesce into a single string with STR-CONS when we run across a non-char. A glob bracket expression is [...] or [^...]. The body is a sequence of <char> and <char>-<char> ranges. or a backslash followed by any character at all. Is the glob pattern free of *'s, ?'s and [...]'s? Escape char Make an effort to get the files in the putative directory PATH. If PATH isn't a directory, or some filesys error happens (such as a broken symlink, or a permissions problem), don't error out, just quietly return the empty list. On any error, return (). Make an effort to find out if the file is a directory. If there's This section of code is responsible for processing the braces in glob patterns. I.e., "{foo,bar}/*.c" -> ("foo/*.c" "bar/*.c") Parse a glob pattern into an equivalent series of brace-free patterns. - the list of patterns - the string index after the pattern terminates. This points at the comma or brace if they terminated the scan, since they are not part of the pattern. Parse the internals of a {foo,bar,baz} brace list from a glob pattern. - an equivalent list of brace-free glob patterns - the index of the char after the terminating brace The list of comma-separated patterns read. Convert a string into a glob pattern that matches that string exactly -- in other words, quote the \ * ? [] and {} chars with backslashes.
Copyright ( c ) 1994 by ( ) . Copyright ( c ) 1994 by ( ) . Copyright ( c ) 2013 by Chaos Eternal ( ) . Dot files will only be returned if the first character (define-module (scsh glob) :use-module (srfi srfi-8) :use-module (srfi srfi-1) :use-module (scsh errno) :use-module (scsh scsh-condition) :use-module (scsh scsh) :use-module (ice-9 regex) :use-module (scsh ssyntax) :export (glob glob* directory-files glob->regexp-list)) (define char->ascii char->integer) (define-syntax glob (syntax-rules () ((_ rest ...) (apply glob* `(rest ...))))) (define (glob* . pattern-list) Expand out braces , and apply GLOB - ONE - PATTERN to all the result patterns . (apply append (map glob-one-pattern (apply append (map glob-remove-braces (map stringify pattern-list)))))) (define (split-file-name fn) (string-split fn #\/)) (define (file-name-as-directory fn) (string-append fn "/")) (define (filter-dot-files dotfile?) (lambda (x) (if (or (equal? x ".") (equal? x "..")) #f (if dotfile? #t (if (eq? (string-ref x 0) #\.) #f #t))))) (define (directory-files dir dotfile?) (filter (filter-dot-files dotfile?) (port->list readdir (opendir dir)))) (define (glob-one-pattern pattern) (let ((plen (string-length pattern))) (if (zero? plen) '() (let ((directories-only? (char=? #\/ (string-ref pattern (- plen 1)))) (if (equal? "" (car patterns)) cwd (define (really-glob root-file patterns directories-only?) (let recur ((file root-file) (pats patterns) (if (pair? pats) (let ((pat (car pats)) (pats (cdr pats)) (dir (file-name-as-directory file))) (receive (winners sure?) (glob-subpat dir pat) (apply append (map (lambda (f) (recur (string-append dir f) pats sure?)) winners)))) (if directories-only? (if (maybe-isdir? file) (list (file-name-as-directory file)) '()) (if (or sure? (file-exists? file)) (list file) '()))))) (cond ((string=? pat "") (values '() #t)) ((constant-glob? pat) (candidates (maybe-directory-files fname dots?)) (re (glob->regexp pat))) (values (filter (lambda (f) (string-match re f)) candidates) (define (glob->regexp pat) (string-join (glob->regexp-list pat) "")) (define (re-repeat x y z) ".*" ) (define re-any ".") (define re-eos "$") (define re-bos "^") (define glob->regexp-list (lambda (pat) (let ((pat-len (string-length pat)) result string - re onto RES . (cons (list->string (reverse chars)) res) res)))) (let lp ((chars '()) (res (list re-bos)) (i 0)) (if (= i pat-len) (reverse (cons re-eos (str-cons chars res))) (let ((c (string-ref pat i)) (i (+ i 1))) (case c ((#\\) (if (< i pat-len) (lp (cons (string-ref pat i) (cons #\\ chars)) res (+ i 1)) (error "Ill-formed glob pattern -- ends in backslash" pat))) ((#\*) (lp '() (cons dot-star (str-cons chars res)) i)) ((#\?) (lp '() (cons re-any (str-cons chars res)) i)) ((#\.) (lp '() (cons "[.]" (str-cons chars res)) i)) ((#\[) (receive (re i) (parse-glob-bracket pat i) (lp '() (cons re (str-cons chars res)) i))) (else (lp (cons c chars) res i)))))))))) A < char > is any character except right - bracket , carat , hypen or backslash , (define (parse-glob-bracket pat i) (let ((pat-len (string-length pat))) (let lp ((elts '(#\[)) (i i)) (if (>= i pat-len) (error "Ill-formed glob pattern -- no terminating close-bracket" pat) (let ((c (string-ref pat i)) (i (+ 1 i))) (case c ((#\]) (values (list->string (reverse (cons #\] elts))) i)) ((#\\) (if (>= i pat-len) (error "Ill-formed glob patten -- ends in backslash" pat) (lp (cons (string-ref pat i) (cons #\\ elts)) (+ 1 i)))) (else (lp (cons c elts) i)))))))) (define (constant-glob? pattern) (let ((patlen (string-length pattern))) (let lp ((i 0)) (or (= i patlen) (let ((next-i (+ i 1))) (case (string-ref pattern i) (if (= next-i patlen) (error "Ill-formed glob pattern -- ends in backslash" pattern) (lp (+ next-i 1)))) ((#\* #\? #\[) #f) (else (lp next-i)))))))) (define (maybe-directory-files path dotfiles?) (with-errno-handler ((errno data) (directory-files (if (string=? path "") "." path) dotfiles?))) any error , return # f. (define (maybe-isdir? path) (with-errno-handler ((errno data) On any error , return # f. (file-is-directory? path))) (define (append-suffix strs suffix) (map (lambda (s) (string-append s suffix)) strs)) (define (cross-append prefixes suffixes) (apply append (map (lambda (sfx) (append-suffix prefixes sfx)) suffixes))) The pattern starts at START and is terminated by ( 1 ) end of string , ( 2 ) an unmatched close brace , or ( 3 ) a comma ( if COMMA - TERMINATES ? is set ) . Returns two values : (define (parse-glob-braces pattern start comma-terminates?) (let ((pattern-len (string-length pattern)) (finish (lambda (prefixes pat) (append-suffix prefixes (list->string (reverse pat)))))) (let lp ((i start) (prefixes '("")) (pat '())) (if (= i pattern-len) (values (finish prefixes pat) i) (let ((c (string-ref pattern i))) (case c ((#\{) (let ((prefixes (append-suffix prefixes (list->string (reverse pat))))) (receive (pats i) (parse-comma-sequence pattern (+ i 1)) (lp i (cross-append prefixes pats) '())))) ((#\\) (let ((next-i (+ i 1))) (if (= next-i pattern-len) (error "Dangling escape char in glob pattern" pattern) (if (memv (string-ref pattern next-i) '(#\{ #\, #\} #\\)) (lp (+ next-i 1) prefixes (cons (string-ref pattern next-i) pat)) (lp (+ i 1) prefixes (cons (string-ref pattern i) pat)))))) ((#\,) (if comma-terminates? (values (finish prefixes pat) i) (lp (+ i 1) prefixes (cons c pat)))) ((#\}) (values (finish prefixes pat) i)) (else (lp (+ i 1) prefixes (cons c pat))))))))) START is the index of the char following the open brace . Returns two values : (define (parse-comma-sequence pattern start) (let ((pattern-len (string-length pattern))) (let lp ((i start) (if (= i pattern-len) (error "Glob brace-expression pattern not terminated" pattern) (receive (pats i) (parse-glob-braces pattern i #t) (let ((patterns (append patterns pats))) (if (= i pattern-len) (error "Unterminated brace in glob pattern" pattern) (let ((c (string-ref pattern i))) (case c ((#\}) (values patterns (+ i 1))) ((#\,) (lp (+ i 1) patterns)) (else (error "glob parser internal error" pattern i))))))))))) (define (glob-remove-braces pattern) (receive (pats i) (parse-glob-braces pattern 0 #f) (if (= i (string-length pattern)) pats (error "Unmatched close brace in glob pattern" pattern i)))) (define (glob-quote string) (let lp ((i (- (string-length string) 1)) (result '())) (if (< i 0) (list->string result) (lp (- i 1) (let* ((c (string-ref string i)) (result (cons c result))) (if (memv c '(#\[ #\] #\* #\? #\{ #\} #\\)) (cons #\\ result) result)))))) (define (glob-unquote string) (let ((len (string-length string))) (let lp ((i 0) (result '())) (if (= i len) (list->string (reverse result)) (let* ((c (string-ref string i))) (if (char=? c #\\) (let ((next-i (+ i 1))) (if (= next-i len) (error "Dangling escape char in glob pattern" string) (let ((quoted (string-ref string next-i))) (lp (+ i 2) (cons quoted result))))) (lp (+ i 1) (cons c result))))))))
6fe72eb5260c66c794742afc938d6ef2c674480cc7e73dfd81a03a1777897837
IUCompilerCourse/public-student-support-code
type-check-Cwhile.rkt
#lang racket ;(require graph) ;(require "multigraph.rkt") (require "utilities.rkt") (require "type-check-Lwhile.rkt") (require "type-check-Cvar.rkt") (require "type-check-Cif.rkt") (provide type-check-Cwhile type-check-Cwhile-mixin type-check-Cwhile-class) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; type-check-Cwhile (define (type-check-Cwhile-mixin super-class) (class super-class (super-new) (inherit check-type-equal?) #;(define/public (combine-types t1 t2) (match (list t1 t2) [(list '_ t2) t2] [(list t1 '_) t1] [else t1])) ;; TODO: move some things from here to later type checkers (define/override (free-vars-exp e) (define (recur e) (send this free-vars-exp e)) (match e [(WhileLoop cnd body) (set-union (recur cnd) (recur body))] [(Begin es e) (apply set-union (cons (recur e) (map recur es)))] [(SetBang x rhs) (set-union (set x) (recur rhs))] ;; C-level expressions [(Void) (set)] [else (super free-vars-exp e)])) #;(define (update-type x t env) (debug 'update-type x t) (cond [(dict-has-key? env x) (define old-t (dict-ref env x)) (unless (type-equal? t old-t) (error 'update-type "old type ~a and new type ~ are inconsistent" old-t t)) (define new-t (combine-types old-t t)) (cond [(not (equal? new-t old-t)) (dict-set! env x new-t) (set! type-changed #t)])] [(eq? t '_) (void)] [else (set! type-changed #t) (dict-set! env x t)])) (define/override ((type-check-atm env) e) (match e [(Void) (values (Void) 'Void)] [else ((super type-check-atm env) e)] )) (define/override (type-check-exp env) (lambda (e) (debug 'type-check-exp "Cwhile" e) (define recur (type-check-exp env)) (match e [(Void) (values (Void) 'Void)] [else ((super type-check-exp env) e)]))) #;(define/override (type-check-program p) (match p [(CProgram info blocks) (define empty-env (make-hash)) (define-values (env t) (type-check-blocks info blocks empty-env 'start)) (unless (type-equal? t 'Integer) (error "return type of program must be Integer, not" t)) (define locals-types (for/list ([(x t) (in-dict env)]) (cons x t))) (define new-info (dict-set info 'locals-types locals-types)) (CProgram new-info blocks)] [else (super type-check-program p)])) )) (define type-check-Cwhile-class (type-check-Cwhile-mixin (type-check-Cif-mixin (type-check-Cvar-mixin type-check-Lwhile-class)))) (define (type-check-Cwhile p) (send (new type-check-Cwhile-class) type-check-program p))
null
https://raw.githubusercontent.com/IUCompilerCourse/public-student-support-code/de33d84247885ea309db456cc8086a12c8cdd067/type-check-Cwhile.rkt
racket
(require graph) (require "multigraph.rkt") type-check-Cwhile (define/public (combine-types t1 t2) TODO: move some things from here to later type checkers C-level expressions (define (update-type x t env) (define/override (type-check-program p)
#lang racket (require "utilities.rkt") (require "type-check-Lwhile.rkt") (require "type-check-Cvar.rkt") (require "type-check-Cif.rkt") (provide type-check-Cwhile type-check-Cwhile-mixin type-check-Cwhile-class) (define (type-check-Cwhile-mixin super-class) (class super-class (super-new) (inherit check-type-equal?) (match (list t1 t2) [(list '_ t2) t2] [(list t1 '_) t1] [else t1])) (define/override (free-vars-exp e) (define (recur e) (send this free-vars-exp e)) (match e [(WhileLoop cnd body) (set-union (recur cnd) (recur body))] [(Begin es e) (apply set-union (cons (recur e) (map recur es)))] [(SetBang x rhs) (set-union (set x) (recur rhs))] [(Void) (set)] [else (super free-vars-exp e)])) (debug 'update-type x t) (cond [(dict-has-key? env x) (define old-t (dict-ref env x)) (unless (type-equal? t old-t) (error 'update-type "old type ~a and new type ~ are inconsistent" old-t t)) (define new-t (combine-types old-t t)) (cond [(not (equal? new-t old-t)) (dict-set! env x new-t) (set! type-changed #t)])] [(eq? t '_) (void)] [else (set! type-changed #t) (dict-set! env x t)])) (define/override ((type-check-atm env) e) (match e [(Void) (values (Void) 'Void)] [else ((super type-check-atm env) e)] )) (define/override (type-check-exp env) (lambda (e) (debug 'type-check-exp "Cwhile" e) (define recur (type-check-exp env)) (match e [(Void) (values (Void) 'Void)] [else ((super type-check-exp env) e)]))) (match p [(CProgram info blocks) (define empty-env (make-hash)) (define-values (env t) (type-check-blocks info blocks empty-env 'start)) (unless (type-equal? t 'Integer) (error "return type of program must be Integer, not" t)) (define locals-types (for/list ([(x t) (in-dict env)]) (cons x t))) (define new-info (dict-set info 'locals-types locals-types)) (CProgram new-info blocks)] [else (super type-check-program p)])) )) (define type-check-Cwhile-class (type-check-Cwhile-mixin (type-check-Cif-mixin (type-check-Cvar-mixin type-check-Lwhile-class)))) (define (type-check-Cwhile p) (send (new type-check-Cwhile-class) type-check-program p))
8034070d3da0294cead7938cea347fb1d168efd693224e1050b35f5278375a73
lisp-korea/sicp
ex-1-1-byulparan.scm
1.1 프로그램을 짤 때 바탕이 되는 것 기본식 primitive expression - 언어에서 가장 단순한 것을 나타낸다 . 엵어내는 수단 means of combination - 간단한 것을 모아 복잡한 것 compound element 으로 만든다 요약하는 수단 means of abstraction - 복잡한 것에 이름을 붙여 하나로 다룰 수 있게끔 간추린다 . ;; 1.1.1 식 486 수를 나타내는 식과 , 기본 프로시저를 나타내는 식 + , 나 * 같은 기호를 엵은 더 복잡한 식 (+ 137 349) (- 1000 334) (* 5 99) (/ 10 5) (+ 2.7 10) 위와 같이 여러 식을 괄호로 묶어 리스트를 만들고 프로시저 적용을 뜻하도록 엵어놓은 식을 엵은 식이라고 한다 . 이 리스트에서 맨 왼쪽에 있는 식은 연산자Operator 가 되고 나머지 식은 피 가 된다 . 1.1.2 이름과 환경 (define size 2) size (* 5 size) (define pi 3.14159) (define radius 10) (* pi (* radius radius)) (define circumference (* 2 pi radius)) 어떤 값에 이름symbol 을 붙여 두었다가 뒤에 그 이름으로 필요한 값을 찾아 쓸 수 있다는 것은 , 실행기 속 어딘가에 이름 - 물체 의 쌍을 저장해둔 메모리가 있다는 뜻이다 . ;; 이런 기억공간을 환경Environment 라고 한다. 지금 여기서 ' 환경 ' 이란 맨 바깥쪽에 있는 바탕환경global environment 을 말한다 ;; 1.1.3 엵은 식을 계산하는 방법 1 . 엵은 식에서 부분식subexpression 의 값을 모두 구한다 2 . 엵은 식에서 맨 왼쪽에 있는 식(연산자 ) 의 값은 프로시저가 되고 , 나머지 식(피연산자 ) 의 값은 인자가 된다 . 프로시저를 인자에 적용하여 엵은 식의 값을 구한다 . 엵은 식의 값을 셈하는 프로세스를 끝내려면 하는데 , 부분식의 값을 셈할 때에도 똑같은 프로세슬 따르도록 하고 있다 . (* (+ 2 (* 4 6)) (+ 3 5 7)) ;; 1.1.4 묽음 프로시저 1 . 수와 산술 연산이 기본 데이터이고 기본 프로시저이다 . 2 . 엵은 식을 겹쳐 쓰는 것이 여러 연산을 한데 묽는 수단이 된다 . 3 . 이름과 값을 짝지워 정의한 것이 모자라나마 요약하는 수단이 된다 . 프로시저를 ;;제곱 (define (square x) (* x x)) (square 21) (square (+ 2 5)) (square (square 3)) (define (sum-of-squares x y) (+ (square x) (square y))) (sum-of-squares 3 4) (define (f a) (sum-of-squares (+ a 1) (* a 2))) (f 5) 1.1.4 맞바꿈 계산법으로 프로시저를 실행하는 방법 ;; 기본프로시저를 계산 하는 방법은 이미 실행기 속에 정해져 있다고 보고 ;; 새로 만들어 쓰는 묽음 프로시저의 적용은 다음 규칙에 따란 계산 된다. - 묽음 프로시저를 인자에 맞춘다는 것은 , 프로시저의 몸속에 있는 모든 인자이름을 저마다 , 그렇게 얻어낸 식의 값을 구하는 (f 5) (sum-of-squares (+ 5 1) (* 5 2)) (+ (square 6) (square 10)) (+ (* 6 6) (+ 10 10)) 인자 먼저 계산법 과 ;; 정의대로 계산법 (sum-of-squares (+ 5 1) (* 5 2)) (+ (square (+ 5 1)) (square (* 5 2))) (+ (* (+ 5 1) (+ 5 1)) (* (* 5 2) (* 5 2))) (+ (* 6 6) (* 10 10)) (+ 36 100) 136 ;; 1.1.6 조건식과 술어 (define (abs x) (cond ((> x 0) x) ((= x 0) 0) ((< x 0) (- x)))) (define (abs x) (cond ((< x 0) (- x)) (else x))) (and (= 10 10) (= 20 20) (= 30 30)) (and (= 10 10) (= 30 30) (* 20 20)) (or (= 10 20) (= 30 20)) (or (= 10 10) (= 30 20)) (or (= 10 20) (+ 100 200) (= 30 20)) 연습문제 1.1 10 (+ 5 3 4) (- 9 1) (/ 6 2) (+ (* 2 4) (- 4 6)) (define a 3) (define b (+ a 1)) (+ a b (* a b)) (= a b) (if (and (> b a) (< b (* a b))) b a) (cond ((= a 4) 6) ((= b 4) (+ 6 7 a)) (else 25)) (+ 2 (if (> b a) b a)) (* (cond ((> a b) a) ((< a b) b) (else -1)) (+ a 1)) 연습문제 1.2 5 + 4 + (2 - (3 - (6 + 4/5))) ----------------------------- 3(6 - 2)(2 - 7) (/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5.0))))) (* 3 (- 6 2) (- 2 7))) 연습문제 1.3 세 숫자를 인자로 받아 그 가운데 큰 숫자 두 개를 제곱한 다음 , 그 다 값을 덧셈하여 내놓는 프로시저를 정의하라 (define (square-of-two-bignum x y z) (if (>= x y) (if (>= y z) (+ (square x) (square y)) (+ (square x) (square z))) (if (>= x z) (+ (square y) (square x)) (+ (square y) (square z))))) 연습문제 1.4 (define (a-plus-abs-b a b) ((if (> b 0) + -) a b)) (a-plus-abs-b 10 -20) ((if (> -20 0) + -) 10 -20) (- 10 -20) 연습문제 1.5 인자 먼저 / 혹은 제때 계산하는 실행기에 따라 어떻게 다른가 . (define (p) (p)) (define (test x y) (if (= x 0) 0 y)) 인자먼저 계산시 test 함수body 에 진입하기 전에 ( p ) 에서 무한루프 ;; 1.1.7 연습 : 뉴튼 법 으로 제곱근 찾기 (define (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) (define (improve guess x) (average guess (/ x guess))) (define (average x y) (/ (+ x y) 2)) (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.001)) 연습문제 1.6 (define (new-if predicate then-clause else-clause) (cond (predicate then-clause) (else else-clause))) (new-if (= 2 3) 0 5) (new-if (= 1 1) 0 5) (define (sqrt-iter guess x) (new-if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) 연습문제 1.7 위의 good - enough ? 으로는 아주 작은 수의 제곱근을 구하지 못한다 . (sqrt 0.00001) (sqrt-iter 1 0.00001) ;; 이에 따라 guess 를 구하기 위해 어림잡은 값을 조금씩 고쳐나가면서 헌값에 견주어 고친값이 그다지 나아지지 않을 때깨지 계산을 이어나가자 . (define (good-enough? guess x) (< (abs (- (improve guess x) guess)) 0.001)) 연습문제 1.8 세제곱근을 구해보자 . 세제곱근 공식 : x / y의 제곱 + 2y ---------------- = (/ (+ (/ x (square y)) (* 2 y)) 3) 3 (define (improve guess x) (/ (+ (/ x (square guess)) (* 2 guess)) 3)) (sqrt-iter 1.0 8) (sqrt-iter 1.0 27) (sqrt-iter 1.0 64) (sqrt-iter 1.0 125) 1.1.8 블랙박스처럼 간추린 프로시저 / 갇힌 이름 / 안쪽 정의와 블록 구조 (define (sqrt x) (sqrt-iter 1.0 x)) (define (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.001)) (define (improve guess x) (average guess (/ x guess)))
null
https://raw.githubusercontent.com/lisp-korea/sicp/4cdc1b1d858c6da7c9f4ec925ff4a724f36041cc/ch01/1.1/ex-1-1-byulparan.scm
scheme
1.1.1 식 이런 기억공간을 환경Environment 라고 한다. 1.1.3 엵은 식을 계산하는 방법 1.1.4 묽음 프로시저 제곱 기본프로시저를 계산 하는 방법은 이미 실행기 속에 정해져 있다고 보고 새로 만들어 쓰는 묽음 프로시저의 적용은 다음 규칙에 따란 계산 된다. 정의대로 계산법 1.1.6 조건식과 술어 1.1.7 연습 : 뉴튼 법 으로 제곱근 찾기 이에 따라 guess 를 구하기 위해 어림잡은 값을 조금씩 고쳐나가면서 헌값에 견주어 고친값이
1.1 프로그램을 짤 때 바탕이 되는 것 기본식 primitive expression - 언어에서 가장 단순한 것을 나타낸다 . 엵어내는 수단 means of combination - 간단한 것을 모아 복잡한 것 compound element 으로 만든다 요약하는 수단 means of abstraction - 복잡한 것에 이름을 붙여 하나로 다룰 수 있게끔 간추린다 . 486 수를 나타내는 식과 , 기본 프로시저를 나타내는 식 + , 나 * 같은 기호를 엵은 더 복잡한 식 (+ 137 349) (- 1000 334) (* 5 99) (/ 10 5) (+ 2.7 10) 위와 같이 여러 식을 괄호로 묶어 리스트를 만들고 프로시저 적용을 뜻하도록 엵어놓은 식을 엵은 식이라고 한다 . 이 리스트에서 맨 왼쪽에 있는 식은 연산자Operator 가 되고 나머지 식은 피 가 된다 . 1.1.2 이름과 환경 (define size 2) size (* 5 size) (define pi 3.14159) (define radius 10) (* pi (* radius radius)) (define circumference (* 2 pi radius)) 어떤 값에 이름symbol 을 붙여 두었다가 뒤에 그 이름으로 필요한 값을 찾아 쓸 수 있다는 것은 , 실행기 속 어딘가에 이름 - 물체 의 쌍을 저장해둔 메모리가 있다는 뜻이다 . 지금 여기서 ' 환경 ' 이란 맨 바깥쪽에 있는 바탕환경global environment 을 말한다 1 . 엵은 식에서 부분식subexpression 의 값을 모두 구한다 2 . 엵은 식에서 맨 왼쪽에 있는 식(연산자 ) 의 값은 프로시저가 되고 , 나머지 식(피연산자 ) 의 값은 인자가 된다 . 프로시저를 인자에 적용하여 엵은 식의 값을 구한다 . 엵은 식의 값을 셈하는 프로세스를 끝내려면 하는데 , 부분식의 값을 셈할 때에도 똑같은 프로세슬 따르도록 하고 있다 . (* (+ 2 (* 4 6)) (+ 3 5 7)) 1 . 수와 산술 연산이 기본 데이터이고 기본 프로시저이다 . 2 . 엵은 식을 겹쳐 쓰는 것이 여러 연산을 한데 묽는 수단이 된다 . 3 . 이름과 값을 짝지워 정의한 것이 모자라나마 요약하는 수단이 된다 . 프로시저를 (define (square x) (* x x)) (square 21) (square (+ 2 5)) (square (square 3)) (define (sum-of-squares x y) (+ (square x) (square y))) (sum-of-squares 3 4) (define (f a) (sum-of-squares (+ a 1) (* a 2))) (f 5) 1.1.4 맞바꿈 계산법으로 프로시저를 실행하는 방법 - 묽음 프로시저를 인자에 맞춘다는 것은 , 프로시저의 몸속에 있는 모든 인자이름을 저마다 , 그렇게 얻어낸 식의 값을 구하는 (f 5) (sum-of-squares (+ 5 1) (* 5 2)) (+ (square 6) (square 10)) (+ (* 6 6) (+ 10 10)) 인자 먼저 계산법 과 (sum-of-squares (+ 5 1) (* 5 2)) (+ (square (+ 5 1)) (square (* 5 2))) (+ (* (+ 5 1) (+ 5 1)) (* (* 5 2) (* 5 2))) (+ (* 6 6) (* 10 10)) (+ 36 100) 136 (define (abs x) (cond ((> x 0) x) ((= x 0) 0) ((< x 0) (- x)))) (define (abs x) (cond ((< x 0) (- x)) (else x))) (and (= 10 10) (= 20 20) (= 30 30)) (and (= 10 10) (= 30 30) (* 20 20)) (or (= 10 20) (= 30 20)) (or (= 10 10) (= 30 20)) (or (= 10 20) (+ 100 200) (= 30 20)) 연습문제 1.1 10 (+ 5 3 4) (- 9 1) (/ 6 2) (+ (* 2 4) (- 4 6)) (define a 3) (define b (+ a 1)) (+ a b (* a b)) (= a b) (if (and (> b a) (< b (* a b))) b a) (cond ((= a 4) 6) ((= b 4) (+ 6 7 a)) (else 25)) (+ 2 (if (> b a) b a)) (* (cond ((> a b) a) ((< a b) b) (else -1)) (+ a 1)) 연습문제 1.2 5 + 4 + (2 - (3 - (6 + 4/5))) ----------------------------- 3(6 - 2)(2 - 7) (/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5.0))))) (* 3 (- 6 2) (- 2 7))) 연습문제 1.3 세 숫자를 인자로 받아 그 가운데 큰 숫자 두 개를 제곱한 다음 , 그 다 값을 덧셈하여 내놓는 프로시저를 정의하라 (define (square-of-two-bignum x y z) (if (>= x y) (if (>= y z) (+ (square x) (square y)) (+ (square x) (square z))) (if (>= x z) (+ (square y) (square x)) (+ (square y) (square z))))) 연습문제 1.4 (define (a-plus-abs-b a b) ((if (> b 0) + -) a b)) (a-plus-abs-b 10 -20) ((if (> -20 0) + -) 10 -20) (- 10 -20) 연습문제 1.5 인자 먼저 / 혹은 제때 계산하는 실행기에 따라 어떻게 다른가 . (define (p) (p)) (define (test x y) (if (= x 0) 0 y)) 인자먼저 계산시 test 함수body 에 진입하기 전에 ( p ) 에서 무한루프 (define (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) (define (improve guess x) (average guess (/ x guess))) (define (average x y) (/ (+ x y) 2)) (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.001)) 연습문제 1.6 (define (new-if predicate then-clause else-clause) (cond (predicate then-clause) (else else-clause))) (new-if (= 2 3) 0 5) (new-if (= 1 1) 0 5) (define (sqrt-iter guess x) (new-if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) 연습문제 1.7 위의 good - enough ? 으로는 아주 작은 수의 제곱근을 구하지 못한다 . (sqrt 0.00001) (sqrt-iter 1 0.00001) 그다지 나아지지 않을 때깨지 계산을 이어나가자 . (define (good-enough? guess x) (< (abs (- (improve guess x) guess)) 0.001)) 연습문제 1.8 세제곱근을 구해보자 . 세제곱근 공식 : x / y의 제곱 + 2y ---------------- = (/ (+ (/ x (square y)) (* 2 y)) 3) 3 (define (improve guess x) (/ (+ (/ x (square guess)) (* 2 guess)) 3)) (sqrt-iter 1.0 8) (sqrt-iter 1.0 27) (sqrt-iter 1.0 64) (sqrt-iter 1.0 125) 1.1.8 블랙박스처럼 간추린 프로시저 / 갇힌 이름 / 안쪽 정의와 블록 구조 (define (sqrt x) (sqrt-iter 1.0 x)) (define (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.001)) (define (improve guess x) (average guess (/ x guess)))
fbee3ab7409e4c5b1be567cb8dacfbf44df010303a4c2ec0f319b3c2ec6324cc
pedestal/pedestal-app
behavior_test.clj
(ns {{namespace}}.behavior-test (:require [io.pedestal.app :as app] [io.pedestal.app.protocols :as p] [io.pedestal.app.tree :as tree] [io.pedestal.app.messages :as msg] [io.pedestal.app.render :as render] [io.pedestal.app.util.test :as test]) (:use clojure.test {{namespace}}.behavior [io.pedestal.app.query :only [q]])) ;; Test a transform function (deftest test-set-value-transform (is (= (set-value-transform {} {msg/type :set-value msg/topic [:greeting] :value "x"}) "x"))) ;; Build an application, send a message to a transform and check the transform ;; state (deftest test-app-state (let [app (app/build example-app)] (app/begin app) (is (vector? (test/run-sync! app [{msg/type :set-value msg/topic [:greeting] :value "x"}]))) (is (= (-> app :state deref :data-model :greeting) "x")))) ;; Use io.pedestal.app.query to query the current application model (deftest test-query-ui (let [app (app/build example-app) app-model (render/consume-app-model app (constantly nil))] (app/begin app) (is (test/run-sync! app [{msg/topic [:greeting] msg/type :set-value :value "x"}])) (is (= (q '[:find ?v :where [?n :t/path [:greeting]] [?n :t/value ?v]] @app-model) [["x"]]))))
null
https://raw.githubusercontent.com/pedestal/pedestal-app/509ab766a54921c0fbb2dd7c6a3cb20223b8e1a1/app-template/src/leiningen/new/pedestal_app/test/behavior_test.clj
clojure
Test a transform function Build an application, send a message to a transform and check the transform state Use io.pedestal.app.query to query the current application model
(ns {{namespace}}.behavior-test (:require [io.pedestal.app :as app] [io.pedestal.app.protocols :as p] [io.pedestal.app.tree :as tree] [io.pedestal.app.messages :as msg] [io.pedestal.app.render :as render] [io.pedestal.app.util.test :as test]) (:use clojure.test {{namespace}}.behavior [io.pedestal.app.query :only [q]])) (deftest test-set-value-transform (is (= (set-value-transform {} {msg/type :set-value msg/topic [:greeting] :value "x"}) "x"))) (deftest test-app-state (let [app (app/build example-app)] (app/begin app) (is (vector? (test/run-sync! app [{msg/type :set-value msg/topic [:greeting] :value "x"}]))) (is (= (-> app :state deref :data-model :greeting) "x")))) (deftest test-query-ui (let [app (app/build example-app) app-model (render/consume-app-model app (constantly nil))] (app/begin app) (is (test/run-sync! app [{msg/topic [:greeting] msg/type :set-value :value "x"}])) (is (= (q '[:find ?v :where [?n :t/path [:greeting]] [?n :t/value ?v]] @app-model) [["x"]]))))
b112741629eacb901494fa09262ef01df5276f1ade1db7eb2f043b0cd3e582a8
alexwl/haskell-code-explorer
Helper.hs
cabal - helper : Simple interface to Cabal 's configuration state Copyright ( C ) 2015 - 2018 < > -- -- 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 </>. # LANGUAGE CPP , RecordWildCards , FlexibleContexts , ConstraintKinds , GeneralizedNewtypeDeriving , DeriveDataTypeable , DeriveGeneric , DeriveFunctor , NamedFieldPuns , OverloadedStrings # GeneralizedNewtypeDeriving, DeriveDataTypeable, DeriveGeneric, DeriveFunctor, NamedFieldPuns, OverloadedStrings #-} {-| Module : Distribution.Helper License : GPL-3 Maintainer : Portability : POSIX -} module Distribution.Helper ( -- * Running Queries Query , runQuery -- * Queries against Cabal\'s on disk state -- ** Package queries , packageId , packageDbStack , packageFlags , compilerVersion , ghcMergedPkgOptions -- ** cabal-install queries , configFlags , nonDefaultConfigFlags -- ** Component queries , ComponentQuery , components , ghcSrcOptions , ghcPkgOptions , ghcLangOptions , ghcOptions , sourceDirs , entrypoints , needsBuildOutput -- * Query environment , QueryEnv , mkQueryEnv , qeReadProcess , qePrograms , qeProjectDir , qeDistDir , qeCabalPkgDb , qeCabalVer , Programs(..) , defaultPrograms -- * Result types , ChModuleName(..) , ChComponentName(..) , ChPkgDb(..) , ChEntrypoint(..) , NeedsBuildOutput(..) -- * General information , buildPlatform -- * Stuff that cabal-install really should export , Distribution.Helper.getSandboxPkgDb -- * Managing @dist/@ , prepare , reconfigure , writeAutogenFiles -- * $libexec related error handling , LibexecNotFoundError(..) , libexecNotFoundError * , module Data.Functor.Apply ) where import Cabal.Plan hiding (findPlanJson) import Control.Applicative import Control.Monad import Control.Monad.IO.Class import Control.Monad.State.Strict import Control.Monad.Reader import Control.Exception as E import Data.Char import Data.List import Data.Maybe import qualified Data.Map as Map import Data.Version import Data.Typeable import Data.Function import Data.Functor.Apply import Distribution.System (buildOS, OS(Windows)) import System.Environment import System.FilePath hiding ((<.>)) import qualified System.FilePath as FP import System.Directory import System.Process import System.IO.Unsafe import Text.Printf import GHC.Generics import Prelude import Paths_cabal_helper (getLibexecDir) import CabalHelper.Shared.InterfaceTypes import CabalHelper.Shared.Sandbox -- | Paths or names of various programs we need. data Programs = Programs { -- | The path to the @cabal@ program. cabalProgram :: FilePath, | The path to the @ghc@ program . ghcProgram :: FilePath, -- | The path to the @ghc-pkg@ program. If -- not changed it will be derived from the path to 'ghcProgram'. ghcPkgProgram :: FilePath } deriving (Eq, Ord, Show, Read, Generic, Typeable) -- | Default all programs to their unqualified names, i.e. they will be searched -- for on @PATH@. defaultPrograms :: Programs defaultPrograms = Programs "cabal" "ghc" "ghc-pkg" -- | Environment for running a 'Query'. The real constructor is not exposed, -- the field accessors are however. See below. Use the 'mkQueryEnv' smart -- constructor to construct one. data QueryEnv = QueryEnv { | Field accessor for ' QueryEnv ' . Defines how to start the cabal - helper -- process. Useful if you need to capture stderr output from the helper. qeReadProcess :: FilePath -> [String] -> String -> IO String, | Field accessor for ' QueryEnv ' . qePrograms :: Programs, | Field accessor for ' QueryEnv ' . Defines path to the project directory , -- i.e. a directory containing a @project.cabal@ file qeProjectDir :: FilePath, | Field accessor for ' QueryEnv ' . Defines path to the @dist/@ directory , /builddir/ in Cabal terminology . qeDistDir :: FilePath, | Field accessor for ' QueryEnv ' . Defines where to look for the -- library when linking the helper. qeCabalPkgDb :: Maybe FilePath, | Field accessor for ' QueryEnv ' . If @dist / setup - config@ wasn\'t written by this version of Cabal an error is thrown when running the query . qeCabalVer :: Maybe Version } | @mkQueryEnv constructor for ' QueryEnv ' . Sets fields ' qeProjectDir ' and ' qeDistDir ' to @projdir@ and -- respectively and provides sensible defaults for the other fields. mkQueryEnv :: FilePath -- ^ Path to the project directory, i.e. the directory containing a -- @project.cabal@ file -> FilePath ^ Path to the @dist/@ directory , called /builddir/ in Cabal -- terminology. -> QueryEnv mkQueryEnv projdir distdir = QueryEnv { qeReadProcess = readProcess , qePrograms = defaultPrograms , qeProjectDir = projdir , qeDistDir = distdir , qeCabalPkgDb = Nothing , qeCabalVer = Nothing } data SomeLocalBuildInfo = SomeLocalBuildInfo { slbiPackageDbStack :: [ChPkgDb], slbiPackageFlags :: [(String, Bool)], slbiCompilerVersion :: (String, Version), slbiGhcMergedPkgOptions :: [String], slbiConfigFlags :: [(String, Bool)], slbiNonDefaultConfigFlags :: [(String, Bool)], slbiGhcSrcOptions :: [(ChComponentName, [String])], slbiGhcPkgOptions :: [(ChComponentName, [String])], slbiGhcLangOptions :: [(ChComponentName, [String])], slbiGhcOptions :: [(ChComponentName, [String])], slbiSourceDirs :: [(ChComponentName, [String])], slbiEntrypoints :: [(ChComponentName, ChEntrypoint)], slbiNeedsBuildOutput :: [(ChComponentName, NeedsBuildOutput)] } deriving (Eq, Ord, Read, Show) | A lazy , cached , query against a package 's Cabal configuration . Use ' ' to execute it . newtype Query m a = Query { unQuery :: StateT (Maybe SomeLocalBuildInfo) (ReaderT QueryEnv m) a } deriving (Functor, Applicative, Monad, MonadIO) instance MonadTrans Query where lift = Query . lift . lift type MonadQuery m = ( MonadIO m , MonadState (Maybe SomeLocalBuildInfo) m , MonadReader QueryEnv m) -- | A 'Query' to run on all components of a package. Use 'components' to get a -- regular 'Query'. newtype ComponentQuery m a = ComponentQuery (Query m [(ChComponentName, a)]) deriving (Functor) instance (Functor m, Monad m) => Apply (ComponentQuery m) where ComponentQuery flab <.> ComponentQuery fla = ComponentQuery $ liftM2 go flab fla where go :: [(ChComponentName, a -> b)] -> [(ChComponentName, a)] -> [(ChComponentName, b)] go lab la = [ (cn, ab a) | (cn, ab) <- lab , (cn', a) <- la , cn == cn' ] run :: Monad m => QueryEnv -> Maybe SomeLocalBuildInfo -> Query m a -> m a run e s action = flip runReaderT e (flip evalStateT s (unQuery action)) | @runQuery env a ' Query ' under a given ' QueryEnv ' . runQuery :: Monad m => QueryEnv -> Query m a -> m a runQuery qe action = run qe Nothing action getSlbi :: MonadQuery m => m SomeLocalBuildInfo getSlbi = do s <- get case s of Nothing -> do slbi <- getSomeConfigState put (Just slbi) return slbi Just slbi -> return slbi -- | List of package databases to use. packageDbStack :: MonadIO m => Query m [ChPkgDb] | Like @ghcPkgOptions@ but for the whole package not just one component ghcMergedPkgOptions :: MonadIO m => Query m [String] -- | Flag definitions from cabal file packageFlags :: MonadIO m => Query m [(String, Bool)] -- | Flag assignments from setup-config configFlags :: MonadIO m => Query m [(String, Bool)] -- | Flag assignments from setup-config which differ from the default -- setting. This can also include flags which cabal decided to modify, -- i.e. don't rely on these being the flags set by the user directly. nonDefaultConfigFlags :: MonadIO m => Query m [(String, Bool)] | The version of GHC the project is configured to use compilerVersion :: MonadIO m => Query m (String, Version) -- | Package identifier, i.e. package name and version packageId :: MonadIO m => Query m (String, Version) | Run a ComponentQuery on all components of the package . components :: Monad m => ComponentQuery m (ChComponentName -> b) -> Query m [b] components (ComponentQuery sc) = map (\(cn, f) -> f cn) `liftM` sc | Modules or files Cabal would have the compiler build directly . Can be used -- to compute the home module closure for a component. entrypoints :: MonadIO m => ComponentQuery m ChEntrypoint -- | The component has a non-default module renaming, so needs build output (). needsBuildOutput :: MonadIO m => ComponentQuery m NeedsBuildOutput | A component 's @source - dirs@ field , beware since if this is empty implicit behaviour in GHC kicks in . sourceDirs :: MonadIO m => ComponentQuery m [FilePath] | All options Cabal would pass to GHC . ghcOptions :: MonadIO m => ComponentQuery m [String] | Only search path related GHC options . ghcSrcOptions :: MonadIO m => ComponentQuery m [String] | Only package related GHC options , sufficient for things do n't need to -- access any home modules. ghcPkgOptions :: MonadIO m => ComponentQuery m [String] -- | Only language related options, i.e. @-XSomeExtension@ ghcLangOptions :: MonadIO m => ComponentQuery m [String] packageId = Query $ getPackageId packageDbStack = Query $ slbiPackageDbStack `liftM` getSlbi packageFlags = Query $ slbiPackageFlags `liftM` getSlbi compilerVersion = Query $ slbiCompilerVersion `liftM` getSlbi ghcMergedPkgOptions = Query $ slbiGhcMergedPkgOptions `liftM` getSlbi configFlags = Query $ slbiConfigFlags `liftM` getSlbi nonDefaultConfigFlags = Query $ slbiNonDefaultConfigFlags `liftM` getSlbi ghcSrcOptions = ComponentQuery $ Query $ slbiGhcSrcOptions `liftM` getSlbi ghcPkgOptions = ComponentQuery $ Query $ slbiGhcPkgOptions `liftM` getSlbi ghcOptions = ComponentQuery $ Query $ slbiGhcOptions `liftM` getSlbi ghcLangOptions = ComponentQuery $ Query $ slbiGhcLangOptions `liftM` getSlbi sourceDirs = ComponentQuery $ Query $ slbiSourceDirs `liftM` getSlbi entrypoints = ComponentQuery $ Query $ slbiEntrypoints `liftM` getSlbi needsBuildOutput = ComponentQuery $ Query $ slbiNeedsBuildOutput `liftM` getSlbi -- | Run @cabal configure@ reconfigure :: MonadIO m => (FilePath -> [String] -> String -> IO String) -> Programs -- ^ Program paths -> [String] -- ^ Command line arguments to be passed to @cabal@ -> m () reconfigure readProc progs cabalOpts = do let progOpts = [ "--with-ghc=" ++ ghcProgram progs ] Only pass ghc - pkg if it was actually set otherwise we -- might break cabal's guessing logic ++ if ghcPkgProgram progs /= "ghc-pkg" then [ "--with-ghc-pkg=" ++ ghcPkgProgram progs ] else [] ++ cabalOpts _ <- liftIO $ readProc (cabalProgram progs) ("configure":progOpts) "" return () readHelper :: (MonadIO m, MonadQuery m) => [String] -> m [Maybe ChResponse] readHelper args = ask >>= \qe -> liftIO $ do out <- either error id <$> invokeHelper qe args let res = read out liftIO $ evaluate res `E.catch` \se@(SomeException _) -> do md <- lookupEnv' "CABAL_HELPER_DEBUG" let msg = "readHelper: exception: '" ++ show se ++ "'" error $ msg ++ case md of Nothing -> ", for more information set the environment variable CABAL_HELPER_DEBUG" Just _ -> ", output: '"++ out ++"'" invokeHelper :: QueryEnv -> [String] -> IO (Either String String) invokeHelper QueryEnv {..} args = do let progArgs = [ "--with-ghc=" ++ ghcProgram qePrograms , "--with-ghc-pkg=" ++ ghcPkgProgram qePrograms , "--with-cabal=" ++ cabalProgram qePrograms ] exe <- findLibexecExe let args' = progArgs ++ "v1-style":qeProjectDir:qeDistDir:args out <- qeReadProcess exe args' "" (Right <$> evaluate out) `E.catch` \(SomeException _) -> return $ Left $ concat ["invokeHelper", ": ", exe, " " , intercalate " " (map show args') , " failed" ] getPackageId :: MonadQuery m => m (String, Version) getPackageId = ask >>= \QueryEnv {..} -> do helper <- readHelper [ "package-id" ] case helper of [ Just (ChResponseVersion pkgName pkgVer) ] -> return (pkgName, pkgVer) _ -> error "getPackageId : readHelper" getSomeConfigState :: MonadQuery m => m SomeLocalBuildInfo getSomeConfigState = ask >>= \QueryEnv {..} -> do res <- readHelper [ "package-db-stack" , "flags" , "compiler-version" , "ghc-merged-pkg-options" , "config-flags" , "non-default-config-flags" , "ghc-src-options" , "ghc-pkg-options" , "ghc-lang-options" , "ghc-options" , "source-dirs" , "entrypoints" , "needs-build-output" ] let [ Just (ChResponsePkgDbs slbiPackageDbStack), Just (ChResponseFlags slbiPackageFlags), Just (ChResponseVersion comp compVer), Just (ChResponseList slbiGhcMergedPkgOptions), Just (ChResponseFlags slbiConfigFlags), Just (ChResponseFlags slbiNonDefaultConfigFlags), Just (ChResponseCompList slbiGhcSrcOptions), Just (ChResponseCompList slbiGhcPkgOptions), Just (ChResponseCompList slbiGhcLangOptions), Just (ChResponseCompList slbiGhcOptions), Just (ChResponseCompList slbiSourceDirs), Just (ChResponseEntrypoints slbiEntrypoints), Just (ChResponseNeedsBuild slbiNeedsBuildOutput) ] = res slbiCompilerVersion = (comp, compVer) return $ SomeLocalBuildInfo {..} -- | Make sure the appropriate helper executable for the given project is -- installed and ready to run queries. prepare :: MonadIO m => QueryEnv -> m () prepare qe = liftIO $ void $ invokeHelper qe [] | Create @cabal_macros.h@ and @Paths_\<pkg\>@ possibly other generated files -- in the usual place. writeAutogenFiles :: MonadIO m => QueryEnv -> m () writeAutogenFiles qe = liftIO $ void $ invokeHelper qe ["write-autogen-files"] -- | Get the path to the sandbox package-db in a project getSandboxPkgDb :: (FilePath -> [String] -> String -> IO String) -> String ^ build platform , i.e. @buildPlatform@ -> Version ^ GHC version ( @cProjectVersion@ is your friend ) -> IO (Maybe FilePath) getSandboxPkgDb readProc = CabalHelper.Shared.Sandbox.getSandboxPkgDb $ unsafePerformIO $ buildPlatform readProc buildPlatform :: (FilePath -> [String] -> String -> IO String) -> IO String buildPlatform readProc = do exe <- findLibexecExe CabalHelper.Shared.Sandbox.dropWhileEnd isSpace <$> readProc exe ["print-build-platform"] "" | This exception is thrown by all ' ' functions if the internal -- wrapper executable cannot be found. You may catch this and present the user -- an appropriate error message however the default is to print -- 'libexecNotFoundError'. data LibexecNotFoundError = LibexecNotFoundError String FilePath deriving (Typeable) instance Exception LibexecNotFoundError instance Show LibexecNotFoundError where show (LibexecNotFoundError exe dir) = libexecNotFoundError exe dir "-code-explorer/issues" findLibexecExe :: IO FilePath findLibexecExe = do libexecdir <- getLibexecDir let exeName = "cabal-helper-wrapper" exe = libexecdir </> exeName FP.<.> exeExtension' exists <- doesFileExist exe if exists then return exe else do mdir <- tryFindCabalHelperTreeDistDir dir <- case mdir of Nothing -> throwIO $ LibexecNotFoundError exeName libexecdir Just dir -> return dir return $ dir </> "build" </> exeName </> exeName findPlanJson :: FilePath -> IO (Maybe FilePath) findPlanJson base = findFile (map (</> "cache") $ parents base) "plan.json" parents :: FilePath -> [FilePath] parents path = takeWhile (not . (`elem` ["", "."]) . dropDrive) dirs where dirs = iterate takeDirectory path data DistDir = DistDir { ddType :: DistDirType, unDistDir :: FilePath } deriving (Eq, Ord, Read, Show) data DistDirType = NewBuildDist | OldBuildDist deriving (Eq, Ord, Read, Show) tryFindCabalHelperTreeDistDir :: IO (Maybe FilePath) tryFindCabalHelperTreeDistDir = do exe <- canonicalizePath =<< getExecutablePath' mplan <- findPlanJson exe let mdistdir = takeDirectory . takeDirectory <$> mplan cwd <- getCurrentDirectory let candidates = sortBy (compare `on` ddType) $ concat [ maybeToList $ DistDir NewBuildDist <$> mdistdir , [ DistDir OldBuildDist $ (!!3) $ iterate takeDirectory exe ] we 're probably in ghci ; try CWD then [ DistDir NewBuildDist $ cwd </> "dist-newstyle" , DistDir NewBuildDist $ cwd </> "dist" , DistDir OldBuildDist $ cwd </> "dist" ] else [] ] distdirs <- filterM isDistDir candidates >>= mapM toOldBuildDistDir return $ fmap unDistDir $ join $ listToMaybe $ distdirs isCabalHelperSourceDir :: FilePath -> IO Bool isCabalHelperSourceDir dir = doesFileExist $ dir </> "cabal-helper.cabal" isDistDir :: DistDir -> IO Bool isDistDir (DistDir NewBuildDist dir) = doesFileExist (dir </> "cache" </> "plan.json") isDistDir (DistDir OldBuildDist dir) = doesFileExist (dir </> "setup-config") toOldBuildDistDir :: DistDir -> IO (Maybe DistDir) toOldBuildDistDir (DistDir NewBuildDist dir) = do PlanJson {pjUnits} <- decodePlanJson $ dir </> "cache" </> "plan.json" let munit = find isCabalHelperUnit $ Map.elems pjUnits return $ DistDir OldBuildDist <$> join ((\Unit { uDistDir = mdistdir } -> mdistdir) <$> munit) where isCabalHelperUnit Unit { uPId = PkgId (PkgName n) _ , uType = UnitTypeLocal , uComps } | n == "cabal-helper" && Map.member (CompNameExe "cabal-helper-wrapper") uComps = True isCabalHelperUnit _ = False toOldBuildDistDir x = return $ Just x libexecNotFoundError :: String -- ^ Name of the executable we were trying to -- find -> FilePath -- ^ Path to @$libexecdir@ -> String -- ^ URL the user will be directed towards to -- report a bug. -> String libexecNotFoundError exe dir reportBug = printf ( "Could not find $libexecdir/%s\n" ++"\n" ++"If you are a cabal-helper developer you can set the environment variable\n" ++"`cabal_helper_libexecdir' to override $libexecdir[1]. The following will\n" ++"work in the cabal-helper source tree:\n" ++"\n" ++" $ export cabal_helper_libexecdir=$PWD/dist/build/%s\n" ++"\n" ++"[1]: %s\n" ++"\n" ++"If you don't know what I'm talking about something went wrong with your\n" ++"installation. Please report this problem here:\n" ++"\n" ++" %s") exe exe dir reportBug getExecutablePath' :: IO FilePath getExecutablePath' = #if MIN_VERSION_base(4,6,0) getExecutablePath #else getProgName #endif lookupEnv' :: String -> IO (Maybe String) lookupEnv' k = lookup k <$> getEnvironment exeExtension' :: FilePath exeExtension' | Windows <- buildOS = "exe" | otherwise = ""
null
https://raw.githubusercontent.com/alexwl/haskell-code-explorer/2f1c2a4c87ebd55b8a335bc4670eec875af8b4c4/vendor/cabal-helper-0.8.1.2/lib/Distribution/Helper.hs
haskell
This program is free software: you can redistribute it and/or modify (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. along with this program. If not, see </>. | Module : Distribution.Helper License : GPL-3 Maintainer : Portability : POSIX * Running Queries * Queries against Cabal\'s on disk state ** Package queries ** cabal-install queries ** Component queries * Query environment * Result types * General information * Stuff that cabal-install really should export * Managing @dist/@ * $libexec related error handling | Paths or names of various programs we need. | The path to the @cabal@ program. | The path to the @ghc-pkg@ program. If not changed it will be derived from the path to 'ghcProgram'. | Default all programs to their unqualified names, i.e. they will be searched for on @PATH@. | Environment for running a 'Query'. The real constructor is not exposed, the field accessors are however. See below. Use the 'mkQueryEnv' smart constructor to construct one. process. Useful if you need to capture stderr output from the helper. i.e. a directory containing a @project.cabal@ file library when linking the helper. respectively and provides sensible defaults for the other fields. ^ Path to the project directory, i.e. the directory containing a @project.cabal@ file terminology. | A 'Query' to run on all components of a package. Use 'components' to get a regular 'Query'. | List of package databases to use. | Flag definitions from cabal file | Flag assignments from setup-config | Flag assignments from setup-config which differ from the default setting. This can also include flags which cabal decided to modify, i.e. don't rely on these being the flags set by the user directly. | Package identifier, i.e. package name and version to compute the home module closure for a component. | The component has a non-default module renaming, so needs build output (). access any home modules. | Only language related options, i.e. @-XSomeExtension@ | Run @cabal configure@ ^ Program paths ^ Command line arguments to be passed to @cabal@ might break cabal's guessing logic | Make sure the appropriate helper executable for the given project is installed and ready to run queries. in the usual place. | Get the path to the sandbox package-db in a project wrapper executable cannot be found. You may catch this and present the user an appropriate error message however the default is to print 'libexecNotFoundError'. ^ Name of the executable we were trying to find ^ Path to @$libexecdir@ ^ URL the user will be directed towards to report a bug.
cabal - helper : Simple interface to Cabal 's configuration state Copyright ( C ) 2015 - 2018 < > it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License # LANGUAGE CPP , RecordWildCards , FlexibleContexts , ConstraintKinds , GeneralizedNewtypeDeriving , DeriveDataTypeable , DeriveGeneric , DeriveFunctor , NamedFieldPuns , OverloadedStrings # GeneralizedNewtypeDeriving, DeriveDataTypeable, DeriveGeneric, DeriveFunctor, NamedFieldPuns, OverloadedStrings #-} module Distribution.Helper ( Query , runQuery , packageId , packageDbStack , packageFlags , compilerVersion , ghcMergedPkgOptions , configFlags , nonDefaultConfigFlags , ComponentQuery , components , ghcSrcOptions , ghcPkgOptions , ghcLangOptions , ghcOptions , sourceDirs , entrypoints , needsBuildOutput , QueryEnv , mkQueryEnv , qeReadProcess , qePrograms , qeProjectDir , qeDistDir , qeCabalPkgDb , qeCabalVer , Programs(..) , defaultPrograms , ChModuleName(..) , ChComponentName(..) , ChPkgDb(..) , ChEntrypoint(..) , NeedsBuildOutput(..) , buildPlatform , Distribution.Helper.getSandboxPkgDb , prepare , reconfigure , writeAutogenFiles , LibexecNotFoundError(..) , libexecNotFoundError * , module Data.Functor.Apply ) where import Cabal.Plan hiding (findPlanJson) import Control.Applicative import Control.Monad import Control.Monad.IO.Class import Control.Monad.State.Strict import Control.Monad.Reader import Control.Exception as E import Data.Char import Data.List import Data.Maybe import qualified Data.Map as Map import Data.Version import Data.Typeable import Data.Function import Data.Functor.Apply import Distribution.System (buildOS, OS(Windows)) import System.Environment import System.FilePath hiding ((<.>)) import qualified System.FilePath as FP import System.Directory import System.Process import System.IO.Unsafe import Text.Printf import GHC.Generics import Prelude import Paths_cabal_helper (getLibexecDir) import CabalHelper.Shared.InterfaceTypes import CabalHelper.Shared.Sandbox data Programs = Programs { cabalProgram :: FilePath, | The path to the @ghc@ program . ghcProgram :: FilePath, ghcPkgProgram :: FilePath } deriving (Eq, Ord, Show, Read, Generic, Typeable) defaultPrograms :: Programs defaultPrograms = Programs "cabal" "ghc" "ghc-pkg" data QueryEnv = QueryEnv { | Field accessor for ' QueryEnv ' . Defines how to start the cabal - helper qeReadProcess :: FilePath -> [String] -> String -> IO String, | Field accessor for ' QueryEnv ' . qePrograms :: Programs, | Field accessor for ' QueryEnv ' . Defines path to the project directory , qeProjectDir :: FilePath, | Field accessor for ' QueryEnv ' . Defines path to the @dist/@ directory , /builddir/ in Cabal terminology . qeDistDir :: FilePath, | Field accessor for ' QueryEnv ' . Defines where to look for the qeCabalPkgDb :: Maybe FilePath, | Field accessor for ' QueryEnv ' . If @dist / setup - config@ wasn\'t written by this version of Cabal an error is thrown when running the query . qeCabalVer :: Maybe Version } | @mkQueryEnv constructor for ' QueryEnv ' . Sets fields ' qeProjectDir ' and ' qeDistDir ' to @projdir@ and mkQueryEnv :: FilePath -> FilePath ^ Path to the @dist/@ directory , called /builddir/ in Cabal -> QueryEnv mkQueryEnv projdir distdir = QueryEnv { qeReadProcess = readProcess , qePrograms = defaultPrograms , qeProjectDir = projdir , qeDistDir = distdir , qeCabalPkgDb = Nothing , qeCabalVer = Nothing } data SomeLocalBuildInfo = SomeLocalBuildInfo { slbiPackageDbStack :: [ChPkgDb], slbiPackageFlags :: [(String, Bool)], slbiCompilerVersion :: (String, Version), slbiGhcMergedPkgOptions :: [String], slbiConfigFlags :: [(String, Bool)], slbiNonDefaultConfigFlags :: [(String, Bool)], slbiGhcSrcOptions :: [(ChComponentName, [String])], slbiGhcPkgOptions :: [(ChComponentName, [String])], slbiGhcLangOptions :: [(ChComponentName, [String])], slbiGhcOptions :: [(ChComponentName, [String])], slbiSourceDirs :: [(ChComponentName, [String])], slbiEntrypoints :: [(ChComponentName, ChEntrypoint)], slbiNeedsBuildOutput :: [(ChComponentName, NeedsBuildOutput)] } deriving (Eq, Ord, Read, Show) | A lazy , cached , query against a package 's Cabal configuration . Use ' ' to execute it . newtype Query m a = Query { unQuery :: StateT (Maybe SomeLocalBuildInfo) (ReaderT QueryEnv m) a } deriving (Functor, Applicative, Monad, MonadIO) instance MonadTrans Query where lift = Query . lift . lift type MonadQuery m = ( MonadIO m , MonadState (Maybe SomeLocalBuildInfo) m , MonadReader QueryEnv m) newtype ComponentQuery m a = ComponentQuery (Query m [(ChComponentName, a)]) deriving (Functor) instance (Functor m, Monad m) => Apply (ComponentQuery m) where ComponentQuery flab <.> ComponentQuery fla = ComponentQuery $ liftM2 go flab fla where go :: [(ChComponentName, a -> b)] -> [(ChComponentName, a)] -> [(ChComponentName, b)] go lab la = [ (cn, ab a) | (cn, ab) <- lab , (cn', a) <- la , cn == cn' ] run :: Monad m => QueryEnv -> Maybe SomeLocalBuildInfo -> Query m a -> m a run e s action = flip runReaderT e (flip evalStateT s (unQuery action)) | @runQuery env a ' Query ' under a given ' QueryEnv ' . runQuery :: Monad m => QueryEnv -> Query m a -> m a runQuery qe action = run qe Nothing action getSlbi :: MonadQuery m => m SomeLocalBuildInfo getSlbi = do s <- get case s of Nothing -> do slbi <- getSomeConfigState put (Just slbi) return slbi Just slbi -> return slbi packageDbStack :: MonadIO m => Query m [ChPkgDb] | Like @ghcPkgOptions@ but for the whole package not just one component ghcMergedPkgOptions :: MonadIO m => Query m [String] packageFlags :: MonadIO m => Query m [(String, Bool)] configFlags :: MonadIO m => Query m [(String, Bool)] nonDefaultConfigFlags :: MonadIO m => Query m [(String, Bool)] | The version of GHC the project is configured to use compilerVersion :: MonadIO m => Query m (String, Version) packageId :: MonadIO m => Query m (String, Version) | Run a ComponentQuery on all components of the package . components :: Monad m => ComponentQuery m (ChComponentName -> b) -> Query m [b] components (ComponentQuery sc) = map (\(cn, f) -> f cn) `liftM` sc | Modules or files Cabal would have the compiler build directly . Can be used entrypoints :: MonadIO m => ComponentQuery m ChEntrypoint needsBuildOutput :: MonadIO m => ComponentQuery m NeedsBuildOutput | A component 's @source - dirs@ field , beware since if this is empty implicit behaviour in GHC kicks in . sourceDirs :: MonadIO m => ComponentQuery m [FilePath] | All options Cabal would pass to GHC . ghcOptions :: MonadIO m => ComponentQuery m [String] | Only search path related GHC options . ghcSrcOptions :: MonadIO m => ComponentQuery m [String] | Only package related GHC options , sufficient for things do n't need to ghcPkgOptions :: MonadIO m => ComponentQuery m [String] ghcLangOptions :: MonadIO m => ComponentQuery m [String] packageId = Query $ getPackageId packageDbStack = Query $ slbiPackageDbStack `liftM` getSlbi packageFlags = Query $ slbiPackageFlags `liftM` getSlbi compilerVersion = Query $ slbiCompilerVersion `liftM` getSlbi ghcMergedPkgOptions = Query $ slbiGhcMergedPkgOptions `liftM` getSlbi configFlags = Query $ slbiConfigFlags `liftM` getSlbi nonDefaultConfigFlags = Query $ slbiNonDefaultConfigFlags `liftM` getSlbi ghcSrcOptions = ComponentQuery $ Query $ slbiGhcSrcOptions `liftM` getSlbi ghcPkgOptions = ComponentQuery $ Query $ slbiGhcPkgOptions `liftM` getSlbi ghcOptions = ComponentQuery $ Query $ slbiGhcOptions `liftM` getSlbi ghcLangOptions = ComponentQuery $ Query $ slbiGhcLangOptions `liftM` getSlbi sourceDirs = ComponentQuery $ Query $ slbiSourceDirs `liftM` getSlbi entrypoints = ComponentQuery $ Query $ slbiEntrypoints `liftM` getSlbi needsBuildOutput = ComponentQuery $ Query $ slbiNeedsBuildOutput `liftM` getSlbi reconfigure :: MonadIO m => (FilePath -> [String] -> String -> IO String) -> m () reconfigure readProc progs cabalOpts = do let progOpts = [ "--with-ghc=" ++ ghcProgram progs ] Only pass ghc - pkg if it was actually set otherwise we ++ if ghcPkgProgram progs /= "ghc-pkg" then [ "--with-ghc-pkg=" ++ ghcPkgProgram progs ] else [] ++ cabalOpts _ <- liftIO $ readProc (cabalProgram progs) ("configure":progOpts) "" return () readHelper :: (MonadIO m, MonadQuery m) => [String] -> m [Maybe ChResponse] readHelper args = ask >>= \qe -> liftIO $ do out <- either error id <$> invokeHelper qe args let res = read out liftIO $ evaluate res `E.catch` \se@(SomeException _) -> do md <- lookupEnv' "CABAL_HELPER_DEBUG" let msg = "readHelper: exception: '" ++ show se ++ "'" error $ msg ++ case md of Nothing -> ", for more information set the environment variable CABAL_HELPER_DEBUG" Just _ -> ", output: '"++ out ++"'" invokeHelper :: QueryEnv -> [String] -> IO (Either String String) invokeHelper QueryEnv {..} args = do let progArgs = [ "--with-ghc=" ++ ghcProgram qePrograms , "--with-ghc-pkg=" ++ ghcPkgProgram qePrograms , "--with-cabal=" ++ cabalProgram qePrograms ] exe <- findLibexecExe let args' = progArgs ++ "v1-style":qeProjectDir:qeDistDir:args out <- qeReadProcess exe args' "" (Right <$> evaluate out) `E.catch` \(SomeException _) -> return $ Left $ concat ["invokeHelper", ": ", exe, " " , intercalate " " (map show args') , " failed" ] getPackageId :: MonadQuery m => m (String, Version) getPackageId = ask >>= \QueryEnv {..} -> do helper <- readHelper [ "package-id" ] case helper of [ Just (ChResponseVersion pkgName pkgVer) ] -> return (pkgName, pkgVer) _ -> error "getPackageId : readHelper" getSomeConfigState :: MonadQuery m => m SomeLocalBuildInfo getSomeConfigState = ask >>= \QueryEnv {..} -> do res <- readHelper [ "package-db-stack" , "flags" , "compiler-version" , "ghc-merged-pkg-options" , "config-flags" , "non-default-config-flags" , "ghc-src-options" , "ghc-pkg-options" , "ghc-lang-options" , "ghc-options" , "source-dirs" , "entrypoints" , "needs-build-output" ] let [ Just (ChResponsePkgDbs slbiPackageDbStack), Just (ChResponseFlags slbiPackageFlags), Just (ChResponseVersion comp compVer), Just (ChResponseList slbiGhcMergedPkgOptions), Just (ChResponseFlags slbiConfigFlags), Just (ChResponseFlags slbiNonDefaultConfigFlags), Just (ChResponseCompList slbiGhcSrcOptions), Just (ChResponseCompList slbiGhcPkgOptions), Just (ChResponseCompList slbiGhcLangOptions), Just (ChResponseCompList slbiGhcOptions), Just (ChResponseCompList slbiSourceDirs), Just (ChResponseEntrypoints slbiEntrypoints), Just (ChResponseNeedsBuild slbiNeedsBuildOutput) ] = res slbiCompilerVersion = (comp, compVer) return $ SomeLocalBuildInfo {..} prepare :: MonadIO m => QueryEnv -> m () prepare qe = liftIO $ void $ invokeHelper qe [] | Create @cabal_macros.h@ and @Paths_\<pkg\>@ possibly other generated files writeAutogenFiles :: MonadIO m => QueryEnv -> m () writeAutogenFiles qe = liftIO $ void $ invokeHelper qe ["write-autogen-files"] getSandboxPkgDb :: (FilePath -> [String] -> String -> IO String) -> String ^ build platform , i.e. @buildPlatform@ -> Version ^ GHC version ( @cProjectVersion@ is your friend ) -> IO (Maybe FilePath) getSandboxPkgDb readProc = CabalHelper.Shared.Sandbox.getSandboxPkgDb $ unsafePerformIO $ buildPlatform readProc buildPlatform :: (FilePath -> [String] -> String -> IO String) -> IO String buildPlatform readProc = do exe <- findLibexecExe CabalHelper.Shared.Sandbox.dropWhileEnd isSpace <$> readProc exe ["print-build-platform"] "" | This exception is thrown by all ' ' functions if the internal data LibexecNotFoundError = LibexecNotFoundError String FilePath deriving (Typeable) instance Exception LibexecNotFoundError instance Show LibexecNotFoundError where show (LibexecNotFoundError exe dir) = libexecNotFoundError exe dir "-code-explorer/issues" findLibexecExe :: IO FilePath findLibexecExe = do libexecdir <- getLibexecDir let exeName = "cabal-helper-wrapper" exe = libexecdir </> exeName FP.<.> exeExtension' exists <- doesFileExist exe if exists then return exe else do mdir <- tryFindCabalHelperTreeDistDir dir <- case mdir of Nothing -> throwIO $ LibexecNotFoundError exeName libexecdir Just dir -> return dir return $ dir </> "build" </> exeName </> exeName findPlanJson :: FilePath -> IO (Maybe FilePath) findPlanJson base = findFile (map (</> "cache") $ parents base) "plan.json" parents :: FilePath -> [FilePath] parents path = takeWhile (not . (`elem` ["", "."]) . dropDrive) dirs where dirs = iterate takeDirectory path data DistDir = DistDir { ddType :: DistDirType, unDistDir :: FilePath } deriving (Eq, Ord, Read, Show) data DistDirType = NewBuildDist | OldBuildDist deriving (Eq, Ord, Read, Show) tryFindCabalHelperTreeDistDir :: IO (Maybe FilePath) tryFindCabalHelperTreeDistDir = do exe <- canonicalizePath =<< getExecutablePath' mplan <- findPlanJson exe let mdistdir = takeDirectory . takeDirectory <$> mplan cwd <- getCurrentDirectory let candidates = sortBy (compare `on` ddType) $ concat [ maybeToList $ DistDir NewBuildDist <$> mdistdir , [ DistDir OldBuildDist $ (!!3) $ iterate takeDirectory exe ] we 're probably in ghci ; try CWD then [ DistDir NewBuildDist $ cwd </> "dist-newstyle" , DistDir NewBuildDist $ cwd </> "dist" , DistDir OldBuildDist $ cwd </> "dist" ] else [] ] distdirs <- filterM isDistDir candidates >>= mapM toOldBuildDistDir return $ fmap unDistDir $ join $ listToMaybe $ distdirs isCabalHelperSourceDir :: FilePath -> IO Bool isCabalHelperSourceDir dir = doesFileExist $ dir </> "cabal-helper.cabal" isDistDir :: DistDir -> IO Bool isDistDir (DistDir NewBuildDist dir) = doesFileExist (dir </> "cache" </> "plan.json") isDistDir (DistDir OldBuildDist dir) = doesFileExist (dir </> "setup-config") toOldBuildDistDir :: DistDir -> IO (Maybe DistDir) toOldBuildDistDir (DistDir NewBuildDist dir) = do PlanJson {pjUnits} <- decodePlanJson $ dir </> "cache" </> "plan.json" let munit = find isCabalHelperUnit $ Map.elems pjUnits return $ DistDir OldBuildDist <$> join ((\Unit { uDistDir = mdistdir } -> mdistdir) <$> munit) where isCabalHelperUnit Unit { uPId = PkgId (PkgName n) _ , uType = UnitTypeLocal , uComps } | n == "cabal-helper" && Map.member (CompNameExe "cabal-helper-wrapper") uComps = True isCabalHelperUnit _ = False toOldBuildDistDir x = return $ Just x -> String libexecNotFoundError exe dir reportBug = printf ( "Could not find $libexecdir/%s\n" ++"\n" ++"If you are a cabal-helper developer you can set the environment variable\n" ++"`cabal_helper_libexecdir' to override $libexecdir[1]. The following will\n" ++"work in the cabal-helper source tree:\n" ++"\n" ++" $ export cabal_helper_libexecdir=$PWD/dist/build/%s\n" ++"\n" ++"[1]: %s\n" ++"\n" ++"If you don't know what I'm talking about something went wrong with your\n" ++"installation. Please report this problem here:\n" ++"\n" ++" %s") exe exe dir reportBug getExecutablePath' :: IO FilePath getExecutablePath' = #if MIN_VERSION_base(4,6,0) getExecutablePath #else getProgName #endif lookupEnv' :: String -> IO (Maybe String) lookupEnv' k = lookup k <$> getEnvironment exeExtension' :: FilePath exeExtension' | Windows <- buildOS = "exe" | otherwise = ""
be4900ba63f94df21edc51b0f1be7e6c0303285be4d823f2d15171ab5c26ffc1
yallop/ocaml-ctypes
libffi_abi.mli
* Copyright ( c ) 2014 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2014 Jeremy Yallop. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) (** Support for various ABIs. *) type abi val aix : abi val darwin : abi val eabi : abi val fastcall : abi val gcc_sysv : abi val linux : abi val linux64 : abi val linux_soft_float : abi val ms_cdecl : abi val n32 : abi val n32_soft_float : abi val n64 : abi val n64_soft_float : abi val o32 : abi val o32_soft_float : abi val osf : abi val pa32 : abi val stdcall : abi val sysv : abi val thiscall : abi val unix : abi val unix64 : abi val v8 : abi val v8plus : abi val v9 : abi val vfp : abi val default_abi : abi val abi_code : abi -> int
null
https://raw.githubusercontent.com/yallop/ocaml-ctypes/52ff621f47dbc1ee5a90c30af0ae0474549946b4/src/ctypes-foreign/libffi_abi.mli
ocaml
* Support for various ABIs.
* Copyright ( c ) 2014 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2014 Jeremy Yallop. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) type abi val aix : abi val darwin : abi val eabi : abi val fastcall : abi val gcc_sysv : abi val linux : abi val linux64 : abi val linux_soft_float : abi val ms_cdecl : abi val n32 : abi val n32_soft_float : abi val n64 : abi val n64_soft_float : abi val o32 : abi val o32_soft_float : abi val osf : abi val pa32 : abi val stdcall : abi val sysv : abi val thiscall : abi val unix : abi val unix64 : abi val v8 : abi val v8plus : abi val v9 : abi val vfp : abi val default_abi : abi val abi_code : abi -> int
2983465b87ac4e94f4294a29e3f103000358bc937d5c5fb3455ed083c8c00c81
gregr/experiments
parsing.rkt
#lang racket (provide check-arity map-parse new-lam-apply new-pair new-pair-access parse-apply parse-bvar parse-combination parse-under penv-empty penv-syntax-add penv-syntax-op-empty penv-vars-add v-0 v-1 v-uno ) (require "syntax-abstract.rkt" gregr-misc/cursor gregr-misc/dict gregr-misc/either gregr-misc/function gregr-misc/list gregr-misc/match gregr-misc/maybe gregr-misc/monad gregr-misc/record ) (record penv syntax vars) (define penv-empty (penv dict-empty '())) (define/destruct (penv-syntax-add (penv syntax vars) name op) (penv (dict-add syntax name op) vars)) (define/destruct (penv-syntax-del (penv syntax vars) name) (penv (dict-remove syntax name) vars)) (define (penv-syntax-get pe name) (dict-get (penv-syntax pe) name)) (define (penv-syntax-rename pe old new) (define (check-vars name msg) (match (penv-vars-get pe name) ((nothing) (right '())) ((just _) (left msg)))) (begin/with-monad either-monad _ <- (check-vars old "cannot rename non-keyword") _ <- (check-vars new "rename-target already bound as a non-keyword") syn-old <- (maybe->either "cannot rename non-existent keyword" (penv-syntax-get pe old)) pe0 = (penv-syntax-del pe old) (pure (penv-syntax-add pe0 new syn-old)))) (define penv-syntax-op-empty '||) (define (penv-syntax-op-get pe op) (match (penv-syntax-get pe op) ((just result) (right result)) ((nothing) (maybe->either (format "invalid operator: ~s" op) (penv-syntax-get pe penv-syntax-op-empty))))) (define/destruct (penv-vars-add (penv syntax vars) name) (penv syntax (cons name vars))) (define (penv-vars-get pe name) (match (list-index-equal (penv-vars pe) name) (-1 (nothing)) (idx (just idx)))) (define v-uno (value (uno))) (define v-0 (value (bit (b-0)))) (define v-1 (value (bit (b-1)))) (define new-lam-apply lam-apply) (define (new-pair-access tcnd tpair) (new-lam-apply (new-lam-apply (value (lam lattr-void (value (lam lattr-void (pair-access (bvar 1) (bvar 0)))))) tcnd) tpair)) (define/match (new-pair l r) (((value vl) (value vr)) (right (value (pair vl vr)))) ((_ _) (left (format "pair arguments must be values: ~v ~v" l r)))) (define (check-arity arity form) (if (equal? (length form) arity) (right '()) (left (format "expected arity-~a form but found arity-~a form: ~s" arity (length form) form)))) (define (check-symbol form) (if (symbol? form) (right '()) (left (format "expected symbol but found: ~s" form)))) (define (parse-combination pe op form) (begin/with-monad either-monad proc <- (penv-syntax-op-get pe op) (proc pe form))) (define ((map-parse parse) pe form) (monad-map either-monad (curry parse pe) form)) (define (((parse-apply map-parse) proc arity) pe form) (begin/with-monad either-monad _ <- (check-arity arity form) args <- (map-parse pe (cdr form)) (pure (apply proc args)))) (define ((parse-under parse) pe params body) (begin/with-monad either-monad _ <- (monad-map either-monad check-symbol params) pe = (foldl (flip penv-vars-add) pe params) (parse pe body))) (define (parse-bvar pe name) (begin/with-monad either-monad _ <- (check-symbol name) _ <- (if (equal? name '_) (left "unexpected reference to _") (right name)) idx <- (maybe->either (format "unbound variable '~a'" name) (penv-vars-get pe name)) (pure (value (bvar idx)))))
null
https://raw.githubusercontent.com/gregr/experiments/cd4c7953f45102539081077bbd6195cf834ba2fa/supercompilation/cog/parsing.rkt
racket
#lang racket (provide check-arity map-parse new-lam-apply new-pair new-pair-access parse-apply parse-bvar parse-combination parse-under penv-empty penv-syntax-add penv-syntax-op-empty penv-vars-add v-0 v-1 v-uno ) (require "syntax-abstract.rkt" gregr-misc/cursor gregr-misc/dict gregr-misc/either gregr-misc/function gregr-misc/list gregr-misc/match gregr-misc/maybe gregr-misc/monad gregr-misc/record ) (record penv syntax vars) (define penv-empty (penv dict-empty '())) (define/destruct (penv-syntax-add (penv syntax vars) name op) (penv (dict-add syntax name op) vars)) (define/destruct (penv-syntax-del (penv syntax vars) name) (penv (dict-remove syntax name) vars)) (define (penv-syntax-get pe name) (dict-get (penv-syntax pe) name)) (define (penv-syntax-rename pe old new) (define (check-vars name msg) (match (penv-vars-get pe name) ((nothing) (right '())) ((just _) (left msg)))) (begin/with-monad either-monad _ <- (check-vars old "cannot rename non-keyword") _ <- (check-vars new "rename-target already bound as a non-keyword") syn-old <- (maybe->either "cannot rename non-existent keyword" (penv-syntax-get pe old)) pe0 = (penv-syntax-del pe old) (pure (penv-syntax-add pe0 new syn-old)))) (define penv-syntax-op-empty '||) (define (penv-syntax-op-get pe op) (match (penv-syntax-get pe op) ((just result) (right result)) ((nothing) (maybe->either (format "invalid operator: ~s" op) (penv-syntax-get pe penv-syntax-op-empty))))) (define/destruct (penv-vars-add (penv syntax vars) name) (penv syntax (cons name vars))) (define (penv-vars-get pe name) (match (list-index-equal (penv-vars pe) name) (-1 (nothing)) (idx (just idx)))) (define v-uno (value (uno))) (define v-0 (value (bit (b-0)))) (define v-1 (value (bit (b-1)))) (define new-lam-apply lam-apply) (define (new-pair-access tcnd tpair) (new-lam-apply (new-lam-apply (value (lam lattr-void (value (lam lattr-void (pair-access (bvar 1) (bvar 0)))))) tcnd) tpair)) (define/match (new-pair l r) (((value vl) (value vr)) (right (value (pair vl vr)))) ((_ _) (left (format "pair arguments must be values: ~v ~v" l r)))) (define (check-arity arity form) (if (equal? (length form) arity) (right '()) (left (format "expected arity-~a form but found arity-~a form: ~s" arity (length form) form)))) (define (check-symbol form) (if (symbol? form) (right '()) (left (format "expected symbol but found: ~s" form)))) (define (parse-combination pe op form) (begin/with-monad either-monad proc <- (penv-syntax-op-get pe op) (proc pe form))) (define ((map-parse parse) pe form) (monad-map either-monad (curry parse pe) form)) (define (((parse-apply map-parse) proc arity) pe form) (begin/with-monad either-monad _ <- (check-arity arity form) args <- (map-parse pe (cdr form)) (pure (apply proc args)))) (define ((parse-under parse) pe params body) (begin/with-monad either-monad _ <- (monad-map either-monad check-symbol params) pe = (foldl (flip penv-vars-add) pe params) (parse pe body))) (define (parse-bvar pe name) (begin/with-monad either-monad _ <- (check-symbol name) _ <- (if (equal? name '_) (left "unexpected reference to _") (right name)) idx <- (maybe->either (format "unbound variable '~a'" name) (penv-vars-get pe name)) (pure (value (bvar idx)))))
f49be95703599d2f369b4164d7a1aa472069631eea2c0088c2e66aa3c8ee0dd5
discus-lang/salt
State.hs
module Salt.LSP.State where import Salt.Core.Exp import Salt.Data.Location import Data.Map (Map) import Data.IORef import qualified System.Exit as System import qualified System.IO as System -- | Language server plugin state. data State = State { statePhase :: Phase , stateLogDebug :: Maybe (FilePath, System.Handle) -- | Checked core files. , stateCoreChecked :: IORef (Map String (Maybe (Module (Range Location)))) } | Phase of the LSP server protocol . data Phase -- | We have just started up and have not yet initialized with the client. = PhaseStartup -- | Initialization with the client failed. | PhaseInitFailed -- | We have initialized with the client and are now handling requests. | PhaseInitialized deriving (Eq, Show) -- | Append a messgage to the server side log file, if we have one. lspLog :: State -> String -> IO () lspLog state str | Just (_, h) <- stateLogDebug state = do System.hPutStr h (str ++ "\n") System.hFlush h | otherwise = return () -- | Append a message to the server side log file and exit the process. lspFail :: State -> String -> IO a lspFail state str = do lspLog state str System.die str
null
https://raw.githubusercontent.com/discus-lang/salt/33c14414ac7e238fdbd8161971b8b8ac67fff569/src/salt/Salt/LSP/State.hs
haskell
| Language server plugin state. | Checked core files. | We have just started up and have not yet initialized with the client. | Initialization with the client failed. | We have initialized with the client and are now handling requests. | Append a messgage to the server side log file, if we have one. | Append a message to the server side log file and exit the process.
module Salt.LSP.State where import Salt.Core.Exp import Salt.Data.Location import Data.Map (Map) import Data.IORef import qualified System.Exit as System import qualified System.IO as System data State = State { statePhase :: Phase , stateLogDebug :: Maybe (FilePath, System.Handle) , stateCoreChecked :: IORef (Map String (Maybe (Module (Range Location)))) } | Phase of the LSP server protocol . data Phase = PhaseStartup | PhaseInitFailed | PhaseInitialized deriving (Eq, Show) lspLog :: State -> String -> IO () lspLog state str | Just (_, h) <- stateLogDebug state = do System.hPutStr h (str ++ "\n") System.hFlush h | otherwise = return () lspFail :: State -> String -> IO a lspFail state str = do lspLog state str System.die str
8da37d5a3f7d46f78d6a402cd1cb55ba26ecabd3df498c65adfd3e9505cc07b4
ocaml-multicore/ocaml-tsan
spill.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 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. *) (* *) (**************************************************************************) (* Insertion of moves to suggest possible spilling / reloading points before register allocation. *) open Reg open Mach We say that a register is " destroyed " if it is live across a construct that potentially destroys all physical registers : function calls or try ... with constructs . The " destroyed " registers must therefore reside in the stack during these instructions .. We will insert spills ( stores ) just after they are defined , and reloads just before their first use following a " destroying " construct . Instructions with more live registers than actual registers also " destroy " registers : we mark as " destroyed " the registers live across the instruction that have n't been used for the longest time . These registers will be spilled and reloaded as described above . that potentially destroys all physical registers: function calls or try...with constructs. The "destroyed" registers must therefore reside in the stack during these instructions.. We will insert spills (stores) just after they are defined, and reloads just before their first use following a "destroying" construct. Instructions with more live registers than actual registers also "destroy" registers: we mark as "destroyed" the registers live across the instruction that haven't been used for the longest time. These registers will be spilled and reloaded as described above. *) (* Association of spill registers to registers *) type reload_data = { spill_env : Reg.t Reg.Map.t ref; mutable use_date : int Reg.Map.t; (* Record the position of last use of registers *) mutable current_date : int; mutable destroyed_at_fork : (instruction * Reg.Set.t) list; (* A-list recording what is destroyed at if-then-else points. *) reload_at_exit : (int, Reg.Set.t) Hashtbl.t; } type spill_data = { spill_env : Reg.t Reg.Map.t ref; destroyed_at_fork : (instruction * Reg.Set.t) list; (* A-list recording what is destroyed at if-then-else points. *) mutable spill_at_raise : Reg.Set.t; mutable inside_arm : bool; mutable inside_catch : bool; spill_at_exit : (int, Reg.Set.t) Hashtbl.t; } let create_reload () = { spill_env = ref Reg.Map.empty; use_date = Reg.Map.empty; current_date = 0; destroyed_at_fork = []; reload_at_exit = Hashtbl.create 20; } let create_spill (reload : reload_data) = { spill_env = reload.spill_env; destroyed_at_fork = reload.destroyed_at_fork; spill_at_raise = Reg.Set.empty; inside_arm = false; inside_catch = false; spill_at_exit = Hashtbl.create 20; } let spill_reg spill_env r = try Reg.Map.find r !spill_env with Not_found -> let spill_r = Reg.create r.typ in spill_r.spill <- true; if not (Reg.anonymous r) then spill_r.raw_name <- r.raw_name; spill_env := Reg.Map.add r spill_r !spill_env; spill_r let record_use t regv = for i = 0 to Array.length regv - 1 do let r = regv.(i) in let prev_date = try Reg.Map.find r t.use_date with Not_found -> 0 in if t.current_date > prev_date then t.use_date <- Reg.Map.add r t.current_date t.use_date done (* Check if the register pressure overflows the maximum pressure allowed at that point. If so, spill enough registers to lower the pressure. *) let add_superpressure_regs t op live_regs res_regs spilled = let max_pressure = Proc.max_register_pressure op in let regs = Reg.add_set_array live_regs res_regs in (* Compute the pressure in each register class *) let pressure = Array.make Proc.num_register_classes 0 in Reg.Set.iter (fun r -> if Reg.Set.mem r spilled then () else begin match r.loc with Stack _ -> () | _ -> let c = Proc.register_class r in pressure.(c) <- pressure.(c) + 1 end) regs; (* Check if pressure is exceeded for each class. *) let rec check_pressure cl spilled = if cl >= Proc.num_register_classes then spilled else if pressure.(cl) <= max_pressure.(cl) then check_pressure (cl+1) spilled else begin (* Find the least recently used, unspilled, unallocated, live register in the class *) let lru_date = ref 1000000 and lru_reg = ref Reg.dummy in Reg.Set.iter (fun r -> if Proc.register_class r = cl && not (Reg.Set.mem r spilled) && r.loc = Unknown then begin try let d = Reg.Map.find r t.use_date in if d < !lru_date then begin lru_date := d; lru_reg := r end with Not_found -> (* Should not happen *) () end) live_regs; if !lru_reg != Reg.dummy then begin pressure.(cl) <- pressure.(cl) - 1; check_pressure cl (Reg.Set.add !lru_reg spilled) end else (* Couldn't find any spillable register, give up for this class *) check_pressure (cl+1) spilled end in check_pressure 0 spilled First pass : insert reload instructions based on an approximation of what is destroyed at pressure points . what is destroyed at pressure points. *) let add_reloads spill_env regset i = Reg.Set.fold (fun r i -> instr_cons (Iop Ireload) [|spill_reg spill_env r|] [|r|] i) regset i let get_reload_at_exit t k = match Hashtbl.find_opt t.reload_at_exit k with | None -> Reg.Set.empty | Some s -> s let set_reload_at_exit t k s = Hashtbl.replace t.reload_at_exit k s let rec reload (t : reload_data) i before = t.current_date <- succ t.current_date; record_use t i.arg; record_use t i.res; match i.desc with Iend -> (i, before) | Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) -> (add_reloads t.spill_env (Reg.inter_set_array before i.arg) i, Reg.Set.empty) | Iop(Icall_ind | Icall_imm _ | Iextcall { alloc = true; }) -> (* All regs live across must be spilled *) let (new_next, finally) = reload t i.next i.live in (add_reloads t.spill_env (Reg.inter_set_array before i.arg) (instr_cons_debug i.desc i.arg i.res i.dbg new_next), finally) | Iop op -> let new_before = (* Quick check to see if the register pressure is below the maximum *) if !Clflags.use_linscan || (Reg.Set.cardinal i.live + Array.length i.res <= Proc.safe_register_pressure op) then before else add_superpressure_regs t op i.live i.res before in let after = Reg.diff_set_array (Reg.diff_set_array new_before i.arg) i.res in let (new_next, finally) = reload t i.next after in (add_reloads t.spill_env (Reg.inter_set_array new_before i.arg) (instr_cons_debug i.desc i.arg i.res i.dbg new_next), finally) | Iifthenelse(test, ifso, ifnot) -> let at_fork = Reg.diff_set_array before i.arg in let date_fork = t.current_date in let (new_ifso, after_ifso) = reload t ifso at_fork in let date_ifso = t.current_date in t.current_date <- date_fork; let (new_ifnot, after_ifnot) = reload t ifnot at_fork in t.current_date <- Int.max date_ifso t.current_date; let (new_next, finally) = reload t i.next (Reg.Set.union after_ifso after_ifnot) in let new_i = instr_cons (Iifthenelse(test, new_ifso, new_ifnot)) i.arg i.res new_next in t.destroyed_at_fork <- (new_i, at_fork) :: t.destroyed_at_fork; (add_reloads t.spill_env (Reg.inter_set_array before i.arg) new_i, finally) | Iswitch(index, cases) -> let at_fork = Reg.diff_set_array before i.arg in let date_fork = t.current_date in let date_join = ref 0 in let after_cases = ref Reg.Set.empty in let new_cases = Array.map (fun c -> t.current_date <- date_fork; let (new_c, after_c) = reload t c at_fork in after_cases := Reg.Set.union !after_cases after_c; date_join := Int.max !date_join t.current_date; new_c) cases in t.current_date <- !date_join; let (new_next, finally) = reload t i.next !after_cases in (add_reloads t.spill_env (Reg.inter_set_array before i.arg) (instr_cons (Iswitch(index, new_cases)) i.arg i.res new_next), finally) | Icatch(rec_flag, handlers, body) -> let (new_body, after_body) = reload t body before in let rec fixpoint () = let at_exits = List.map (fun (nfail, _) -> (nfail, get_reload_at_exit t nfail)) handlers in let res = List.map2 (fun (nfail', handler) (nfail, at_exit) -> assert(nfail = nfail'); reload t handler at_exit) handlers at_exits in match rec_flag with | Cmm.Nonrecursive -> res | Cmm.Recursive -> let equal = List.for_all2 (fun (nfail', _) (nfail, at_exit) -> assert(nfail = nfail'); Reg.Set.equal at_exit (get_reload_at_exit t nfail)) handlers at_exits in if equal then res else fixpoint () in let res = fixpoint () in let union = List.fold_left (fun acc (_, after_handler) -> Reg.Set.union acc after_handler) after_body res in let (new_next, finally) = reload t i.next union in let new_handlers = List.map2 (fun (nfail, _) (new_handler, _) -> nfail, new_handler) handlers res in (instr_cons (Icatch(rec_flag, new_handlers, new_body)) i.arg i.res new_next, finally) | Iexit nfail -> set_reload_at_exit t nfail (Reg.Set.union (get_reload_at_exit t nfail) before); (i, Reg.Set.empty) | Itrywith(body, handler) -> let (new_body, after_body) = reload t body before in (* All registers live at the beginning of the handler are destroyed, except the exception bucket *) let before_handler = Reg.Set.remove Proc.loc_exn_bucket (Reg.add_set_array handler.live handler.arg) in let (new_handler, after_handler) = reload t handler before_handler in let (new_next, finally) = reload t i.next (Reg.Set.union after_body after_handler) in (instr_cons (Itrywith(new_body, new_handler)) i.arg i.res new_next, finally) | Iraise _ -> (add_reloads t.spill_env (Reg.inter_set_array before i.arg) i, Reg.Set.empty) Second pass : add spill instructions based on what we 've decided to reload . That is , any register that may be reloaded in the future must be spilled just after its definition . That is, any register that may be reloaded in the future must be spilled just after its definition. *) As an optimization , if a register needs to be spilled in one branch of a conditional but not in the other , then we spill it late on entrance in the branch that needs it spilled . NB : This strategy is turned off in loops , as it may prevent a spill from being lifted up all the way out of the loop . NB again : This strategy is also off in switch arms as it generates many useless spills inside switch arms NB ter : is it the same thing for catch bodies ? As an optimization, if a register needs to be spilled in one branch of a conditional but not in the other, then we spill it late on entrance in the branch that needs it spilled. NB: This strategy is turned off in loops, as it may prevent a spill from being lifted up all the way out of the loop. NB again: This strategy is also off in switch arms as it generates many useless spills inside switch arms NB ter: is it the same thing for catch bodies ? *) let get_spill_at_exit t k = match Hashtbl.find_opt t.spill_at_exit k with | None -> Reg.Set.empty | Some s -> s let set_spill_at_exit t k s = Hashtbl.replace t.spill_at_exit k s let add_spills t regset i = Reg.Set.fold (fun r i -> instr_cons (Iop Ispill) [|r|] [|spill_reg t r|] i) regset i let rec spill (t : spill_data) i finally = match i.desc with Iend -> (i, finally) | Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) -> (i, Reg.Set.empty) | Iop Ireload -> let (new_next, after) = spill t i.next finally in let before1 = Reg.diff_set_array after i.res in (instr_cons i.desc i.arg i.res new_next, Reg.add_set_array before1 i.res) | Iop op -> let (new_next, after) = spill t i.next finally in let before1 = Reg.diff_set_array after i.res in let before = if operation_can_raise op then Reg.Set.union before1 t.spill_at_raise else before1 in (instr_cons_debug i.desc i.arg i.res i.dbg (add_spills t.spill_env (Reg.inter_set_array after i.res) new_next), before) | Iifthenelse(test, ifso, ifnot) -> let (new_next, at_join) = spill t i.next finally in let (new_ifso, before_ifso) = spill t ifso at_join in let (new_ifnot, before_ifnot) = spill t ifnot at_join in if t.inside_arm || t.inside_catch then (instr_cons (Iifthenelse(test, new_ifso, new_ifnot)) i.arg i.res new_next, Reg.Set.union before_ifso before_ifnot) else begin let destroyed = List.assq i t.destroyed_at_fork in let spill_ifso_branch = Reg.Set.diff (Reg.Set.diff before_ifso before_ifnot) destroyed and spill_ifnot_branch = Reg.Set.diff (Reg.Set.diff before_ifnot before_ifso) destroyed in (instr_cons (Iifthenelse(test, add_spills t.spill_env spill_ifso_branch new_ifso, add_spills t.spill_env spill_ifnot_branch new_ifnot)) i.arg i.res new_next, Reg.Set.diff (Reg.Set.diff (Reg.Set.union before_ifso before_ifnot) spill_ifso_branch) spill_ifnot_branch) end | Iswitch(index, cases) -> let (new_next, at_join) = spill t i.next finally in let saved_inside_arm = t.inside_arm in t.inside_arm <- true ; let before = ref Reg.Set.empty in let new_cases = Array.map (fun c -> let (new_c, before_c) = spill t c at_join in before := Reg.Set.union !before before_c; new_c) cases in t.inside_arm <- saved_inside_arm ; (instr_cons (Iswitch(index, new_cases)) i.arg i.res new_next, !before) | Icatch(rec_flag, handlers, body) -> let (new_next, at_join) = spill t i.next finally in let saved_inside_catch = t.inside_catch in t.inside_catch <- true ; let rec fixpoint () = let res = List.map (fun (_, handler) -> spill t handler at_join) handlers in let update changed (k, _handler) (_new_handler, before_handler) = if Reg.Set.equal before_handler (get_spill_at_exit t k) then changed else (set_spill_at_exit t k before_handler; true) in let changed = List.fold_left2 update false handlers res in if rec_flag = Cmm.Recursive && changed then fixpoint () else res in let res = fixpoint () in t.inside_catch <- saved_inside_catch ; let (new_body, before) = spill t body at_join in let new_handlers = List.map2 (fun (nfail, _) (new_handler, _) -> (nfail, new_handler)) handlers res in (instr_cons (Icatch(rec_flag, new_handlers, new_body)) i.arg i.res new_next, before) | Iexit nfail -> (i, get_spill_at_exit t nfail) | Itrywith(body, handler) -> let (new_next, at_join) = spill t i.next finally in let (new_handler, before_handler) = spill t handler at_join in let saved_spill_at_raise = t.spill_at_raise in t.spill_at_raise <- before_handler; let (new_body, before_body) = spill t body at_join in t.spill_at_raise <- saved_spill_at_raise; (instr_cons (Itrywith(new_body, new_handler)) i.arg i.res new_next, before_body) | Iraise _ -> (i, t.spill_at_raise) (* Entry point *) let fundecl f = let reload_data = create_reload () in let (body1, _) = reload reload_data f.fun_body Reg.Set.empty in let spill_data = create_spill reload_data in let (body2, tospill_at_entry) = spill spill_data body1 Reg.Set.empty in let new_body = add_spills spill_data.spill_env (Reg.inter_set_array tospill_at_entry f.fun_args) body2 in { fun_name = f.fun_name; fun_args = f.fun_args; fun_body = new_body; fun_codegen_options = f.fun_codegen_options; fun_poll = f.fun_poll; fun_dbg = f.fun_dbg; fun_num_stack_slots = f.fun_num_stack_slots; fun_contains_calls = f.fun_contains_calls; }
null
https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/ae9c1502103845550162a49fcd3f76276cdfa866/asmcomp/spill.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Insertion of moves to suggest possible spilling / reloading points before register allocation. Association of spill registers to registers Record the position of last use of registers A-list recording what is destroyed at if-then-else points. A-list recording what is destroyed at if-then-else points. Check if the register pressure overflows the maximum pressure allowed at that point. If so, spill enough registers to lower the pressure. Compute the pressure in each register class Check if pressure is exceeded for each class. Find the least recently used, unspilled, unallocated, live register in the class Should not happen Couldn't find any spillable register, give up for this class All regs live across must be spilled Quick check to see if the register pressure is below the maximum All registers live at the beginning of the handler are destroyed, except the exception bucket Entry point
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Reg open Mach We say that a register is " destroyed " if it is live across a construct that potentially destroys all physical registers : function calls or try ... with constructs . The " destroyed " registers must therefore reside in the stack during these instructions .. We will insert spills ( stores ) just after they are defined , and reloads just before their first use following a " destroying " construct . Instructions with more live registers than actual registers also " destroy " registers : we mark as " destroyed " the registers live across the instruction that have n't been used for the longest time . These registers will be spilled and reloaded as described above . that potentially destroys all physical registers: function calls or try...with constructs. The "destroyed" registers must therefore reside in the stack during these instructions.. We will insert spills (stores) just after they are defined, and reloads just before their first use following a "destroying" construct. Instructions with more live registers than actual registers also "destroy" registers: we mark as "destroyed" the registers live across the instruction that haven't been used for the longest time. These registers will be spilled and reloaded as described above. *) type reload_data = { spill_env : Reg.t Reg.Map.t ref; mutable use_date : int Reg.Map.t; mutable current_date : int; mutable destroyed_at_fork : (instruction * Reg.Set.t) list; reload_at_exit : (int, Reg.Set.t) Hashtbl.t; } type spill_data = { spill_env : Reg.t Reg.Map.t ref; destroyed_at_fork : (instruction * Reg.Set.t) list; mutable spill_at_raise : Reg.Set.t; mutable inside_arm : bool; mutable inside_catch : bool; spill_at_exit : (int, Reg.Set.t) Hashtbl.t; } let create_reload () = { spill_env = ref Reg.Map.empty; use_date = Reg.Map.empty; current_date = 0; destroyed_at_fork = []; reload_at_exit = Hashtbl.create 20; } let create_spill (reload : reload_data) = { spill_env = reload.spill_env; destroyed_at_fork = reload.destroyed_at_fork; spill_at_raise = Reg.Set.empty; inside_arm = false; inside_catch = false; spill_at_exit = Hashtbl.create 20; } let spill_reg spill_env r = try Reg.Map.find r !spill_env with Not_found -> let spill_r = Reg.create r.typ in spill_r.spill <- true; if not (Reg.anonymous r) then spill_r.raw_name <- r.raw_name; spill_env := Reg.Map.add r spill_r !spill_env; spill_r let record_use t regv = for i = 0 to Array.length regv - 1 do let r = regv.(i) in let prev_date = try Reg.Map.find r t.use_date with Not_found -> 0 in if t.current_date > prev_date then t.use_date <- Reg.Map.add r t.current_date t.use_date done let add_superpressure_regs t op live_regs res_regs spilled = let max_pressure = Proc.max_register_pressure op in let regs = Reg.add_set_array live_regs res_regs in let pressure = Array.make Proc.num_register_classes 0 in Reg.Set.iter (fun r -> if Reg.Set.mem r spilled then () else begin match r.loc with Stack _ -> () | _ -> let c = Proc.register_class r in pressure.(c) <- pressure.(c) + 1 end) regs; let rec check_pressure cl spilled = if cl >= Proc.num_register_classes then spilled else if pressure.(cl) <= max_pressure.(cl) then check_pressure (cl+1) spilled else begin let lru_date = ref 1000000 and lru_reg = ref Reg.dummy in Reg.Set.iter (fun r -> if Proc.register_class r = cl && not (Reg.Set.mem r spilled) && r.loc = Unknown then begin try let d = Reg.Map.find r t.use_date in if d < !lru_date then begin lru_date := d; lru_reg := r end () end) live_regs; if !lru_reg != Reg.dummy then begin pressure.(cl) <- pressure.(cl) - 1; check_pressure cl (Reg.Set.add !lru_reg spilled) end else check_pressure (cl+1) spilled end in check_pressure 0 spilled First pass : insert reload instructions based on an approximation of what is destroyed at pressure points . what is destroyed at pressure points. *) let add_reloads spill_env regset i = Reg.Set.fold (fun r i -> instr_cons (Iop Ireload) [|spill_reg spill_env r|] [|r|] i) regset i let get_reload_at_exit t k = match Hashtbl.find_opt t.reload_at_exit k with | None -> Reg.Set.empty | Some s -> s let set_reload_at_exit t k s = Hashtbl.replace t.reload_at_exit k s let rec reload (t : reload_data) i before = t.current_date <- succ t.current_date; record_use t i.arg; record_use t i.res; match i.desc with Iend -> (i, before) | Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) -> (add_reloads t.spill_env (Reg.inter_set_array before i.arg) i, Reg.Set.empty) | Iop(Icall_ind | Icall_imm _ | Iextcall { alloc = true; }) -> let (new_next, finally) = reload t i.next i.live in (add_reloads t.spill_env (Reg.inter_set_array before i.arg) (instr_cons_debug i.desc i.arg i.res i.dbg new_next), finally) | Iop op -> let new_before = if !Clflags.use_linscan || (Reg.Set.cardinal i.live + Array.length i.res <= Proc.safe_register_pressure op) then before else add_superpressure_regs t op i.live i.res before in let after = Reg.diff_set_array (Reg.diff_set_array new_before i.arg) i.res in let (new_next, finally) = reload t i.next after in (add_reloads t.spill_env (Reg.inter_set_array new_before i.arg) (instr_cons_debug i.desc i.arg i.res i.dbg new_next), finally) | Iifthenelse(test, ifso, ifnot) -> let at_fork = Reg.diff_set_array before i.arg in let date_fork = t.current_date in let (new_ifso, after_ifso) = reload t ifso at_fork in let date_ifso = t.current_date in t.current_date <- date_fork; let (new_ifnot, after_ifnot) = reload t ifnot at_fork in t.current_date <- Int.max date_ifso t.current_date; let (new_next, finally) = reload t i.next (Reg.Set.union after_ifso after_ifnot) in let new_i = instr_cons (Iifthenelse(test, new_ifso, new_ifnot)) i.arg i.res new_next in t.destroyed_at_fork <- (new_i, at_fork) :: t.destroyed_at_fork; (add_reloads t.spill_env (Reg.inter_set_array before i.arg) new_i, finally) | Iswitch(index, cases) -> let at_fork = Reg.diff_set_array before i.arg in let date_fork = t.current_date in let date_join = ref 0 in let after_cases = ref Reg.Set.empty in let new_cases = Array.map (fun c -> t.current_date <- date_fork; let (new_c, after_c) = reload t c at_fork in after_cases := Reg.Set.union !after_cases after_c; date_join := Int.max !date_join t.current_date; new_c) cases in t.current_date <- !date_join; let (new_next, finally) = reload t i.next !after_cases in (add_reloads t.spill_env (Reg.inter_set_array before i.arg) (instr_cons (Iswitch(index, new_cases)) i.arg i.res new_next), finally) | Icatch(rec_flag, handlers, body) -> let (new_body, after_body) = reload t body before in let rec fixpoint () = let at_exits = List.map (fun (nfail, _) -> (nfail, get_reload_at_exit t nfail)) handlers in let res = List.map2 (fun (nfail', handler) (nfail, at_exit) -> assert(nfail = nfail'); reload t handler at_exit) handlers at_exits in match rec_flag with | Cmm.Nonrecursive -> res | Cmm.Recursive -> let equal = List.for_all2 (fun (nfail', _) (nfail, at_exit) -> assert(nfail = nfail'); Reg.Set.equal at_exit (get_reload_at_exit t nfail)) handlers at_exits in if equal then res else fixpoint () in let res = fixpoint () in let union = List.fold_left (fun acc (_, after_handler) -> Reg.Set.union acc after_handler) after_body res in let (new_next, finally) = reload t i.next union in let new_handlers = List.map2 (fun (nfail, _) (new_handler, _) -> nfail, new_handler) handlers res in (instr_cons (Icatch(rec_flag, new_handlers, new_body)) i.arg i.res new_next, finally) | Iexit nfail -> set_reload_at_exit t nfail (Reg.Set.union (get_reload_at_exit t nfail) before); (i, Reg.Set.empty) | Itrywith(body, handler) -> let (new_body, after_body) = reload t body before in let before_handler = Reg.Set.remove Proc.loc_exn_bucket (Reg.add_set_array handler.live handler.arg) in let (new_handler, after_handler) = reload t handler before_handler in let (new_next, finally) = reload t i.next (Reg.Set.union after_body after_handler) in (instr_cons (Itrywith(new_body, new_handler)) i.arg i.res new_next, finally) | Iraise _ -> (add_reloads t.spill_env (Reg.inter_set_array before i.arg) i, Reg.Set.empty) Second pass : add spill instructions based on what we 've decided to reload . That is , any register that may be reloaded in the future must be spilled just after its definition . That is, any register that may be reloaded in the future must be spilled just after its definition. *) As an optimization , if a register needs to be spilled in one branch of a conditional but not in the other , then we spill it late on entrance in the branch that needs it spilled . NB : This strategy is turned off in loops , as it may prevent a spill from being lifted up all the way out of the loop . NB again : This strategy is also off in switch arms as it generates many useless spills inside switch arms NB ter : is it the same thing for catch bodies ? As an optimization, if a register needs to be spilled in one branch of a conditional but not in the other, then we spill it late on entrance in the branch that needs it spilled. NB: This strategy is turned off in loops, as it may prevent a spill from being lifted up all the way out of the loop. NB again: This strategy is also off in switch arms as it generates many useless spills inside switch arms NB ter: is it the same thing for catch bodies ? *) let get_spill_at_exit t k = match Hashtbl.find_opt t.spill_at_exit k with | None -> Reg.Set.empty | Some s -> s let set_spill_at_exit t k s = Hashtbl.replace t.spill_at_exit k s let add_spills t regset i = Reg.Set.fold (fun r i -> instr_cons (Iop Ispill) [|r|] [|spill_reg t r|] i) regset i let rec spill (t : spill_data) i finally = match i.desc with Iend -> (i, finally) | Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) -> (i, Reg.Set.empty) | Iop Ireload -> let (new_next, after) = spill t i.next finally in let before1 = Reg.diff_set_array after i.res in (instr_cons i.desc i.arg i.res new_next, Reg.add_set_array before1 i.res) | Iop op -> let (new_next, after) = spill t i.next finally in let before1 = Reg.diff_set_array after i.res in let before = if operation_can_raise op then Reg.Set.union before1 t.spill_at_raise else before1 in (instr_cons_debug i.desc i.arg i.res i.dbg (add_spills t.spill_env (Reg.inter_set_array after i.res) new_next), before) | Iifthenelse(test, ifso, ifnot) -> let (new_next, at_join) = spill t i.next finally in let (new_ifso, before_ifso) = spill t ifso at_join in let (new_ifnot, before_ifnot) = spill t ifnot at_join in if t.inside_arm || t.inside_catch then (instr_cons (Iifthenelse(test, new_ifso, new_ifnot)) i.arg i.res new_next, Reg.Set.union before_ifso before_ifnot) else begin let destroyed = List.assq i t.destroyed_at_fork in let spill_ifso_branch = Reg.Set.diff (Reg.Set.diff before_ifso before_ifnot) destroyed and spill_ifnot_branch = Reg.Set.diff (Reg.Set.diff before_ifnot before_ifso) destroyed in (instr_cons (Iifthenelse(test, add_spills t.spill_env spill_ifso_branch new_ifso, add_spills t.spill_env spill_ifnot_branch new_ifnot)) i.arg i.res new_next, Reg.Set.diff (Reg.Set.diff (Reg.Set.union before_ifso before_ifnot) spill_ifso_branch) spill_ifnot_branch) end | Iswitch(index, cases) -> let (new_next, at_join) = spill t i.next finally in let saved_inside_arm = t.inside_arm in t.inside_arm <- true ; let before = ref Reg.Set.empty in let new_cases = Array.map (fun c -> let (new_c, before_c) = spill t c at_join in before := Reg.Set.union !before before_c; new_c) cases in t.inside_arm <- saved_inside_arm ; (instr_cons (Iswitch(index, new_cases)) i.arg i.res new_next, !before) | Icatch(rec_flag, handlers, body) -> let (new_next, at_join) = spill t i.next finally in let saved_inside_catch = t.inside_catch in t.inside_catch <- true ; let rec fixpoint () = let res = List.map (fun (_, handler) -> spill t handler at_join) handlers in let update changed (k, _handler) (_new_handler, before_handler) = if Reg.Set.equal before_handler (get_spill_at_exit t k) then changed else (set_spill_at_exit t k before_handler; true) in let changed = List.fold_left2 update false handlers res in if rec_flag = Cmm.Recursive && changed then fixpoint () else res in let res = fixpoint () in t.inside_catch <- saved_inside_catch ; let (new_body, before) = spill t body at_join in let new_handlers = List.map2 (fun (nfail, _) (new_handler, _) -> (nfail, new_handler)) handlers res in (instr_cons (Icatch(rec_flag, new_handlers, new_body)) i.arg i.res new_next, before) | Iexit nfail -> (i, get_spill_at_exit t nfail) | Itrywith(body, handler) -> let (new_next, at_join) = spill t i.next finally in let (new_handler, before_handler) = spill t handler at_join in let saved_spill_at_raise = t.spill_at_raise in t.spill_at_raise <- before_handler; let (new_body, before_body) = spill t body at_join in t.spill_at_raise <- saved_spill_at_raise; (instr_cons (Itrywith(new_body, new_handler)) i.arg i.res new_next, before_body) | Iraise _ -> (i, t.spill_at_raise) let fundecl f = let reload_data = create_reload () in let (body1, _) = reload reload_data f.fun_body Reg.Set.empty in let spill_data = create_spill reload_data in let (body2, tospill_at_entry) = spill spill_data body1 Reg.Set.empty in let new_body = add_spills spill_data.spill_env (Reg.inter_set_array tospill_at_entry f.fun_args) body2 in { fun_name = f.fun_name; fun_args = f.fun_args; fun_body = new_body; fun_codegen_options = f.fun_codegen_options; fun_poll = f.fun_poll; fun_dbg = f.fun_dbg; fun_num_stack_slots = f.fun_num_stack_slots; fun_contains_calls = f.fun_contains_calls; }
f41bd05d759970dc8c73c5666e3251e1aa721d9e0337c84bd20e72e977c89669
pixlsus/registry.gimp.org_static
sf-will-glow_0.scm
Shadow Glow - This is a script for The GIMP that inverts the lightness of the layer without affecting colour Copyright ( C ) 2010 ;; ;; 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 </>. (define (script-fu-shadow-glow img drawable brightness) (let* ((new-layer 0) (array (cons-array 4 'byte))) ;Set array values (cond ((= brightness 0) (aset array 0 0) (aset array 1 255) (aset array 2 255) (aset array 3 0) ) ((> brightness 0) (aset array 0 brightness) (aset array 1 255) (aset array 2 255) (aset array 3 0) ) ((< brightness 0) (aset array 0 0) (aset array 1 255) (aset array 2 (+ 255 brightness)) (aset array 3 0) ) ) (gimp-image-undo-group-start img) ; Create a new layer (set! new-layer (car (gimp-layer-copy drawable 1))) (gimp-layer-set-name new-layer "Glow Layer") (gimp-image-add-layer img new-layer -1) ; Process the new layer ;(gimp-invert new-layer) (gimp-curves-spline new-layer 0 4 array) (gimp-hue-saturation new-layer 0 100 0 0) (gimp-layer-set-mode new-layer 10) (gimp-image-undo-group-end img) ; Update the display (gimp-displays-flush) ) ) (script-fu-register "script-fu-shadow-glow" "Shadow Glow..." "Replaces shadows and dark areas with glowing areas. Works best with images that have good light/dark balance" "Will Morrison" "GNU General Public License" "2010" "RGB*" SF-IMAGE "Image" 0 SF-DRAWABLE "Layer to invert" 0 SF-ADJUSTMENT "Threshold" '(0 -255 255 1 25 0 0) ) (script-fu-menu-register "script-fu-shadow-glow" "<Image>/Filters/Will's Script Pack")
null
https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/sf-will-glow_0.scm
scheme
This program is free software: you can redistribute it and/or modify (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. along with this program. If not, see </>. Set array values Create a new layer Process the new layer (gimp-invert new-layer) Update the display
Shadow Glow - This is a script for The GIMP that inverts the lightness of the layer without affecting colour Copyright ( C ) 2010 it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (define (script-fu-shadow-glow img drawable brightness) (let* ((new-layer 0) (array (cons-array 4 'byte))) (cond ((= brightness 0) (aset array 0 0) (aset array 1 255) (aset array 2 255) (aset array 3 0) ) ((> brightness 0) (aset array 0 brightness) (aset array 1 255) (aset array 2 255) (aset array 3 0) ) ((< brightness 0) (aset array 0 0) (aset array 1 255) (aset array 2 (+ 255 brightness)) (aset array 3 0) ) ) (gimp-image-undo-group-start img) (set! new-layer (car (gimp-layer-copy drawable 1))) (gimp-layer-set-name new-layer "Glow Layer") (gimp-image-add-layer img new-layer -1) (gimp-curves-spline new-layer 0 4 array) (gimp-hue-saturation new-layer 0 100 0 0) (gimp-layer-set-mode new-layer 10) (gimp-image-undo-group-end img) (gimp-displays-flush) ) ) (script-fu-register "script-fu-shadow-glow" "Shadow Glow..." "Replaces shadows and dark areas with glowing areas. Works best with images that have good light/dark balance" "Will Morrison" "GNU General Public License" "2010" "RGB*" SF-IMAGE "Image" 0 SF-DRAWABLE "Layer to invert" 0 SF-ADJUSTMENT "Threshold" '(0 -255 255 1 25 0 0) ) (script-fu-menu-register "script-fu-shadow-glow" "<Image>/Filters/Will's Script Pack")
5ccf49cc327e1e5d40d6e4921c5efe93409fe21a5fa43333fc13db06fd33eb53
xapi-project/xen-api
xen_test.ml
(* This was created on a creedence host. I have deliberately removed the field *) (* *) (* "name": "foo" *) (* *) (* from just after the 'id' field. This is to test that the field gets defaulted *) (* to the value specified in the idl. *) let old_vm_t = "{\"id\": \"bc6b8e8a-f0a5-4746-6489-2745756f21b2\", \"ssidref\": 0, \ \"xsdata\": {\"vm-data\": \"\"}, \"platformdata\": {\"generation-id\": \ \"\", \"timeoffset\": \"0\", \"usb\": \"true\", \"usb_tablet\": \"true\"}, \ \"bios_strings\": {\"bios-vendor\": \"Xen\", \"bios-version\": \"\", \ \"system-manufacturer\": \"Xen\", \"system-product-name\": \"HVM domU\", \ \"system-version\": \"\", \"system-serial-number\": \"\", \"hp-rombios\": \ \"\", \"oem-1\":\"Xen\", \"oem-2\": \ \"MS_VM_CERT/SHA1/bdbeb6e0a816d43fa6d3fe8aaef04c2bad9d3e3d\"}, \"ty\": \ [\"HVM\", {\"hap\": true, \"shadow_multiplier\": 1.000000, \"timeoffset\": \ \"0\", \"video_mib\": 4, \"video\": \"Cirrus\", \"acpi\": true, \"serial\": \ \"pty\", \"keymap\": \"en-us\", \"pci_emulations\": [], \ \"pci_passthrough\": false, \"boot_order\": \"cd\", \"qemu_disk_cmdline\": \ false, \"qemu_stubdom\": false}], \"suppress_spurious_page_faults\": false, \ \"memory_static_max\": 268435456, \"memory_dynamic_max\": 268435456, \ \"memory_dynamic_min\": 134217728, \"vcpu_max\": 1, \"vcpus\": 1, \ \"scheduler_params\": {\"priority\": [256, 0], \"affinity\": []}, \ \"on_softreboot\": [\"Shutdown\"], \"on_crash\": [\"Shutdown\"], \ \"on_shutdown\": [\"Shutdown\"], \"on_reboot\": [\"Start\"], \ \"pci_msitranslate\": true, \"pci_power_mgmt\": false}" let test_upgrade_rules () = let old_json = old_vm_t in let rpc = Jsonrpc.of_string old_json in let vm_t = match Rpcmarshal.unmarshal Xenops_interface.Vm.t.Rpc.Types.ty rpc with | Ok vm -> vm | Error (`Msg m) -> failwith (Printf.sprintf "Failed to unmarshal: %s" m) in Alcotest.(check string) "VM name" vm_t.Xenops_interface.Vm.name "unnamed" (* this value is the default in xenops_interface.ml *) let tests = [("check upgrade rule", `Quick, test_upgrade_rules)]
null
https://raw.githubusercontent.com/xapi-project/xen-api/42ebd10a2b3ec82c8f9fa4bf69c10324e6c1093c/ocaml/xapi-idl/lib_test/xen_test.ml
ocaml
This was created on a creedence host. I have deliberately removed the field "name": "foo" from just after the 'id' field. This is to test that the field gets defaulted to the value specified in the idl. this value is the default in xenops_interface.ml
let old_vm_t = "{\"id\": \"bc6b8e8a-f0a5-4746-6489-2745756f21b2\", \"ssidref\": 0, \ \"xsdata\": {\"vm-data\": \"\"}, \"platformdata\": {\"generation-id\": \ \"\", \"timeoffset\": \"0\", \"usb\": \"true\", \"usb_tablet\": \"true\"}, \ \"bios_strings\": {\"bios-vendor\": \"Xen\", \"bios-version\": \"\", \ \"system-manufacturer\": \"Xen\", \"system-product-name\": \"HVM domU\", \ \"system-version\": \"\", \"system-serial-number\": \"\", \"hp-rombios\": \ \"\", \"oem-1\":\"Xen\", \"oem-2\": \ \"MS_VM_CERT/SHA1/bdbeb6e0a816d43fa6d3fe8aaef04c2bad9d3e3d\"}, \"ty\": \ [\"HVM\", {\"hap\": true, \"shadow_multiplier\": 1.000000, \"timeoffset\": \ \"0\", \"video_mib\": 4, \"video\": \"Cirrus\", \"acpi\": true, \"serial\": \ \"pty\", \"keymap\": \"en-us\", \"pci_emulations\": [], \ \"pci_passthrough\": false, \"boot_order\": \"cd\", \"qemu_disk_cmdline\": \ false, \"qemu_stubdom\": false}], \"suppress_spurious_page_faults\": false, \ \"memory_static_max\": 268435456, \"memory_dynamic_max\": 268435456, \ \"memory_dynamic_min\": 134217728, \"vcpu_max\": 1, \"vcpus\": 1, \ \"scheduler_params\": {\"priority\": [256, 0], \"affinity\": []}, \ \"on_softreboot\": [\"Shutdown\"], \"on_crash\": [\"Shutdown\"], \ \"on_shutdown\": [\"Shutdown\"], \"on_reboot\": [\"Start\"], \ \"pci_msitranslate\": true, \"pci_power_mgmt\": false}" let test_upgrade_rules () = let old_json = old_vm_t in let rpc = Jsonrpc.of_string old_json in let vm_t = match Rpcmarshal.unmarshal Xenops_interface.Vm.t.Rpc.Types.ty rpc with | Ok vm -> vm | Error (`Msg m) -> failwith (Printf.sprintf "Failed to unmarshal: %s" m) in Alcotest.(check string) "VM name" vm_t.Xenops_interface.Vm.name "unnamed" let tests = [("check upgrade rule", `Quick, test_upgrade_rules)]
919d19ceb9279e12bd889cc8a5c0929171c1dd16a1c1bef8c2c6597934073940
oliyh/re-graph
deprecated_integration_test.cljc
(ns re-graph.deprecated-integration-test (:require [re-graph.core-deprecated :as re-graph] [re-graph.core :as re-graph-core] [re-graph.internals :as internals] #?(:clj [clojure.test :refer [deftest testing is use-fixtures]] :cljs [cljs.test :refer-macros [deftest testing is]]) [day8.re-frame.test :refer [run-test-async wait-for #?(:clj with-temp-re-frame-state)]] [re-frame.core :as re-frame] [re-frame.db :as rfdb] #?(:clj [re-graph.integration-server :refer [with-server]]))) #?(:clj (use-fixtures :once with-server)) (defn register-callback! [] (re-frame/reg-event-db ::callback (fn [db [_ response]] (assoc db ::response response)))) (deftest async-http-query-test (run-test-async (re-graph/init {:ws nil :http {:url ":8888/graphql"}}) (register-callback!) (wait-for [::re-graph-core/init] (testing "async query" (re-graph/query "{ pets { id name } }" {} #(re-frame/dispatch [::callback %])) (wait-for [::callback] (is (= {:data {:pets [{:id "123", :name "Billy"} {:id "234", :name "Bob"} {:id "345", :name "Beatrice"}]}} (::response @rfdb/app-db))) (testing "instances, query ids, etc" ;; todo ) (testing "http parameters" ;; todo )))))) (deftest async-http-mutate-test (run-test-async (re-graph/init {:ws nil :http {:url ":8888/graphql"}}) (register-callback!) (wait-for [::re-graph-core/init] (testing "async mutate" (re-graph/mutate "mutation { createPet(name: \"Zorro\") { id name } }" {} #(re-frame/dispatch [::callback %])) (wait-for [::callback] (is (= {:data {:createPet {:id "999", :name "Zorro"}}} (::response @rfdb/app-db)))))))) #?(:clj (deftest sync-http-test (with-temp-re-frame-state (re-graph/init {:ws nil :http {:url ":8888/graphql"}}) (testing "sync query" (is (= {:data {:pets [{:id "123", :name "Billy"} {:id "234", :name "Bob"} {:id "345", :name "Beatrice"}]}} (re-graph/query-sync "{ pets { id name } }" {})))) (testing "sync mutate" (is (= {:data {:createPet {:id "999", :name "Zorro"}}} (re-graph/mutate-sync "mutation { createPet(name: \"Zorro\") { id name } }" {})))) (testing "error handling" (is (= {:errors [{:message "Cannot query field `malformed' on type `Query'.", :locations [{:line 1, :column 9}], :extensions {:type-name "Query" :field-name "malformed" :status 400}}]} (re-graph/query-sync "{ malformed }" {}))))))) (deftest websocket-query-test (run-test-async (re-graph/init {:ws {:url "ws:8888/graphql-ws"} :http nil}) (re-frame/reg-fx ::internals/disconnect-ws (fn [_] (re-frame/dispatch [::ws-disconnected]))) (re-frame/reg-event-fx ::ws-disconnected (fn [& _args] ;; do nothing {})) (re-frame/reg-event-db ::complete (fn [db _] db)) (re-frame/reg-event-fx ::callback (fn [{:keys [db]} [_ response]] (let [new-db (update db ::responses conj response)] (merge {:db new-db} (when (<= 5 (count (::responses new-db))) {:dispatch [::complete]}))))) (wait-for [::re-graph-core/init] (testing "subscriptions" (re-graph/subscribe :all-pets "MyPets($count: Int) { pets(count: $count) { id name } }" {:count 5} #(re-frame/dispatch [::callback %])) (wait-for [::complete] (let [responses (::responses @rfdb/app-db)] (is (every? #(= {:data {:pets [{:id "123", :name "Billy"} {:id "234", :name "Bob"} {:id "345", :name "Beatrice"}]}} %) responses)) (is (= 5 (count responses))))))))) (deftest websocket-mutation-test (run-test-async (re-graph/init {:ws {:url "ws:8888/graphql-ws"} :http nil}) (register-callback!) (re-frame/reg-fx ::internals/disconnect-ws (fn [_] (re-frame/dispatch [::ws-disconnected]))) (re-frame/reg-event-fx ::ws-disconnected (fn [& _args] ;; do nothing {})) (wait-for [::re-graph-core/init] (testing "mutations" (testing "async mutate" (re-graph/mutate "mutation { createPet(name: \"Zorro\") { id name } }" {} #(re-frame/dispatch [::callback %])) (wait-for [::callback] (is (= {:data {:createPet {:id "999", :name "Zorro"}}} (::response @rfdb/app-db)))))))))
null
https://raw.githubusercontent.com/oliyh/re-graph/99e65fc6c169ae251226875700034fc988d819e4/test/re_graph/deprecated_integration_test.cljc
clojure
todo todo do nothing do nothing
(ns re-graph.deprecated-integration-test (:require [re-graph.core-deprecated :as re-graph] [re-graph.core :as re-graph-core] [re-graph.internals :as internals] #?(:clj [clojure.test :refer [deftest testing is use-fixtures]] :cljs [cljs.test :refer-macros [deftest testing is]]) [day8.re-frame.test :refer [run-test-async wait-for #?(:clj with-temp-re-frame-state)]] [re-frame.core :as re-frame] [re-frame.db :as rfdb] #?(:clj [re-graph.integration-server :refer [with-server]]))) #?(:clj (use-fixtures :once with-server)) (defn register-callback! [] (re-frame/reg-event-db ::callback (fn [db [_ response]] (assoc db ::response response)))) (deftest async-http-query-test (run-test-async (re-graph/init {:ws nil :http {:url ":8888/graphql"}}) (register-callback!) (wait-for [::re-graph-core/init] (testing "async query" (re-graph/query "{ pets { id name } }" {} #(re-frame/dispatch [::callback %])) (wait-for [::callback] (is (= {:data {:pets [{:id "123", :name "Billy"} {:id "234", :name "Bob"} {:id "345", :name "Beatrice"}]}} (::response @rfdb/app-db))) (testing "instances, query ids, etc" ) (testing "http parameters" )))))) (deftest async-http-mutate-test (run-test-async (re-graph/init {:ws nil :http {:url ":8888/graphql"}}) (register-callback!) (wait-for [::re-graph-core/init] (testing "async mutate" (re-graph/mutate "mutation { createPet(name: \"Zorro\") { id name } }" {} #(re-frame/dispatch [::callback %])) (wait-for [::callback] (is (= {:data {:createPet {:id "999", :name "Zorro"}}} (::response @rfdb/app-db)))))))) #?(:clj (deftest sync-http-test (with-temp-re-frame-state (re-graph/init {:ws nil :http {:url ":8888/graphql"}}) (testing "sync query" (is (= {:data {:pets [{:id "123", :name "Billy"} {:id "234", :name "Bob"} {:id "345", :name "Beatrice"}]}} (re-graph/query-sync "{ pets { id name } }" {})))) (testing "sync mutate" (is (= {:data {:createPet {:id "999", :name "Zorro"}}} (re-graph/mutate-sync "mutation { createPet(name: \"Zorro\") { id name } }" {})))) (testing "error handling" (is (= {:errors [{:message "Cannot query field `malformed' on type `Query'.", :locations [{:line 1, :column 9}], :extensions {:type-name "Query" :field-name "malformed" :status 400}}]} (re-graph/query-sync "{ malformed }" {}))))))) (deftest websocket-query-test (run-test-async (re-graph/init {:ws {:url "ws:8888/graphql-ws"} :http nil}) (re-frame/reg-fx ::internals/disconnect-ws (fn [_] (re-frame/dispatch [::ws-disconnected]))) (re-frame/reg-event-fx ::ws-disconnected (fn [& _args] {})) (re-frame/reg-event-db ::complete (fn [db _] db)) (re-frame/reg-event-fx ::callback (fn [{:keys [db]} [_ response]] (let [new-db (update db ::responses conj response)] (merge {:db new-db} (when (<= 5 (count (::responses new-db))) {:dispatch [::complete]}))))) (wait-for [::re-graph-core/init] (testing "subscriptions" (re-graph/subscribe :all-pets "MyPets($count: Int) { pets(count: $count) { id name } }" {:count 5} #(re-frame/dispatch [::callback %])) (wait-for [::complete] (let [responses (::responses @rfdb/app-db)] (is (every? #(= {:data {:pets [{:id "123", :name "Billy"} {:id "234", :name "Bob"} {:id "345", :name "Beatrice"}]}} %) responses)) (is (= 5 (count responses))))))))) (deftest websocket-mutation-test (run-test-async (re-graph/init {:ws {:url "ws:8888/graphql-ws"} :http nil}) (register-callback!) (re-frame/reg-fx ::internals/disconnect-ws (fn [_] (re-frame/dispatch [::ws-disconnected]))) (re-frame/reg-event-fx ::ws-disconnected (fn [& _args] {})) (wait-for [::re-graph-core/init] (testing "mutations" (testing "async mutate" (re-graph/mutate "mutation { createPet(name: \"Zorro\") { id name } }" {} #(re-frame/dispatch [::callback %])) (wait-for [::callback] (is (= {:data {:createPet {:id "999", :name "Zorro"}}} (::response @rfdb/app-db)))))))))
fe79edbfd4072adaa56e6f01286def66d86a39f17ddc6994c6172644e9931b1b
kumarshantanu/lein-clr
project.clj
(defproject lein-clr "0.2.2" :description "Leiningen plugin to automate build tasks for ClojureCLR projects" :url "-clr" :license {:name "Eclipse Public License" :url "-v10.html"} :min-lein-version "2.0.0" :eval-in-leiningen true)
null
https://raw.githubusercontent.com/kumarshantanu/lein-clr/de43519353c3c4a8a4e1520faf7f9a576910382e/plugin/project.clj
clojure
(defproject lein-clr "0.2.2" :description "Leiningen plugin to automate build tasks for ClojureCLR projects" :url "-clr" :license {:name "Eclipse Public License" :url "-v10.html"} :min-lein-version "2.0.0" :eval-in-leiningen true)
a2209ab3338631cae9371db54880780c1836ed0be24c894981a0359d167c08af
techascent/tech.datatype
statistics.clj
(ns tech.v2.datatype.statistics (:require [tech.v2.datatype.base :as dtype-base] [tech.v2.datatype.protocols :as dtype-proto] [tech.v2.datatype.boolean-op :as boolean-op] [tech.v2.datatype.unary-op :as unary-op] [tech.v2.datatype.reduce-op :as reduce-op] [tech.v2.datatype.array] [kixi.stats.core :as kixi]) (:refer-clojure :exclude [min max]) (:import [org.apache.commons.math3.stat.correlation KendallsCorrelation PearsonsCorrelation SpearmansCorrelation] [org.apache.commons.math3.stat.descriptive DescriptiveStatistics] [org.apache.commons.math3.stat.descriptive.rank Median])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn- desc-stats-sum-of-squares ^double [^DescriptiveStatistics stats] (->> (.getSortedValues stats) (unary-op/unary-reader :float64 (* x x)) (reduce-op/iterable-reduce :float64 (+ accum next)))) (defn- desc-stats-sum-of-logs ^double [^DescriptiveStatistics stats] (->> (.getSortedValues stats) (unary-op/unary-reader :float64 (Math/log x)) (reduce-op/commutative-reduce :float64 (+ accum next)))) (defn- desc-stats-product ^double [^DescriptiveStatistics stats] (->> (.getSortedValues stats) (reduce-op/commutative-reduce :float64 (* accum next)))) (def supported-stats-map {:mean #(.getMean ^DescriptiveStatistics %) :min #(.getMin ^DescriptiveStatistics %) :max #(.getMax ^DescriptiveStatistics %) :median #(.getPercentile ^DescriptiveStatistics % 50.0) :variance #(.getVariance ^DescriptiveStatistics %) :skew #(.getSkewness ^DescriptiveStatistics %) :kurtosis #(.getKurtosis ^DescriptiveStatistics %) :geometric-mean #(.getGeometricMean ^DescriptiveStatistics %) :sum-of-squares desc-stats-sum-of-squares :sum-of-logs desc-stats-sum-of-logs :quadratic-mean #(.getQuadraticMean ^DescriptiveStatistics %) :standard-deviation #(.getStandardDeviation ^DescriptiveStatistics %) :variance-population #(.getPopulationVariance ^DescriptiveStatistics %) :sum #(.getSum ^DescriptiveStatistics %) :product desc-stats-product :quartile-1 #(.getPercentile ^DescriptiveStatistics % 25.0) :quartile-3 #(.getPercentile ^DescriptiveStatistics % 75.0) :ecount #(.getN ^DescriptiveStatistics %) }) (defn supported-descriptive-stats [] (keys supported-stats-map)) (defn descriptive-stats "Generate descriptive statistics for a particular item." [item & [stats-set]] (let [stats-set (set (or stats-set [:mean :median :min :max :ecount :standard-deviation :skew])) stats-desc (DescriptiveStatistics. (dtype-base/->double-array item))] (->> stats-set (map (fn [stats-key] (if-let [supported-stat (get supported-stats-map stats-key)] [stats-key (supported-stat stats-desc)] (throw (ex-info (format "Unsupported statistic: %s" stats-key) {}))))) (into {})))) (defn percentile "Get the nth percentile. Percent ranges from 0-100." [item percent] (-> (DescriptiveStatistics. (dtype-base/->double-array item)) (.getPercentile (double percent)))) (defmacro define-supported-stats-oneoffs [] `(do ~@(->> (supported-descriptive-stats) (map (fn [stat-name] `(defn ~(symbol (name stat-name)) ~(format "Supported stat %s" (name stat-name)) [~'item] (-> (descriptive-stats ~'item [~stat-name]) ~stat-name))))))) (define-supported-stats-oneoffs) (defn- kixi-apply [kixi-fn item] (transduce identity kixi-fn (or (dtype-proto/as-reader item) (dtype-proto/as-iterable item)))) (defn harmonic-mean [item] (kixi-apply kixi/harmonic-mean item)) (defn standard-deviation-population [item] (kixi-apply kixi/standard-deviation-p item)) (defn standard-error [item] (kixi-apply kixi/standard-error item)) (defn skewness [item] (skew item)) (defn skewness-population [item] (kixi-apply kixi/skewness-p item)) (defn kurtosis [item] (kixi-apply kixi/kurtosis item)) (defn kurtosis-population [item] (kixi-apply kixi/kurtosis-p item)) (defn pearsons-correlation [lhs rhs] (-> (PearsonsCorrelation.) (.correlation (dtype-base/->double-array lhs) (dtype-base/->double-array rhs)))) (defn spearmans-correlation [lhs rhs] (-> (SpearmansCorrelation.) (.correlation (dtype-base/->double-array lhs) (dtype-base/->double-array rhs)))) (defn kendalls-correlation [lhs rhs] (-> (KendallsCorrelation.) (.correlation (dtype-base/->double-array lhs) (dtype-base/->double-array rhs)))) (defn quartiles "return [min, 25 50 75 max] of item" [item] (let [stats (DescriptiveStatistics. (dtype-base/->double-array item))] [(.getMin stats) (.getPercentile stats 25.0) (.getPercentile stats 50.0) (.getPercentile stats 75.0) (.getMax stats)])) (defn quartile-outlier-fn "Create a function that, given floating point data, will return true or false if that data is an outlier. Default range mult is 1.5: (or (< val (- q1 (* range-mult iqr))) (> val (+ q3 (* range-mult iqr)))" [item & [range-mult]] (let [[_ q1 _ q3 _] (quartiles item) q1 (double q1) q3 (double q3) iqr (- q3 q1) range-mult (double (or range-mult 1.5))] (boolean-op/make-float-double-boolean-unary-op (or (< x (- q1 (* range-mult iqr))) (> x (+ q3 (* range-mult iqr)))))))
null
https://raw.githubusercontent.com/techascent/tech.datatype/8cc83d771d9621d580fd5d4d0625005bd7ab0e0c/src/tech/v2/datatype/statistics.clj
clojure
(ns tech.v2.datatype.statistics (:require [tech.v2.datatype.base :as dtype-base] [tech.v2.datatype.protocols :as dtype-proto] [tech.v2.datatype.boolean-op :as boolean-op] [tech.v2.datatype.unary-op :as unary-op] [tech.v2.datatype.reduce-op :as reduce-op] [tech.v2.datatype.array] [kixi.stats.core :as kixi]) (:refer-clojure :exclude [min max]) (:import [org.apache.commons.math3.stat.correlation KendallsCorrelation PearsonsCorrelation SpearmansCorrelation] [org.apache.commons.math3.stat.descriptive DescriptiveStatistics] [org.apache.commons.math3.stat.descriptive.rank Median])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn- desc-stats-sum-of-squares ^double [^DescriptiveStatistics stats] (->> (.getSortedValues stats) (unary-op/unary-reader :float64 (* x x)) (reduce-op/iterable-reduce :float64 (+ accum next)))) (defn- desc-stats-sum-of-logs ^double [^DescriptiveStatistics stats] (->> (.getSortedValues stats) (unary-op/unary-reader :float64 (Math/log x)) (reduce-op/commutative-reduce :float64 (+ accum next)))) (defn- desc-stats-product ^double [^DescriptiveStatistics stats] (->> (.getSortedValues stats) (reduce-op/commutative-reduce :float64 (* accum next)))) (def supported-stats-map {:mean #(.getMean ^DescriptiveStatistics %) :min #(.getMin ^DescriptiveStatistics %) :max #(.getMax ^DescriptiveStatistics %) :median #(.getPercentile ^DescriptiveStatistics % 50.0) :variance #(.getVariance ^DescriptiveStatistics %) :skew #(.getSkewness ^DescriptiveStatistics %) :kurtosis #(.getKurtosis ^DescriptiveStatistics %) :geometric-mean #(.getGeometricMean ^DescriptiveStatistics %) :sum-of-squares desc-stats-sum-of-squares :sum-of-logs desc-stats-sum-of-logs :quadratic-mean #(.getQuadraticMean ^DescriptiveStatistics %) :standard-deviation #(.getStandardDeviation ^DescriptiveStatistics %) :variance-population #(.getPopulationVariance ^DescriptiveStatistics %) :sum #(.getSum ^DescriptiveStatistics %) :product desc-stats-product :quartile-1 #(.getPercentile ^DescriptiveStatistics % 25.0) :quartile-3 #(.getPercentile ^DescriptiveStatistics % 75.0) :ecount #(.getN ^DescriptiveStatistics %) }) (defn supported-descriptive-stats [] (keys supported-stats-map)) (defn descriptive-stats "Generate descriptive statistics for a particular item." [item & [stats-set]] (let [stats-set (set (or stats-set [:mean :median :min :max :ecount :standard-deviation :skew])) stats-desc (DescriptiveStatistics. (dtype-base/->double-array item))] (->> stats-set (map (fn [stats-key] (if-let [supported-stat (get supported-stats-map stats-key)] [stats-key (supported-stat stats-desc)] (throw (ex-info (format "Unsupported statistic: %s" stats-key) {}))))) (into {})))) (defn percentile "Get the nth percentile. Percent ranges from 0-100." [item percent] (-> (DescriptiveStatistics. (dtype-base/->double-array item)) (.getPercentile (double percent)))) (defmacro define-supported-stats-oneoffs [] `(do ~@(->> (supported-descriptive-stats) (map (fn [stat-name] `(defn ~(symbol (name stat-name)) ~(format "Supported stat %s" (name stat-name)) [~'item] (-> (descriptive-stats ~'item [~stat-name]) ~stat-name))))))) (define-supported-stats-oneoffs) (defn- kixi-apply [kixi-fn item] (transduce identity kixi-fn (or (dtype-proto/as-reader item) (dtype-proto/as-iterable item)))) (defn harmonic-mean [item] (kixi-apply kixi/harmonic-mean item)) (defn standard-deviation-population [item] (kixi-apply kixi/standard-deviation-p item)) (defn standard-error [item] (kixi-apply kixi/standard-error item)) (defn skewness [item] (skew item)) (defn skewness-population [item] (kixi-apply kixi/skewness-p item)) (defn kurtosis [item] (kixi-apply kixi/kurtosis item)) (defn kurtosis-population [item] (kixi-apply kixi/kurtosis-p item)) (defn pearsons-correlation [lhs rhs] (-> (PearsonsCorrelation.) (.correlation (dtype-base/->double-array lhs) (dtype-base/->double-array rhs)))) (defn spearmans-correlation [lhs rhs] (-> (SpearmansCorrelation.) (.correlation (dtype-base/->double-array lhs) (dtype-base/->double-array rhs)))) (defn kendalls-correlation [lhs rhs] (-> (KendallsCorrelation.) (.correlation (dtype-base/->double-array lhs) (dtype-base/->double-array rhs)))) (defn quartiles "return [min, 25 50 75 max] of item" [item] (let [stats (DescriptiveStatistics. (dtype-base/->double-array item))] [(.getMin stats) (.getPercentile stats 25.0) (.getPercentile stats 50.0) (.getPercentile stats 75.0) (.getMax stats)])) (defn quartile-outlier-fn "Create a function that, given floating point data, will return true or false if that data is an outlier. Default range mult is 1.5: (or (< val (- q1 (* range-mult iqr))) (> val (+ q3 (* range-mult iqr)))" [item & [range-mult]] (let [[_ q1 _ q3 _] (quartiles item) q1 (double q1) q3 (double q3) iqr (- q3 q1) range-mult (double (or range-mult 1.5))] (boolean-op/make-float-double-boolean-unary-op (or (< x (- q1 (* range-mult iqr))) (> x (+ q3 (* range-mult iqr)))))))
ee68a037f27d2af0e4cf9eda54abcc825a6b516c26f4e679ed4ca479113bb87b
peterholko/pax_server
game_loop.erl
Author : Created : Dec 27 , 2008 %% Description: TODO: Add description to game_loop -module(game_loop). %% %% Include files %% -include("common.hrl"). -include("game.hrl"). %% %% Exported Functions %% -export([loop/2]). %% %% API Functions %% loop(LastTime, GamePID) -> %StartLoopTime = util:get_time(), CurrentTick = gen_server:call(GamePID, 'GET_TICK'), EventList = gen_server:call(GamePID, 'GET_EVENTS'), UpdatePerceptions = gen_server:call(GamePID, 'GET_UPDATE_PERCEPTION'), %Process events process_events(GamePID, CurrentTick, EventList), %Build simple perception perceptions(EntityList , ObjectList ) , %Send perceptions send_perceptions(UpdatePerceptions), clear_perceptions(GamePID), gen_server:cast(GamePID, 'NEXT_TICK'), CurrentTime = util:get_time(), CalcSleepTime = LastTime - CurrentTime + ?GAME_LOOP_TICK, if CalcSleepTime =< 0 -> NextTime = LastTime + ?GAME_LOOP_TICK * 4, SleepTime = 1; true -> NextTime = LastTime + ?GAME_LOOP_TICK, SleepTime = CalcSleepTime end, timer:sleep(SleepTime), = util : get_time ( ) , io : fwrite("game_loop - StartLoopTime : ~w CurrentTime : ~w EndTime : ~w SleepTime : ~w LastTime : ~w ~ n " , [ StartLoopTime , CurrentTime , , SleepTime , LastTime ] ) , log4erl:debug("End loop"), loop(NextTime, GamePID). %% %% Local Functions %% process_events(_, _, []) -> ok; process_events(GamePID, CurrentTick, EventList) -> [Event | Rest] = EventList, {EventId, Pid, Type, EventData, EventTick} = Event, if CurrentTick =:= EventTick -> gen_server:cast(Pid, {'PROCESS_EVENT', EventTick, EventData, Type}), gen_server:cast(GamePID, {'DELETE_EVENT', EventId}); true -> ok end, process_events(GamePID, CurrentTick, Rest). send_perceptions([]) -> ok; send_perceptions(UpdatePerception) -> [PlayerId | Rest] = UpdatePerception, PlayerPid = global:whereis_name({player,PlayerId}), case is_pid(PlayerPid) of true -> gen_server:cast(PlayerPid, {'SEND_PERCEPTION'}); false -> ok end, send_perceptions(Rest). clear_perceptions(GamePID) -> gen_server:cast(GamePID, 'CLEAR_PERCEPTIONS').
null
https://raw.githubusercontent.com/peterholko/pax_server/62b2ec1fae195ff915d19af06e56a7c4567fd4b8/src/game_loop.erl
erlang
Description: TODO: Add description to game_loop Include files Exported Functions API Functions StartLoopTime = util:get_time(), Process events Build simple perception Send perceptions Local Functions
Author : Created : Dec 27 , 2008 -module(game_loop). -include("common.hrl"). -include("game.hrl"). -export([loop/2]). loop(LastTime, GamePID) -> CurrentTick = gen_server:call(GamePID, 'GET_TICK'), EventList = gen_server:call(GamePID, 'GET_EVENTS'), UpdatePerceptions = gen_server:call(GamePID, 'GET_UPDATE_PERCEPTION'), process_events(GamePID, CurrentTick, EventList), perceptions(EntityList , ObjectList ) , send_perceptions(UpdatePerceptions), clear_perceptions(GamePID), gen_server:cast(GamePID, 'NEXT_TICK'), CurrentTime = util:get_time(), CalcSleepTime = LastTime - CurrentTime + ?GAME_LOOP_TICK, if CalcSleepTime =< 0 -> NextTime = LastTime + ?GAME_LOOP_TICK * 4, SleepTime = 1; true -> NextTime = LastTime + ?GAME_LOOP_TICK, SleepTime = CalcSleepTime end, timer:sleep(SleepTime), = util : get_time ( ) , io : fwrite("game_loop - StartLoopTime : ~w CurrentTime : ~w EndTime : ~w SleepTime : ~w LastTime : ~w ~ n " , [ StartLoopTime , CurrentTime , , SleepTime , LastTime ] ) , log4erl:debug("End loop"), loop(NextTime, GamePID). process_events(_, _, []) -> ok; process_events(GamePID, CurrentTick, EventList) -> [Event | Rest] = EventList, {EventId, Pid, Type, EventData, EventTick} = Event, if CurrentTick =:= EventTick -> gen_server:cast(Pid, {'PROCESS_EVENT', EventTick, EventData, Type}), gen_server:cast(GamePID, {'DELETE_EVENT', EventId}); true -> ok end, process_events(GamePID, CurrentTick, Rest). send_perceptions([]) -> ok; send_perceptions(UpdatePerception) -> [PlayerId | Rest] = UpdatePerception, PlayerPid = global:whereis_name({player,PlayerId}), case is_pid(PlayerPid) of true -> gen_server:cast(PlayerPid, {'SEND_PERCEPTION'}); false -> ok end, send_perceptions(Rest). clear_perceptions(GamePID) -> gen_server:cast(GamePID, 'CLEAR_PERCEPTIONS').
936fab4ebb8c24944a5dbc2194530b17fe5fd34fb87881486cafdbae949024a5
rtoy/cmucl
iso8859-4.lisp
;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: STREAM -*- ;;; ;;; ********************************************************************** This code was written by and has been placed in the public ;;; domain. ;;; (ext:file-comment "$Header: src/pcl/simple-streams/external-formats/iso8859-4.lisp $") (in-package "STREAM") (intl:textdomain "cmucl") (defconstant +iso-8859-4+ (make-array 96 :element-type '(unsigned-byte 16) :initial-contents #(160 260 312 342 164 296 315 167 168 352 274 290 358 173 381 175 176 261 731 343 180 297 316 711 184 353 275 291 359 330 382 331 256 193 194 195 196 197 198 302 268 201 280 203 278 205 206 298 272 325 332 310 212 213 214 215 216 370 218 219 220 360 362 223 257 225 226 227 228 229 230 303 269 233 281 235 279 237 238 299 273 326 333 311 244 245 246 247 248 371 250 251 252 361 363 729))) (define-external-format :iso8859-4 (:base :iso8859-2 :documentation "ISO8859-4 is an 8-bit character encoding for North European languages including Estonian, Latvian, Lithuanian, Greenlandic, and Sami. By default, illegal inputs are replaced by the Unicode replacement character and illegal outputs are replaced by a question mark.") ((table +iso-8859-4+)))
null
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/pcl/simple-streams/external-formats/iso8859-4.lisp
lisp
-*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: STREAM -*- ********************************************************************** domain.
This code was written by and has been placed in the public (ext:file-comment "$Header: src/pcl/simple-streams/external-formats/iso8859-4.lisp $") (in-package "STREAM") (intl:textdomain "cmucl") (defconstant +iso-8859-4+ (make-array 96 :element-type '(unsigned-byte 16) :initial-contents #(160 260 312 342 164 296 315 167 168 352 274 290 358 173 381 175 176 261 731 343 180 297 316 711 184 353 275 291 359 330 382 331 256 193 194 195 196 197 198 302 268 201 280 203 278 205 206 298 272 325 332 310 212 213 214 215 216 370 218 219 220 360 362 223 257 225 226 227 228 229 230 303 269 233 281 235 279 237 238 299 273 326 333 311 244 245 246 247 248 371 250 251 252 361 363 729))) (define-external-format :iso8859-4 (:base :iso8859-2 :documentation "ISO8859-4 is an 8-bit character encoding for North European languages including Estonian, Latvian, Lithuanian, Greenlandic, and Sami. By default, illegal inputs are replaced by the Unicode replacement character and illegal outputs are replaced by a question mark.") ((table +iso-8859-4+)))
965fc04f732c49f1ad9193bd4523b460aa18ea848944a0fc64da55dfa2946601
granule-project/gerty
Pretty.hs
# LANGUAGE FlexibleInstances # {-# LANGUAGE TypeSynonymInstances #-} module Language.Gerty.Util.Pretty ( module Text.PrettyPrint.Annotated , Pretty(..) , Doc , pprintParened , pprintShow , pprintShowWithOpts , RenderOptions(..) , defaultRenderOptions -- * Helpers , identifier , pprintList , pprintPair , quoted , angles , bold , red , green ) where import Data.Int import Prelude hiding ((<>)) import Text.PrettyPrint.Annotated hiding (Doc) import qualified Text.PrettyPrint.Annotated as P import Text.PrettyPrint.Annotated.HughesPJ (AnnotDetails(..)) ----------------- -- Annotations -- ----------------- data Annot = AnnotIdentNum Integer data RenderOptions = RenderOptions { showIdentNumbers :: Bool } defaultRenderOptions :: RenderOptions defaultRenderOptions = RenderOptions { showIdentNumbers = False } type Doc = P.Doc Annot --------------------- -- Pretty-printing -- --------------------- pprintParened :: Pretty t => t -> Doc pprintParened t = (if isLexicallyAtomic t then id else parens) $ pprint t pprintShow :: Pretty t => t -> String pprintShow = pprintShowWithOpts defaultRenderOptions -- | Pretty-print a value to a string, with options. pprintShowWithOpts :: Pretty t => RenderOptions -> t -> String pprintShowWithOpts opts = fullRenderAnn (mode style) (lineLength style) (ribbonsPerLine style) (printer opts) "" . pprint printer :: RenderOptions -> AnnotDetails Annot -> String -> String -- this is an identifier attachment printer opts (AnnotEnd (AnnotIdentNum n)) s = if showIdentNumbers opts then "`" ++ show n ++ s else s printer _opts AnnotStart s = s printer _opts (NoAnnot t _) s = txtPrinter t s -- | Default TextDetails printer (from -1.1.3.6/docs/src/Text.PrettyPrint.Annotated.HughesPJ.html#txtPrinter). txtPrinter :: TextDetails -> String -> String txtPrinter (Chr c) s = c:s txtPrinter (Str s1) s2 = s1 ++ s2 txtPrinter (PStr s1) s2 = s1 ++ s2 class Pretty a where -- | Does the component (not) need wrapping in delimiters to disambiguate -- | it from the surrounding environment? -- | -- | The default is that no components are lexically atomic. isLexicallyAtomic :: a -> Bool isLexicallyAtomic _ = False pprint :: a -> Doc instance Pretty Int32 where pprint = text . show instance Pretty Int where pprint = text . show instance Pretty String where pprint = text instance Pretty Doc where pprint = id ------------------- ----- Helpers ----- ------------------- quoted :: (Pretty a) => a -> Doc quoted = quotes . pprint -- | Pretty-print a value inside angle brackets. angles :: (Pretty a) => a -> Doc angles p = char '<' <> pprint p <> char '>' -- | Pretty-print an identifier. identifier :: (Pretty a) => Integer -> a -> Doc identifier gid n = annotate (AnnotIdentNum gid) (pprint n) pprintList :: (Pretty a) => [a] -> Doc pprintList = brackets . hsep . punctuate comma . fmap pprint pprintPair :: (Pretty a, Pretty b) => (a, b) -> Doc pprintPair (x, y) = parens ((pprint x <> comma) <+> pprint y) withAnsi :: Doc -> Doc -> Doc withAnsi ansiCode doc = ansiCode <> doc <> ansiReset bold, red, green :: Doc -> Doc bold = withAnsi ansiBold red = withAnsi ansiRed green = withAnsi ansiGreen ansiReset, ansiBold, ansiRed, ansiGreen :: Doc ansiReset = "\x1b[0m" ansiBold = "\x1b[1m" ansiRed = "\x1b[31m" ansiGreen = "\x1b[32m"
null
https://raw.githubusercontent.com/granule-project/gerty/972fa027973032a4499747039b45e744ca17e9e2/src/Language/Gerty/Util/Pretty.hs
haskell
# LANGUAGE TypeSynonymInstances # * Helpers --------------- Annotations -- --------------- ------------------- Pretty-printing -- ------------------- | Pretty-print a value to a string, with options. this is an identifier attachment | Default TextDetails printer (from -1.1.3.6/docs/src/Text.PrettyPrint.Annotated.HughesPJ.html#txtPrinter). | Does the component (not) need wrapping in delimiters to disambiguate | it from the surrounding environment? | | The default is that no components are lexically atomic. ----------------- --- Helpers ----- ----------------- | Pretty-print a value inside angle brackets. | Pretty-print an identifier.
# LANGUAGE FlexibleInstances # module Language.Gerty.Util.Pretty ( module Text.PrettyPrint.Annotated , Pretty(..) , Doc , pprintParened , pprintShow , pprintShowWithOpts , RenderOptions(..) , defaultRenderOptions , identifier , pprintList , pprintPair , quoted , angles , bold , red , green ) where import Data.Int import Prelude hiding ((<>)) import Text.PrettyPrint.Annotated hiding (Doc) import qualified Text.PrettyPrint.Annotated as P import Text.PrettyPrint.Annotated.HughesPJ (AnnotDetails(..)) data Annot = AnnotIdentNum Integer data RenderOptions = RenderOptions { showIdentNumbers :: Bool } defaultRenderOptions :: RenderOptions defaultRenderOptions = RenderOptions { showIdentNumbers = False } type Doc = P.Doc Annot pprintParened :: Pretty t => t -> Doc pprintParened t = (if isLexicallyAtomic t then id else parens) $ pprint t pprintShow :: Pretty t => t -> String pprintShow = pprintShowWithOpts defaultRenderOptions pprintShowWithOpts :: Pretty t => RenderOptions -> t -> String pprintShowWithOpts opts = fullRenderAnn (mode style) (lineLength style) (ribbonsPerLine style) (printer opts) "" . pprint printer :: RenderOptions -> AnnotDetails Annot -> String -> String printer opts (AnnotEnd (AnnotIdentNum n)) s = if showIdentNumbers opts then "`" ++ show n ++ s else s printer _opts AnnotStart s = s printer _opts (NoAnnot t _) s = txtPrinter t s txtPrinter :: TextDetails -> String -> String txtPrinter (Chr c) s = c:s txtPrinter (Str s1) s2 = s1 ++ s2 txtPrinter (PStr s1) s2 = s1 ++ s2 class Pretty a where isLexicallyAtomic :: a -> Bool isLexicallyAtomic _ = False pprint :: a -> Doc instance Pretty Int32 where pprint = text . show instance Pretty Int where pprint = text . show instance Pretty String where pprint = text instance Pretty Doc where pprint = id quoted :: (Pretty a) => a -> Doc quoted = quotes . pprint angles :: (Pretty a) => a -> Doc angles p = char '<' <> pprint p <> char '>' identifier :: (Pretty a) => Integer -> a -> Doc identifier gid n = annotate (AnnotIdentNum gid) (pprint n) pprintList :: (Pretty a) => [a] -> Doc pprintList = brackets . hsep . punctuate comma . fmap pprint pprintPair :: (Pretty a, Pretty b) => (a, b) -> Doc pprintPair (x, y) = parens ((pprint x <> comma) <+> pprint y) withAnsi :: Doc -> Doc -> Doc withAnsi ansiCode doc = ansiCode <> doc <> ansiReset bold, red, green :: Doc -> Doc bold = withAnsi ansiBold red = withAnsi ansiRed green = withAnsi ansiGreen ansiReset, ansiBold, ansiRed, ansiGreen :: Doc ansiReset = "\x1b[0m" ansiBold = "\x1b[1m" ansiRed = "\x1b[31m" ansiGreen = "\x1b[32m"
61bc4ea20e1e1a790fc53bddbb0d2c52a32156f485c8c195a13618ad5e473695
input-output-hk/project-icarus-importer
Main.hs
{-# LANGUAGE FlexibleContexts #-} # LANGUAGE GADTs # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # module Main where import Universum import Control.Concurrent.STM (newTQueueIO) import Data.Default (def) import Data.Maybe (fromJust, isJust) import Mockable (Production, runProduction) import qualified Network.Transport.TCP as TCP import Options.Generic (getRecord) import Pos.Client.CLI (CommonArgs (..), CommonNodeArgs (..), NodeArgs (..), getNodeParams, gtSscParams) import Pos.Core (Timestamp (..)) import Pos.DB.DB (initNodeDBs) import Pos.DB.Rocks.Functions (openNodeDBs) import Pos.DB.Rocks.Types (NodeDBs) import Pos.Launcher (ConfigurationOptions (..), HasConfigurations, NodeResources (..), bracketNodeResources, defaultConfigurationOptions, npBehaviorConfig, npUserSecret, withConfigurations) import Pos.Network.CLI (NetworkConfigOpts (..)) import Pos.Network.Types (NetworkConfig (..), Topology (..), topologyDequeuePolicy, topologyEnqueuePolicy, topologyFailurePolicy) import Pos.Txp (txpGlobalSettings) import Pos.Util.CompileInfo (HasCompileInfo, retrieveCompileTimeInfo, withCompileInfo) import Pos.Util.JsonLog.Events (jsonLogConfigFromHandle) import Pos.Util.UserSecret (usVss) import Pos.Wallet.Web.Mode (WalletWebModeContext (..)) import Pos.Wallet.Web.State.Acidic (closeState, openState) import Pos.Wallet.Web.State.State (WalletDB) import Pos.WorkMode (RealModeContext (..)) import Serokell.Util (sec) import System.Wlog (HasLoggerName (..), LoggerName (..)) import CLI (CLI (..)) import Lib (generateWalletDB, loadGenSpec) import Rendering (bold, say) import Stats (showStatsAndExit, showStatsData) import Types (UberMonad) defaultNetworkConfig :: Topology kademlia -> NetworkConfig kademlia defaultNetworkConfig ncTopology = NetworkConfig { ncDefaultPort = 3000 , ncSelfName = Nothing , ncEnqueuePolicy = topologyEnqueuePolicy ncTopology , ncDequeuePolicy = topologyDequeuePolicy ncTopology , ncFailurePolicy = topologyFailurePolicy ncTopology , ncTcpAddr = TCP.Unaddressable , .. } newRealModeContext :: HasConfigurations => NodeDBs -> ConfigurationOptions -> FilePath -> Production (RealModeContext ()) newRealModeContext dbs confOpts secretKeyPath = do let nodeArgs = NodeArgs { behaviorConfigPath = Nothing } let networkOps = NetworkConfigOpts { ncoTopology = Nothing , ncoKademlia = Nothing , ncoSelf = Nothing , ncoPort = 3030 , ncoPolicies = Nothing , ncoBindAddress = Nothing , ncoExternalAddress = Nothing } let cArgs@CommonNodeArgs {..} = CommonNodeArgs { dbPath = Just "node-db" , rebuildDB = True , devGenesisSecretI = Nothing , keyfilePath = secretKeyPath , networkConfigOpts = networkOps , jlPath = Nothing , commonArgs = CommonArgs { logConfig = Nothing , logPrefix = Nothing , reportServers = mempty , updateServers = mempty , configurationOptions = confOpts } , updateLatestPath = "update" , updateWithPackage = False , route53Params = Nothing , enableMetrics = False , ekgParams = Nothing , statsdParams = Nothing , cnaDumpGenesisDataPath = Nothing , cnaDumpConfiguration = False } loggerName <- askLoggerName nodeParams <- getNodeParams loggerName cArgs nodeArgs let vssSK = fromJust $ npUserSecret nodeParams ^. usVss let gtParams = gtSscParams cArgs vssSK (npBehaviorConfig nodeParams) bracketNodeResources @() nodeParams gtParams txpGlobalSettings initNodeDBs $ \NodeResources{..} -> RealModeContext <$> pure dbs <*> pure nrSscState <*> pure nrTxpState <*> pure nrDlgState <*> jsonLogConfigFromHandle stdout <*> pure (LoggerName "dbgen") <*> pure nrContext < * > initQueue ( defaultNetworkConfig ( TopologyAuxx mempty ) ) Nothing walletRunner :: (HasConfigurations, HasCompileInfo) => ConfigurationOptions -> NodeDBs -> FilePath -> WalletDB -> UberMonad a -> IO a walletRunner confOpts dbs secretKeyPath ws act = runProduction $ do wwmc <- WalletWebModeContext <$> pure ws <*> newTVarIO def <*> liftIO newTQueueIO <*> newRealModeContext dbs confOpts secretKeyPath runReaderT act wwmc newWalletState :: (MonadIO m, HasConfigurations) => Bool -> FilePath -> m WalletDB newWalletState recreate walletPath = -- If the user passed the `--add-to` option, it means we don't have to rebuild the DB , but rather append stuff into it . liftIO $ openState (not recreate) walletPath instance HasLoggerName IO where askLoggerName = pure $ LoggerName "dbgen" modifyLoggerName _ x = x TODO(ks ): Fix according to Pos . Client . CLI.Options newConfig :: CLI -> ConfigurationOptions newConfig CLI{..} = defaultConfigurationOptions { cfoSystemStart = Timestamp . sec <$> systemStart , cfoFilePath = configurationPath , cfoKey = toText configurationProf } -- stack exec dbgen -- --config ./tools/src/dbgen/config.json --nodeDB db-mainnet --walletDB wdb-mainnet --configPath node/configuration.yaml --secretKey secret-mainnet.key --configProf mainnet_full main :: IO () main = do cli@CLI{..} <- getRecord "DBGen" let cfg = newConfig cli withConfigurations cfg $ \_ -> withCompileInfo $(retrieveCompileTimeInfo) $ do when showStats (showStatsAndExit walletPath) say $ bold "Starting the modification of the wallet..." showStatsData "before" walletPath dbs <- openNodeDBs False nodePath -- Do not recreate! spec <- loadGenSpec config Recreate or not let generatedWallet = generateWalletDB cli spec walletRunner cfg dbs secretKeyPath ws generatedWallet closeState ws showStatsData "after" walletPath
null
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/tools/src/dbgen/Main.hs
haskell
# LANGUAGE FlexibleContexts # # LANGUAGE RankNTypes # If the user passed the `--add-to` option, it means we don't have stack exec dbgen -- --config ./tools/src/dbgen/config.json --nodeDB db-mainnet --walletDB wdb-mainnet --configPath node/configuration.yaml --secretKey secret-mainnet.key --configProf mainnet_full Do not recreate!
# LANGUAGE GADTs # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # module Main where import Universum import Control.Concurrent.STM (newTQueueIO) import Data.Default (def) import Data.Maybe (fromJust, isJust) import Mockable (Production, runProduction) import qualified Network.Transport.TCP as TCP import Options.Generic (getRecord) import Pos.Client.CLI (CommonArgs (..), CommonNodeArgs (..), NodeArgs (..), getNodeParams, gtSscParams) import Pos.Core (Timestamp (..)) import Pos.DB.DB (initNodeDBs) import Pos.DB.Rocks.Functions (openNodeDBs) import Pos.DB.Rocks.Types (NodeDBs) import Pos.Launcher (ConfigurationOptions (..), HasConfigurations, NodeResources (..), bracketNodeResources, defaultConfigurationOptions, npBehaviorConfig, npUserSecret, withConfigurations) import Pos.Network.CLI (NetworkConfigOpts (..)) import Pos.Network.Types (NetworkConfig (..), Topology (..), topologyDequeuePolicy, topologyEnqueuePolicy, topologyFailurePolicy) import Pos.Txp (txpGlobalSettings) import Pos.Util.CompileInfo (HasCompileInfo, retrieveCompileTimeInfo, withCompileInfo) import Pos.Util.JsonLog.Events (jsonLogConfigFromHandle) import Pos.Util.UserSecret (usVss) import Pos.Wallet.Web.Mode (WalletWebModeContext (..)) import Pos.Wallet.Web.State.Acidic (closeState, openState) import Pos.Wallet.Web.State.State (WalletDB) import Pos.WorkMode (RealModeContext (..)) import Serokell.Util (sec) import System.Wlog (HasLoggerName (..), LoggerName (..)) import CLI (CLI (..)) import Lib (generateWalletDB, loadGenSpec) import Rendering (bold, say) import Stats (showStatsAndExit, showStatsData) import Types (UberMonad) defaultNetworkConfig :: Topology kademlia -> NetworkConfig kademlia defaultNetworkConfig ncTopology = NetworkConfig { ncDefaultPort = 3000 , ncSelfName = Nothing , ncEnqueuePolicy = topologyEnqueuePolicy ncTopology , ncDequeuePolicy = topologyDequeuePolicy ncTopology , ncFailurePolicy = topologyFailurePolicy ncTopology , ncTcpAddr = TCP.Unaddressable , .. } newRealModeContext :: HasConfigurations => NodeDBs -> ConfigurationOptions -> FilePath -> Production (RealModeContext ()) newRealModeContext dbs confOpts secretKeyPath = do let nodeArgs = NodeArgs { behaviorConfigPath = Nothing } let networkOps = NetworkConfigOpts { ncoTopology = Nothing , ncoKademlia = Nothing , ncoSelf = Nothing , ncoPort = 3030 , ncoPolicies = Nothing , ncoBindAddress = Nothing , ncoExternalAddress = Nothing } let cArgs@CommonNodeArgs {..} = CommonNodeArgs { dbPath = Just "node-db" , rebuildDB = True , devGenesisSecretI = Nothing , keyfilePath = secretKeyPath , networkConfigOpts = networkOps , jlPath = Nothing , commonArgs = CommonArgs { logConfig = Nothing , logPrefix = Nothing , reportServers = mempty , updateServers = mempty , configurationOptions = confOpts } , updateLatestPath = "update" , updateWithPackage = False , route53Params = Nothing , enableMetrics = False , ekgParams = Nothing , statsdParams = Nothing , cnaDumpGenesisDataPath = Nothing , cnaDumpConfiguration = False } loggerName <- askLoggerName nodeParams <- getNodeParams loggerName cArgs nodeArgs let vssSK = fromJust $ npUserSecret nodeParams ^. usVss let gtParams = gtSscParams cArgs vssSK (npBehaviorConfig nodeParams) bracketNodeResources @() nodeParams gtParams txpGlobalSettings initNodeDBs $ \NodeResources{..} -> RealModeContext <$> pure dbs <*> pure nrSscState <*> pure nrTxpState <*> pure nrDlgState <*> jsonLogConfigFromHandle stdout <*> pure (LoggerName "dbgen") <*> pure nrContext < * > initQueue ( defaultNetworkConfig ( TopologyAuxx mempty ) ) Nothing walletRunner :: (HasConfigurations, HasCompileInfo) => ConfigurationOptions -> NodeDBs -> FilePath -> WalletDB -> UberMonad a -> IO a walletRunner confOpts dbs secretKeyPath ws act = runProduction $ do wwmc <- WalletWebModeContext <$> pure ws <*> newTVarIO def <*> liftIO newTQueueIO <*> newRealModeContext dbs confOpts secretKeyPath runReaderT act wwmc newWalletState :: (MonadIO m, HasConfigurations) => Bool -> FilePath -> m WalletDB newWalletState recreate walletPath = to rebuild the DB , but rather append stuff into it . liftIO $ openState (not recreate) walletPath instance HasLoggerName IO where askLoggerName = pure $ LoggerName "dbgen" modifyLoggerName _ x = x TODO(ks ): Fix according to Pos . Client . CLI.Options newConfig :: CLI -> ConfigurationOptions newConfig CLI{..} = defaultConfigurationOptions { cfoSystemStart = Timestamp . sec <$> systemStart , cfoFilePath = configurationPath , cfoKey = toText configurationProf } main :: IO () main = do cli@CLI{..} <- getRecord "DBGen" let cfg = newConfig cli withConfigurations cfg $ \_ -> withCompileInfo $(retrieveCompileTimeInfo) $ do when showStats (showStatsAndExit walletPath) say $ bold "Starting the modification of the wallet..." showStatsData "before" walletPath spec <- loadGenSpec config Recreate or not let generatedWallet = generateWalletDB cli spec walletRunner cfg dbs secretKeyPath ws generatedWallet closeState ws showStatsData "after" walletPath
ecf3023cf02a0d09ff9c7649ee70f22508d982935f8b2bc0f1e05dae87393096
EasyCrypt/easycrypt
ecEnv.ml
(* -------------------------------------------------------------------- *) open EcUtils open EcSymbols open EcPath open EcTypes open EcCoreFol open EcMemory open EcDecl open EcModules open EcTheory open EcBaseLogic (* -------------------------------------------------------------------- *) module Ssym = EcSymbols.Ssym module Msym = EcSymbols.Msym module Mp = EcPath.Mp module Sid = EcIdent.Sid module Mid = EcIdent.Mid module TC = EcTypeClass module Mint = EcMaps.Mint (* -------------------------------------------------------------------- *) type 'a suspension = { sp_target : 'a; sp_params : int * (EcIdent.t * module_type) list; } (* -------------------------------------------------------------------- *) let check_not_suspended (params, obj) = if not (List.for_all (fun x -> x = None) params) then assert false; obj (* -------------------------------------------------------------------- *) (* Paths as stored in the environment: * - Either a full path (sequence of symbols) * - Either a ident (module variable) followed by a optional path (inner path) * * No functor applications are present in these paths. *) type ipath = | IPPath of EcPath.path | IPIdent of EcIdent.t * EcPath.path option let ibasename p = match p with | IPPath p -> EcPath.basename p | IPIdent (m, None) -> EcIdent.name m | IPIdent (_, Some p) -> EcPath.basename p module IPathC = struct type t = ipath let compare p1 p2 = match p1, p2 with | IPIdent _, IPPath _ -> -1 | IPPath _, IPIdent _ -> 1 | IPIdent (i1, p1), IPIdent (i2, p2) -> begin match EcIdent.id_compare i1 i2 with | 0 -> ocompare EcPath.p_compare p1 p2 | i -> i end | IPPath p1, IPPath p2 -> EcPath.p_compare p1 p2 end module Mip = EcMaps.Map.Make(IPathC) module Sip = EcMaps.Set.MakeOfMap(Mip) let ippath_as_path (ip : ipath) = match ip with IPPath p -> p | _ -> assert false type glob_var_bind = EcTypes.ty type mc = { mc_parameters : ((EcIdent.t * module_type) list) option; mc_variables : (ipath * glob_var_bind) MMsym.t; mc_functions : (ipath * function_) MMsym.t; mc_modules : (ipath * (module_expr * locality option)) MMsym.t; mc_modsigs : (ipath * top_module_sig) MMsym.t; mc_tydecls : (ipath * EcDecl.tydecl) MMsym.t; mc_operators : (ipath * EcDecl.operator) MMsym.t; mc_axioms : (ipath * EcDecl.axiom) MMsym.t; mc_schemas : (ipath * EcDecl.ax_schema) MMsym.t; mc_theories : (ipath * ctheory) MMsym.t; mc_typeclasses: (ipath * typeclass) MMsym.t; mc_rwbase : (ipath * path) MMsym.t; mc_components : ipath MMsym.t; } type use = { us_pv : ty Mx.t; us_gl : Sid.t; } let use_union us1 us2 = { us_pv = Mx.union (fun _ ty _ -> Some ty) us1.us_pv us2.us_pv; us_gl = Sid.union us1.us_gl us2.us_gl; } let use_empty = { us_pv = Mx.empty; us_gl = Sid.empty; } type env_norm = { norm_mp : EcPath.mpath Mm.t; norm_xpv : EcPath.xpath Mx.t; (* for global program variable *) norm_xfun : EcPath.xpath Mx.t; (* for fun and local program variable *) mod_use : use Mm.t; get_restr_use : (use EcModules.use_restr) Mm.t; } (* -------------------------------------------------------------------- *) type red_topsym = [ | `Path of path | `Tuple | `Cost of [`Path of path | `Tuple] ] module Mrd = EcMaps.Map.Make(struct type t = red_topsym let rec compare (p1 : t) (p2 : t) = match p1, p2 with | `Path p1, `Path p2 -> EcPath.p_compare p1 p2 | `Tuple , `Tuple -> 0 | `Cost p1, `Cost p2 -> compare (p1 :> red_topsym) (p2 :> red_topsym) | `Tuple , `Path _ | `Cost _ , `Path _ | `Cost _ , `Tuple -> -1 | `Path _ , `Tuple | `Path _ , `Cost _ | `Tuple , `Cost _ -> 1 end) (* -------------------------------------------------------------------- *) module Mmem : sig type 'a t val empty : 'a t val all : 'a t -> (EcIdent.t * 'a) list val byid : EcIdent.t -> 'a t -> 'a val bysym : EcSymbols.symbol -> 'a t -> EcIdent.t * 'a val add : EcIdent.t -> 'a -> 'a t -> 'a t end = struct type 'a t = { m_s : memory Msym.t; m_id : 'a Mid.t; } let empty = { m_s = Msym.empty; m_id = Mid.empty; } let all m = Mid.bindings m.m_id let byid id m = Mid.find id m.m_id let bysym s m = let id = Msym.find s m.m_s in id, byid id m let add id a m = { m_s = Msym.add (EcIdent.name id) id m.m_s; m_id = Mid.add id a m.m_id } end (* -------------------------------------------------------------------- *) type preenv = { env_top : EcPath.path option; env_gstate : EcGState.gstate; env_scope : escope; env_current : mc; env_comps : mc Mip.t; env_locals : (EcIdent.t * EcTypes.ty) MMsym.t; env_memories : EcMemory.memtype Mmem.t; env_actmem : EcMemory.memory option; env_abs_st : EcModules.abs_uses Mid.t; env_tci : ((ty_params * ty) * tcinstance) list; env_tc : TC.graph; env_rwbase : Sp.t Mip.t; env_atbase : (path list Mint.t) Msym.t; env_redbase : mredinfo; env_ntbase : (path * env_notation) list; env_modlcs : Sid.t; (* declared modules *) env_item : theory_item list; (* in reverse order *) env_norm : env_norm ref; } and escope = { ec_path : EcPath.path; ec_scope : scope; } and scope = [ | `Theory | `Module of EcPath.mpath | `Fun of EcPath.xpath ] and tcinstance = [ | `Ring of EcDecl.ring | `Field of EcDecl.field | `General of EcPath.path ] and redinfo = { ri_priomap : (EcTheory.rule list) Mint.t; ri_list : (EcTheory.rule list) Lazy.t; } and mredinfo = redinfo Mrd.t and env_notation = ty_params * EcDecl.notation (* -------------------------------------------------------------------- *) type env = preenv (* -------------------------------------------------------------------- *) let root (env : env) = env.env_scope.ec_path let mroot (env : env) = match env.env_scope.ec_scope with | `Theory -> EcPath.mpath_crt (root env) [] None | `Module m -> m | `Fun x -> x.EcPath.x_top let xroot (env : env) = match env.env_scope.ec_scope with | `Fun x -> Some x | _ -> None let scope (env : env) = env.env_scope.ec_scope (* -------------------------------------------------------------------- *) let astop (env : env) = { env with env_top = Some (root env); } (* -------------------------------------------------------------------- *) let gstate (env : env) = env.env_gstate (* -------------------------------------------------------------------- *) let notify ?(immediate = true) (env : preenv) (lvl : EcGState.loglevel) msg = let buf = Buffer.create 0 in let fbuf = Format.formatter_of_buffer buf in ignore immediate; Format.kfprintf (fun _ -> Format.pp_print_flush fbuf (); EcGState.notify lvl (lazy (Buffer.contents buf)) (gstate env)) fbuf msg (* -------------------------------------------------------------------- *) let empty_mc params = { mc_parameters = params; mc_modules = MMsym.empty; mc_modsigs = MMsym.empty; mc_tydecls = MMsym.empty; mc_operators = MMsym.empty; mc_axioms = MMsym.empty; mc_schemas = MMsym.empty; mc_theories = MMsym.empty; mc_variables = MMsym.empty; mc_functions = MMsym.empty; mc_typeclasses= MMsym.empty; mc_rwbase = MMsym.empty; mc_components = MMsym.empty; } (* -------------------------------------------------------------------- *) let empty_norm_cache = { norm_mp = Mm.empty; norm_xpv = Mx.empty; norm_xfun = Mx.empty; mod_use = Mm.empty; get_restr_use = Mm.empty; } (* -------------------------------------------------------------------- *) let empty gstate = let name = EcCoreLib.i_top in let path = EcPath.psymbol name in let env_current = let icomps = MMsym.add name (IPPath path) MMsym.empty in { (empty_mc None) with mc_components = icomps } in { env_top = None; env_gstate = gstate; env_scope = { ec_path = path; ec_scope = `Theory; }; env_current = env_current; env_comps = Mip.singleton (IPPath path) (empty_mc None); env_locals = MMsym.empty; env_memories = Mmem.empty; env_actmem = None; env_abs_st = Mid.empty; env_tci = []; env_tc = TC.Graph.empty; env_rwbase = Mip.empty; env_atbase = Msym.empty; env_redbase = Mrd.empty; env_ntbase = []; env_modlcs = Sid.empty; env_item = []; env_norm = ref empty_norm_cache; } (* -------------------------------------------------------------------- *) let copy (env : env) = { env with env_gstate = EcGState.copy env.env_gstate } (* -------------------------------------------------------------------- *) type lookup_error = [ | `XPath of xpath | `MPath of mpath | `Path of path | `QSymbol of qsymbol | `AbsStmt of EcIdent.t ] exception LookupFailure of lookup_error let pp_lookup_failure fmt e = let p = match e with | `XPath p -> EcPath.x_tostring p | `MPath p -> EcPath.m_tostring p | `Path p -> EcPath.tostring p | `QSymbol p -> string_of_qsymbol p | `AbsStmt p -> EcIdent.tostring p in Format.fprintf fmt "unknown symbol: %s" p let () = let pp fmt exn = match exn with | LookupFailure p -> pp_lookup_failure fmt p | _ -> raise exn in EcPException.register pp let lookup_error cause = raise (LookupFailure cause) (* -------------------------------------------------------------------- *) exception NotReducible (* -------------------------------------------------------------------- *) exception DuplicatedBinding of symbol let _ = EcPException.register (fun fmt exn -> match exn with | DuplicatedBinding s -> Format.fprintf fmt "the symbol %s already exists" s | _ -> raise exn) (* -------------------------------------------------------------------- *) module MC = struct (* ------------------------------------------------------------------ *) let top_path = EcPath.psymbol EcCoreLib.i_top (* ------------------------------------------------------------------ *) let _cutpath i p = let rec doit i p = match p.EcPath.p_node with | EcPath.Psymbol _ -> (p, `Ct (i-1)) | EcPath.Pqname (p, x) -> begin match doit i p with | (p, `Ct 0) -> (p, `Dn (EcPath.psymbol x)) | (p, `Ct i) -> (EcPath.pqname p x, `Ct (i-1)) | (p, `Dn q) -> (p, `Dn (EcPath.pqname q x)) end in match doit i p with | (p, `Ct 0) -> (p, None) | (_, `Ct _) -> assert false | (p, `Dn q) -> (p, Some q) (* ------------------------------------------------------------------ *) let _downpath_for_modcp isvar ~spsc env p args = let prefix = let prefix_of_mtop = function | `Concrete (p1, _) -> Some p1 | `Local _ -> None in match env.env_scope.ec_scope with | `Theory -> None | `Module m -> prefix_of_mtop m.EcPath.m_top | `Fun m -> prefix_of_mtop m.EcPath.x_top.EcPath.m_top in try let (l, a, r) = List.find_pivot (fun x -> x <> None) args in if not (List.for_all (fun x -> x = None) r) then assert false; let i = List.length l in (* position of args in path *) let a = oget a in (* arguments of top enclosing module *) let n = List.map fst a in (* argument names *) let (ap, inscope) = match p with | IPPath p -> begin p , q = frontier with the first module let (p, q) = _cutpath (i+1) p in match q with | None -> assert false | Some q -> begin let ap = EcPath.xpath (EcPath.mpath_crt p (if isvar then [] else List.map EcPath.mident n) (EcPath.prefix q)) (EcPath.basename q) in (ap, odfl false (prefix |> omap (EcPath.p_equal p))) end end | IPIdent (m, x) -> begin if i <> 0 then assert false; match x |> omap (fun x -> x.EcPath.p_node) with | Some (EcPath.Psymbol x) -> let ap = EcPath.xpath (EcPath.mpath_abs m (if isvar then [] else List.map EcPath.mident n)) x in (ap, false) | _ -> assert false end in ((i+1, if (inscope && not spsc) || isvar then [] else a), ap) with Not_found -> assert false let _downpath_for_var = _downpath_for_modcp true let _downpath_for_fun = _downpath_for_modcp false (* ------------------------------------------------------------------ *) let _downpath_for_mod spsc env p args = let prefix = let prefix_of_mtop = function | `Concrete (p1, _) -> Some p1 | `Local _ -> None in match env.env_scope.ec_scope with | `Theory -> None | `Module m -> prefix_of_mtop m.EcPath.m_top | `Fun m -> prefix_of_mtop m.EcPath.x_top.EcPath.m_top in let (l, a, r) = try List.find_pivot (fun x -> x <> None) args with Not_found -> (args, Some [], []) in if not (List.for_all (fun x -> x = None) r) then assert false; let i = List.length l in (* position of args in path *) let a = oget a in (* arguments of top enclosing module *) let n = List.map fst a in (* argument names *) let (ap, inscope) = match p with | IPPath p -> p , q = frontier with the first module let (p, q) = _cutpath (i+1) p in (EcPath.mpath_crt p (List.map EcPath.mident n) q, odfl false (prefix |> omap (EcPath.p_equal p))) | IPIdent (m, None) -> if i <> 0 then assert false; (EcPath.mpath_abs m (List.map EcPath.mident n), false) | _ -> assert false in ((List.length l, if inscope && not spsc then [] else a), ap) (* ------------------------------------------------------------------ *) let _downpath_for_th _env p args = if not (List.for_all (fun x -> x = None) args) then assert false; match p with | IPIdent _ -> assert false | IPPath p -> p let _downpath_for_tydecl = _downpath_for_th let _downpath_for_modsig = _downpath_for_th let _downpath_for_operator = _downpath_for_th let _downpath_for_axiom = _downpath_for_th let _downpath_for_schema = _downpath_for_th let _downpath_for_typeclass = _downpath_for_th let _downpath_for_rwbase = _downpath_for_th (* ------------------------------------------------------------------ *) let _params_of_path p env = let rec _params_of_path acc p = match EcPath.prefix p with | None -> acc | Some p -> let mc = oget (Mip.find_opt (IPPath p) env.env_comps) in _params_of_path (mc.mc_parameters :: acc) p in _params_of_path [] p (* ------------------------------------------------------------------ *) let _params_of_ipath p env = match p with | IPPath p -> _params_of_path p env | IPIdent (_, None) -> [] | IPIdent (m, Some p) -> assert (is_none (EcPath.prefix p)); let mc = Mip.find_opt (IPIdent (m, None)) env.env_comps in [(oget mc).mc_parameters] (* ------------------------------------------------------------------ *) let by_path proj p env = let mcx = match p with | IPPath p -> begin match p.EcPath.p_node with | EcPath.Psymbol x -> Some (oget (Mip.find_opt (IPPath top_path) env.env_comps), x) | EcPath.Pqname (p, x) -> omap (fun mc -> (mc, x)) (Mip.find_opt (IPPath p) env.env_comps) end | IPIdent (id, None) -> Some (env.env_current, EcIdent.name id) | IPIdent (m, Some p) -> let prefix = EcPath.prefix p in let name = EcPath.basename p in omap (fun mc -> (mc, name)) (Mip.find_opt (IPIdent (m, prefix)) env.env_comps) in let lookup (mc, x) = List.filter (fun (ip, _) -> IPathC.compare ip p = 0) (MMsym.all x (proj mc)) in match mcx |> omap lookup with | None | Some [] -> None | Some (obj :: _) -> Some (_params_of_ipath p env, snd obj) (* ------------------------------------------------------------------ *) let path_of_qn (top : EcPath.path) (qn : symbol list) = List.fold_left EcPath.pqname top qn let pcat (p1 : EcPath.path) (p2 : EcPath.path) = path_of_qn p1 (EcPath.tolist p2) let lookup_mc qn env = match qn with | [] -> Some env.env_current | x :: qn when x = EcCoreLib.i_self && is_some env.env_top -> let p = IPPath (path_of_qn (oget env.env_top) qn) in Mip.find_opt p env.env_comps | x :: qn -> let x = if x = EcCoreLib.i_self then EcCoreLib.i_top else x in let p = (MMsym.last x env.env_current.mc_components) |> obind (fun p -> match p, qn with | IPIdent _, [] -> Some p | IPIdent _, _ -> None | IPPath p, _ -> Some (IPPath (path_of_qn p qn))) in p |> obind (fun p -> Mip.find_opt p env.env_comps) (* ------------------------------------------------------------------ *) let lookup proj (qn, x) env = let mc = lookup_mc qn env in omap (fun (p, obj) -> (p, (_params_of_ipath p env, obj))) (mc |> obind (fun mc -> MMsym.last x (proj mc))) (* ------------------------------------------------------------------ *) let lookup_all proj (qn, x) env = let mc = lookup_mc qn env in let objs = odfl [] (mc |> omap (fun mc -> MMsym.all x (proj mc))) in let _, objs = List.map_fold (fun ps ((p, _) as obj)-> if Sip.mem p ps then (ps, None) else (Sip.add p ps, Some obj)) Sip.empty objs in List.pmap (omap (fun (p, obj) -> (p, (_params_of_ipath p env, obj)))) objs (* ------------------------------------------------------------------ *) let bind up x obj env = let obj = (IPPath (EcPath.pqname (root env) x), obj) in let env = { env with env_current = up true env.env_current x obj } in { env with env_comps = Mip.change (fun mc -> Some (up false (oget mc) x obj)) (IPPath (root env)) env.env_comps; } let import up p obj env = let name = ibasename p in { env with env_current = up env.env_current name (p, obj) } (* -------------------------------------------------------------------- *) let lookup_var qnx env = match lookup (fun mc -> mc.mc_variables) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, ty)) -> (_downpath_for_var ~spsc:false env p args, ty) let _up_var candup mc x obj = if not candup && MMsym.last x mc.mc_variables <> None then raise (DuplicatedBinding x); { mc with mc_variables = MMsym.add x obj mc.mc_variables } let import_var p var env = import (_up_var true) p var env (* -------------------------------------------------------------------- *) let lookup_fun qnx env = match lookup (fun mc -> mc.mc_functions) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_fun ~spsc:false env p args, obj) let _up_fun candup mc x obj = if not candup && MMsym.last x mc.mc_functions <> None then raise (DuplicatedBinding x); { mc with mc_functions = MMsym.add x obj mc.mc_functions } let import_fun p fun_ env = import (_up_fun true) p fun_ env (* -------------------------------------------------------------------- *) let lookup_mod qnx env = match lookup (fun mc -> mc.mc_modules) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_mod false env p args, obj) let _up_mod candup mc x obj = if not candup && MMsym.last x mc.mc_modules <> None then raise (DuplicatedBinding x); { mc with mc_modules = MMsym.add x obj mc.mc_modules } let import_mod p mod_ env = import (_up_mod true) p mod_ env (* -------------------------------------------------------------------- *) let lookup_axiom qnx env = match lookup (fun mc -> mc.mc_axioms) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_axiom env p args, obj) let lookup_axioms qnx env = List.map (fun (p, (args, obj)) -> (_downpath_for_axiom env p args, obj)) (lookup_all (fun mc -> mc.mc_axioms) qnx env) let _up_axiom candup mc x obj = if not candup && MMsym.last x mc.mc_axioms <> None then raise (DuplicatedBinding x); { mc with mc_axioms = MMsym.add x obj mc.mc_axioms } let import_axiom p ax env = import (_up_axiom true) (IPPath p) ax env (* -------------------------------------------------------------------- *) let lookup_schema qnx env = match lookup (fun mc -> mc.mc_schemas) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_schema env p args, obj) let lookup_schemas qnx env = List.map (fun (p, (args, obj)) -> (_downpath_for_schema env p args, obj)) (lookup_all (fun mc -> mc.mc_schemas) qnx env) let _up_schema candup mc x obj = if not candup && MMsym.last x mc.mc_schemas <> None then raise (DuplicatedBinding x); { mc with mc_schemas = MMsym.add x obj mc.mc_schemas } let import_schema p sc env = import (_up_schema true) (IPPath p) sc env (* -------------------------------------------------------------------- *) let lookup_operator qnx env = match lookup (fun mc -> mc.mc_operators) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_operator env p args, obj) let lookup_operators qnx env = List.map (fun (p, (args, obj)) -> (_downpath_for_operator env p args, obj)) (lookup_all (fun mc -> mc.mc_operators) qnx env) let _up_operator candup mc x obj = let module ELI = EcInductive in if not candup && MMsym.last x mc.mc_operators <> None then raise (DuplicatedBinding x); let mypath = lazy (ippath_as_path (fst obj)) in let mc = { mc with mc_operators = MMsym.add x obj mc.mc_operators } in let ax = match (snd obj).op_kind with | OB_pred (Some (PR_Ind pri)) -> let pri = { ELI.ip_path = ippath_as_path (fst obj); ELI.ip_tparams = (snd obj).op_tparams; ELI.ip_prind = pri; } in ELI.prind_schemes pri | _ -> [] in let ax = List.map (fun (name, (tv, cl)) -> let axp = EcPath.prefix (Lazy.force mypath) in let axp = IPPath (EcPath.pqoname axp name) in let ax = { ax_kind = `Axiom (Ssym.empty, false); ax_tparams = tv; ax_spec = cl; ax_loca = (snd obj).op_loca; ax_visibility = `Visible; } in (name, (axp, ax))) ax in List.fold_left (fun mc -> curry (_up_axiom candup mc)) mc ax let import_operator p op env = import (_up_operator true) (IPPath p) op env (* -------------------------------------------------------------------- *) let lookup_tydecl qnx env = match lookup (fun mc -> mc.mc_tydecls) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_tydecl env p args, obj) let lookup_tydecls qnx env = List.map (fun (p, (args, obj)) -> (_downpath_for_tydecl env p args, obj)) (lookup_all (fun mc -> mc.mc_tydecls) qnx env) let _up_tydecl candup mc x obj = if not candup && MMsym.last x mc.mc_tydecls <> None then raise (DuplicatedBinding x); let mc = { mc with mc_tydecls = MMsym.add x obj mc.mc_tydecls } in let mc = let mypath, tyd = match obj with IPPath p, x -> (p, x) | _, _ -> assert false in let ipath name = IPPath (EcPath.pqoname (EcPath.prefix mypath) name) in let loca = tyd.tyd_loca in match tyd.tyd_type with | `Concrete _ -> mc | `Abstract _ -> mc | `Datatype dtype -> let cs = dtype.tydt_ctors in let schelim = dtype.tydt_schelim in let schcase = dtype.tydt_schcase in let params = List.map (fun (x, _) -> tvar x) tyd.tyd_params in let for1 i (c, aty) = let aty = EcTypes.toarrow aty (tconstr mypath params) in let aty = EcSubst.freshen_type (tyd.tyd_params, aty) in let cop = mk_op ~opaque:false (fst aty) (snd aty) (Some (OP_Constr (mypath, i))) loca in let cop = (ipath c, cop) in (c, cop) in let (schelim, schcase) = let do1 scheme name = let scname = Printf.sprintf "%s_%s" x name in (scname, { ax_tparams = tyd.tyd_params; ax_spec = scheme; ax_kind = `Axiom (Ssym.empty, false); ax_loca = loca; ax_visibility = `NoSmt; }) in (do1 schelim "ind", do1 schcase "case") in let cs = List.mapi for1 cs in let mc = List.fold_left (fun mc (c, cop) -> _up_operator candup mc c cop) mc cs in let mc = _up_axiom candup mc (fst schcase) (fst_map ipath schcase) in let mc = _up_axiom candup mc (fst schelim) (fst_map ipath schelim) in let projs = (mypath, tyd.tyd_params, dtype) in let projs = EcInductive.datatype_projectors projs in List.fold_left (fun mc (c, op) -> let name = EcInductive.datatype_proj_name c in _up_operator candup mc name (ipath name, op) ) mc projs | `Record (scheme, fields) -> let params = List.map (fun (x, _) -> tvar x) tyd.tyd_params in let nfields = List.length fields in let cfields = let for1 i (f, aty) = let aty = EcTypes.tfun (tconstr mypath params) aty in let aty = EcSubst.freshen_type (tyd.tyd_params, aty) in let fop = mk_op ~opaque:false (fst aty) (snd aty) (Some (OP_Proj (mypath, i, nfields))) loca in let fop = (ipath f, fop) in (f, fop) in List.mapi for1 fields in let scheme = let scname = Printf.sprintf "%s_ind" x in (scname, { ax_tparams = tyd.tyd_params; ax_spec = scheme; ax_kind = `Axiom (Ssym.empty, false); ax_loca = loca; ax_visibility = `NoSmt; }) in let stname = Printf.sprintf "mk_%s" x in let stop = let stty = toarrow (List.map snd fields) (tconstr mypath params) in let stty = EcSubst.freshen_type (tyd.tyd_params, stty) in mk_op ~opaque:false (fst stty) (snd stty) (Some (OP_Record mypath)) loca in let mc = List.fold_left (fun mc (f, fop) -> _up_operator candup mc f fop) mc ((stname, (ipath stname, stop)) :: cfields) in _up_axiom candup mc (fst scheme) (fst_map ipath scheme) in mc let import_tydecl p tyd env = import (_up_tydecl true) (IPPath p) tyd env (* -------------------------------------------------------------------- *) let lookup_modty qnx env = match lookup (fun mc -> mc.mc_modsigs) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_modsig env p args, obj) let _up_modty candup mc x obj = if not candup && MMsym.last x mc.mc_modsigs <> None then raise (DuplicatedBinding x); { mc with mc_modsigs = MMsym.add x obj mc.mc_modsigs } let import_modty p msig env = import (_up_modty true) (IPPath p) msig env (* -------------------------------------------------------------------- *) let lookup_typeclass qnx env = match lookup (fun mc -> mc.mc_typeclasses) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_typeclass env p args, obj) let _up_typeclass candup mc x obj = if not candup && MMsym.last x mc.mc_typeclasses <> None then raise (DuplicatedBinding x); let mc = { mc with mc_typeclasses = MMsym.add x obj mc.mc_typeclasses } in let mc = let mypath, tc = match obj with IPPath p, x -> (p, x) | _, _ -> assert false in let xpath name = EcPath.pqoname (EcPath.prefix mypath) name in let loca = match tc.tc_loca with `Local -> `Local | `Global -> `Global in let self = EcIdent.create "'self" in let tsubst = { ty_subst_id with ts_def = Mp.add mypath ([], tvar self) Mp.empty } in let operators = let on1 (opid, optype) = let opname = EcIdent.name opid in let optype = ty_subst tsubst optype in let opdecl = mk_op ~opaque:false [(self, Sp.singleton mypath)] optype (Some OP_TC) loca in (opid, xpath opname, optype, opdecl) in List.map on1 tc.tc_ops in let fsubst = List.fold_left (fun s (x, xp, xty, _) -> let fop = EcCoreFol.f_op xp [tvar self] xty in Fsubst.f_bind_local s x fop) (Fsubst.f_subst_init ~sty:tsubst ()) operators in let axioms = List.map (fun (x, ax) -> let ax = Fsubst.f_subst fsubst ax in (x, { ax_tparams = [(self, Sp.singleton mypath)]; ax_spec = ax; ax_kind = `Axiom (Ssym.empty, false); ax_loca = loca; ax_visibility = `NoSmt; })) tc.tc_axs in let mc = List.fold_left (fun mc (_, fpath, _, fop) -> _up_operator candup mc (EcPath.basename fpath) (IPPath fpath, fop)) mc operators in List.fold_left (fun mc (x, ax) -> _up_axiom candup mc x (IPPath (xpath x), ax)) mc axioms in mc let import_typeclass p ax env = import (_up_typeclass true) (IPPath p) ax env (* -------------------------------------------------------------------- *) let lookup_rwbase qnx env = match lookup (fun mc -> mc.mc_rwbase) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_rwbase env p args, obj) let _up_rwbase candup mc x obj= if not candup && MMsym.last x mc.mc_rwbase <> None then raise (DuplicatedBinding x); { mc with mc_rwbase = MMsym.add x obj mc.mc_rwbase } let import_rwbase p env = import (_up_rwbase true) (IPPath p) p env (* -------------------------------------------------------------------- *) let _up_theory candup mc x obj = if not candup && MMsym.last x mc.mc_theories <> None then raise (DuplicatedBinding x); { mc with mc_theories = MMsym.add x obj mc.mc_theories } let lookup_theory qnx env = match lookup (fun mc -> mc.mc_theories) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_th env p args, obj) let import_theory p th env = import (_up_theory true) (IPPath p) th env (* -------------------------------------------------------------------- *) let _up_mc candup mc p = let name = ibasename p in if not candup && MMsym.last name mc.mc_components <> None then raise (DuplicatedBinding name); { mc with mc_components = MMsym.add name p mc.mc_components } let import_mc p env = let mc = _up_mc true env.env_current p in { env with env_current = mc } (* ------------------------------------------------------------------ *) let rec mc_of_module_r (p1, args, p2, lc) me = let subp2 x = let p = EcPath.pqoname p2 x in (p, pcat p1 p) in let mc1_of_module (mc : mc) = function | MI_Module subme -> assert (subme.me_params = []); let (subp2, mep) = subp2 subme.me_name in let submcs = mc_of_module_r (p1, args, Some subp2, None) subme in let mc = _up_mc false mc (IPPath mep) in let mc = _up_mod false mc subme.me_name (IPPath mep, (subme, lc)) in (mc, Some submcs) | MI_Variable v -> let (_subp2, mep) = subp2 v.v_name in let vty = v.v_type in (_up_var false mc v.v_name (IPPath mep, vty), None) | MI_Function f -> let (_subp2, mep) = subp2 f.f_name in (_up_fun false mc f.f_name (IPPath mep, f), None) in let (mc, submcs) = List.map_fold mc1_of_module (empty_mc (if p2 = None then Some me.me_params else None)) me.me_comps in ((me.me_name, mc), List.rev_pmap (fun x -> x) submcs) let mc_of_module (env : env) { tme_expr = me; tme_loca = lc; } = match env.env_scope.ec_scope with | `Theory -> let p1 = EcPath.pqname (root env) me.me_name and args = me.me_params in mc_of_module_r (p1, args, None, Some lc) me | `Module mpath -> begin assert (lc = `Global); match mpath.EcPath.m_top with | `Concrete (p1, p2) -> let p2 = EcPath.pqoname p2 me.me_name in mc_of_module_r (p1, mpath.EcPath.m_args, Some p2, None) me | `Local _ -> assert false end | `Fun _ -> assert false (* ------------------------------------------------------------------ *) let mc_of_module_param (mid : EcIdent.t) (me : module_expr) = let xpath (x : symbol) = IPIdent (mid, Some (EcPath.psymbol x)) in let mc1_of_module (mc : mc) = function | MI_Module _ -> assert false | MI_Variable v -> _up_var false mc v.v_name (xpath v.v_name, v.v_type) | MI_Function f -> _up_fun false mc f.f_name (xpath f.f_name, f) in List.fold_left mc1_of_module (empty_mc (Some me.me_params)) me.me_comps (* ------------------------------------------------------------------ *) let rec mc_of_theory_r (scope : EcPath.path) (x, cth) = let subscope = EcPath.pqname scope x in let expath = fun x -> EcPath.pqname subscope x in let add2mc up name obj mc = up false mc name (IPPath (expath name), obj) in let mc1_of_theory (mc : mc) (item : theory_item) = match item.ti_item with | Th_type (xtydecl, tydecl) -> (add2mc _up_tydecl xtydecl tydecl mc, None) | Th_operator (xop, op) -> (add2mc _up_operator xop op mc, None) | Th_axiom (xax, ax) -> (add2mc _up_axiom xax ax mc, None) | Th_schema (x, schema) -> (add2mc _up_schema x schema mc, None) | Th_modtype (xmodty, modty) -> (add2mc _up_modty xmodty modty mc, None) | Th_module { tme_expr = subme; tme_loca = lc; } -> let args = subme.me_params in let submcs = mc_of_module_r (expath subme.me_name, args, None, Some lc) subme in (add2mc _up_mod subme.me_name (subme, Some lc) mc, Some submcs) | Th_theory (xsubth, cth) -> if cth.cth_mode = `Concrete then let submcs = mc_of_theory_r subscope (xsubth, cth) in let mc = _up_mc false mc (IPPath (expath xsubth)) in (add2mc _up_theory xsubth cth mc, Some submcs) else (add2mc _up_theory xsubth cth mc, None) | Th_typeclass (x, tc) -> (add2mc _up_typeclass x tc mc, None) | Th_baserw (x, _) -> (add2mc _up_rwbase x (expath x) mc, None) | Th_export _ | Th_addrw _ | Th_instance _ | Th_auto _ | Th_reduction _ -> (mc, None) in let (mc, submcs) = List.map_fold mc1_of_theory (empty_mc None) cth.cth_items in ((x, mc), List.rev_pmap identity submcs) let mc_of_theory (env : env) (x : symbol) (cth : ctheory) = match cth.cth_mode with | `Concrete -> Some (mc_of_theory_r (root env) (x, cth)) | `Abstract -> None (* ------------------------------------------------------------------ *) let rec bind_submc env path ((name, mc), submcs) = let path = EcPath.pqname path name in if Mip.find_opt (IPPath path) env.env_comps <> None then raise (DuplicatedBinding (EcPath.basename path)); bind_submcs { env with env_comps = Mip.add (IPPath path) mc env.env_comps } path submcs and bind_submcs env path submcs = List.fold_left (bind_submc^~ path) env submcs and bind_mc x mc env = let path = EcPath.pqname (root env) x in { env with env_current = _up_mc true env.env_current (IPPath path); env_comps = Mip.change (fun mc -> Some (_up_mc false (oget mc) (IPPath path))) (IPPath (root env)) (Mip.add (IPPath path) mc env.env_comps); } and bind_theory x (th:ctheory) env = match mc_of_theory env x th with | None -> bind _up_theory x th env | Some ((_, mc), submcs) -> let env = bind _up_theory x th env in let env = bind_mc x mc env in bind_submcs env (EcPath.pqname (root env) x) submcs and bind_mod x mod_ env = let (_, mc), submcs = mc_of_module env mod_ in let env = bind _up_mod x (mod_.tme_expr, Some mod_.tme_loca) env in let env = bind_mc x mc env in let env = bind_submcs env (EcPath.pqname (root env) x) submcs in env and bind_fun x vb env = bind _up_fun x vb env and bind_var x vb env = bind _up_var x vb env and bind_axiom x ax env = bind _up_axiom x ax env and bind_schema x ax env = bind _up_schema x ax env and bind_operator x op env = bind _up_operator x op env and bind_modty x msig env = bind _up_modty x msig env and bind_tydecl x tyd env = bind _up_tydecl x tyd env and bind_typeclass x tc env = bind _up_typeclass x tc env and bind_rwbase x p env = bind _up_rwbase x p env end (* -------------------------------------------------------------------- *) exception InvalidStateForEnter let enter mode (name : symbol) (env : env) = let path = EcPath.pqname (root env) name in if Mip.find_opt (IPPath path) env.env_comps <> None then raise (DuplicatedBinding name); match mode, env.env_scope.ec_scope with | `Theory, `Theory -> let env = MC.bind_mc name (empty_mc None) env in { env with env_scope = { ec_path = path; ec_scope = `Theory; }; env_item = []; } | `Module [], `Module mpath -> let mpath = EcPath.mqname mpath name in let env = MC.bind_mc name (empty_mc None) env in { env with env_scope = { ec_path = path; ec_scope = `Module mpath; }; env_item = []; } | `Module params, `Theory -> let idents = List.map (fun (x, _) -> EcPath.mident x) params in let mpath = EcPath.mpath_crt path idents None in let env = MC.bind_mc name (empty_mc (Some params)) env in { env with env_scope = { ec_path = path; ec_scope = `Module mpath; }; env_item = []; } | `Fun, `Module mpath -> let xpath = EcPath.xpath mpath name in let env = MC.bind_mc name (empty_mc None) env in (* FIXME: remove *) { env with env_scope = { ec_path = path; ec_scope = `Fun xpath; }; env_item = []; } | _, _ -> raise InvalidStateForEnter (* -------------------------------------------------------------------- *) type meerror = | UnknownMemory of [`Symbol of symbol | `Memory of memory] exception MEError of meerror (* -------------------------------------------------------------------- *) module Memory = struct let all env = Mmem.all env.env_memories let byid (me : memory) (env : env) = try Some (me, Mmem.byid me env.env_memories) with Not_found -> None let lookup (me : symbol) (env : env) = try Some (Mmem.bysym me env.env_memories) with Not_found -> None let set_active (me : memory) (env : env) = match byid me env with | None -> raise (MEError (UnknownMemory (`Memory me))) | Some _ -> { env with env_actmem = Some me } let get_active (env : env) = env.env_actmem let current (env : env) = match env.env_actmem with | None -> None | Some me -> byid me env let update (me: EcMemory.memenv) (env : env) = { env with env_memories = Mmem.add (fst me) (snd me) env.env_memories; } let push (me : EcMemory.memenv) (env : env) = (* TODO : A: *) FIXME : assert ( ( EcMemory.memory me ) env = None ) ; update me env let push_all memenvs env = List.fold_left (fun env m -> push m env) env memenvs let push_active memenv env = set_active (EcMemory.memory memenv) (push memenv env) end (* -------------------------------------------------------------------- *) let ipath_of_mpath (p : mpath) = match p.EcPath.m_top with | `Local i -> (IPIdent (i, None), (0, p.EcPath.m_args)) | `Concrete (p1, p2) -> let pr = odfl p1 (p2 |> omap (MC.pcat p1)) in (IPPath pr, ((EcPath.p_size p1)-1, p.EcPath.m_args)) let ipath_of_xpath (p : xpath) = let x = p.EcPath.x_sub in let xt p = match p with | IPPath p -> Some (IPPath (EcPath.pqname p x)) | IPIdent (m, None) -> Some (IPIdent (m, Some (EcPath.psymbol x))) | _ -> None in let (p, (i, a)) = ipath_of_mpath p.EcPath.x_top in (xt p) |> omap (fun p -> (p, (i+1, a))) (* -------------------------------------------------------------------- *) let try_lf f = try Some (f ()) with LookupFailure _ -> None (* -------------------------------------------------------------------- *) let gen_iter fmc flk ?name f env = match name with | Some name -> List.iter (fun (p, ax) -> f p ax) (flk name env) | None -> Mip.iter (fun _ mc -> MMsym.iter (fun _ (ip, obj) -> match ip with IPPath p -> f p obj | _ -> ()) (fmc mc)) env.env_comps (* -------------------------------------------------------------------- *) let gen_all fmc flk ?(check = fun _ _ -> true) ?name (env : env) = match name with | Some name -> List.filter (fun (p, ax) -> check p ax) (flk name env) | None -> Mip.fold (fun _ mc aout -> MMsym.fold (fun _ objs aout -> List.fold_right (fun (ip, obj) aout -> match ip with | IPPath p -> if check p obj then (p, obj) :: aout else aout | _ -> aout) objs aout) (fmc mc) aout) env.env_comps [] (* ------------------------------------------------------------------ *) module TypeClass = struct type t = typeclass let by_path_opt (p : EcPath.path) (env : env) = omap check_not_suspended (MC.by_path (fun mc -> mc.mc_typeclasses) (IPPath p) env) let by_path (p : EcPath.path) (env : env) = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_typeclass p obj env let rebind name tc env = let env = MC.bind_typeclass name tc env in match tc.tc_prt with | None -> env | Some prt -> let myself = EcPath.pqname (root env) name in { env with env_tc = TC.Graph.add ~src:myself ~dst:prt env.env_tc } let bind ?(import = import0) name tc env = let env = if import.im_immediate then rebind name tc env else env in { env with env_item = mkitem import (Th_typeclass (name, tc)) :: env.env_item } let lookup qname (env : env) = MC.lookup_typeclass qname env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let graph (env : env) = env.env_tc let bind_instance ty cr tci = (ty, cr) :: tci let add_instance ?(import = import0) ty cr lc env = let env = if import.im_immediate then { env with env_tci = bind_instance ty cr env.env_tci } else env in { env with env_tci = bind_instance ty cr env.env_tci; env_item = mkitem import (Th_instance (ty, cr, lc)) :: env.env_item; } let get_instances env = env.env_tci end (* -------------------------------------------------------------------- *) module BaseRw = struct let by_path_opt (p : EcPath.path) (env : env) = let ip = IPPath p in Mip.find_opt ip env.env_rwbase let by_path (p : EcPath.path) env = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let lookup qname env = let _ip, p = MC.lookup_rwbase qname env in p, by_path p env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let is_base name env = match lookup_opt name env with | None -> false | Some _ -> true let add ?(import = import0) name lc env = let p = EcPath.pqname (root env) name in let env = if import.im_immediate then MC.bind_rwbase name p env else env in let ip = IPPath p in { env with env_rwbase = Mip.add ip Sp.empty env.env_rwbase; env_item = mkitem import (Th_baserw (name, lc)) :: env.env_item; } let addto ?(import = import0) p l lc env = let env = if import.im_immediate then { env with env_rwbase = Mip.change (omap (fun s -> List.fold_left (fun s r -> Sp.add r s) s l)) (IPPath p) env.env_rwbase } else env in { env with env_rwbase = Mip.change (omap (fun s -> List.fold_left (fun s r -> Sp.add r s) s l)) (IPPath p) env.env_rwbase; env_item = mkitem import (Th_addrw (p, l, lc)) :: env.env_item; } end (* -------------------------------------------------------------------- *) module Reduction = struct type rule = EcTheory.rule type topsym = red_topsym let add_rule ((_, rule) : path * rule option) (db : mredinfo) = match rule with None -> db | Some rule -> let p = match rule.rl_ptn with | Rule (`Op p, _) -> `Path (fst p) | Rule (`Tuple, _) -> `Tuple | Cost (_, _, Rule (`Op p, _)) -> `Cost (`Path (fst p)) | Cost (_, _, Rule (`Tuple, _)) -> `Cost `Tuple | Cost _ | Var _ | Int _ -> assert false in Mrd.change (fun rls -> let { ri_priomap } = match rls with | None -> { ri_priomap = Mint.empty; ri_list = Lazy.from_val [] } | Some x -> x in let ri_priomap = let change prules = Some (odfl [] prules @ [rule]) in Mint.change change (abs rule.rl_prio) ri_priomap in let ri_list = Lazy.from_fun (fun () -> List.flatten (Mint.values ri_priomap)) in Some { ri_priomap; ri_list }) p db let add_rules (rules : (path * rule option) list) (db : mredinfo) = List.fold_left ((^~) add_rule) db rules let add ?(import = import0) (rules : (path * rule_option * rule option) list) (env : env) = let rstrip = List.map (fun (x, _, y) -> (x, y)) rules in let env = if import.im_immediate then { env with env_redbase = add_rules rstrip env.env_redbase; } else env in { env with env_item = mkitem import (Th_reduction rules) :: env.env_item; } let add1 (prule : path * rule_option * rule option) (env : env) = add [prule] env let get (p : topsym) (env : env) = Mrd.find_opt p env.env_redbase |> omap (fun x -> Lazy.force x.ri_list) |> odfl [] end (* -------------------------------------------------------------------- *) module Auto = struct let dname : symbol = "" let updatedb ~level ?base (ps : path list) (db : (path list Mint.t) Msym.t) = let nbase = (odfl dname base) in let ps' = Msym.find_def Mint.empty nbase db in let ps' = let doit x = Some (ofold (fun x ps -> ps @ x) ps x) in Mint.change doit level ps' in Msym.add nbase ps' db let add ?(import = import0) ~level ?base (ps : path list) lc (env : env) = let env = if import.im_immediate then { env with env_atbase = updatedb ?base ~level ps env.env_atbase; } else env in { env with env_item = mkitem import (Th_auto (level, base, ps, lc)) :: env.env_item; } let add1 ?import ~level ?base (p : path) lc (env : env) = add ?import ?base ~level [p] lc env let get_core ?base (env : env) = Msym.find_def Mint.empty (odfl dname base) env.env_atbase let flatten_db (db : path list Mint.t) = Mint.fold_left (fun ps _ ps' -> ps @ ps') [] db let get ?base (env : env) = flatten_db (get_core ?base env) let getall (bases : symbol list) (env : env) = let dbs = List.map (fun base -> get_core ~base env) bases in let dbs = List.fold_left (fun db mi -> Mint.union (fun _ sp1 sp2 -> Some (sp1 @ sp2)) db mi) Mint.empty dbs in flatten_db dbs let getx (base : symbol) (env : env) = let db = Msym.find_def Mint.empty base env.env_atbase in Mint.bindings db end (* -------------------------------------------------------------------- *) module Fun = struct type t = EcModules.function_ let enter (x : symbol) (env : env) = enter `Fun x env let by_ipath (p : ipath) (env : env) = MC.by_path (fun mc -> mc.mc_functions) p env let by_xpath_r ~susp ~spsc (p : EcPath.xpath) (env : env) = match ipath_of_xpath p with | None -> lookup_error (`XPath p) | Some (ip, (i, args)) -> begin match MC.by_path (fun mc -> mc.mc_functions) ip env with | None -> lookup_error (`XPath p) | Some (params, o) -> let ((spi, params), _op) = MC._downpath_for_fun ~spsc env ip params in if i <> spi || susp && args <> [] then assert false; if not susp && List.length args <> List.length params then assert false; if susp then o else let s = List.fold_left2 (fun s (x, _) a -> EcSubst.add_module s x a) (EcSubst.empty ()) params args in EcSubst.subst_function s o end let by_xpath (p : EcPath.xpath) (env : env) = by_xpath_r ~susp:false ~spsc:true p env let by_xpath_opt (p : EcPath.xpath) (env : env) = try_lf (fun () -> by_xpath p env) let lookup qname (env : env) = let (((_, a), p), x) = MC.lookup_fun qname env in if a <> [] then raise (LookupFailure (`QSymbol qname)); (p, x) let lookup_opt name env = try_lf (fun () -> lookup name env) let sp_lookup qname (env : env) = let (((i, a), p), x) = MC.lookup_fun qname env in let obj = { sp_target = x; sp_params = (i, a); } in (p, obj) let sp_lookup_opt name env = try_lf (fun () -> sp_lookup name env) let lookup_path name env = fst (lookup name env) let bind name fun_ env = MC.bind_fun name fun_ env let add (path : EcPath.xpath) (env : env) = let obj = by_xpath path env in let ip = fst (oget (ipath_of_xpath path)) in MC.import_fun ip obj env let adds_in_memenv memenv vd = EcMemory.bindall vd memenv let add_in_memenv memenv vd = adds_in_memenv memenv [vd] let add_params mem fun_ = adds_in_memenv mem fun_.f_sig.fs_anames let actmem_pre me fun_ = let mem = EcMemory.empty_local ~witharg:true me in add_params mem fun_ let actmem_post me fun_ = let mem = EcMemory.empty_local ~witharg:false me in add_in_memenv mem { ov_name = Some res_symbol; ov_type = fun_.f_sig.fs_ret} let actmem_body me fun_ = match fun_.f_def with | FBabs _ -> assert false (* FIXME error message *) | FBalias _ -> assert false (* FIXME error message *) | FBdef fd -> let mem = EcMemory.empty_local ~witharg:false me in let mem = add_params mem fun_ in let locals = List.map ovar_of_var fd.f_locals in (fun_.f_sig,fd), adds_in_memenv mem locals let inv_memory side = let id = if side = `Left then EcCoreFol.mleft else EcCoreFol.mright in EcMemory.abstract id let inv_memenv env = Memory.push_all [inv_memory `Left; inv_memory `Rigth] env let inv_memenv1 env = let mem = EcMemory.abstract EcCoreFol.mhr in Memory.push_active mem env let prF_memenv m path env = let fun_ = by_xpath path env in actmem_post m fun_ let prF path env = let post = prF_memenv EcCoreFol.mhr path env in Memory.push_active post env let hoareF_memenv path env = let (ip, _) = oget (ipath_of_xpath path) in let fun_ = snd (oget (by_ipath ip env)) in let pre = actmem_pre EcCoreFol.mhr fun_ in let post = actmem_post EcCoreFol.mhr fun_ in pre, post let hoareF path env = let pre, post = hoareF_memenv path env in Memory.push_active pre env, Memory.push_active post env let hoareS path env = let fun_ = by_xpath path env in let fd, memenv = actmem_body EcCoreFol.mhr fun_ in memenv, fd, Memory.push_active memenv env let equivF_memenv path1 path2 env = let (ip1, _) = oget (ipath_of_xpath path1) in let (ip2, _) = oget (ipath_of_xpath path2) in let fun1 = snd (oget (by_ipath ip1 env)) in let fun2 = snd (oget (by_ipath ip2 env)) in let pre1 = actmem_pre EcCoreFol.mleft fun1 in let pre2 = actmem_pre EcCoreFol.mright fun2 in let post1 = actmem_post EcCoreFol.mleft fun1 in let post2 = actmem_post EcCoreFol.mright fun2 in (pre1,pre2), (post1,post2) let equivF path1 path2 env = let (pre1,pre2),(post1,post2) = equivF_memenv path1 path2 env in Memory.push_all [pre1; pre2] env, Memory.push_all [post1; post2] env let equivS path1 path2 env = let fun1 = by_xpath path1 env in let fun2 = by_xpath path2 env in let fd1, mem1 = actmem_body EcCoreFol.mleft fun1 in let fd2, mem2 = actmem_body EcCoreFol.mright fun2 in mem1, fd1, mem2, fd2, Memory.push_all [mem1; mem2] env end (* -------------------------------------------------------------------- *) module Var = struct type t = glob_var_bind let by_xpath_r (spsc : bool) (p : xpath) (env : env) = match ipath_of_xpath p with | None -> lookup_error (`XPath p) | Some (ip, (i, _args)) -> match MC.by_path (fun mc -> mc.mc_variables) ip env with | None -> lookup_error (`XPath p) | Some (params, ty) -> let ((spi, _params), _) = MC._downpath_for_var ~spsc env ip params in if i <> spi then assert false; ty let by_xpath (p : xpath) (env : env) = by_xpath_r true p env let by_xpath_opt (p : xpath) (env : env) = try_lf (fun () -> by_xpath p env) let add (path : EcPath.xpath) (env : env) = let obj = by_xpath path env in let ip = fst (oget (ipath_of_xpath path)) in MC.import_var ip obj env let lookup_locals name env = MMsym.all name env.env_locals let lookup_local name env = match MMsym.last name env.env_locals with | None -> raise (LookupFailure (`QSymbol ([], name))) | Some x -> x let lookup_local_opt name env = MMsym.last name env.env_locals let lookup_progvar ?side qname env = let inmem side = match fst qname with | [] -> let memenv = oget (Memory.byid side env) in begin match EcMemory.lookup_me (snd qname) memenv with | Some (v, Some pa, _) -> Some (`Proj(pv_arg, pa), v.v_type) | Some (v, None, _) -> Some (`Var (pv_loc v.v_name), v.v_type) | None -> None end | _ -> None in match obind inmem side with | None -> let (((_, _), p), ty) = MC.lookup_var qname env in (`Var (pv_glob p), ty) | Some pvt -> pvt let lookup_progvar_opt ?side name env = try_lf (fun () -> lookup_progvar ?side name env) let bind_pvglob name ty env = MC.bind_var name ty env let bindall_pvglob bindings env = List.fold_left (fun env (name, ty) -> bind_pvglob name ty env) env bindings exception DuplicatedLocalBinding of EcIdent.t let bind_local ?uniq:(uniq=false) name ty env = let s = EcIdent.name name in if uniq && MMsym.all s env.env_locals <> [] then raise (DuplicatedLocalBinding name); { env with env_locals = MMsym.add s (name, ty) env.env_locals } let bind_locals ?uniq:(uniq=false) bindings env = List.fold_left (fun env (name, ty) -> bind_local ~uniq:uniq name ty env) env bindings end (* -------------------------------------------------------------------- *) module AbsStmt = struct type t = EcModules.abs_uses let byid id env = try Mid.find id env.env_abs_st with Not_found -> raise (LookupFailure (`AbsStmt id)) let bind id us env = { env with env_abs_st = Mid.add id us env.env_abs_st } end (* -------------------------------------------------------------------- *) module Mod = struct type t = top_module_expr type lkt = module_expr * locality option type spt = mpath * module_expr suspension * locality option let unsuspend_r f istop (i, args) (spi, params) o = if List.length args > List.length params then assert false; if i <> spi then assert false; if (not istop && List.length args <> List.length params) then assert false; let params = List.take (List.length args) params in let s = List.fold_left2 (fun s (x, _) a -> EcSubst.add_module s x a) (EcSubst.empty ()) params args in f s o let clearparams n params = let _, remaining = List.takedrop n params in remaining let unsuspend istop (i, args) (spi, params) me = let me = match args with | [] -> me | _ -> { me with me_params = clearparams (List.length args) me.me_params } in unsuspend_r EcSubst.subst_module istop (i, args) (spi, params) me let by_ipath_r (spsc : bool) (p : ipath) (env : env) = let obj = MC.by_path (fun mc -> mc.mc_modules) p env in obj |> omap (fun (args, obj) -> (fst (MC._downpath_for_mod spsc env p args), obj)) let by_mpath (p : mpath) (env : env) = let (ip, (i, args)) = ipath_of_mpath p in match MC.by_path (fun mc -> mc.mc_modules) ip env with | None -> lookup_error (`MPath p) | Some (params, (o, lc)) -> let ((spi, params), op) = MC._downpath_for_mod true env ip params in let (params, istop) = match op.EcPath.m_top with | `Concrete (p, Some _) -> assert ((params = []) || ((spi+1) = EcPath.p_size p)); (params, false) | `Concrete (p, None) -> assert ((params = []) || ((spi+1) = EcPath.p_size p)); ((if args = [] then [] else o.me_params), true) | `Local _m -> assert ((params = []) || spi = 0); ((if args = [] then [] else o.me_params), true) in (unsuspend istop (i, args) (spi, params) o, lc) let by_mpath_opt (p : EcPath.mpath) (env : env) = try_lf (fun () -> by_mpath p env) let add (p : EcPath.mpath) (env : env) = let obj = by_mpath p env in MC.import_mod (fst (ipath_of_mpath p)) obj env let lookup qname (env : env) = let (((_, _a), p), x) = MC.lookup_mod qname env in (* FIXME : this test is dubious for functors lookup *) if a < > [ ] then raise ( LookupFailure ( ` QSymbol qname ) ) ; raise (LookupFailure (`QSymbol qname)); *) (p, x) let lookup_opt name env = try_lf (fun () -> lookup name env) let sp_lookup qname (env : env) = let (((i, a), p), (x, lc)) = MC.lookup_mod qname env in let obj = { sp_target = x; sp_params = (i, a); } in (p, obj, lc) let sp_lookup_opt name env = try_lf (fun () -> sp_lookup name env) let lookup_path name env = fst (lookup name env) let add_xs_to_declared xs env = let update_id id mods = let update me = match me.me_body with | ME_Decl ({ mt_restr } as mt) -> let mt_restr = mr_add_restr mt_restr (ur_empty xs) (ur_empty Sm.empty) in { me with me_body = ME_Decl { mt with mt_restr } } | _ -> me in MMsym.map_at (List.map (fun (ip, (me, lc)) -> if ip = IPIdent (id, None) then (ip, (update me, lc)) else (ip, (me, lc)))) (EcIdent.name id) mods in let envc = { env.env_current with mc_modules = Sid.fold update_id env.env_modlcs env.env_current.mc_modules; } in let en = !(env.env_norm) in let norm = { en with get_restr_use = Mm.empty } in { env with env_current = envc; env_norm = ref norm; } let rec vars_me mp xs me = vars_mb (EcPath.mqname mp me.me_name) xs me.me_body and vars_mb mp xs = function | ME_Alias _ | ME_Decl _ -> xs | ME_Structure ms -> List.fold_left (vars_item mp) xs ms.ms_body and vars_item mp xs = function | MI_Module me -> vars_me mp xs me (* FIXME:MERGE-COST *) | MI_Variable v -> Sx.add (EcPath.xpath mp v.v_name) xs | MI_Function _ -> xs let add_restr_to_declared p me env = if me.tme_loca = `Local then let p = pqname p me.tme_expr.me_name in let mp = EcPath.mpath_crt p [] None in let xs = vars_mb mp Sx.empty me.tme_expr.me_body in add_xs_to_declared xs env else env let bind ?(import = import0) name me env = assert (name = me.tme_expr.me_name); let env = if import.im_immediate then MC.bind_mod name me env else env in let env = { env with env_item = mkitem import (Th_module me) :: env.env_item; env_norm = ref !(env.env_norm); } in add_restr_to_declared (root env) me env let me_of_mt env name modty = let modsig = let modsig = match omap check_not_suspended (MC.by_path (fun mc -> mc.mc_modsigs) (IPPath modty.mt_name) env) with | None -> lookup_error (`Path modty.mt_name) | Some x -> x in EcSubst.subst_modsig ~params:(List.map fst modty.mt_params) (EcSubst.empty ()) modsig.tms_sig in module_expr_of_module_sig name modty modsig let bind_local name modty env = let me = me_of_mt env name modty in let path = IPIdent (name, None) in let comps = MC.mc_of_module_param name me in let env = { env with env_current = ( let current = env.env_current in let current = MC._up_mc true current path in let current = MC._up_mod true current me.me_name (path, (me, None)) in current); env_comps = Mip.add path comps env.env_comps; env_norm = ref !(env.env_norm); } in env let declare_local id modty env = { (bind_local id modty env) with env_modlcs = Sid.add id env.env_modlcs; } let add_restr_to_locals (rx : Sx.t use_restr) (rm : Sm.t use_restr) env = let update_id id mods = let update me = match me.me_body with | ME_Decl mt -> let mr = mr_add_restr mt.mt_restr rx rm in { me with me_body = ME_Decl { mt with mt_restr = mr } } | _ -> me in MMsym.map_at (List.map (fun (ip, (me, lc)) -> if ip = IPIdent (id, None) then (ip, (update me, lc)) else (ip, (me, lc)))) (EcIdent.name id) mods in let envc = let mc_modules = Sid.fold update_id env.env_modlcs env.env_current.mc_modules in { env.env_current with mc_modules } in let en = !(env.env_norm) in let norm = { en with get_restr_use = Mm.empty } in { env with env_current = envc; env_norm = ref norm; } let is_declared id env = Sid.mem id env.env_modlcs let bind_locals bindings env = List.fold_left (fun env (name, me) -> bind_local name me env) env bindings let enter name params env = let env = enter (`Module params) name env in bind_locals params env let add_mod_binding bd env = let do1 env (x,gty) = match gty with | GTmodty p -> bind_local x p env | _ -> env in List.fold_left do1 env bd let import_vars env p = let do1 env = function | MI_Variable v -> let vp = EcPath.xpath p v.v_name in let ip = fst (oget (ipath_of_xpath vp)) in let obj = v.v_type in MC.import_var ip obj env | _ -> env in List.fold_left do1 env (fst (by_mpath p env)).me_comps let iter ?name f (env : env) = gen_iter (fun mc -> mc.mc_modules) (assert false) ?name f env let all ?check ?name (env : env) = gen_all (fun mc -> mc.mc_modules) (assert false) ?check ?name env end (* -------------------------------------------------------------------- *) module NormMp = struct let rec norm_mpath_for_typing env p = let (ip, (i, args)) = ipath_of_mpath p in match Mod.by_ipath_r true ip env with | Some ((spi, params), ({ me_body = ME_Alias (arity,alias) } as m, _)) -> assert (m.me_params = [] && arity = 0); let p = Mod.unsuspend_r EcSubst.subst_mpath true (i, args) (spi, params) alias in norm_mpath_for_typing env p | _ -> begin match p.EcPath.m_top with | `Local _ | `Concrete (_, None) -> p | `Concrete (p1, Some p2) -> begin let name = EcPath.basename p2 in let pr = EcPath.mpath_crt p1 p.EcPath.m_args (EcPath.prefix p2) in let pr = norm_mpath_for_typing env pr in match pr.EcPath.m_top with | `Local _ -> p | `Concrete (p1, p2) -> EcPath.mpath_crt p1 pr.EcPath.m_args (Some (EcPath.pqoname p2 name)) end end let rec norm_mpath_def env p = let top = EcPath.m_functor p in let args = p.EcPath.m_args in let sub = match p.EcPath.m_top with | `Local _ -> None | `Concrete(_,o) -> o in p is ( top args).sub match Mod.by_mpath_opt top env with | None -> norm_mpath_for_typing env p | Some (me, _) -> begin match me.me_body with | ME_Alias (arity,mp) -> let nargs = List.length args in if arity <= nargs then let args, extra = List.takedrop arity args in let params = List.take arity me.me_params in let s = List.fold_left2 (fun s (x, _) a -> EcSubst.add_module s x a) (EcSubst.empty ()) params args in let mp = EcSubst.subst_mpath s mp in let args' = mp.EcPath.m_args in let args2 = if extra = [] then args' else args' @ extra in let mp = match mp.EcPath.m_top with | `Local _ as x -> assert (sub = None); EcPath.mpath x args2 ( ( top ' args ' ) args).sub EcPath.mpath_crt top' args2 sub | `Concrete(top',(Some p' as sub')) -> (* ((top' args').sub').sub *) assert (args = []); (* A submodule cannot be a functor *) match sub with | None -> EcPath.mpath_crt top' args2 sub' | Some p -> EcPath.mpath_crt top' args2 (Some (pappend p' p)) in norm_mpath env mp else EcPath.mpath p.EcPath.m_top (List.map (norm_mpath env) args) | ME_Structure _ when sub <> None -> begin let (ip, (i, args)) = ipath_of_mpath p in match Mod.by_ipath_r true ip env with | Some ((spi, params), ({ me_body = ME_Alias (_,alias) } as m, _)) -> assert (m.me_params = []); let p = Mod.unsuspend_r EcSubst.subst_mpath false (i, args) (spi, params) alias in norm_mpath env p | _ -> EcPath.mpath p.EcPath.m_top (List.map (norm_mpath env) args) end | _ -> (* The top is in normal form simply normalize the arguments *) EcPath.mpath p.EcPath.m_top (List.map (norm_mpath env) args) end and norm_mpath env p = try Mm.find p !(env.env_norm).norm_mp with Not_found -> let res = norm_mpath_def env p in let en = !(env.env_norm) in env.env_norm := { en with norm_mp = Mm.add p res en.norm_mp }; res let rec norm_xfun env p = try Mx.find p !(env.env_norm).norm_xfun with Not_found -> let res = let mp = norm_mpath env p.x_top in let pf = EcPath.xpath mp p.x_sub in TODO B : use | Some {f_def = FBalias xp} -> norm_xfun env xp | _ -> pf in let en = !(env.env_norm) in env.env_norm := { en with norm_xfun = Mx.add p res en.norm_xfun }; res let norm_xpv env p = try Mx.find p !(env.env_norm).norm_xpv with Not_found -> let mp = p.x_top in assert (mp.m_args = []); let top = m_functor p.x_top in match Mod.by_mpath_opt top env with | None -> (* We are in typing mod .... *) let mp = norm_mpath env mp in let xp = EcPath.xpath mp p.x_sub in let res = xp_glob xp in res | Some (me, _) -> let params = me.me_params in let env', mp = if params = [] then env, mp else Mod.bind_locals params env, EcPath.m_apply mp (List.map (fun (id,_)->EcPath.mident id) params)in let mp = norm_mpath env' mp in let xp = EcPath.xpath mp p.x_sub in let res = xp_glob xp in let en = !(env.env_norm) in env.env_norm := { en with norm_xpv = Mx.add p res en.norm_xpv }; res let use_equal us1 us2 = Mx.equal (fun _ _ -> true) us1.us_pv us2.us_pv && Sid.equal us1.us_gl us2.us_gl let mem_xp x us = Mx.mem x us.us_pv (* Return [true] if [x] is forbidden in [restr]. *) let use_mem_xp x (restr : use use_restr) = let bneg = mem_xp x restr.ur_neg and bpos = match restr.ur_pos with | None -> false | Some sp -> not (mem_xp x sp) in bneg || bpos let mem_gl mp us = assert (mp.m_args = []); match mp.m_top with | `Local id -> Sid.mem id us.us_gl | _ -> assert false let use_mem_gl m restr = let bneg = mem_gl m restr.ur_neg and bpos = match restr.ur_pos with | None -> false | Some sp -> not (mem_gl m sp) in bneg || bpos let add_var env xp us = let xp = xp_glob xp in let xp = norm_xpv env xp in let ty = Var.by_xpath xp env in { us with us_pv = Mx.add xp ty us.us_pv } let add_glob id us = { us with us_gl = Sid.add id us.us_gl } let add_glob_except rm id us = if Sid.mem id rm then us else add_glob id us let gen_fun_use env fdone rm = let rec fun_use us f = let f = norm_xfun env f in if Mx.mem f !fdone then us else let f1 = Fun.by_xpath f env in fdone := Sx.add f !fdone; match f1.f_def with | FBdef fdef -> let f_uses = fdef.f_uses in let vars = Sx.union f_uses.us_reads f_uses.us_writes in let us = Sx.fold (add_var env) vars us in List.fold_left fun_use us f_uses.us_calls | FBabs oi -> let id = match f.x_top.m_top with | `Local id -> id | _ -> assert false in let us = add_glob_except rm id us in List.fold_left fun_use us (OI.allowed oi) | FBalias _ -> assert false in fun_use let fun_use env xp = gen_fun_use env (ref Sx.empty) Sid.empty use_empty xp The four functions below are used in mod_use_top and item_use . let rec mod_use env rm fdone us mp = let mp = norm_mpath env mp in let me, _ = Mod.by_mpath mp env in assert (me.me_params = []); body_use env rm fdone mp us me.me_comps me.me_body and item_use env rm fdone mp us item = match item with | MI_Module me -> mod_use env rm fdone us (EcPath.mqname mp me.me_name) | MI_Variable v -> add_var env (xpath mp v.v_name) us | MI_Function f -> fun_use_aux env rm fdone us (xpath mp f.f_name) and body_use env rm fdone mp us comps body = match body with | ME_Alias _ -> assert false | ME_Decl _ -> let id = match mp.m_top with `Local id -> id | _ -> assert false in let us = add_glob_except rm id us in List.fold_left (item_use env rm fdone mp) us comps | ME_Structure ms -> List.fold_left (item_use env rm fdone mp) us ms.ms_body and fun_use_aux env rm fdone us f = gen_fun_use env fdone rm us f let mod_use_top env mp = let mp = norm_mpath env mp in let me, _ = Mod.by_mpath mp env in let params = me.me_params in let rm = List.fold_left (fun rm (id,_) -> Sid.add id rm) Sid.empty params in let env' = Mod.bind_locals params env in let mp' = EcPath.m_apply mp (List.map (fun (id,_) -> EcPath.mident id) params) in let fdone = ref Sx.empty in mod_use env' rm fdone use_empty mp' let mod_use env mp = try Mm.find mp !(env.env_norm).mod_use with Not_found -> let res = mod_use_top env mp in let en = !(env.env_norm) in env.env_norm := { en with mod_use = Mm.add mp res en.mod_use }; res let item_use env mp item = item_use env Sid.empty (ref Sx.empty) mp use_empty item let restr_use env (mr : mod_restr) = let get_use sx sm = Sx.fold (fun xp r -> add_var env xp r) sx use_empty |> Sm.fold (fun mp r -> use_union r (mod_use env mp)) sm in If any of the two positive restrictions is [ None ] , then anything is allowed . allowed. *) let ur_pos = match mr.mr_xpaths.ur_pos, mr.mr_mpaths.ur_pos with | None, _ | _, None -> None | Some sx, Some sm -> some @@ get_use sx sm in { ur_pos = ur_pos; ur_neg = get_use mr.mr_xpaths.ur_neg mr.mr_mpaths.ur_neg; } let get_restr_use env mp = try Mm.find mp !(env.env_norm).get_restr_use with Not_found -> let res = match (fst (Mod.by_mpath mp env)).me_body with | EcModules.ME_Decl mt -> restr_use env mt.mt_restr | _ -> assert false in let en = !(env.env_norm) in env.env_norm := { en with get_restr_use = Mm.add mp res en.get_restr_use }; res let get_restr_me env me mp = match me.me_body with | EcModules.ME_Decl mt -> (* As an invariant, we have that [mt] is fully applied. *) assert (List.length mt.mt_params = List.length mt.mt_args); (* We need to clear the oracle restriction using [me] params *) let keep = List.fold_left (fun k (x,_) -> EcPath.Sm.add (EcPath.mident x) k) EcPath.Sm.empty me.me_params in let keep_info f = EcPath.Sm.mem (f.EcPath.x_top) keep in let do1 oi = OI.filter keep_info oi in { mt.mt_restr with mr_oinfos = Msym.map do1 mt.mt_restr.mr_oinfos } | _ -> (* We compute the oracle call information. *) let mparams = List.fold_left (fun mparams (id,_) -> Sm.add (EcPath.mident id) mparams) Sm.empty me.me_params in let env = List.fold_left (fun env (x,mt) -> Mod.bind_local x mt env ) env me.me_params in let comp_oi oi it = match it with | MI_Module _ | MI_Variable _ -> oi | MI_Function f -> let rec f_call c f = let f = norm_xfun env f in if EcPath.Sx.mem f c then c else let c = EcPath.Sx.add f c in let fun_ = Fun.by_xpath f env in match fun_.f_def with | FBalias _ -> assert false | FBdef def -> List.fold_left f_call c def.f_uses.us_calls | FBabs oi -> List.fold_left f_call c (OI.allowed oi) in let all_calls = match f.f_def with | FBalias f -> f_call EcPath.Sx.empty f | FBdef def -> List.fold_left f_call EcPath.Sx.empty def.f_uses.us_calls | FBabs oi -> List.fold_left f_call EcPath.Sx.empty (OI.allowed oi) in let filter f = let ftop = EcPath.m_functor f.EcPath.x_top in Sm.mem ftop mparams in let calls = List.filter filter (EcPath.Sx.elements all_calls) in Msym.add f.f_name (OI.mk calls `Unbounded) oi in let oi = List.fold_left comp_oi Msym.empty me.me_comps in (* We compute the postive restriction *) let use = mod_use env mp in let sx = EcPath.Mx.map (fun _ -> ()) use.us_pv in let ur_xpaths = { ur_pos = Some sx; ur_neg = Sx.empty; } in let sm = Sid.fold (fun m sm -> Sm.add (EcPath.mident m) sm ) use.us_gl Sm.empty in let ur_mpaths = { ur_pos = Some sm; ur_neg = Sm.empty; } in { mr_xpaths = ur_xpaths; mr_mpaths = ur_mpaths; mr_oinfos = oi; } let get_restr env mp = let mp = norm_mpath env mp in let me, _ = Mod.by_mpath mp env in get_restr_me env me mp let equal_restr (f_equiv : form -> form -> bool) env r1 r2 = let us1,us2 = restr_use env r1, restr_use env r2 in ur_equal use_equal us1 us2 && Msym.equal (PreOI.equal f_equiv) r1.mr_oinfos r2.mr_oinfos let sig_of_mp env mp = let mp = norm_mpath env mp in let me, _ = Mod.by_mpath mp env in { mis_params = me.me_params; mis_body = me.me_sig_body; mis_restr = get_restr_me env me mp } let norm_pvar env pv = match pv with | PVloc _ -> pv | PVglob xp -> let p = norm_xpv env xp in if x_equal p xp then pv else EcTypes.pv_glob p let globals env m mp = let us = mod_use env mp in let l = Sid.fold (fun id l -> f_glob (EcPath.mident id) m :: l) us.us_gl [] in let l = Mx.fold (fun xp ty l -> f_pvar (EcTypes.pv_glob xp) ty m :: l) us.us_pv l in f_tuple l let norm_glob env m mp = globals env m mp let norm_tglob env mp = let g = (norm_glob env mhr mp) in g.f_ty let tglob_reducible env mp = match (norm_tglob env mp).ty_node with | Tglob mp' -> not (EcPath.m_equal mp mp') | _ -> true let norm_ty env = EcTypes.Hty.memo_rec 107 ( fun aux ty -> match ty.ty_node with | Tglob mp -> norm_tglob env mp | _ -> ty_map aux ty) let rec norm_form env = let norm_ty1 : ty -> ty = norm_ty env in let norm_gty env (id,gty) = let gty = match gty with | GTty ty -> GTty (norm_ty env ty) | GTmodty _ -> gty | GTmem mt -> GTmem (mt_subst (norm_ty env) mt) in id,gty in let has_mod b = List.exists (fun (_,gty) -> match gty with GTmodty _ -> true | _ -> false) b in FIXME : use FSmart EcCoreFol.Hf.memo_rec 107 (fun aux f -> match f.f_node with | Fquant(q,bd,f) -> if has_mod bd then let env = Mod.add_mod_binding bd env in let bd = List.map (norm_gty env) bd in f_quant q bd (norm_form env f) else let bd = List.map (norm_gty env) bd in f_quant q bd (aux f) | Fpvar(p,m) -> let p' = norm_pvar env p in if p == p' then f else f_pvar p' f.f_ty m | Fglob(p,m) -> norm_glob env m p | FhoareF hf -> let pre' = aux hf.hf_pr and p' = norm_xfun env hf.hf_f and post' = aux hf.hf_po in if hf.hf_pr == pre' && hf.hf_f == p' && hf.hf_po == post' then f else f_hoareF pre' p' post' | FcHoareF chf -> let pre' = aux chf.chf_pr and p' = norm_xfun env chf.chf_f and post' = aux chf.chf_po in let c_self' = aux chf.chf_co.c_self in let c_calls' = Mx.fold (fun f c calls -> let f' = f (* not normalized. *) and c' = call_bound_r (aux c.cb_cost) (aux c.cb_called) in Mx.change (fun old -> assert (old = None); Some c') f' calls ) chf.chf_co.c_calls Mx.empty in if chf.chf_pr == pre' && chf.chf_f == p' && chf.chf_po == post' && chf.chf_co.c_self == c_self' && Mx.equal (fun a b -> a == b) chf.chf_co.c_calls c_calls' then f else let calls' = cost_r c_self' c_calls' in f_cHoareF pre' p' post' calls' TODO : missing cases : and every | FequivF ef -> let pre' = aux ef.ef_pr and l' = norm_xfun env ef.ef_fl and r' = norm_xfun env ef.ef_fr and post' = aux ef.ef_po in if ef.ef_pr == pre' && ef.ef_fl == l' && ef.ef_fr == r' && ef.ef_po == post' then f else f_equivF pre' l' r' post' | Fcoe coe -> let coe' = { coe_mem = coe.coe_mem; coe_pre = aux coe.coe_pre; coe_e = coe.coe_e; } in FSmart.f_coe (f, coe) coe' | Fpr pr -> let pr' = { pr_mem = pr.pr_mem; pr_fun = norm_xfun env pr.pr_fun; pr_args = aux pr.pr_args; pr_event = aux pr.pr_event; } in FSmart.f_pr (f, pr) pr' | _ -> EcCoreFol.f_map norm_ty1 aux f) in norm_form let norm_op env op = let kind = match op.op_kind with | OB_pred (Some (PR_Plain f)) -> OB_pred (Some (PR_Plain (norm_form env f))) | OB_pred (Some (PR_Ind pri)) -> let pri = { pri with pri_ctors = List.map (fun x -> { x with prc_spec = List.map (norm_form env) x.prc_spec }) pri.pri_ctors } in OB_pred (Some (PR_Ind pri)) | _ -> op.op_kind in { op with op_kind = kind; op_ty = norm_ty env op.op_ty; } let norm_ax env ax = { ax with ax_spec = norm_form env ax.ax_spec } let norm_sc env sc = { sc with axs_spec = norm_form env sc.axs_spec } let is_abstract_fun f env = let f = norm_xfun env f in match (Fun.by_xpath f env).f_def with | FBabs _ -> true | _ -> false let x_equal env f1 f2 = EcPath.x_equal (norm_xfun env f1) (norm_xfun env f2) let pv_equal env pv1 pv2 = EcTypes.pv_equal (norm_pvar env pv1) (norm_pvar env pv2) end (* -------------------------------------------------------------------- *) module ModTy = struct type t = top_module_sig let by_path_opt (p : EcPath.path) (env : env) = omap check_not_suspended (MC.by_path (fun mc -> mc.mc_modsigs) (IPPath p) env) let by_path (p : EcPath.path) (env : env) = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_modty p obj env let lookup qname (env : env) = MC.lookup_modty qname env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let modtype p env = let { tms_sig = sig_ } = by_path p env in (* eta-normal form *) { mt_params = sig_.mis_params; mt_name = p; mt_args = List.map (EcPath.mident -| fst) sig_.mis_params; mt_restr = sig_.mis_restr; } let bind ?(import = import0) name modty env = let env = if import.im_immediate then MC.bind_modty name modty env else env in { env with env_item = mkitem import (Th_modtype (name, modty)) :: env.env_item } exception ModTypeNotEquiv let rec mod_type_equiv (f_equiv : form -> form -> bool) env mty1 mty2 = if not (EcPath.p_equal mty1.mt_name mty2.mt_name) then raise ModTypeNotEquiv; if List.length mty1.mt_params <> List.length mty2.mt_params then raise ModTypeNotEquiv; if List.length mty1.mt_args <> List.length mty2.mt_args then raise ModTypeNotEquiv; if not (NormMp.equal_restr f_equiv env mty1.mt_restr mty2.mt_restr) then raise ModTypeNotEquiv; let subst = List.fold_left2 (fun subst (x1, p1) (x2, p2) -> let p1 = EcSubst.subst_modtype subst p1 in let p2 = EcSubst.subst_modtype subst p2 in mod_type_equiv f_equiv env p1 p2; EcSubst.add_module subst x1 (EcPath.mident x2)) (EcSubst.empty ()) mty1.mt_params mty2.mt_params in if not ( List.all2 (fun m1 m2 -> let m1 = NormMp.norm_mpath env (EcSubst.subst_mpath subst m1) in let m2 = NormMp.norm_mpath env (EcSubst.subst_mpath subst m2) in EcPath.m_equal m1 m2) mty1.mt_args mty2.mt_args) then raise ModTypeNotEquiv let mod_type_equiv (f_equiv : form -> form -> bool) env mty1 mty2 = try mod_type_equiv f_equiv env mty1 mty2; true with ModTypeNotEquiv -> false let has_mod_type (env : env) (dst : module_type list) (src : module_type) = List.exists (mod_type_equiv f_equal env src) dst let sig_of_mt env (mt:module_type) = let { tms_sig = sig_ } = by_path mt.mt_name env in let subst = List.fold_left2 (fun s (x1,_) a -> EcSubst.add_module s x1 a) (EcSubst.empty ()) sig_.mis_params mt.mt_args in let items = EcSubst.subst_modsig_body subst sig_.mis_body in let params = mt.mt_params in let keep = List.fold_left (fun k (x,_) -> EcPath.Sm.add (EcPath.mident x) k) EcPath.Sm.empty params in let keep_info f = EcPath.Sm.mem (f.EcPath.x_top) keep in let do1 oi = OI.filter keep_info oi in let restr = { mt.mt_restr with mr_oinfos = Msym.map do1 mt.mt_restr.mr_oinfos } in { mis_params = params; mis_body = items; mis_restr = restr; } end (* -------------------------------------------------------------------- *) module Ty = struct type t = EcDecl.tydecl let by_path_opt (p : EcPath.path) (env : env) = omap check_not_suspended (MC.by_path (fun mc -> mc.mc_tydecls) (IPPath p) env) let by_path (p : EcPath.path) (env : env) = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_tydecl p obj env let lookup qname (env : env) = MC.lookup_tydecl qname env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let defined (name : EcPath.path) (env : env) = match by_path_opt name env with | Some { tyd_type = `Concrete _ } -> true | _ -> false let unfold (name : EcPath.path) (args : EcTypes.ty list) (env : env) = match by_path_opt name env with | Some ({ tyd_type = `Concrete body } as tyd) -> EcTypes.Tvar.subst (EcTypes.Tvar.init (List.map fst tyd.tyd_params) args) body | _ -> raise (LookupFailure (`Path name)) let rec hnorm (ty : ty) (env : env) = match ty.ty_node with | Tconstr (p, tys) when defined p env -> hnorm (unfold p tys env) env | _ -> ty let rec ty_hnorm (ty : ty) (env : env) = match ty.ty_node with | Tconstr (p, tys) when defined p env -> ty_hnorm (unfold p tys env) env | Tglob p -> NormMp.norm_tglob env p | _ -> ty let rec decompose_fun (ty : ty) (env : env) : dom * ty = match (hnorm ty env).ty_node with | Tfun (ty1, ty2) -> fst_map (fun tys -> ty1 :: tys) (decompose_fun ty2 env) | _ -> ([], ty) let signature env = let rec doit acc ty = match (hnorm ty env).ty_node with | Tfun (dom, codom) -> doit (dom::acc) codom | _ -> (List.rev acc, ty) in fun ty -> doit [] ty let scheme_of_ty mode (ty : ty) (env : env) = let ty = hnorm ty env in match ty.ty_node with | Tconstr (p, tys) -> begin match by_path_opt p env with | Some ({ tyd_type = (`Datatype _ | `Record _) as body }) -> let prefix = EcPath.prefix p in let basename = EcPath.basename p in let basename = match body, mode with | `Record _, (`Ind | `Case) -> basename ^ "_ind" | `Datatype _, `Ind -> basename ^ "_ind" | `Datatype _, `Case -> basename ^ "_case" in Some (EcPath.pqoname prefix basename, tys) | _ -> None end | _ -> None let get_top_decl (ty : ty) (env : env) = match (ty_hnorm ty env).ty_node with | Tconstr (p, tys) -> Some (p, oget (by_path_opt p env), tys) | _ -> None let rebind name ty env = let env = MC.bind_tydecl name ty env in match ty.tyd_type with | `Abstract tc -> let myty = let myp = EcPath.pqname (root env) name in let typ = List.map (fst_map EcIdent.fresh) ty.tyd_params in (typ, EcTypes.tconstr myp (List.map (tvar |- fst) typ)) in let instr = Sp.fold (fun p inst -> TypeClass.bind_instance myty (`General p) inst) tc env.env_tci in { env with env_tci = instr } | _ -> env let bind ?(import = import0) name ty env = let env = if import.im_immediate then rebind name ty env else env in { env with env_item = mkitem import (Th_type (name, ty)) :: env.env_item } let iter ?name f (env : env) = gen_iter (fun mc -> mc.mc_tydecls) MC.lookup_tydecls ?name f env let all ?check ?name (env : env) = gen_all (fun mc -> mc.mc_tydecls) MC.lookup_tydecls ?check ?name env end let ty_hnorm = Ty.ty_hnorm (* -------------------------------------------------------------------- *) module Op = struct type t = EcDecl.operator let by_path_opt (p : EcPath.path) (env : env) = omap check_not_suspended (MC.by_path (fun mc -> mc.mc_operators) (IPPath p) env) let by_path (p : EcPath.path) (env : env) = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_operator p obj env let lookup qname (env : env) = MC.lookup_operator qname env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let bind ?(import = import0) name op env = let env = if import.im_immediate then MC.bind_operator name op env else env in let op = NormMp.norm_op env op in let nt = match op.op_kind with | OB_nott nt -> Some (EcPath.pqname (root env) name, (op.op_tparams, nt)) | _ -> None in { env with env_ntbase = ofold List.cons env.env_ntbase nt; env_item = mkitem import (Th_operator (name, op)) :: env.env_item; } let rebind name op env = MC.bind_operator name op env let reducible ?(force = false) env p = try let op = by_path p env in match op.op_kind with | OB_oper (Some (OP_Plain _)) | OB_pred (Some _) when force || not op.op_opaque -> true | _ -> false with LookupFailure _ -> false let reduce ?(force = false) env p tys = let op = oget (by_path_opt p env) in let f = match op.op_kind with | OB_oper (Some (OP_Plain (e, _))) when force || not op.op_opaque -> form_of_expr EcCoreFol.mhr e | OB_pred (Some (PR_Plain f)) when force || not op.op_opaque -> f | _ -> raise NotReducible in EcCoreFol.Fsubst.subst_tvar (EcTypes.Tvar.init (List.map fst op.op_tparams) tys) f let is_projection env p = try EcDecl.is_proj (by_path p env) with LookupFailure _ -> false let is_record_ctor env p = try EcDecl.is_rcrd (by_path p env) with LookupFailure _ -> false let is_dtype_ctor ?nargs env p = try match (by_path p env).op_kind with | OB_oper (Some (OP_Constr (pt,i))) -> begin match nargs with | None -> true | Some nargs -> let tyv = Ty.by_path pt env in let tyv = oget (EcDecl.tydecl_as_datatype tyv) in let ctor_ty = snd (List.nth tyv.tydt_ctors i) in List.length ctor_ty = nargs end | _ -> false with LookupFailure _ -> false let is_fix_def env p = try EcDecl.is_fix (by_path p env) with LookupFailure _ -> false let is_abbrev env p = try EcDecl.is_abbrev (by_path p env) with LookupFailure _ -> false let is_prind env p = try EcDecl.is_prind (by_path p env) with LookupFailure _ -> false let scheme_of_prind env (_mode : [`Case | `Ind]) p = match by_path_opt p env with | Some { op_kind = OB_pred (Some (PR_Ind pri)) } -> Some (EcInductive.prind_indsc_path p, List.length pri.pri_ctors) | _ -> None type notation = env_notation let get_notations env = env.env_ntbase let iter ?name f (env : env) = gen_iter (fun mc -> mc.mc_operators) MC.lookup_operators ?name f env let all ?check ?name (env : env) = gen_all (fun mc -> mc.mc_operators) MC.lookup_operators ?check ?name env end (* -------------------------------------------------------------------- *) module Ax = struct type t = axiom let by_path_opt (p : EcPath.path) (env : env) = omap check_not_suspended (MC.by_path (fun mc -> mc.mc_axioms) (IPPath p) env) let by_path (p : EcPath.path) (env : env) = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_axiom p obj env let lookup qname (env : env) = MC.lookup_axiom qname env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let bind ?(import = import0) name ax env = let ax = NormMp.norm_ax env ax in let env = if import.im_immediate then MC.bind_axiom name ax env else env in { env with env_item = mkitem import (Th_axiom (name, ax)) :: env.env_item } let rebind name ax env = MC.bind_axiom name ax env let instanciate p tys env = match by_path_opt p env with | Some ({ ax_spec = f } as ax) -> Fsubst.subst_tvar (EcTypes.Tvar.init (List.map fst ax.ax_tparams) tys) f | _ -> raise (LookupFailure (`Path p)) let iter ?name f (env : env) = gen_iter (fun mc -> mc.mc_axioms) MC.lookup_axioms ?name f env let all ?check ?name (env : env) = gen_all (fun mc -> mc.mc_axioms) MC.lookup_axioms ?check ?name env end (* -------------------------------------------------------------------- *) module Schema = struct type t = ax_schema let by_path_opt (p : EcPath.path) (env : env) = omap check_not_suspended (MC.by_path (fun mc -> mc.mc_schemas) (IPPath p) env) let by_path (p : EcPath.path) (env : env) = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_schema p obj env let lookup qname (env : env) = MC.lookup_schema qname env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let bind ?(import = import0) name ax env = let ax = NormMp.norm_sc env ax in let env = MC.bind_schema name ax env in { env with env_item = mkitem import (Th_schema (name, ax)) :: env.env_item } let rebind name ax env = MC.bind_schema name ax env let instanciate p tys (mt : EcMemory.memtype) ps es env = match by_path_opt p env with | Some ({ axs_spec = f } as sc) -> EcDecl.sc_instantiate sc.axs_tparams sc.axs_pparams sc.axs_params tys mt ps es f | _ -> raise (LookupFailure (`Path p)) let iter ?name f (env : env) = match name with | Some name -> let scs = MC.lookup_schemas name env in List.iter (fun (p,sc) -> f p sc) scs | None -> Mip.iter (fun _ mc -> MMsym.iter (fun _ (ip, sc) -> match ip with IPPath p -> f p sc | _ -> ()) mc.mc_schemas) env.env_comps let all ?(check = fun _ _ -> true) ?name (env : env) = match name with | Some name -> let scs = MC.lookup_schemas name env in List.filter (fun (p, sc) -> check p sc) scs | None -> Mip.fold (fun _ mc aout -> MMsym.fold (fun _ schemas aout -> List.fold_right (fun (ip, sc) aout -> match ip with | IPPath p -> if check p sc then (p, sc) :: aout else aout | _ -> aout) schemas aout) mc.mc_schemas aout) env.env_comps [] end (* -------------------------------------------------------------------- *) module Algebra = struct let bind_ring ty cr env = assert (Mid.is_empty ty.ty_fv); { env with env_tci = TypeClass.bind_instance ([], ty) (`Ring cr) env.env_tci } let bind_field ty cr env = assert (Mid.is_empty ty.ty_fv); { env with env_tci = TypeClass.bind_instance ([], ty) (`Field cr) env.env_tci } let add_ring ty cr lc env = TypeClass.add_instance ([], ty) (`Ring cr) lc env let add_field ty cr lc env = TypeClass.add_instance ([], ty) (`Field cr) lc env end (* -------------------------------------------------------------------- *) module Theory = struct type t = ctheory type mode = [`All | thmode] (* ------------------------------------------------------------------ *) let enter name env = enter `Theory name env (* ------------------------------------------------------------------ *) let by_path_opt ?(mode = `All)(p : EcPath.path) (env : env) = let obj = match MC.by_path (fun mc -> mc.mc_theories) (IPPath p) env, mode with | (Some (_, {cth_mode = `Concrete })) as obj, (`All | `Concrete) -> obj | (Some (_, {cth_mode = `Abstract })) as obj, (`All | `Abstract) -> obj | _, _ -> None in omap check_not_suspended obj let by_path ?mode (p : EcPath.path) (env : env) = match by_path_opt ?mode p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_theory p obj env let lookup ?(mode = `Concrete) qname (env : env) = match MC.lookup_theory qname env, mode with | (_, { cth_mode = `Concrete }) as obj, (`All | `Concrete) -> obj | (_, { cth_mode = `Abstract }) as obj, (`All | `Abstract) -> obj | _ -> lookup_error (`QSymbol qname) let lookup_opt ?mode name env = try_lf (fun () -> lookup ?mode name env) let lookup_path ?mode name env = fst (lookup ?mode name env) (* ------------------------------------------------------------------ *) let rec bind_instance_th path inst cth = List.fold_left (bind_instance_th_item path) inst cth and bind_instance_th_item path inst item = if not item.ti_import.im_atimport then inst else let xpath x = EcPath.pqname path x in match item.ti_item with | Th_instance (ty, k, _) -> TypeClass.bind_instance ty k inst | Th_theory (x, cth) when cth.cth_mode = `Concrete -> bind_instance_th (xpath x) inst cth.cth_items | Th_type (x, tyd) -> begin match tyd.tyd_type with | `Abstract tc -> let myty = let typ = List.map (fst_map EcIdent.fresh) tyd.tyd_params in (typ, EcTypes.tconstr (xpath x) (List.map (tvar |- fst) typ)) in Sp.fold (fun p inst -> TypeClass.bind_instance myty (`General p) inst) tc inst | _ -> inst end | _ -> inst (* ------------------------------------------------------------------ *) let rec bind_base_th tx path base cth = List.fold_left (bind_base_th_item tx path) base cth and bind_base_th_item tx path base item = if not item.ti_import.im_atimport then base else let xpath x = EcPath.pqname path x in match item.ti_item with | Th_theory (x, cth) -> begin match cth.cth_mode with | `Concrete -> bind_base_th tx (xpath x) base cth.cth_items | `Abstract -> base end | _ -> odfl base (tx path base item.ti_item) (* ------------------------------------------------------------------ *) let bind_tc_th = let for1 path base = function | Th_typeclass (x, tc) -> tc.tc_prt |> omap (fun prt -> let src = EcPath.pqname path x in TC.Graph.add ~src ~dst:prt base) | _ -> None in bind_base_th for1 (* ------------------------------------------------------------------ *) let bind_br_th = let for1 path base = function | Th_baserw (x,_) -> let ip = IPPath (EcPath.pqname path x) in assert (not (Mip.mem ip base)); Some (Mip.add ip Sp.empty base) | Th_addrw (b, r, _) -> let change = function | None -> assert false | Some s -> Some (List.fold_left (fun s r -> Sp.add r s) s r) in Some (Mip.change change (IPPath b) base) | _ -> None in bind_base_th for1 (* ------------------------------------------------------------------ *) let bind_at_th = let for1 _path db = function | Th_auto (level, base, ps, _) -> Some (Auto.updatedb ?base ~level ps db) | _ -> None in bind_base_th for1 (* ------------------------------------------------------------------ *) let bind_nt_th = let for1 path base = function | Th_operator (x, ({ op_kind = OB_nott nt } as op)) -> Some ((EcPath.pqname path x, (op.op_tparams, nt)) :: base) | _ -> None in bind_base_th for1 (* ------------------------------------------------------------------ *) let bind_rd_th = let for1 _path db = function | Th_reduction rules -> let rules = List.map (fun (x, _, y) -> (x, y)) rules in Some (Reduction.add_rules rules db) | _ -> None in bind_base_th for1 (* ------------------------------------------------------------------ *) let add_restr_th = let for1 path env = function | Th_module me -> Some (Mod.add_restr_to_declared path me env) | _ -> None in bind_base_th for1 (* ------------------------------------------------------------------ *) let bind ?(import = import0) name ({ cth_items = items; cth_mode = mode } as cth) env = let env = MC.bind_theory name cth env in let env = { env with env_item = mkitem import (Th_theory (name, cth)) :: env.env_item } in match import, mode with | _, `Concrete -> let thname = EcPath.pqname (root env) name in let env_tci = bind_instance_th thname env.env_tci items in let env_tc = bind_tc_th thname env.env_tc items in let env_rwbase = bind_br_th thname env.env_rwbase items in let env_atbase = bind_at_th thname env.env_atbase items in let env_ntbase = bind_nt_th thname env.env_ntbase items in let env_redbase = bind_rd_th thname env.env_redbase items in let env = { env with env_tci; env_tc; env_rwbase; env_atbase; env_ntbase; env_redbase; } in add_restr_th thname env items | _, _ -> env (* ------------------------------------------------------------------ *) let rebind name th env = MC.bind_theory name th env (* ------------------------------------------------------------------ *) let import (path : EcPath.path) (env : env) = let rec import (env : env) path (th : theory) = let xpath x = EcPath.pqname path x in let import_th_item (env : env) (item : theory_item) = if not item.ti_import.im_atimport then env else match item.ti_item with | Th_type (x, ty) -> if ty.tyd_resolve then MC.import_tydecl (xpath x) ty env else env | Th_operator (x, op) -> MC.import_operator (xpath x) op env | Th_axiom (x, ax) -> if ax.ax_visibility <> `Hidden then MC.import_axiom (xpath x) ax env else env | Th_schema (x, schema) -> MC.import_schema (xpath x) schema env | Th_modtype (x, mty) -> MC.import_modty (xpath x) mty env | Th_module ({ tme_expr = me; tme_loca = lc; }) -> let env = MC.import_mod (IPPath (xpath me.me_name)) (me, Some lc) env in let env = MC.import_mc (IPPath (xpath me.me_name)) env in env | Th_export (p, _) -> import env p (by_path ~mode:`Concrete p env).cth_items | Th_theory (x, ({cth_mode = `Concrete} as th)) -> let env = MC.import_theory (xpath x) th env in let env = MC.import_mc (IPPath (xpath x)) env in env | Th_theory (x, ({cth_mode = `Abstract} as th)) -> MC.import_theory (xpath x) th env | Th_typeclass (x, tc) -> MC.import_typeclass (xpath x) tc env | Th_baserw (x, _) -> MC.import_rwbase (xpath x) env | Th_addrw _ | Th_instance _ | Th_auto _ | Th_reduction _ -> env in List.fold_left import_th_item env th in import env path (by_path ~mode:`Concrete path env).cth_items (* ------------------------------------------------------------------ *) let export (path : EcPath.path) lc (env : env) = let env = import path env in { env with env_item = mkitem import0 (Th_export (path, lc)) :: env.env_item } (* ------------------------------------------------------------------ *) let rec filter clears root cleared items = snd_map (List.pmap identity) (List.map_fold (filter1 clears root) cleared items) and filter_th clears root cleared items = let mempty = List.exists (EcPath.p_equal root) clears in let cleared, items = filter clears root cleared items in if mempty && List.is_empty items then (Sp.add root cleared, None) else (cleared, Some items) and filter1 clears root = let inclear p = List.exists (EcPath.p_equal p) clears in let thclear = inclear root in fun cleared item -> let cleared, item_r = match item.ti_item with | Th_theory (x, cth) -> let cleared, items = let xpath = EcPath.pqname root x in filter_th clears xpath cleared cth.cth_items in let item = items |> omap (fun items -> let cth = { cth with cth_items = items } in Th_theory (x, cth)) in (cleared, item) | _ -> let item_r = match item.ti_item with | Th_axiom (_, { ax_kind = `Lemma }) when thclear -> None | Th_axiom (x, ({ ax_kind = `Axiom (tags, false) } as ax)) when thclear -> Some (Th_axiom (x, { ax with ax_kind = `Axiom (tags, true) })) | Th_addrw (p, ps, lc) -> let ps = List.filter ((not) |- inclear |- oget |- EcPath.prefix) ps in if List.is_empty ps then None else Some (Th_addrw (p, ps,lc)) | Th_auto (lvl, base, ps, lc) -> let ps = List.filter ((not) |- inclear |- oget |- EcPath.prefix) ps in if List.is_empty ps then None else Some (Th_auto (lvl, base, ps, lc)) | (Th_export (p, _)) as item -> if Sp.mem p cleared then None else Some item | _ as item -> Some item in (cleared, item_r) in (cleared, omap (fun item_r -> { item with ti_item = item_r; }) item_r) (* ------------------------------------------------------------------ *) let close ?(clears = []) ?(pempty = `No) loca mode env = let items = List.rev env.env_item in let items = if List.is_empty clears then (if List.is_empty items then None else Some items) else snd (filter_th clears (root env) Sp.empty items) in let items = match items, pempty with | None, (`No | `ClearOnly) -> Some [] | _, _ -> items in items |> omap (fun items -> { cth_items = items; cth_source = None; cth_loca = loca; cth_mode = mode; }) (* ------------------------------------------------------------------ *) let require x cth env = let rootnm = EcCoreLib.p_top in let thpath = EcPath.pqname rootnm x in let env = match cth.cth_mode with | `Concrete -> let (_, thmc), submcs = MC.mc_of_theory_r rootnm (x, cth) in MC.bind_submc env rootnm ((x, thmc), submcs) | `Abstract -> env in let th = cth in let topmc = Mip.find (IPPath rootnm) env.env_comps in let topmc = MC._up_theory false topmc x (IPPath thpath, th) in let topmc = MC._up_mc false topmc (IPPath thpath) in let current = env.env_current in let current = MC._up_theory true current x (IPPath thpath, th) in let current = MC._up_mc true current (IPPath thpath) in let comps = env.env_comps in let comps = Mip.add (IPPath rootnm) topmc comps in let env = { env with env_current = current; env_comps = comps; } in match cth.cth_mode with | `Abstract -> env | `Concrete -> { env with env_tci = bind_instance_th thpath env.env_tci cth.cth_items; env_tc = bind_tc_th thpath env.env_tc cth.cth_items; env_rwbase = bind_br_th thpath env.env_rwbase cth.cth_items; env_atbase = bind_at_th thpath env.env_atbase cth.cth_items; env_ntbase = bind_nt_th thpath env.env_ntbase cth.cth_items; env_redbase = bind_rd_th thpath env.env_redbase cth.cth_items; } end (* -------------------------------------------------------------------- *) let initial gstate = empty gstate (* -------------------------------------------------------------------- *) type ebinding = [ | `Variable of EcTypes.ty | `Function of function_ | `Module of module_expr | `ModType of module_sig ] (* FIXME section : Global ? *) let bind1 ((x, eb) : symbol * ebinding) (env : env) = match eb with | `Variable ty -> Var .bind_pvglob x ty env | `Function f -> Fun .bind x f env | `Module m -> Mod .bind x {tme_expr = m; tme_loca = `Global} env | `ModType i -> ModTy .bind x {tms_sig = i; tms_loca = `Global} env let bindall (items : (symbol * ebinding) list) (env : env) = List.fold_left ((^~) bind1) env items (* -------------------------------------------------------------------- *) module LDecl = struct type error = | InvalidKind of EcIdent.t * [`Variable | `Hypothesis] | CannotClear of EcIdent.t * EcIdent.t | NameClash of [`Ident of EcIdent.t | `Symbol of symbol] | LookupError of [`Ident of EcIdent.t | `Symbol of symbol] exception LdeclError of error let pp_error fmt (exn : error) = match exn with | LookupError (`Symbol s) -> Format.fprintf fmt "unknown symbol %s" s | NameClash (`Symbol s) -> Format.fprintf fmt "an hypothesis or variable named `%s` already exists" s | InvalidKind (x, `Variable) -> Format.fprintf fmt "`%s` is not a variable" (EcIdent.name x) | InvalidKind (x, `Hypothesis) -> Format.fprintf fmt "`%s` is not an hypothesis" (EcIdent.name x) | CannotClear (id1,id2) -> Format.fprintf fmt "cannot clear %s as it is used in %s" (EcIdent.name id1) (EcIdent.name id2) | LookupError (`Ident id) -> Format.fprintf fmt "unknown identifier `%s`, please report" (EcIdent.tostring id) | NameClash (`Ident id) -> Format.fprintf fmt "name clash for `%s`, please report" (EcIdent.tostring id) let _ = EcPException.register (fun fmt exn -> match exn with | LdeclError e -> pp_error fmt e | _ -> raise exn) let error e = raise (LdeclError e) (* ------------------------------------------------------------------ *) let ld_subst s ld = match ld with | LD_var (ty, body) -> LD_var (s.fs_ty ty, body |> omap (Fsubst.f_subst s)) | LD_mem mt -> let mt = EcMemory.mt_subst s.fs_ty mt in LD_mem mt | LD_modty p -> let p = gty_as_mod (Fsubst.subst_gty s (GTmodty p)) in LD_modty p | LD_hyp f -> LD_hyp (Fsubst.f_subst s f) FIXME assert false (* ------------------------------------------------------------------ *) let ld_fv = function | LD_var (ty, None) -> ty.ty_fv | LD_var (ty,Some f) -> EcIdent.fv_union ty.ty_fv f.f_fv | LD_mem mt -> EcMemory.mt_fv mt | LD_hyp f -> f.f_fv | LD_modty p -> gty_fv (GTmodty p) | LD_abs_st us -> let add fv (x,_) = match x with | PVglob x -> EcPath.x_fv fv x | PVloc _ -> fv in let fv = Mid.empty in let fv = List.fold_left add fv us.aus_reads in let fv = List.fold_left add fv us.aus_writes in List.fold_left EcPath.x_fv fv us.aus_calls (* ------------------------------------------------------------------ *) let by_name s hyps = match List.ofind ((=) s |- EcIdent.name |- fst) hyps.h_local with | None -> error (LookupError (`Symbol s)) | Some h -> h let by_id id hyps = match List.ofind (EcIdent.id_equal id |- fst) hyps.h_local with | None -> error (LookupError (`Ident id)) | Some x -> snd x (* ------------------------------------------------------------------ *) let as_hyp = function | (id, LD_hyp f) -> (id, f) | (id, _) -> error (InvalidKind (id, `Hypothesis)) let as_var = function | (id, LD_var (ty, _)) -> (id, ty) | (id, _) -> error (InvalidKind (id, `Variable)) (* ------------------------------------------------------------------ *) let hyp_by_name s hyps = as_hyp (by_name s hyps) let var_by_name s hyps = as_var (by_name s hyps) (* ------------------------------------------------------------------ *) let hyp_by_id x hyps = as_hyp (x, by_id x hyps) let var_by_id x hyps = as_var (x, by_id x hyps) (* ------------------------------------------------------------------ *) let has_gen dcast s hyps = try ignore (dcast (by_name s hyps)); true with LdeclError (InvalidKind _ | LookupError _) -> false let hyp_exists s hyps = has_gen as_hyp s hyps let var_exists s hyps = has_gen as_var s hyps (* ------------------------------------------------------------------ *) let has_id x hyps = try ignore (by_id x hyps); true with LdeclError (LookupError _) -> false let has_inld s = function | LD_mem mt -> is_bound s mt | _ -> false let has_name ?(dep = false) s hyps = let test (id, k) = EcIdent.name id = s || (dep && has_inld s k) in List.exists test hyps.h_local (* ------------------------------------------------------------------ *) let can_unfold id hyps = try match by_id id hyps with LD_var (_, Some _) -> true | _ -> false with LdeclError _ -> false let unfold id hyps = try match by_id id hyps with | LD_var (_, Some f) -> f | _ -> raise NotReducible with LdeclError _ -> raise NotReducible (* ------------------------------------------------------------------ *) let check_name_clash id hyps = if has_id id hyps then error (NameClash (`Ident id)) else let s = EcIdent.name id in if s <> "_" && has_name ~dep:false s hyps then error (NameClash (`Symbol s)) let add_local id ld hyps = check_name_clash id hyps; { hyps with h_local = (id, ld) :: hyps.h_local } (* ------------------------------------------------------------------ *) let fresh_id hyps s = let s = if s = "_" || not (has_name ~dep:true s hyps) then s else let rec aux n = let s = Printf.sprintf "%s%d" s n in if has_name ~dep:true s hyps then aux (n+1) else s in aux 0 in EcIdent.create s let fresh_ids hyps names = let do1 hyps s = let id = fresh_id hyps s in (add_local id (LD_var (tbool, None)) hyps, id) in List.map_fold do1 hyps names (* ------------------------------------------------------------------ *) type hyps = { le_init : env; le_env : env; le_hyps : EcBaseLogic.hyps; } let tohyps lenv = lenv.le_hyps let toenv lenv = lenv.le_env let baseenv lenv = lenv.le_init let add_local_env x k env = match k with | LD_var (ty, _) -> Var.bind_local x ty env | LD_mem mt -> Memory.push (x, mt) env | LD_modty i -> Mod.bind_local x i env | LD_hyp _ -> env | LD_abs_st us -> AbsStmt.bind x us env (* ------------------------------------------------------------------ *) let add_local x k h = let le_hyps = add_local x k (tohyps h) in let le_env = add_local_env x k h.le_env in { h with le_hyps; le_env; } (* ------------------------------------------------------------------ *) let init env ?(locals = []) tparams = let buildenv env = List.fold_right (fun (x, k) env -> add_local_env x k env) locals env in { le_init = env; le_env = buildenv env; le_hyps = { h_tvar = tparams; h_local = locals; }; } (* ------------------------------------------------------------------ *) let clear ?(leniant = false) ids hyps = let rec filter ids hyps = match hyps with [] -> [] | ((id, lk) as bd) :: hyps -> let ids, bd = if EcIdent.Sid.mem id ids then (ids, None) else let fv = ld_fv lk in if Mid.set_disjoint ids fv then (ids, Some bd) else if leniant then (Mid.set_diff ids fv, Some bd) else let inter = Mid.set_inter ids fv in error (CannotClear (Sid.choose inter, id)) in List.ocons bd (filter ids hyps) in let locals = filter ids hyps.le_hyps.h_local in init hyps.le_init ~locals hyps.le_hyps.h_tvar (* ------------------------------------------------------------------ *) let hyp_convert x check hyps = let module E = struct exception NoOp end in let init locals = init hyps.le_init ~locals hyps.le_hyps.h_tvar in let rec doit locals = match locals with | (y, LD_hyp fp) :: locals when EcIdent.id_equal x y -> begin let fp' = check (lazy (init locals)) fp in if fp == fp' then raise E.NoOp else (x, LD_hyp fp') :: locals end | [] -> error (LookupError (`Ident x)) | ld :: locals -> ld :: (doit locals) in (try Some (doit hyps.le_hyps.h_local) with E.NoOp -> None) |> omap init (* ------------------------------------------------------------------ *) let local_hyps x hyps = let rec doit locals = match locals with | (y, _) :: locals -> if EcIdent.id_equal x y then locals else doit locals | [] -> error (LookupError (`Ident x)) in let locals = doit hyps.le_hyps.h_local in init hyps.le_init ~locals hyps.le_hyps.h_tvar (* ------------------------------------------------------------------ *) let by_name s hyps = by_name s (tohyps hyps) let by_id x hyps = by_id x (tohyps hyps) let has_name s hyps = has_name ~dep:false s (tohyps hyps) let has_id x hyps = has_id x (tohyps hyps) let hyp_by_name s hyps = hyp_by_name s (tohyps hyps) let hyp_exists s hyps = hyp_exists s (tohyps hyps) let hyp_by_id x hyps = snd (hyp_by_id x (tohyps hyps)) let var_by_name s hyps = var_by_name s (tohyps hyps) let var_exists s hyps = var_exists s (tohyps hyps) let var_by_id x hyps = snd (var_by_id x (tohyps hyps)) let can_unfold x hyps = can_unfold x (tohyps hyps) let unfold x hyps = unfold x (tohyps hyps) let fresh_id hyps s = fresh_id (tohyps hyps) s let fresh_ids hyps s = snd (fresh_ids (tohyps hyps) s) (* ------------------------------------------------------------------ *) let push_active m lenv = { lenv with le_env = Memory.push_active m lenv.le_env } let push_all l lenv = { lenv with le_env = Memory.push_all l lenv.le_env } let hoareF xp lenv = let env1, env2 = Fun.hoareF xp lenv.le_env in { lenv with le_env = env1}, {lenv with le_env = env2 } let equivF xp1 xp2 lenv = let env1, env2 = Fun.equivF xp1 xp2 lenv.le_env in { lenv with le_env = env1}, {lenv with le_env = env2 } let inv_memenv lenv = { lenv with le_env = Fun.inv_memenv lenv.le_env } let inv_memenv1 lenv = { lenv with le_env = Fun.inv_memenv1 lenv.le_env } end let pp_debug_form = ref (fun _env _fmt _f -> assert false)
null
https://raw.githubusercontent.com/EasyCrypt/easycrypt/2e53a4272c940b41400de9ce42c8db7f6a514ee7/src/ecEnv.ml
ocaml
-------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- Paths as stored in the environment: * - Either a full path (sequence of symbols) * - Either a ident (module variable) followed by a optional path (inner path) * * No functor applications are present in these paths. for global program variable for fun and local program variable -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- declared modules in reverse order -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ position of args in path arguments of top enclosing module argument names ------------------------------------------------------------------ position of args in path arguments of top enclosing module argument names ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ -------------------------------------------------------------------- FIXME: remove -------------------------------------------------------------------- -------------------------------------------------------------------- TODO : A: -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- ------------------------------------------------------------------ -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- FIXME error message FIXME error message -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- FIXME : this test is dubious for functors lookup FIXME:MERGE-COST -------------------------------------------------------------------- ((top' args').sub').sub A submodule cannot be a functor The top is in normal form simply normalize the arguments We are in typing mod .... Return [true] if [x] is forbidden in [restr]. As an invariant, we have that [mt] is fully applied. We need to clear the oracle restriction using [me] params We compute the oracle call information. We compute the postive restriction not normalized. -------------------------------------------------------------------- eta-normal form -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ -------------------------------------------------------------------- -------------------------------------------------------------------- FIXME section : Global ? -------------------------------------------------------------------- ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------
open EcUtils open EcSymbols open EcPath open EcTypes open EcCoreFol open EcMemory open EcDecl open EcModules open EcTheory open EcBaseLogic module Ssym = EcSymbols.Ssym module Msym = EcSymbols.Msym module Mp = EcPath.Mp module Sid = EcIdent.Sid module Mid = EcIdent.Mid module TC = EcTypeClass module Mint = EcMaps.Mint type 'a suspension = { sp_target : 'a; sp_params : int * (EcIdent.t * module_type) list; } let check_not_suspended (params, obj) = if not (List.for_all (fun x -> x = None) params) then assert false; obj type ipath = | IPPath of EcPath.path | IPIdent of EcIdent.t * EcPath.path option let ibasename p = match p with | IPPath p -> EcPath.basename p | IPIdent (m, None) -> EcIdent.name m | IPIdent (_, Some p) -> EcPath.basename p module IPathC = struct type t = ipath let compare p1 p2 = match p1, p2 with | IPIdent _, IPPath _ -> -1 | IPPath _, IPIdent _ -> 1 | IPIdent (i1, p1), IPIdent (i2, p2) -> begin match EcIdent.id_compare i1 i2 with | 0 -> ocompare EcPath.p_compare p1 p2 | i -> i end | IPPath p1, IPPath p2 -> EcPath.p_compare p1 p2 end module Mip = EcMaps.Map.Make(IPathC) module Sip = EcMaps.Set.MakeOfMap(Mip) let ippath_as_path (ip : ipath) = match ip with IPPath p -> p | _ -> assert false type glob_var_bind = EcTypes.ty type mc = { mc_parameters : ((EcIdent.t * module_type) list) option; mc_variables : (ipath * glob_var_bind) MMsym.t; mc_functions : (ipath * function_) MMsym.t; mc_modules : (ipath * (module_expr * locality option)) MMsym.t; mc_modsigs : (ipath * top_module_sig) MMsym.t; mc_tydecls : (ipath * EcDecl.tydecl) MMsym.t; mc_operators : (ipath * EcDecl.operator) MMsym.t; mc_axioms : (ipath * EcDecl.axiom) MMsym.t; mc_schemas : (ipath * EcDecl.ax_schema) MMsym.t; mc_theories : (ipath * ctheory) MMsym.t; mc_typeclasses: (ipath * typeclass) MMsym.t; mc_rwbase : (ipath * path) MMsym.t; mc_components : ipath MMsym.t; } type use = { us_pv : ty Mx.t; us_gl : Sid.t; } let use_union us1 us2 = { us_pv = Mx.union (fun _ ty _ -> Some ty) us1.us_pv us2.us_pv; us_gl = Sid.union us1.us_gl us2.us_gl; } let use_empty = { us_pv = Mx.empty; us_gl = Sid.empty; } type env_norm = { norm_mp : EcPath.mpath Mm.t; mod_use : use Mm.t; get_restr_use : (use EcModules.use_restr) Mm.t; } type red_topsym = [ | `Path of path | `Tuple | `Cost of [`Path of path | `Tuple] ] module Mrd = EcMaps.Map.Make(struct type t = red_topsym let rec compare (p1 : t) (p2 : t) = match p1, p2 with | `Path p1, `Path p2 -> EcPath.p_compare p1 p2 | `Tuple , `Tuple -> 0 | `Cost p1, `Cost p2 -> compare (p1 :> red_topsym) (p2 :> red_topsym) | `Tuple , `Path _ | `Cost _ , `Path _ | `Cost _ , `Tuple -> -1 | `Path _ , `Tuple | `Path _ , `Cost _ | `Tuple , `Cost _ -> 1 end) module Mmem : sig type 'a t val empty : 'a t val all : 'a t -> (EcIdent.t * 'a) list val byid : EcIdent.t -> 'a t -> 'a val bysym : EcSymbols.symbol -> 'a t -> EcIdent.t * 'a val add : EcIdent.t -> 'a -> 'a t -> 'a t end = struct type 'a t = { m_s : memory Msym.t; m_id : 'a Mid.t; } let empty = { m_s = Msym.empty; m_id = Mid.empty; } let all m = Mid.bindings m.m_id let byid id m = Mid.find id m.m_id let bysym s m = let id = Msym.find s m.m_s in id, byid id m let add id a m = { m_s = Msym.add (EcIdent.name id) id m.m_s; m_id = Mid.add id a m.m_id } end type preenv = { env_top : EcPath.path option; env_gstate : EcGState.gstate; env_scope : escope; env_current : mc; env_comps : mc Mip.t; env_locals : (EcIdent.t * EcTypes.ty) MMsym.t; env_memories : EcMemory.memtype Mmem.t; env_actmem : EcMemory.memory option; env_abs_st : EcModules.abs_uses Mid.t; env_tci : ((ty_params * ty) * tcinstance) list; env_tc : TC.graph; env_rwbase : Sp.t Mip.t; env_atbase : (path list Mint.t) Msym.t; env_redbase : mredinfo; env_ntbase : (path * env_notation) list; env_norm : env_norm ref; } and escope = { ec_path : EcPath.path; ec_scope : scope; } and scope = [ | `Theory | `Module of EcPath.mpath | `Fun of EcPath.xpath ] and tcinstance = [ | `Ring of EcDecl.ring | `Field of EcDecl.field | `General of EcPath.path ] and redinfo = { ri_priomap : (EcTheory.rule list) Mint.t; ri_list : (EcTheory.rule list) Lazy.t; } and mredinfo = redinfo Mrd.t and env_notation = ty_params * EcDecl.notation type env = preenv let root (env : env) = env.env_scope.ec_path let mroot (env : env) = match env.env_scope.ec_scope with | `Theory -> EcPath.mpath_crt (root env) [] None | `Module m -> m | `Fun x -> x.EcPath.x_top let xroot (env : env) = match env.env_scope.ec_scope with | `Fun x -> Some x | _ -> None let scope (env : env) = env.env_scope.ec_scope let astop (env : env) = { env with env_top = Some (root env); } let gstate (env : env) = env.env_gstate let notify ?(immediate = true) (env : preenv) (lvl : EcGState.loglevel) msg = let buf = Buffer.create 0 in let fbuf = Format.formatter_of_buffer buf in ignore immediate; Format.kfprintf (fun _ -> Format.pp_print_flush fbuf (); EcGState.notify lvl (lazy (Buffer.contents buf)) (gstate env)) fbuf msg let empty_mc params = { mc_parameters = params; mc_modules = MMsym.empty; mc_modsigs = MMsym.empty; mc_tydecls = MMsym.empty; mc_operators = MMsym.empty; mc_axioms = MMsym.empty; mc_schemas = MMsym.empty; mc_theories = MMsym.empty; mc_variables = MMsym.empty; mc_functions = MMsym.empty; mc_typeclasses= MMsym.empty; mc_rwbase = MMsym.empty; mc_components = MMsym.empty; } let empty_norm_cache = { norm_mp = Mm.empty; norm_xpv = Mx.empty; norm_xfun = Mx.empty; mod_use = Mm.empty; get_restr_use = Mm.empty; } let empty gstate = let name = EcCoreLib.i_top in let path = EcPath.psymbol name in let env_current = let icomps = MMsym.add name (IPPath path) MMsym.empty in { (empty_mc None) with mc_components = icomps } in { env_top = None; env_gstate = gstate; env_scope = { ec_path = path; ec_scope = `Theory; }; env_current = env_current; env_comps = Mip.singleton (IPPath path) (empty_mc None); env_locals = MMsym.empty; env_memories = Mmem.empty; env_actmem = None; env_abs_st = Mid.empty; env_tci = []; env_tc = TC.Graph.empty; env_rwbase = Mip.empty; env_atbase = Msym.empty; env_redbase = Mrd.empty; env_ntbase = []; env_modlcs = Sid.empty; env_item = []; env_norm = ref empty_norm_cache; } let copy (env : env) = { env with env_gstate = EcGState.copy env.env_gstate } type lookup_error = [ | `XPath of xpath | `MPath of mpath | `Path of path | `QSymbol of qsymbol | `AbsStmt of EcIdent.t ] exception LookupFailure of lookup_error let pp_lookup_failure fmt e = let p = match e with | `XPath p -> EcPath.x_tostring p | `MPath p -> EcPath.m_tostring p | `Path p -> EcPath.tostring p | `QSymbol p -> string_of_qsymbol p | `AbsStmt p -> EcIdent.tostring p in Format.fprintf fmt "unknown symbol: %s" p let () = let pp fmt exn = match exn with | LookupFailure p -> pp_lookup_failure fmt p | _ -> raise exn in EcPException.register pp let lookup_error cause = raise (LookupFailure cause) exception NotReducible exception DuplicatedBinding of symbol let _ = EcPException.register (fun fmt exn -> match exn with | DuplicatedBinding s -> Format.fprintf fmt "the symbol %s already exists" s | _ -> raise exn) module MC = struct let top_path = EcPath.psymbol EcCoreLib.i_top let _cutpath i p = let rec doit i p = match p.EcPath.p_node with | EcPath.Psymbol _ -> (p, `Ct (i-1)) | EcPath.Pqname (p, x) -> begin match doit i p with | (p, `Ct 0) -> (p, `Dn (EcPath.psymbol x)) | (p, `Ct i) -> (EcPath.pqname p x, `Ct (i-1)) | (p, `Dn q) -> (p, `Dn (EcPath.pqname q x)) end in match doit i p with | (p, `Ct 0) -> (p, None) | (_, `Ct _) -> assert false | (p, `Dn q) -> (p, Some q) let _downpath_for_modcp isvar ~spsc env p args = let prefix = let prefix_of_mtop = function | `Concrete (p1, _) -> Some p1 | `Local _ -> None in match env.env_scope.ec_scope with | `Theory -> None | `Module m -> prefix_of_mtop m.EcPath.m_top | `Fun m -> prefix_of_mtop m.EcPath.x_top.EcPath.m_top in try let (l, a, r) = List.find_pivot (fun x -> x <> None) args in if not (List.for_all (fun x -> x = None) r) then assert false; let (ap, inscope) = match p with | IPPath p -> begin p , q = frontier with the first module let (p, q) = _cutpath (i+1) p in match q with | None -> assert false | Some q -> begin let ap = EcPath.xpath (EcPath.mpath_crt p (if isvar then [] else List.map EcPath.mident n) (EcPath.prefix q)) (EcPath.basename q) in (ap, odfl false (prefix |> omap (EcPath.p_equal p))) end end | IPIdent (m, x) -> begin if i <> 0 then assert false; match x |> omap (fun x -> x.EcPath.p_node) with | Some (EcPath.Psymbol x) -> let ap = EcPath.xpath (EcPath.mpath_abs m (if isvar then [] else List.map EcPath.mident n)) x in (ap, false) | _ -> assert false end in ((i+1, if (inscope && not spsc) || isvar then [] else a), ap) with Not_found -> assert false let _downpath_for_var = _downpath_for_modcp true let _downpath_for_fun = _downpath_for_modcp false let _downpath_for_mod spsc env p args = let prefix = let prefix_of_mtop = function | `Concrete (p1, _) -> Some p1 | `Local _ -> None in match env.env_scope.ec_scope with | `Theory -> None | `Module m -> prefix_of_mtop m.EcPath.m_top | `Fun m -> prefix_of_mtop m.EcPath.x_top.EcPath.m_top in let (l, a, r) = try List.find_pivot (fun x -> x <> None) args with Not_found -> (args, Some [], []) in if not (List.for_all (fun x -> x = None) r) then assert false; let (ap, inscope) = match p with | IPPath p -> p , q = frontier with the first module let (p, q) = _cutpath (i+1) p in (EcPath.mpath_crt p (List.map EcPath.mident n) q, odfl false (prefix |> omap (EcPath.p_equal p))) | IPIdent (m, None) -> if i <> 0 then assert false; (EcPath.mpath_abs m (List.map EcPath.mident n), false) | _ -> assert false in ((List.length l, if inscope && not spsc then [] else a), ap) let _downpath_for_th _env p args = if not (List.for_all (fun x -> x = None) args) then assert false; match p with | IPIdent _ -> assert false | IPPath p -> p let _downpath_for_tydecl = _downpath_for_th let _downpath_for_modsig = _downpath_for_th let _downpath_for_operator = _downpath_for_th let _downpath_for_axiom = _downpath_for_th let _downpath_for_schema = _downpath_for_th let _downpath_for_typeclass = _downpath_for_th let _downpath_for_rwbase = _downpath_for_th let _params_of_path p env = let rec _params_of_path acc p = match EcPath.prefix p with | None -> acc | Some p -> let mc = oget (Mip.find_opt (IPPath p) env.env_comps) in _params_of_path (mc.mc_parameters :: acc) p in _params_of_path [] p let _params_of_ipath p env = match p with | IPPath p -> _params_of_path p env | IPIdent (_, None) -> [] | IPIdent (m, Some p) -> assert (is_none (EcPath.prefix p)); let mc = Mip.find_opt (IPIdent (m, None)) env.env_comps in [(oget mc).mc_parameters] let by_path proj p env = let mcx = match p with | IPPath p -> begin match p.EcPath.p_node with | EcPath.Psymbol x -> Some (oget (Mip.find_opt (IPPath top_path) env.env_comps), x) | EcPath.Pqname (p, x) -> omap (fun mc -> (mc, x)) (Mip.find_opt (IPPath p) env.env_comps) end | IPIdent (id, None) -> Some (env.env_current, EcIdent.name id) | IPIdent (m, Some p) -> let prefix = EcPath.prefix p in let name = EcPath.basename p in omap (fun mc -> (mc, name)) (Mip.find_opt (IPIdent (m, prefix)) env.env_comps) in let lookup (mc, x) = List.filter (fun (ip, _) -> IPathC.compare ip p = 0) (MMsym.all x (proj mc)) in match mcx |> omap lookup with | None | Some [] -> None | Some (obj :: _) -> Some (_params_of_ipath p env, snd obj) let path_of_qn (top : EcPath.path) (qn : symbol list) = List.fold_left EcPath.pqname top qn let pcat (p1 : EcPath.path) (p2 : EcPath.path) = path_of_qn p1 (EcPath.tolist p2) let lookup_mc qn env = match qn with | [] -> Some env.env_current | x :: qn when x = EcCoreLib.i_self && is_some env.env_top -> let p = IPPath (path_of_qn (oget env.env_top) qn) in Mip.find_opt p env.env_comps | x :: qn -> let x = if x = EcCoreLib.i_self then EcCoreLib.i_top else x in let p = (MMsym.last x env.env_current.mc_components) |> obind (fun p -> match p, qn with | IPIdent _, [] -> Some p | IPIdent _, _ -> None | IPPath p, _ -> Some (IPPath (path_of_qn p qn))) in p |> obind (fun p -> Mip.find_opt p env.env_comps) let lookup proj (qn, x) env = let mc = lookup_mc qn env in omap (fun (p, obj) -> (p, (_params_of_ipath p env, obj))) (mc |> obind (fun mc -> MMsym.last x (proj mc))) let lookup_all proj (qn, x) env = let mc = lookup_mc qn env in let objs = odfl [] (mc |> omap (fun mc -> MMsym.all x (proj mc))) in let _, objs = List.map_fold (fun ps ((p, _) as obj)-> if Sip.mem p ps then (ps, None) else (Sip.add p ps, Some obj)) Sip.empty objs in List.pmap (omap (fun (p, obj) -> (p, (_params_of_ipath p env, obj)))) objs let bind up x obj env = let obj = (IPPath (EcPath.pqname (root env) x), obj) in let env = { env with env_current = up true env.env_current x obj } in { env with env_comps = Mip.change (fun mc -> Some (up false (oget mc) x obj)) (IPPath (root env)) env.env_comps; } let import up p obj env = let name = ibasename p in { env with env_current = up env.env_current name (p, obj) } let lookup_var qnx env = match lookup (fun mc -> mc.mc_variables) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, ty)) -> (_downpath_for_var ~spsc:false env p args, ty) let _up_var candup mc x obj = if not candup && MMsym.last x mc.mc_variables <> None then raise (DuplicatedBinding x); { mc with mc_variables = MMsym.add x obj mc.mc_variables } let import_var p var env = import (_up_var true) p var env let lookup_fun qnx env = match lookup (fun mc -> mc.mc_functions) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_fun ~spsc:false env p args, obj) let _up_fun candup mc x obj = if not candup && MMsym.last x mc.mc_functions <> None then raise (DuplicatedBinding x); { mc with mc_functions = MMsym.add x obj mc.mc_functions } let import_fun p fun_ env = import (_up_fun true) p fun_ env let lookup_mod qnx env = match lookup (fun mc -> mc.mc_modules) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_mod false env p args, obj) let _up_mod candup mc x obj = if not candup && MMsym.last x mc.mc_modules <> None then raise (DuplicatedBinding x); { mc with mc_modules = MMsym.add x obj mc.mc_modules } let import_mod p mod_ env = import (_up_mod true) p mod_ env let lookup_axiom qnx env = match lookup (fun mc -> mc.mc_axioms) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_axiom env p args, obj) let lookup_axioms qnx env = List.map (fun (p, (args, obj)) -> (_downpath_for_axiom env p args, obj)) (lookup_all (fun mc -> mc.mc_axioms) qnx env) let _up_axiom candup mc x obj = if not candup && MMsym.last x mc.mc_axioms <> None then raise (DuplicatedBinding x); { mc with mc_axioms = MMsym.add x obj mc.mc_axioms } let import_axiom p ax env = import (_up_axiom true) (IPPath p) ax env let lookup_schema qnx env = match lookup (fun mc -> mc.mc_schemas) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_schema env p args, obj) let lookup_schemas qnx env = List.map (fun (p, (args, obj)) -> (_downpath_for_schema env p args, obj)) (lookup_all (fun mc -> mc.mc_schemas) qnx env) let _up_schema candup mc x obj = if not candup && MMsym.last x mc.mc_schemas <> None then raise (DuplicatedBinding x); { mc with mc_schemas = MMsym.add x obj mc.mc_schemas } let import_schema p sc env = import (_up_schema true) (IPPath p) sc env let lookup_operator qnx env = match lookup (fun mc -> mc.mc_operators) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_operator env p args, obj) let lookup_operators qnx env = List.map (fun (p, (args, obj)) -> (_downpath_for_operator env p args, obj)) (lookup_all (fun mc -> mc.mc_operators) qnx env) let _up_operator candup mc x obj = let module ELI = EcInductive in if not candup && MMsym.last x mc.mc_operators <> None then raise (DuplicatedBinding x); let mypath = lazy (ippath_as_path (fst obj)) in let mc = { mc with mc_operators = MMsym.add x obj mc.mc_operators } in let ax = match (snd obj).op_kind with | OB_pred (Some (PR_Ind pri)) -> let pri = { ELI.ip_path = ippath_as_path (fst obj); ELI.ip_tparams = (snd obj).op_tparams; ELI.ip_prind = pri; } in ELI.prind_schemes pri | _ -> [] in let ax = List.map (fun (name, (tv, cl)) -> let axp = EcPath.prefix (Lazy.force mypath) in let axp = IPPath (EcPath.pqoname axp name) in let ax = { ax_kind = `Axiom (Ssym.empty, false); ax_tparams = tv; ax_spec = cl; ax_loca = (snd obj).op_loca; ax_visibility = `Visible; } in (name, (axp, ax))) ax in List.fold_left (fun mc -> curry (_up_axiom candup mc)) mc ax let import_operator p op env = import (_up_operator true) (IPPath p) op env let lookup_tydecl qnx env = match lookup (fun mc -> mc.mc_tydecls) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_tydecl env p args, obj) let lookup_tydecls qnx env = List.map (fun (p, (args, obj)) -> (_downpath_for_tydecl env p args, obj)) (lookup_all (fun mc -> mc.mc_tydecls) qnx env) let _up_tydecl candup mc x obj = if not candup && MMsym.last x mc.mc_tydecls <> None then raise (DuplicatedBinding x); let mc = { mc with mc_tydecls = MMsym.add x obj mc.mc_tydecls } in let mc = let mypath, tyd = match obj with IPPath p, x -> (p, x) | _, _ -> assert false in let ipath name = IPPath (EcPath.pqoname (EcPath.prefix mypath) name) in let loca = tyd.tyd_loca in match tyd.tyd_type with | `Concrete _ -> mc | `Abstract _ -> mc | `Datatype dtype -> let cs = dtype.tydt_ctors in let schelim = dtype.tydt_schelim in let schcase = dtype.tydt_schcase in let params = List.map (fun (x, _) -> tvar x) tyd.tyd_params in let for1 i (c, aty) = let aty = EcTypes.toarrow aty (tconstr mypath params) in let aty = EcSubst.freshen_type (tyd.tyd_params, aty) in let cop = mk_op ~opaque:false (fst aty) (snd aty) (Some (OP_Constr (mypath, i))) loca in let cop = (ipath c, cop) in (c, cop) in let (schelim, schcase) = let do1 scheme name = let scname = Printf.sprintf "%s_%s" x name in (scname, { ax_tparams = tyd.tyd_params; ax_spec = scheme; ax_kind = `Axiom (Ssym.empty, false); ax_loca = loca; ax_visibility = `NoSmt; }) in (do1 schelim "ind", do1 schcase "case") in let cs = List.mapi for1 cs in let mc = List.fold_left (fun mc (c, cop) -> _up_operator candup mc c cop) mc cs in let mc = _up_axiom candup mc (fst schcase) (fst_map ipath schcase) in let mc = _up_axiom candup mc (fst schelim) (fst_map ipath schelim) in let projs = (mypath, tyd.tyd_params, dtype) in let projs = EcInductive.datatype_projectors projs in List.fold_left (fun mc (c, op) -> let name = EcInductive.datatype_proj_name c in _up_operator candup mc name (ipath name, op) ) mc projs | `Record (scheme, fields) -> let params = List.map (fun (x, _) -> tvar x) tyd.tyd_params in let nfields = List.length fields in let cfields = let for1 i (f, aty) = let aty = EcTypes.tfun (tconstr mypath params) aty in let aty = EcSubst.freshen_type (tyd.tyd_params, aty) in let fop = mk_op ~opaque:false (fst aty) (snd aty) (Some (OP_Proj (mypath, i, nfields))) loca in let fop = (ipath f, fop) in (f, fop) in List.mapi for1 fields in let scheme = let scname = Printf.sprintf "%s_ind" x in (scname, { ax_tparams = tyd.tyd_params; ax_spec = scheme; ax_kind = `Axiom (Ssym.empty, false); ax_loca = loca; ax_visibility = `NoSmt; }) in let stname = Printf.sprintf "mk_%s" x in let stop = let stty = toarrow (List.map snd fields) (tconstr mypath params) in let stty = EcSubst.freshen_type (tyd.tyd_params, stty) in mk_op ~opaque:false (fst stty) (snd stty) (Some (OP_Record mypath)) loca in let mc = List.fold_left (fun mc (f, fop) -> _up_operator candup mc f fop) mc ((stname, (ipath stname, stop)) :: cfields) in _up_axiom candup mc (fst scheme) (fst_map ipath scheme) in mc let import_tydecl p tyd env = import (_up_tydecl true) (IPPath p) tyd env let lookup_modty qnx env = match lookup (fun mc -> mc.mc_modsigs) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_modsig env p args, obj) let _up_modty candup mc x obj = if not candup && MMsym.last x mc.mc_modsigs <> None then raise (DuplicatedBinding x); { mc with mc_modsigs = MMsym.add x obj mc.mc_modsigs } let import_modty p msig env = import (_up_modty true) (IPPath p) msig env let lookup_typeclass qnx env = match lookup (fun mc -> mc.mc_typeclasses) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_typeclass env p args, obj) let _up_typeclass candup mc x obj = if not candup && MMsym.last x mc.mc_typeclasses <> None then raise (DuplicatedBinding x); let mc = { mc with mc_typeclasses = MMsym.add x obj mc.mc_typeclasses } in let mc = let mypath, tc = match obj with IPPath p, x -> (p, x) | _, _ -> assert false in let xpath name = EcPath.pqoname (EcPath.prefix mypath) name in let loca = match tc.tc_loca with `Local -> `Local | `Global -> `Global in let self = EcIdent.create "'self" in let tsubst = { ty_subst_id with ts_def = Mp.add mypath ([], tvar self) Mp.empty } in let operators = let on1 (opid, optype) = let opname = EcIdent.name opid in let optype = ty_subst tsubst optype in let opdecl = mk_op ~opaque:false [(self, Sp.singleton mypath)] optype (Some OP_TC) loca in (opid, xpath opname, optype, opdecl) in List.map on1 tc.tc_ops in let fsubst = List.fold_left (fun s (x, xp, xty, _) -> let fop = EcCoreFol.f_op xp [tvar self] xty in Fsubst.f_bind_local s x fop) (Fsubst.f_subst_init ~sty:tsubst ()) operators in let axioms = List.map (fun (x, ax) -> let ax = Fsubst.f_subst fsubst ax in (x, { ax_tparams = [(self, Sp.singleton mypath)]; ax_spec = ax; ax_kind = `Axiom (Ssym.empty, false); ax_loca = loca; ax_visibility = `NoSmt; })) tc.tc_axs in let mc = List.fold_left (fun mc (_, fpath, _, fop) -> _up_operator candup mc (EcPath.basename fpath) (IPPath fpath, fop)) mc operators in List.fold_left (fun mc (x, ax) -> _up_axiom candup mc x (IPPath (xpath x), ax)) mc axioms in mc let import_typeclass p ax env = import (_up_typeclass true) (IPPath p) ax env let lookup_rwbase qnx env = match lookup (fun mc -> mc.mc_rwbase) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_rwbase env p args, obj) let _up_rwbase candup mc x obj= if not candup && MMsym.last x mc.mc_rwbase <> None then raise (DuplicatedBinding x); { mc with mc_rwbase = MMsym.add x obj mc.mc_rwbase } let import_rwbase p env = import (_up_rwbase true) (IPPath p) p env let _up_theory candup mc x obj = if not candup && MMsym.last x mc.mc_theories <> None then raise (DuplicatedBinding x); { mc with mc_theories = MMsym.add x obj mc.mc_theories } let lookup_theory qnx env = match lookup (fun mc -> mc.mc_theories) qnx env with | None -> lookup_error (`QSymbol qnx) | Some (p, (args, obj)) -> (_downpath_for_th env p args, obj) let import_theory p th env = import (_up_theory true) (IPPath p) th env let _up_mc candup mc p = let name = ibasename p in if not candup && MMsym.last name mc.mc_components <> None then raise (DuplicatedBinding name); { mc with mc_components = MMsym.add name p mc.mc_components } let import_mc p env = let mc = _up_mc true env.env_current p in { env with env_current = mc } let rec mc_of_module_r (p1, args, p2, lc) me = let subp2 x = let p = EcPath.pqoname p2 x in (p, pcat p1 p) in let mc1_of_module (mc : mc) = function | MI_Module subme -> assert (subme.me_params = []); let (subp2, mep) = subp2 subme.me_name in let submcs = mc_of_module_r (p1, args, Some subp2, None) subme in let mc = _up_mc false mc (IPPath mep) in let mc = _up_mod false mc subme.me_name (IPPath mep, (subme, lc)) in (mc, Some submcs) | MI_Variable v -> let (_subp2, mep) = subp2 v.v_name in let vty = v.v_type in (_up_var false mc v.v_name (IPPath mep, vty), None) | MI_Function f -> let (_subp2, mep) = subp2 f.f_name in (_up_fun false mc f.f_name (IPPath mep, f), None) in let (mc, submcs) = List.map_fold mc1_of_module (empty_mc (if p2 = None then Some me.me_params else None)) me.me_comps in ((me.me_name, mc), List.rev_pmap (fun x -> x) submcs) let mc_of_module (env : env) { tme_expr = me; tme_loca = lc; } = match env.env_scope.ec_scope with | `Theory -> let p1 = EcPath.pqname (root env) me.me_name and args = me.me_params in mc_of_module_r (p1, args, None, Some lc) me | `Module mpath -> begin assert (lc = `Global); match mpath.EcPath.m_top with | `Concrete (p1, p2) -> let p2 = EcPath.pqoname p2 me.me_name in mc_of_module_r (p1, mpath.EcPath.m_args, Some p2, None) me | `Local _ -> assert false end | `Fun _ -> assert false let mc_of_module_param (mid : EcIdent.t) (me : module_expr) = let xpath (x : symbol) = IPIdent (mid, Some (EcPath.psymbol x)) in let mc1_of_module (mc : mc) = function | MI_Module _ -> assert false | MI_Variable v -> _up_var false mc v.v_name (xpath v.v_name, v.v_type) | MI_Function f -> _up_fun false mc f.f_name (xpath f.f_name, f) in List.fold_left mc1_of_module (empty_mc (Some me.me_params)) me.me_comps let rec mc_of_theory_r (scope : EcPath.path) (x, cth) = let subscope = EcPath.pqname scope x in let expath = fun x -> EcPath.pqname subscope x in let add2mc up name obj mc = up false mc name (IPPath (expath name), obj) in let mc1_of_theory (mc : mc) (item : theory_item) = match item.ti_item with | Th_type (xtydecl, tydecl) -> (add2mc _up_tydecl xtydecl tydecl mc, None) | Th_operator (xop, op) -> (add2mc _up_operator xop op mc, None) | Th_axiom (xax, ax) -> (add2mc _up_axiom xax ax mc, None) | Th_schema (x, schema) -> (add2mc _up_schema x schema mc, None) | Th_modtype (xmodty, modty) -> (add2mc _up_modty xmodty modty mc, None) | Th_module { tme_expr = subme; tme_loca = lc; } -> let args = subme.me_params in let submcs = mc_of_module_r (expath subme.me_name, args, None, Some lc) subme in (add2mc _up_mod subme.me_name (subme, Some lc) mc, Some submcs) | Th_theory (xsubth, cth) -> if cth.cth_mode = `Concrete then let submcs = mc_of_theory_r subscope (xsubth, cth) in let mc = _up_mc false mc (IPPath (expath xsubth)) in (add2mc _up_theory xsubth cth mc, Some submcs) else (add2mc _up_theory xsubth cth mc, None) | Th_typeclass (x, tc) -> (add2mc _up_typeclass x tc mc, None) | Th_baserw (x, _) -> (add2mc _up_rwbase x (expath x) mc, None) | Th_export _ | Th_addrw _ | Th_instance _ | Th_auto _ | Th_reduction _ -> (mc, None) in let (mc, submcs) = List.map_fold mc1_of_theory (empty_mc None) cth.cth_items in ((x, mc), List.rev_pmap identity submcs) let mc_of_theory (env : env) (x : symbol) (cth : ctheory) = match cth.cth_mode with | `Concrete -> Some (mc_of_theory_r (root env) (x, cth)) | `Abstract -> None let rec bind_submc env path ((name, mc), submcs) = let path = EcPath.pqname path name in if Mip.find_opt (IPPath path) env.env_comps <> None then raise (DuplicatedBinding (EcPath.basename path)); bind_submcs { env with env_comps = Mip.add (IPPath path) mc env.env_comps } path submcs and bind_submcs env path submcs = List.fold_left (bind_submc^~ path) env submcs and bind_mc x mc env = let path = EcPath.pqname (root env) x in { env with env_current = _up_mc true env.env_current (IPPath path); env_comps = Mip.change (fun mc -> Some (_up_mc false (oget mc) (IPPath path))) (IPPath (root env)) (Mip.add (IPPath path) mc env.env_comps); } and bind_theory x (th:ctheory) env = match mc_of_theory env x th with | None -> bind _up_theory x th env | Some ((_, mc), submcs) -> let env = bind _up_theory x th env in let env = bind_mc x mc env in bind_submcs env (EcPath.pqname (root env) x) submcs and bind_mod x mod_ env = let (_, mc), submcs = mc_of_module env mod_ in let env = bind _up_mod x (mod_.tme_expr, Some mod_.tme_loca) env in let env = bind_mc x mc env in let env = bind_submcs env (EcPath.pqname (root env) x) submcs in env and bind_fun x vb env = bind _up_fun x vb env and bind_var x vb env = bind _up_var x vb env and bind_axiom x ax env = bind _up_axiom x ax env and bind_schema x ax env = bind _up_schema x ax env and bind_operator x op env = bind _up_operator x op env and bind_modty x msig env = bind _up_modty x msig env and bind_tydecl x tyd env = bind _up_tydecl x tyd env and bind_typeclass x tc env = bind _up_typeclass x tc env and bind_rwbase x p env = bind _up_rwbase x p env end exception InvalidStateForEnter let enter mode (name : symbol) (env : env) = let path = EcPath.pqname (root env) name in if Mip.find_opt (IPPath path) env.env_comps <> None then raise (DuplicatedBinding name); match mode, env.env_scope.ec_scope with | `Theory, `Theory -> let env = MC.bind_mc name (empty_mc None) env in { env with env_scope = { ec_path = path; ec_scope = `Theory; }; env_item = []; } | `Module [], `Module mpath -> let mpath = EcPath.mqname mpath name in let env = MC.bind_mc name (empty_mc None) env in { env with env_scope = { ec_path = path; ec_scope = `Module mpath; }; env_item = []; } | `Module params, `Theory -> let idents = List.map (fun (x, _) -> EcPath.mident x) params in let mpath = EcPath.mpath_crt path idents None in let env = MC.bind_mc name (empty_mc (Some params)) env in { env with env_scope = { ec_path = path; ec_scope = `Module mpath; }; env_item = []; } | `Fun, `Module mpath -> let xpath = EcPath.xpath mpath name in { env with env_scope = { ec_path = path; ec_scope = `Fun xpath; }; env_item = []; } | _, _ -> raise InvalidStateForEnter type meerror = | UnknownMemory of [`Symbol of symbol | `Memory of memory] exception MEError of meerror module Memory = struct let all env = Mmem.all env.env_memories let byid (me : memory) (env : env) = try Some (me, Mmem.byid me env.env_memories) with Not_found -> None let lookup (me : symbol) (env : env) = try Some (Mmem.bysym me env.env_memories) with Not_found -> None let set_active (me : memory) (env : env) = match byid me env with | None -> raise (MEError (UnknownMemory (`Memory me))) | Some _ -> { env with env_actmem = Some me } let get_active (env : env) = env.env_actmem let current (env : env) = match env.env_actmem with | None -> None | Some me -> byid me env let update (me: EcMemory.memenv) (env : env) = { env with env_memories = Mmem.add (fst me) (snd me) env.env_memories; } let push (me : EcMemory.memenv) (env : env) = FIXME : assert ( ( EcMemory.memory me ) env = None ) ; update me env let push_all memenvs env = List.fold_left (fun env m -> push m env) env memenvs let push_active memenv env = set_active (EcMemory.memory memenv) (push memenv env) end let ipath_of_mpath (p : mpath) = match p.EcPath.m_top with | `Local i -> (IPIdent (i, None), (0, p.EcPath.m_args)) | `Concrete (p1, p2) -> let pr = odfl p1 (p2 |> omap (MC.pcat p1)) in (IPPath pr, ((EcPath.p_size p1)-1, p.EcPath.m_args)) let ipath_of_xpath (p : xpath) = let x = p.EcPath.x_sub in let xt p = match p with | IPPath p -> Some (IPPath (EcPath.pqname p x)) | IPIdent (m, None) -> Some (IPIdent (m, Some (EcPath.psymbol x))) | _ -> None in let (p, (i, a)) = ipath_of_mpath p.EcPath.x_top in (xt p) |> omap (fun p -> (p, (i+1, a))) let try_lf f = try Some (f ()) with LookupFailure _ -> None let gen_iter fmc flk ?name f env = match name with | Some name -> List.iter (fun (p, ax) -> f p ax) (flk name env) | None -> Mip.iter (fun _ mc -> MMsym.iter (fun _ (ip, obj) -> match ip with IPPath p -> f p obj | _ -> ()) (fmc mc)) env.env_comps let gen_all fmc flk ?(check = fun _ _ -> true) ?name (env : env) = match name with | Some name -> List.filter (fun (p, ax) -> check p ax) (flk name env) | None -> Mip.fold (fun _ mc aout -> MMsym.fold (fun _ objs aout -> List.fold_right (fun (ip, obj) aout -> match ip with | IPPath p -> if check p obj then (p, obj) :: aout else aout | _ -> aout) objs aout) (fmc mc) aout) env.env_comps [] module TypeClass = struct type t = typeclass let by_path_opt (p : EcPath.path) (env : env) = omap check_not_suspended (MC.by_path (fun mc -> mc.mc_typeclasses) (IPPath p) env) let by_path (p : EcPath.path) (env : env) = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_typeclass p obj env let rebind name tc env = let env = MC.bind_typeclass name tc env in match tc.tc_prt with | None -> env | Some prt -> let myself = EcPath.pqname (root env) name in { env with env_tc = TC.Graph.add ~src:myself ~dst:prt env.env_tc } let bind ?(import = import0) name tc env = let env = if import.im_immediate then rebind name tc env else env in { env with env_item = mkitem import (Th_typeclass (name, tc)) :: env.env_item } let lookup qname (env : env) = MC.lookup_typeclass qname env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let graph (env : env) = env.env_tc let bind_instance ty cr tci = (ty, cr) :: tci let add_instance ?(import = import0) ty cr lc env = let env = if import.im_immediate then { env with env_tci = bind_instance ty cr env.env_tci } else env in { env with env_tci = bind_instance ty cr env.env_tci; env_item = mkitem import (Th_instance (ty, cr, lc)) :: env.env_item; } let get_instances env = env.env_tci end module BaseRw = struct let by_path_opt (p : EcPath.path) (env : env) = let ip = IPPath p in Mip.find_opt ip env.env_rwbase let by_path (p : EcPath.path) env = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let lookup qname env = let _ip, p = MC.lookup_rwbase qname env in p, by_path p env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let is_base name env = match lookup_opt name env with | None -> false | Some _ -> true let add ?(import = import0) name lc env = let p = EcPath.pqname (root env) name in let env = if import.im_immediate then MC.bind_rwbase name p env else env in let ip = IPPath p in { env with env_rwbase = Mip.add ip Sp.empty env.env_rwbase; env_item = mkitem import (Th_baserw (name, lc)) :: env.env_item; } let addto ?(import = import0) p l lc env = let env = if import.im_immediate then { env with env_rwbase = Mip.change (omap (fun s -> List.fold_left (fun s r -> Sp.add r s) s l)) (IPPath p) env.env_rwbase } else env in { env with env_rwbase = Mip.change (omap (fun s -> List.fold_left (fun s r -> Sp.add r s) s l)) (IPPath p) env.env_rwbase; env_item = mkitem import (Th_addrw (p, l, lc)) :: env.env_item; } end module Reduction = struct type rule = EcTheory.rule type topsym = red_topsym let add_rule ((_, rule) : path * rule option) (db : mredinfo) = match rule with None -> db | Some rule -> let p = match rule.rl_ptn with | Rule (`Op p, _) -> `Path (fst p) | Rule (`Tuple, _) -> `Tuple | Cost (_, _, Rule (`Op p, _)) -> `Cost (`Path (fst p)) | Cost (_, _, Rule (`Tuple, _)) -> `Cost `Tuple | Cost _ | Var _ | Int _ -> assert false in Mrd.change (fun rls -> let { ri_priomap } = match rls with | None -> { ri_priomap = Mint.empty; ri_list = Lazy.from_val [] } | Some x -> x in let ri_priomap = let change prules = Some (odfl [] prules @ [rule]) in Mint.change change (abs rule.rl_prio) ri_priomap in let ri_list = Lazy.from_fun (fun () -> List.flatten (Mint.values ri_priomap)) in Some { ri_priomap; ri_list }) p db let add_rules (rules : (path * rule option) list) (db : mredinfo) = List.fold_left ((^~) add_rule) db rules let add ?(import = import0) (rules : (path * rule_option * rule option) list) (env : env) = let rstrip = List.map (fun (x, _, y) -> (x, y)) rules in let env = if import.im_immediate then { env with env_redbase = add_rules rstrip env.env_redbase; } else env in { env with env_item = mkitem import (Th_reduction rules) :: env.env_item; } let add1 (prule : path * rule_option * rule option) (env : env) = add [prule] env let get (p : topsym) (env : env) = Mrd.find_opt p env.env_redbase |> omap (fun x -> Lazy.force x.ri_list) |> odfl [] end module Auto = struct let dname : symbol = "" let updatedb ~level ?base (ps : path list) (db : (path list Mint.t) Msym.t) = let nbase = (odfl dname base) in let ps' = Msym.find_def Mint.empty nbase db in let ps' = let doit x = Some (ofold (fun x ps -> ps @ x) ps x) in Mint.change doit level ps' in Msym.add nbase ps' db let add ?(import = import0) ~level ?base (ps : path list) lc (env : env) = let env = if import.im_immediate then { env with env_atbase = updatedb ?base ~level ps env.env_atbase; } else env in { env with env_item = mkitem import (Th_auto (level, base, ps, lc)) :: env.env_item; } let add1 ?import ~level ?base (p : path) lc (env : env) = add ?import ?base ~level [p] lc env let get_core ?base (env : env) = Msym.find_def Mint.empty (odfl dname base) env.env_atbase let flatten_db (db : path list Mint.t) = Mint.fold_left (fun ps _ ps' -> ps @ ps') [] db let get ?base (env : env) = flatten_db (get_core ?base env) let getall (bases : symbol list) (env : env) = let dbs = List.map (fun base -> get_core ~base env) bases in let dbs = List.fold_left (fun db mi -> Mint.union (fun _ sp1 sp2 -> Some (sp1 @ sp2)) db mi) Mint.empty dbs in flatten_db dbs let getx (base : symbol) (env : env) = let db = Msym.find_def Mint.empty base env.env_atbase in Mint.bindings db end module Fun = struct type t = EcModules.function_ let enter (x : symbol) (env : env) = enter `Fun x env let by_ipath (p : ipath) (env : env) = MC.by_path (fun mc -> mc.mc_functions) p env let by_xpath_r ~susp ~spsc (p : EcPath.xpath) (env : env) = match ipath_of_xpath p with | None -> lookup_error (`XPath p) | Some (ip, (i, args)) -> begin match MC.by_path (fun mc -> mc.mc_functions) ip env with | None -> lookup_error (`XPath p) | Some (params, o) -> let ((spi, params), _op) = MC._downpath_for_fun ~spsc env ip params in if i <> spi || susp && args <> [] then assert false; if not susp && List.length args <> List.length params then assert false; if susp then o else let s = List.fold_left2 (fun s (x, _) a -> EcSubst.add_module s x a) (EcSubst.empty ()) params args in EcSubst.subst_function s o end let by_xpath (p : EcPath.xpath) (env : env) = by_xpath_r ~susp:false ~spsc:true p env let by_xpath_opt (p : EcPath.xpath) (env : env) = try_lf (fun () -> by_xpath p env) let lookup qname (env : env) = let (((_, a), p), x) = MC.lookup_fun qname env in if a <> [] then raise (LookupFailure (`QSymbol qname)); (p, x) let lookup_opt name env = try_lf (fun () -> lookup name env) let sp_lookup qname (env : env) = let (((i, a), p), x) = MC.lookup_fun qname env in let obj = { sp_target = x; sp_params = (i, a); } in (p, obj) let sp_lookup_opt name env = try_lf (fun () -> sp_lookup name env) let lookup_path name env = fst (lookup name env) let bind name fun_ env = MC.bind_fun name fun_ env let add (path : EcPath.xpath) (env : env) = let obj = by_xpath path env in let ip = fst (oget (ipath_of_xpath path)) in MC.import_fun ip obj env let adds_in_memenv memenv vd = EcMemory.bindall vd memenv let add_in_memenv memenv vd = adds_in_memenv memenv [vd] let add_params mem fun_ = adds_in_memenv mem fun_.f_sig.fs_anames let actmem_pre me fun_ = let mem = EcMemory.empty_local ~witharg:true me in add_params mem fun_ let actmem_post me fun_ = let mem = EcMemory.empty_local ~witharg:false me in add_in_memenv mem { ov_name = Some res_symbol; ov_type = fun_.f_sig.fs_ret} let actmem_body me fun_ = match fun_.f_def with | FBdef fd -> let mem = EcMemory.empty_local ~witharg:false me in let mem = add_params mem fun_ in let locals = List.map ovar_of_var fd.f_locals in (fun_.f_sig,fd), adds_in_memenv mem locals let inv_memory side = let id = if side = `Left then EcCoreFol.mleft else EcCoreFol.mright in EcMemory.abstract id let inv_memenv env = Memory.push_all [inv_memory `Left; inv_memory `Rigth] env let inv_memenv1 env = let mem = EcMemory.abstract EcCoreFol.mhr in Memory.push_active mem env let prF_memenv m path env = let fun_ = by_xpath path env in actmem_post m fun_ let prF path env = let post = prF_memenv EcCoreFol.mhr path env in Memory.push_active post env let hoareF_memenv path env = let (ip, _) = oget (ipath_of_xpath path) in let fun_ = snd (oget (by_ipath ip env)) in let pre = actmem_pre EcCoreFol.mhr fun_ in let post = actmem_post EcCoreFol.mhr fun_ in pre, post let hoareF path env = let pre, post = hoareF_memenv path env in Memory.push_active pre env, Memory.push_active post env let hoareS path env = let fun_ = by_xpath path env in let fd, memenv = actmem_body EcCoreFol.mhr fun_ in memenv, fd, Memory.push_active memenv env let equivF_memenv path1 path2 env = let (ip1, _) = oget (ipath_of_xpath path1) in let (ip2, _) = oget (ipath_of_xpath path2) in let fun1 = snd (oget (by_ipath ip1 env)) in let fun2 = snd (oget (by_ipath ip2 env)) in let pre1 = actmem_pre EcCoreFol.mleft fun1 in let pre2 = actmem_pre EcCoreFol.mright fun2 in let post1 = actmem_post EcCoreFol.mleft fun1 in let post2 = actmem_post EcCoreFol.mright fun2 in (pre1,pre2), (post1,post2) let equivF path1 path2 env = let (pre1,pre2),(post1,post2) = equivF_memenv path1 path2 env in Memory.push_all [pre1; pre2] env, Memory.push_all [post1; post2] env let equivS path1 path2 env = let fun1 = by_xpath path1 env in let fun2 = by_xpath path2 env in let fd1, mem1 = actmem_body EcCoreFol.mleft fun1 in let fd2, mem2 = actmem_body EcCoreFol.mright fun2 in mem1, fd1, mem2, fd2, Memory.push_all [mem1; mem2] env end module Var = struct type t = glob_var_bind let by_xpath_r (spsc : bool) (p : xpath) (env : env) = match ipath_of_xpath p with | None -> lookup_error (`XPath p) | Some (ip, (i, _args)) -> match MC.by_path (fun mc -> mc.mc_variables) ip env with | None -> lookup_error (`XPath p) | Some (params, ty) -> let ((spi, _params), _) = MC._downpath_for_var ~spsc env ip params in if i <> spi then assert false; ty let by_xpath (p : xpath) (env : env) = by_xpath_r true p env let by_xpath_opt (p : xpath) (env : env) = try_lf (fun () -> by_xpath p env) let add (path : EcPath.xpath) (env : env) = let obj = by_xpath path env in let ip = fst (oget (ipath_of_xpath path)) in MC.import_var ip obj env let lookup_locals name env = MMsym.all name env.env_locals let lookup_local name env = match MMsym.last name env.env_locals with | None -> raise (LookupFailure (`QSymbol ([], name))) | Some x -> x let lookup_local_opt name env = MMsym.last name env.env_locals let lookup_progvar ?side qname env = let inmem side = match fst qname with | [] -> let memenv = oget (Memory.byid side env) in begin match EcMemory.lookup_me (snd qname) memenv with | Some (v, Some pa, _) -> Some (`Proj(pv_arg, pa), v.v_type) | Some (v, None, _) -> Some (`Var (pv_loc v.v_name), v.v_type) | None -> None end | _ -> None in match obind inmem side with | None -> let (((_, _), p), ty) = MC.lookup_var qname env in (`Var (pv_glob p), ty) | Some pvt -> pvt let lookup_progvar_opt ?side name env = try_lf (fun () -> lookup_progvar ?side name env) let bind_pvglob name ty env = MC.bind_var name ty env let bindall_pvglob bindings env = List.fold_left (fun env (name, ty) -> bind_pvglob name ty env) env bindings exception DuplicatedLocalBinding of EcIdent.t let bind_local ?uniq:(uniq=false) name ty env = let s = EcIdent.name name in if uniq && MMsym.all s env.env_locals <> [] then raise (DuplicatedLocalBinding name); { env with env_locals = MMsym.add s (name, ty) env.env_locals } let bind_locals ?uniq:(uniq=false) bindings env = List.fold_left (fun env (name, ty) -> bind_local ~uniq:uniq name ty env) env bindings end module AbsStmt = struct type t = EcModules.abs_uses let byid id env = try Mid.find id env.env_abs_st with Not_found -> raise (LookupFailure (`AbsStmt id)) let bind id us env = { env with env_abs_st = Mid.add id us env.env_abs_st } end module Mod = struct type t = top_module_expr type lkt = module_expr * locality option type spt = mpath * module_expr suspension * locality option let unsuspend_r f istop (i, args) (spi, params) o = if List.length args > List.length params then assert false; if i <> spi then assert false; if (not istop && List.length args <> List.length params) then assert false; let params = List.take (List.length args) params in let s = List.fold_left2 (fun s (x, _) a -> EcSubst.add_module s x a) (EcSubst.empty ()) params args in f s o let clearparams n params = let _, remaining = List.takedrop n params in remaining let unsuspend istop (i, args) (spi, params) me = let me = match args with | [] -> me | _ -> { me with me_params = clearparams (List.length args) me.me_params } in unsuspend_r EcSubst.subst_module istop (i, args) (spi, params) me let by_ipath_r (spsc : bool) (p : ipath) (env : env) = let obj = MC.by_path (fun mc -> mc.mc_modules) p env in obj |> omap (fun (args, obj) -> (fst (MC._downpath_for_mod spsc env p args), obj)) let by_mpath (p : mpath) (env : env) = let (ip, (i, args)) = ipath_of_mpath p in match MC.by_path (fun mc -> mc.mc_modules) ip env with | None -> lookup_error (`MPath p) | Some (params, (o, lc)) -> let ((spi, params), op) = MC._downpath_for_mod true env ip params in let (params, istop) = match op.EcPath.m_top with | `Concrete (p, Some _) -> assert ((params = []) || ((spi+1) = EcPath.p_size p)); (params, false) | `Concrete (p, None) -> assert ((params = []) || ((spi+1) = EcPath.p_size p)); ((if args = [] then [] else o.me_params), true) | `Local _m -> assert ((params = []) || spi = 0); ((if args = [] then [] else o.me_params), true) in (unsuspend istop (i, args) (spi, params) o, lc) let by_mpath_opt (p : EcPath.mpath) (env : env) = try_lf (fun () -> by_mpath p env) let add (p : EcPath.mpath) (env : env) = let obj = by_mpath p env in MC.import_mod (fst (ipath_of_mpath p)) obj env let lookup qname (env : env) = let (((_, _a), p), x) = MC.lookup_mod qname env in if a < > [ ] then raise ( LookupFailure ( ` QSymbol qname ) ) ; raise (LookupFailure (`QSymbol qname)); *) (p, x) let lookup_opt name env = try_lf (fun () -> lookup name env) let sp_lookup qname (env : env) = let (((i, a), p), (x, lc)) = MC.lookup_mod qname env in let obj = { sp_target = x; sp_params = (i, a); } in (p, obj, lc) let sp_lookup_opt name env = try_lf (fun () -> sp_lookup name env) let lookup_path name env = fst (lookup name env) let add_xs_to_declared xs env = let update_id id mods = let update me = match me.me_body with | ME_Decl ({ mt_restr } as mt) -> let mt_restr = mr_add_restr mt_restr (ur_empty xs) (ur_empty Sm.empty) in { me with me_body = ME_Decl { mt with mt_restr } } | _ -> me in MMsym.map_at (List.map (fun (ip, (me, lc)) -> if ip = IPIdent (id, None) then (ip, (update me, lc)) else (ip, (me, lc)))) (EcIdent.name id) mods in let envc = { env.env_current with mc_modules = Sid.fold update_id env.env_modlcs env.env_current.mc_modules; } in let en = !(env.env_norm) in let norm = { en with get_restr_use = Mm.empty } in { env with env_current = envc; env_norm = ref norm; } let rec vars_me mp xs me = vars_mb (EcPath.mqname mp me.me_name) xs me.me_body and vars_mb mp xs = function | ME_Alias _ | ME_Decl _ -> xs | ME_Structure ms -> List.fold_left (vars_item mp) xs ms.ms_body and vars_item mp xs = function | MI_Module me -> vars_me mp xs me | MI_Variable v -> Sx.add (EcPath.xpath mp v.v_name) xs | MI_Function _ -> xs let add_restr_to_declared p me env = if me.tme_loca = `Local then let p = pqname p me.tme_expr.me_name in let mp = EcPath.mpath_crt p [] None in let xs = vars_mb mp Sx.empty me.tme_expr.me_body in add_xs_to_declared xs env else env let bind ?(import = import0) name me env = assert (name = me.tme_expr.me_name); let env = if import.im_immediate then MC.bind_mod name me env else env in let env = { env with env_item = mkitem import (Th_module me) :: env.env_item; env_norm = ref !(env.env_norm); } in add_restr_to_declared (root env) me env let me_of_mt env name modty = let modsig = let modsig = match omap check_not_suspended (MC.by_path (fun mc -> mc.mc_modsigs) (IPPath modty.mt_name) env) with | None -> lookup_error (`Path modty.mt_name) | Some x -> x in EcSubst.subst_modsig ~params:(List.map fst modty.mt_params) (EcSubst.empty ()) modsig.tms_sig in module_expr_of_module_sig name modty modsig let bind_local name modty env = let me = me_of_mt env name modty in let path = IPIdent (name, None) in let comps = MC.mc_of_module_param name me in let env = { env with env_current = ( let current = env.env_current in let current = MC._up_mc true current path in let current = MC._up_mod true current me.me_name (path, (me, None)) in current); env_comps = Mip.add path comps env.env_comps; env_norm = ref !(env.env_norm); } in env let declare_local id modty env = { (bind_local id modty env) with env_modlcs = Sid.add id env.env_modlcs; } let add_restr_to_locals (rx : Sx.t use_restr) (rm : Sm.t use_restr) env = let update_id id mods = let update me = match me.me_body with | ME_Decl mt -> let mr = mr_add_restr mt.mt_restr rx rm in { me with me_body = ME_Decl { mt with mt_restr = mr } } | _ -> me in MMsym.map_at (List.map (fun (ip, (me, lc)) -> if ip = IPIdent (id, None) then (ip, (update me, lc)) else (ip, (me, lc)))) (EcIdent.name id) mods in let envc = let mc_modules = Sid.fold update_id env.env_modlcs env.env_current.mc_modules in { env.env_current with mc_modules } in let en = !(env.env_norm) in let norm = { en with get_restr_use = Mm.empty } in { env with env_current = envc; env_norm = ref norm; } let is_declared id env = Sid.mem id env.env_modlcs let bind_locals bindings env = List.fold_left (fun env (name, me) -> bind_local name me env) env bindings let enter name params env = let env = enter (`Module params) name env in bind_locals params env let add_mod_binding bd env = let do1 env (x,gty) = match gty with | GTmodty p -> bind_local x p env | _ -> env in List.fold_left do1 env bd let import_vars env p = let do1 env = function | MI_Variable v -> let vp = EcPath.xpath p v.v_name in let ip = fst (oget (ipath_of_xpath vp)) in let obj = v.v_type in MC.import_var ip obj env | _ -> env in List.fold_left do1 env (fst (by_mpath p env)).me_comps let iter ?name f (env : env) = gen_iter (fun mc -> mc.mc_modules) (assert false) ?name f env let all ?check ?name (env : env) = gen_all (fun mc -> mc.mc_modules) (assert false) ?check ?name env end module NormMp = struct let rec norm_mpath_for_typing env p = let (ip, (i, args)) = ipath_of_mpath p in match Mod.by_ipath_r true ip env with | Some ((spi, params), ({ me_body = ME_Alias (arity,alias) } as m, _)) -> assert (m.me_params = [] && arity = 0); let p = Mod.unsuspend_r EcSubst.subst_mpath true (i, args) (spi, params) alias in norm_mpath_for_typing env p | _ -> begin match p.EcPath.m_top with | `Local _ | `Concrete (_, None) -> p | `Concrete (p1, Some p2) -> begin let name = EcPath.basename p2 in let pr = EcPath.mpath_crt p1 p.EcPath.m_args (EcPath.prefix p2) in let pr = norm_mpath_for_typing env pr in match pr.EcPath.m_top with | `Local _ -> p | `Concrete (p1, p2) -> EcPath.mpath_crt p1 pr.EcPath.m_args (Some (EcPath.pqoname p2 name)) end end let rec norm_mpath_def env p = let top = EcPath.m_functor p in let args = p.EcPath.m_args in let sub = match p.EcPath.m_top with | `Local _ -> None | `Concrete(_,o) -> o in p is ( top args).sub match Mod.by_mpath_opt top env with | None -> norm_mpath_for_typing env p | Some (me, _) -> begin match me.me_body with | ME_Alias (arity,mp) -> let nargs = List.length args in if arity <= nargs then let args, extra = List.takedrop arity args in let params = List.take arity me.me_params in let s = List.fold_left2 (fun s (x, _) a -> EcSubst.add_module s x a) (EcSubst.empty ()) params args in let mp = EcSubst.subst_mpath s mp in let args' = mp.EcPath.m_args in let args2 = if extra = [] then args' else args' @ extra in let mp = match mp.EcPath.m_top with | `Local _ as x -> assert (sub = None); EcPath.mpath x args2 ( ( top ' args ' ) args).sub EcPath.mpath_crt top' args2 sub match sub with | None -> EcPath.mpath_crt top' args2 sub' | Some p -> EcPath.mpath_crt top' args2 (Some (pappend p' p)) in norm_mpath env mp else EcPath.mpath p.EcPath.m_top (List.map (norm_mpath env) args) | ME_Structure _ when sub <> None -> begin let (ip, (i, args)) = ipath_of_mpath p in match Mod.by_ipath_r true ip env with | Some ((spi, params), ({ me_body = ME_Alias (_,alias) } as m, _)) -> assert (m.me_params = []); let p = Mod.unsuspend_r EcSubst.subst_mpath false (i, args) (spi, params) alias in norm_mpath env p | _ -> EcPath.mpath p.EcPath.m_top (List.map (norm_mpath env) args) end | _ -> EcPath.mpath p.EcPath.m_top (List.map (norm_mpath env) args) end and norm_mpath env p = try Mm.find p !(env.env_norm).norm_mp with Not_found -> let res = norm_mpath_def env p in let en = !(env.env_norm) in env.env_norm := { en with norm_mp = Mm.add p res en.norm_mp }; res let rec norm_xfun env p = try Mx.find p !(env.env_norm).norm_xfun with Not_found -> let res = let mp = norm_mpath env p.x_top in let pf = EcPath.xpath mp p.x_sub in TODO B : use | Some {f_def = FBalias xp} -> norm_xfun env xp | _ -> pf in let en = !(env.env_norm) in env.env_norm := { en with norm_xfun = Mx.add p res en.norm_xfun }; res let norm_xpv env p = try Mx.find p !(env.env_norm).norm_xpv with Not_found -> let mp = p.x_top in assert (mp.m_args = []); let top = m_functor p.x_top in match Mod.by_mpath_opt top env with let mp = norm_mpath env mp in let xp = EcPath.xpath mp p.x_sub in let res = xp_glob xp in res | Some (me, _) -> let params = me.me_params in let env', mp = if params = [] then env, mp else Mod.bind_locals params env, EcPath.m_apply mp (List.map (fun (id,_)->EcPath.mident id) params)in let mp = norm_mpath env' mp in let xp = EcPath.xpath mp p.x_sub in let res = xp_glob xp in let en = !(env.env_norm) in env.env_norm := { en with norm_xpv = Mx.add p res en.norm_xpv }; res let use_equal us1 us2 = Mx.equal (fun _ _ -> true) us1.us_pv us2.us_pv && Sid.equal us1.us_gl us2.us_gl let mem_xp x us = Mx.mem x us.us_pv let use_mem_xp x (restr : use use_restr) = let bneg = mem_xp x restr.ur_neg and bpos = match restr.ur_pos with | None -> false | Some sp -> not (mem_xp x sp) in bneg || bpos let mem_gl mp us = assert (mp.m_args = []); match mp.m_top with | `Local id -> Sid.mem id us.us_gl | _ -> assert false let use_mem_gl m restr = let bneg = mem_gl m restr.ur_neg and bpos = match restr.ur_pos with | None -> false | Some sp -> not (mem_gl m sp) in bneg || bpos let add_var env xp us = let xp = xp_glob xp in let xp = norm_xpv env xp in let ty = Var.by_xpath xp env in { us with us_pv = Mx.add xp ty us.us_pv } let add_glob id us = { us with us_gl = Sid.add id us.us_gl } let add_glob_except rm id us = if Sid.mem id rm then us else add_glob id us let gen_fun_use env fdone rm = let rec fun_use us f = let f = norm_xfun env f in if Mx.mem f !fdone then us else let f1 = Fun.by_xpath f env in fdone := Sx.add f !fdone; match f1.f_def with | FBdef fdef -> let f_uses = fdef.f_uses in let vars = Sx.union f_uses.us_reads f_uses.us_writes in let us = Sx.fold (add_var env) vars us in List.fold_left fun_use us f_uses.us_calls | FBabs oi -> let id = match f.x_top.m_top with | `Local id -> id | _ -> assert false in let us = add_glob_except rm id us in List.fold_left fun_use us (OI.allowed oi) | FBalias _ -> assert false in fun_use let fun_use env xp = gen_fun_use env (ref Sx.empty) Sid.empty use_empty xp The four functions below are used in mod_use_top and item_use . let rec mod_use env rm fdone us mp = let mp = norm_mpath env mp in let me, _ = Mod.by_mpath mp env in assert (me.me_params = []); body_use env rm fdone mp us me.me_comps me.me_body and item_use env rm fdone mp us item = match item with | MI_Module me -> mod_use env rm fdone us (EcPath.mqname mp me.me_name) | MI_Variable v -> add_var env (xpath mp v.v_name) us | MI_Function f -> fun_use_aux env rm fdone us (xpath mp f.f_name) and body_use env rm fdone mp us comps body = match body with | ME_Alias _ -> assert false | ME_Decl _ -> let id = match mp.m_top with `Local id -> id | _ -> assert false in let us = add_glob_except rm id us in List.fold_left (item_use env rm fdone mp) us comps | ME_Structure ms -> List.fold_left (item_use env rm fdone mp) us ms.ms_body and fun_use_aux env rm fdone us f = gen_fun_use env fdone rm us f let mod_use_top env mp = let mp = norm_mpath env mp in let me, _ = Mod.by_mpath mp env in let params = me.me_params in let rm = List.fold_left (fun rm (id,_) -> Sid.add id rm) Sid.empty params in let env' = Mod.bind_locals params env in let mp' = EcPath.m_apply mp (List.map (fun (id,_) -> EcPath.mident id) params) in let fdone = ref Sx.empty in mod_use env' rm fdone use_empty mp' let mod_use env mp = try Mm.find mp !(env.env_norm).mod_use with Not_found -> let res = mod_use_top env mp in let en = !(env.env_norm) in env.env_norm := { en with mod_use = Mm.add mp res en.mod_use }; res let item_use env mp item = item_use env Sid.empty (ref Sx.empty) mp use_empty item let restr_use env (mr : mod_restr) = let get_use sx sm = Sx.fold (fun xp r -> add_var env xp r) sx use_empty |> Sm.fold (fun mp r -> use_union r (mod_use env mp)) sm in If any of the two positive restrictions is [ None ] , then anything is allowed . allowed. *) let ur_pos = match mr.mr_xpaths.ur_pos, mr.mr_mpaths.ur_pos with | None, _ | _, None -> None | Some sx, Some sm -> some @@ get_use sx sm in { ur_pos = ur_pos; ur_neg = get_use mr.mr_xpaths.ur_neg mr.mr_mpaths.ur_neg; } let get_restr_use env mp = try Mm.find mp !(env.env_norm).get_restr_use with Not_found -> let res = match (fst (Mod.by_mpath mp env)).me_body with | EcModules.ME_Decl mt -> restr_use env mt.mt_restr | _ -> assert false in let en = !(env.env_norm) in env.env_norm := { en with get_restr_use = Mm.add mp res en.get_restr_use }; res let get_restr_me env me mp = match me.me_body with | EcModules.ME_Decl mt -> assert (List.length mt.mt_params = List.length mt.mt_args); let keep = List.fold_left (fun k (x,_) -> EcPath.Sm.add (EcPath.mident x) k) EcPath.Sm.empty me.me_params in let keep_info f = EcPath.Sm.mem (f.EcPath.x_top) keep in let do1 oi = OI.filter keep_info oi in { mt.mt_restr with mr_oinfos = Msym.map do1 mt.mt_restr.mr_oinfos } | _ -> let mparams = List.fold_left (fun mparams (id,_) -> Sm.add (EcPath.mident id) mparams) Sm.empty me.me_params in let env = List.fold_left (fun env (x,mt) -> Mod.bind_local x mt env ) env me.me_params in let comp_oi oi it = match it with | MI_Module _ | MI_Variable _ -> oi | MI_Function f -> let rec f_call c f = let f = norm_xfun env f in if EcPath.Sx.mem f c then c else let c = EcPath.Sx.add f c in let fun_ = Fun.by_xpath f env in match fun_.f_def with | FBalias _ -> assert false | FBdef def -> List.fold_left f_call c def.f_uses.us_calls | FBabs oi -> List.fold_left f_call c (OI.allowed oi) in let all_calls = match f.f_def with | FBalias f -> f_call EcPath.Sx.empty f | FBdef def -> List.fold_left f_call EcPath.Sx.empty def.f_uses.us_calls | FBabs oi -> List.fold_left f_call EcPath.Sx.empty (OI.allowed oi) in let filter f = let ftop = EcPath.m_functor f.EcPath.x_top in Sm.mem ftop mparams in let calls = List.filter filter (EcPath.Sx.elements all_calls) in Msym.add f.f_name (OI.mk calls `Unbounded) oi in let oi = List.fold_left comp_oi Msym.empty me.me_comps in let use = mod_use env mp in let sx = EcPath.Mx.map (fun _ -> ()) use.us_pv in let ur_xpaths = { ur_pos = Some sx; ur_neg = Sx.empty; } in let sm = Sid.fold (fun m sm -> Sm.add (EcPath.mident m) sm ) use.us_gl Sm.empty in let ur_mpaths = { ur_pos = Some sm; ur_neg = Sm.empty; } in { mr_xpaths = ur_xpaths; mr_mpaths = ur_mpaths; mr_oinfos = oi; } let get_restr env mp = let mp = norm_mpath env mp in let me, _ = Mod.by_mpath mp env in get_restr_me env me mp let equal_restr (f_equiv : form -> form -> bool) env r1 r2 = let us1,us2 = restr_use env r1, restr_use env r2 in ur_equal use_equal us1 us2 && Msym.equal (PreOI.equal f_equiv) r1.mr_oinfos r2.mr_oinfos let sig_of_mp env mp = let mp = norm_mpath env mp in let me, _ = Mod.by_mpath mp env in { mis_params = me.me_params; mis_body = me.me_sig_body; mis_restr = get_restr_me env me mp } let norm_pvar env pv = match pv with | PVloc _ -> pv | PVglob xp -> let p = norm_xpv env xp in if x_equal p xp then pv else EcTypes.pv_glob p let globals env m mp = let us = mod_use env mp in let l = Sid.fold (fun id l -> f_glob (EcPath.mident id) m :: l) us.us_gl [] in let l = Mx.fold (fun xp ty l -> f_pvar (EcTypes.pv_glob xp) ty m :: l) us.us_pv l in f_tuple l let norm_glob env m mp = globals env m mp let norm_tglob env mp = let g = (norm_glob env mhr mp) in g.f_ty let tglob_reducible env mp = match (norm_tglob env mp).ty_node with | Tglob mp' -> not (EcPath.m_equal mp mp') | _ -> true let norm_ty env = EcTypes.Hty.memo_rec 107 ( fun aux ty -> match ty.ty_node with | Tglob mp -> norm_tglob env mp | _ -> ty_map aux ty) let rec norm_form env = let norm_ty1 : ty -> ty = norm_ty env in let norm_gty env (id,gty) = let gty = match gty with | GTty ty -> GTty (norm_ty env ty) | GTmodty _ -> gty | GTmem mt -> GTmem (mt_subst (norm_ty env) mt) in id,gty in let has_mod b = List.exists (fun (_,gty) -> match gty with GTmodty _ -> true | _ -> false) b in FIXME : use FSmart EcCoreFol.Hf.memo_rec 107 (fun aux f -> match f.f_node with | Fquant(q,bd,f) -> if has_mod bd then let env = Mod.add_mod_binding bd env in let bd = List.map (norm_gty env) bd in f_quant q bd (norm_form env f) else let bd = List.map (norm_gty env) bd in f_quant q bd (aux f) | Fpvar(p,m) -> let p' = norm_pvar env p in if p == p' then f else f_pvar p' f.f_ty m | Fglob(p,m) -> norm_glob env m p | FhoareF hf -> let pre' = aux hf.hf_pr and p' = norm_xfun env hf.hf_f and post' = aux hf.hf_po in if hf.hf_pr == pre' && hf.hf_f == p' && hf.hf_po == post' then f else f_hoareF pre' p' post' | FcHoareF chf -> let pre' = aux chf.chf_pr and p' = norm_xfun env chf.chf_f and post' = aux chf.chf_po in let c_self' = aux chf.chf_co.c_self in let c_calls' = Mx.fold (fun f c calls -> and c' = call_bound_r (aux c.cb_cost) (aux c.cb_called) in Mx.change (fun old -> assert (old = None); Some c') f' calls ) chf.chf_co.c_calls Mx.empty in if chf.chf_pr == pre' && chf.chf_f == p' && chf.chf_po == post' && chf.chf_co.c_self == c_self' && Mx.equal (fun a b -> a == b) chf.chf_co.c_calls c_calls' then f else let calls' = cost_r c_self' c_calls' in f_cHoareF pre' p' post' calls' TODO : missing cases : and every | FequivF ef -> let pre' = aux ef.ef_pr and l' = norm_xfun env ef.ef_fl and r' = norm_xfun env ef.ef_fr and post' = aux ef.ef_po in if ef.ef_pr == pre' && ef.ef_fl == l' && ef.ef_fr == r' && ef.ef_po == post' then f else f_equivF pre' l' r' post' | Fcoe coe -> let coe' = { coe_mem = coe.coe_mem; coe_pre = aux coe.coe_pre; coe_e = coe.coe_e; } in FSmart.f_coe (f, coe) coe' | Fpr pr -> let pr' = { pr_mem = pr.pr_mem; pr_fun = norm_xfun env pr.pr_fun; pr_args = aux pr.pr_args; pr_event = aux pr.pr_event; } in FSmart.f_pr (f, pr) pr' | _ -> EcCoreFol.f_map norm_ty1 aux f) in norm_form let norm_op env op = let kind = match op.op_kind with | OB_pred (Some (PR_Plain f)) -> OB_pred (Some (PR_Plain (norm_form env f))) | OB_pred (Some (PR_Ind pri)) -> let pri = { pri with pri_ctors = List.map (fun x -> { x with prc_spec = List.map (norm_form env) x.prc_spec }) pri.pri_ctors } in OB_pred (Some (PR_Ind pri)) | _ -> op.op_kind in { op with op_kind = kind; op_ty = norm_ty env op.op_ty; } let norm_ax env ax = { ax with ax_spec = norm_form env ax.ax_spec } let norm_sc env sc = { sc with axs_spec = norm_form env sc.axs_spec } let is_abstract_fun f env = let f = norm_xfun env f in match (Fun.by_xpath f env).f_def with | FBabs _ -> true | _ -> false let x_equal env f1 f2 = EcPath.x_equal (norm_xfun env f1) (norm_xfun env f2) let pv_equal env pv1 pv2 = EcTypes.pv_equal (norm_pvar env pv1) (norm_pvar env pv2) end module ModTy = struct type t = top_module_sig let by_path_opt (p : EcPath.path) (env : env) = omap check_not_suspended (MC.by_path (fun mc -> mc.mc_modsigs) (IPPath p) env) let by_path (p : EcPath.path) (env : env) = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_modty p obj env let lookup qname (env : env) = MC.lookup_modty qname env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let modtype p env = let { tms_sig = sig_ } = by_path p env in { mt_params = sig_.mis_params; mt_name = p; mt_args = List.map (EcPath.mident -| fst) sig_.mis_params; mt_restr = sig_.mis_restr; } let bind ?(import = import0) name modty env = let env = if import.im_immediate then MC.bind_modty name modty env else env in { env with env_item = mkitem import (Th_modtype (name, modty)) :: env.env_item } exception ModTypeNotEquiv let rec mod_type_equiv (f_equiv : form -> form -> bool) env mty1 mty2 = if not (EcPath.p_equal mty1.mt_name mty2.mt_name) then raise ModTypeNotEquiv; if List.length mty1.mt_params <> List.length mty2.mt_params then raise ModTypeNotEquiv; if List.length mty1.mt_args <> List.length mty2.mt_args then raise ModTypeNotEquiv; if not (NormMp.equal_restr f_equiv env mty1.mt_restr mty2.mt_restr) then raise ModTypeNotEquiv; let subst = List.fold_left2 (fun subst (x1, p1) (x2, p2) -> let p1 = EcSubst.subst_modtype subst p1 in let p2 = EcSubst.subst_modtype subst p2 in mod_type_equiv f_equiv env p1 p2; EcSubst.add_module subst x1 (EcPath.mident x2)) (EcSubst.empty ()) mty1.mt_params mty2.mt_params in if not ( List.all2 (fun m1 m2 -> let m1 = NormMp.norm_mpath env (EcSubst.subst_mpath subst m1) in let m2 = NormMp.norm_mpath env (EcSubst.subst_mpath subst m2) in EcPath.m_equal m1 m2) mty1.mt_args mty2.mt_args) then raise ModTypeNotEquiv let mod_type_equiv (f_equiv : form -> form -> bool) env mty1 mty2 = try mod_type_equiv f_equiv env mty1 mty2; true with ModTypeNotEquiv -> false let has_mod_type (env : env) (dst : module_type list) (src : module_type) = List.exists (mod_type_equiv f_equal env src) dst let sig_of_mt env (mt:module_type) = let { tms_sig = sig_ } = by_path mt.mt_name env in let subst = List.fold_left2 (fun s (x1,_) a -> EcSubst.add_module s x1 a) (EcSubst.empty ()) sig_.mis_params mt.mt_args in let items = EcSubst.subst_modsig_body subst sig_.mis_body in let params = mt.mt_params in let keep = List.fold_left (fun k (x,_) -> EcPath.Sm.add (EcPath.mident x) k) EcPath.Sm.empty params in let keep_info f = EcPath.Sm.mem (f.EcPath.x_top) keep in let do1 oi = OI.filter keep_info oi in let restr = { mt.mt_restr with mr_oinfos = Msym.map do1 mt.mt_restr.mr_oinfos } in { mis_params = params; mis_body = items; mis_restr = restr; } end module Ty = struct type t = EcDecl.tydecl let by_path_opt (p : EcPath.path) (env : env) = omap check_not_suspended (MC.by_path (fun mc -> mc.mc_tydecls) (IPPath p) env) let by_path (p : EcPath.path) (env : env) = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_tydecl p obj env let lookup qname (env : env) = MC.lookup_tydecl qname env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let defined (name : EcPath.path) (env : env) = match by_path_opt name env with | Some { tyd_type = `Concrete _ } -> true | _ -> false let unfold (name : EcPath.path) (args : EcTypes.ty list) (env : env) = match by_path_opt name env with | Some ({ tyd_type = `Concrete body } as tyd) -> EcTypes.Tvar.subst (EcTypes.Tvar.init (List.map fst tyd.tyd_params) args) body | _ -> raise (LookupFailure (`Path name)) let rec hnorm (ty : ty) (env : env) = match ty.ty_node with | Tconstr (p, tys) when defined p env -> hnorm (unfold p tys env) env | _ -> ty let rec ty_hnorm (ty : ty) (env : env) = match ty.ty_node with | Tconstr (p, tys) when defined p env -> ty_hnorm (unfold p tys env) env | Tglob p -> NormMp.norm_tglob env p | _ -> ty let rec decompose_fun (ty : ty) (env : env) : dom * ty = match (hnorm ty env).ty_node with | Tfun (ty1, ty2) -> fst_map (fun tys -> ty1 :: tys) (decompose_fun ty2 env) | _ -> ([], ty) let signature env = let rec doit acc ty = match (hnorm ty env).ty_node with | Tfun (dom, codom) -> doit (dom::acc) codom | _ -> (List.rev acc, ty) in fun ty -> doit [] ty let scheme_of_ty mode (ty : ty) (env : env) = let ty = hnorm ty env in match ty.ty_node with | Tconstr (p, tys) -> begin match by_path_opt p env with | Some ({ tyd_type = (`Datatype _ | `Record _) as body }) -> let prefix = EcPath.prefix p in let basename = EcPath.basename p in let basename = match body, mode with | `Record _, (`Ind | `Case) -> basename ^ "_ind" | `Datatype _, `Ind -> basename ^ "_ind" | `Datatype _, `Case -> basename ^ "_case" in Some (EcPath.pqoname prefix basename, tys) | _ -> None end | _ -> None let get_top_decl (ty : ty) (env : env) = match (ty_hnorm ty env).ty_node with | Tconstr (p, tys) -> Some (p, oget (by_path_opt p env), tys) | _ -> None let rebind name ty env = let env = MC.bind_tydecl name ty env in match ty.tyd_type with | `Abstract tc -> let myty = let myp = EcPath.pqname (root env) name in let typ = List.map (fst_map EcIdent.fresh) ty.tyd_params in (typ, EcTypes.tconstr myp (List.map (tvar |- fst) typ)) in let instr = Sp.fold (fun p inst -> TypeClass.bind_instance myty (`General p) inst) tc env.env_tci in { env with env_tci = instr } | _ -> env let bind ?(import = import0) name ty env = let env = if import.im_immediate then rebind name ty env else env in { env with env_item = mkitem import (Th_type (name, ty)) :: env.env_item } let iter ?name f (env : env) = gen_iter (fun mc -> mc.mc_tydecls) MC.lookup_tydecls ?name f env let all ?check ?name (env : env) = gen_all (fun mc -> mc.mc_tydecls) MC.lookup_tydecls ?check ?name env end let ty_hnorm = Ty.ty_hnorm module Op = struct type t = EcDecl.operator let by_path_opt (p : EcPath.path) (env : env) = omap check_not_suspended (MC.by_path (fun mc -> mc.mc_operators) (IPPath p) env) let by_path (p : EcPath.path) (env : env) = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_operator p obj env let lookup qname (env : env) = MC.lookup_operator qname env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let bind ?(import = import0) name op env = let env = if import.im_immediate then MC.bind_operator name op env else env in let op = NormMp.norm_op env op in let nt = match op.op_kind with | OB_nott nt -> Some (EcPath.pqname (root env) name, (op.op_tparams, nt)) | _ -> None in { env with env_ntbase = ofold List.cons env.env_ntbase nt; env_item = mkitem import (Th_operator (name, op)) :: env.env_item; } let rebind name op env = MC.bind_operator name op env let reducible ?(force = false) env p = try let op = by_path p env in match op.op_kind with | OB_oper (Some (OP_Plain _)) | OB_pred (Some _) when force || not op.op_opaque -> true | _ -> false with LookupFailure _ -> false let reduce ?(force = false) env p tys = let op = oget (by_path_opt p env) in let f = match op.op_kind with | OB_oper (Some (OP_Plain (e, _))) when force || not op.op_opaque -> form_of_expr EcCoreFol.mhr e | OB_pred (Some (PR_Plain f)) when force || not op.op_opaque -> f | _ -> raise NotReducible in EcCoreFol.Fsubst.subst_tvar (EcTypes.Tvar.init (List.map fst op.op_tparams) tys) f let is_projection env p = try EcDecl.is_proj (by_path p env) with LookupFailure _ -> false let is_record_ctor env p = try EcDecl.is_rcrd (by_path p env) with LookupFailure _ -> false let is_dtype_ctor ?nargs env p = try match (by_path p env).op_kind with | OB_oper (Some (OP_Constr (pt,i))) -> begin match nargs with | None -> true | Some nargs -> let tyv = Ty.by_path pt env in let tyv = oget (EcDecl.tydecl_as_datatype tyv) in let ctor_ty = snd (List.nth tyv.tydt_ctors i) in List.length ctor_ty = nargs end | _ -> false with LookupFailure _ -> false let is_fix_def env p = try EcDecl.is_fix (by_path p env) with LookupFailure _ -> false let is_abbrev env p = try EcDecl.is_abbrev (by_path p env) with LookupFailure _ -> false let is_prind env p = try EcDecl.is_prind (by_path p env) with LookupFailure _ -> false let scheme_of_prind env (_mode : [`Case | `Ind]) p = match by_path_opt p env with | Some { op_kind = OB_pred (Some (PR_Ind pri)) } -> Some (EcInductive.prind_indsc_path p, List.length pri.pri_ctors) | _ -> None type notation = env_notation let get_notations env = env.env_ntbase let iter ?name f (env : env) = gen_iter (fun mc -> mc.mc_operators) MC.lookup_operators ?name f env let all ?check ?name (env : env) = gen_all (fun mc -> mc.mc_operators) MC.lookup_operators ?check ?name env end module Ax = struct type t = axiom let by_path_opt (p : EcPath.path) (env : env) = omap check_not_suspended (MC.by_path (fun mc -> mc.mc_axioms) (IPPath p) env) let by_path (p : EcPath.path) (env : env) = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_axiom p obj env let lookup qname (env : env) = MC.lookup_axiom qname env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let bind ?(import = import0) name ax env = let ax = NormMp.norm_ax env ax in let env = if import.im_immediate then MC.bind_axiom name ax env else env in { env with env_item = mkitem import (Th_axiom (name, ax)) :: env.env_item } let rebind name ax env = MC.bind_axiom name ax env let instanciate p tys env = match by_path_opt p env with | Some ({ ax_spec = f } as ax) -> Fsubst.subst_tvar (EcTypes.Tvar.init (List.map fst ax.ax_tparams) tys) f | _ -> raise (LookupFailure (`Path p)) let iter ?name f (env : env) = gen_iter (fun mc -> mc.mc_axioms) MC.lookup_axioms ?name f env let all ?check ?name (env : env) = gen_all (fun mc -> mc.mc_axioms) MC.lookup_axioms ?check ?name env end module Schema = struct type t = ax_schema let by_path_opt (p : EcPath.path) (env : env) = omap check_not_suspended (MC.by_path (fun mc -> mc.mc_schemas) (IPPath p) env) let by_path (p : EcPath.path) (env : env) = match by_path_opt p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_schema p obj env let lookup qname (env : env) = MC.lookup_schema qname env let lookup_opt name env = try_lf (fun () -> lookup name env) let lookup_path name env = fst (lookup name env) let bind ?(import = import0) name ax env = let ax = NormMp.norm_sc env ax in let env = MC.bind_schema name ax env in { env with env_item = mkitem import (Th_schema (name, ax)) :: env.env_item } let rebind name ax env = MC.bind_schema name ax env let instanciate p tys (mt : EcMemory.memtype) ps es env = match by_path_opt p env with | Some ({ axs_spec = f } as sc) -> EcDecl.sc_instantiate sc.axs_tparams sc.axs_pparams sc.axs_params tys mt ps es f | _ -> raise (LookupFailure (`Path p)) let iter ?name f (env : env) = match name with | Some name -> let scs = MC.lookup_schemas name env in List.iter (fun (p,sc) -> f p sc) scs | None -> Mip.iter (fun _ mc -> MMsym.iter (fun _ (ip, sc) -> match ip with IPPath p -> f p sc | _ -> ()) mc.mc_schemas) env.env_comps let all ?(check = fun _ _ -> true) ?name (env : env) = match name with | Some name -> let scs = MC.lookup_schemas name env in List.filter (fun (p, sc) -> check p sc) scs | None -> Mip.fold (fun _ mc aout -> MMsym.fold (fun _ schemas aout -> List.fold_right (fun (ip, sc) aout -> match ip with | IPPath p -> if check p sc then (p, sc) :: aout else aout | _ -> aout) schemas aout) mc.mc_schemas aout) env.env_comps [] end module Algebra = struct let bind_ring ty cr env = assert (Mid.is_empty ty.ty_fv); { env with env_tci = TypeClass.bind_instance ([], ty) (`Ring cr) env.env_tci } let bind_field ty cr env = assert (Mid.is_empty ty.ty_fv); { env with env_tci = TypeClass.bind_instance ([], ty) (`Field cr) env.env_tci } let add_ring ty cr lc env = TypeClass.add_instance ([], ty) (`Ring cr) lc env let add_field ty cr lc env = TypeClass.add_instance ([], ty) (`Field cr) lc env end module Theory = struct type t = ctheory type mode = [`All | thmode] let enter name env = enter `Theory name env let by_path_opt ?(mode = `All)(p : EcPath.path) (env : env) = let obj = match MC.by_path (fun mc -> mc.mc_theories) (IPPath p) env, mode with | (Some (_, {cth_mode = `Concrete })) as obj, (`All | `Concrete) -> obj | (Some (_, {cth_mode = `Abstract })) as obj, (`All | `Abstract) -> obj | _, _ -> None in omap check_not_suspended obj let by_path ?mode (p : EcPath.path) (env : env) = match by_path_opt ?mode p env with | None -> lookup_error (`Path p) | Some obj -> obj let add (p : EcPath.path) (env : env) = let obj = by_path p env in MC.import_theory p obj env let lookup ?(mode = `Concrete) qname (env : env) = match MC.lookup_theory qname env, mode with | (_, { cth_mode = `Concrete }) as obj, (`All | `Concrete) -> obj | (_, { cth_mode = `Abstract }) as obj, (`All | `Abstract) -> obj | _ -> lookup_error (`QSymbol qname) let lookup_opt ?mode name env = try_lf (fun () -> lookup ?mode name env) let lookup_path ?mode name env = fst (lookup ?mode name env) let rec bind_instance_th path inst cth = List.fold_left (bind_instance_th_item path) inst cth and bind_instance_th_item path inst item = if not item.ti_import.im_atimport then inst else let xpath x = EcPath.pqname path x in match item.ti_item with | Th_instance (ty, k, _) -> TypeClass.bind_instance ty k inst | Th_theory (x, cth) when cth.cth_mode = `Concrete -> bind_instance_th (xpath x) inst cth.cth_items | Th_type (x, tyd) -> begin match tyd.tyd_type with | `Abstract tc -> let myty = let typ = List.map (fst_map EcIdent.fresh) tyd.tyd_params in (typ, EcTypes.tconstr (xpath x) (List.map (tvar |- fst) typ)) in Sp.fold (fun p inst -> TypeClass.bind_instance myty (`General p) inst) tc inst | _ -> inst end | _ -> inst let rec bind_base_th tx path base cth = List.fold_left (bind_base_th_item tx path) base cth and bind_base_th_item tx path base item = if not item.ti_import.im_atimport then base else let xpath x = EcPath.pqname path x in match item.ti_item with | Th_theory (x, cth) -> begin match cth.cth_mode with | `Concrete -> bind_base_th tx (xpath x) base cth.cth_items | `Abstract -> base end | _ -> odfl base (tx path base item.ti_item) let bind_tc_th = let for1 path base = function | Th_typeclass (x, tc) -> tc.tc_prt |> omap (fun prt -> let src = EcPath.pqname path x in TC.Graph.add ~src ~dst:prt base) | _ -> None in bind_base_th for1 let bind_br_th = let for1 path base = function | Th_baserw (x,_) -> let ip = IPPath (EcPath.pqname path x) in assert (not (Mip.mem ip base)); Some (Mip.add ip Sp.empty base) | Th_addrw (b, r, _) -> let change = function | None -> assert false | Some s -> Some (List.fold_left (fun s r -> Sp.add r s) s r) in Some (Mip.change change (IPPath b) base) | _ -> None in bind_base_th for1 let bind_at_th = let for1 _path db = function | Th_auto (level, base, ps, _) -> Some (Auto.updatedb ?base ~level ps db) | _ -> None in bind_base_th for1 let bind_nt_th = let for1 path base = function | Th_operator (x, ({ op_kind = OB_nott nt } as op)) -> Some ((EcPath.pqname path x, (op.op_tparams, nt)) :: base) | _ -> None in bind_base_th for1 let bind_rd_th = let for1 _path db = function | Th_reduction rules -> let rules = List.map (fun (x, _, y) -> (x, y)) rules in Some (Reduction.add_rules rules db) | _ -> None in bind_base_th for1 let add_restr_th = let for1 path env = function | Th_module me -> Some (Mod.add_restr_to_declared path me env) | _ -> None in bind_base_th for1 let bind ?(import = import0) name ({ cth_items = items; cth_mode = mode } as cth) env = let env = MC.bind_theory name cth env in let env = { env with env_item = mkitem import (Th_theory (name, cth)) :: env.env_item } in match import, mode with | _, `Concrete -> let thname = EcPath.pqname (root env) name in let env_tci = bind_instance_th thname env.env_tci items in let env_tc = bind_tc_th thname env.env_tc items in let env_rwbase = bind_br_th thname env.env_rwbase items in let env_atbase = bind_at_th thname env.env_atbase items in let env_ntbase = bind_nt_th thname env.env_ntbase items in let env_redbase = bind_rd_th thname env.env_redbase items in let env = { env with env_tci; env_tc; env_rwbase; env_atbase; env_ntbase; env_redbase; } in add_restr_th thname env items | _, _ -> env let rebind name th env = MC.bind_theory name th env let import (path : EcPath.path) (env : env) = let rec import (env : env) path (th : theory) = let xpath x = EcPath.pqname path x in let import_th_item (env : env) (item : theory_item) = if not item.ti_import.im_atimport then env else match item.ti_item with | Th_type (x, ty) -> if ty.tyd_resolve then MC.import_tydecl (xpath x) ty env else env | Th_operator (x, op) -> MC.import_operator (xpath x) op env | Th_axiom (x, ax) -> if ax.ax_visibility <> `Hidden then MC.import_axiom (xpath x) ax env else env | Th_schema (x, schema) -> MC.import_schema (xpath x) schema env | Th_modtype (x, mty) -> MC.import_modty (xpath x) mty env | Th_module ({ tme_expr = me; tme_loca = lc; }) -> let env = MC.import_mod (IPPath (xpath me.me_name)) (me, Some lc) env in let env = MC.import_mc (IPPath (xpath me.me_name)) env in env | Th_export (p, _) -> import env p (by_path ~mode:`Concrete p env).cth_items | Th_theory (x, ({cth_mode = `Concrete} as th)) -> let env = MC.import_theory (xpath x) th env in let env = MC.import_mc (IPPath (xpath x)) env in env | Th_theory (x, ({cth_mode = `Abstract} as th)) -> MC.import_theory (xpath x) th env | Th_typeclass (x, tc) -> MC.import_typeclass (xpath x) tc env | Th_baserw (x, _) -> MC.import_rwbase (xpath x) env | Th_addrw _ | Th_instance _ | Th_auto _ | Th_reduction _ -> env in List.fold_left import_th_item env th in import env path (by_path ~mode:`Concrete path env).cth_items let export (path : EcPath.path) lc (env : env) = let env = import path env in { env with env_item = mkitem import0 (Th_export (path, lc)) :: env.env_item } let rec filter clears root cleared items = snd_map (List.pmap identity) (List.map_fold (filter1 clears root) cleared items) and filter_th clears root cleared items = let mempty = List.exists (EcPath.p_equal root) clears in let cleared, items = filter clears root cleared items in if mempty && List.is_empty items then (Sp.add root cleared, None) else (cleared, Some items) and filter1 clears root = let inclear p = List.exists (EcPath.p_equal p) clears in let thclear = inclear root in fun cleared item -> let cleared, item_r = match item.ti_item with | Th_theory (x, cth) -> let cleared, items = let xpath = EcPath.pqname root x in filter_th clears xpath cleared cth.cth_items in let item = items |> omap (fun items -> let cth = { cth with cth_items = items } in Th_theory (x, cth)) in (cleared, item) | _ -> let item_r = match item.ti_item with | Th_axiom (_, { ax_kind = `Lemma }) when thclear -> None | Th_axiom (x, ({ ax_kind = `Axiom (tags, false) } as ax)) when thclear -> Some (Th_axiom (x, { ax with ax_kind = `Axiom (tags, true) })) | Th_addrw (p, ps, lc) -> let ps = List.filter ((not) |- inclear |- oget |- EcPath.prefix) ps in if List.is_empty ps then None else Some (Th_addrw (p, ps,lc)) | Th_auto (lvl, base, ps, lc) -> let ps = List.filter ((not) |- inclear |- oget |- EcPath.prefix) ps in if List.is_empty ps then None else Some (Th_auto (lvl, base, ps, lc)) | (Th_export (p, _)) as item -> if Sp.mem p cleared then None else Some item | _ as item -> Some item in (cleared, item_r) in (cleared, omap (fun item_r -> { item with ti_item = item_r; }) item_r) let close ?(clears = []) ?(pempty = `No) loca mode env = let items = List.rev env.env_item in let items = if List.is_empty clears then (if List.is_empty items then None else Some items) else snd (filter_th clears (root env) Sp.empty items) in let items = match items, pempty with | None, (`No | `ClearOnly) -> Some [] | _, _ -> items in items |> omap (fun items -> { cth_items = items; cth_source = None; cth_loca = loca; cth_mode = mode; }) let require x cth env = let rootnm = EcCoreLib.p_top in let thpath = EcPath.pqname rootnm x in let env = match cth.cth_mode with | `Concrete -> let (_, thmc), submcs = MC.mc_of_theory_r rootnm (x, cth) in MC.bind_submc env rootnm ((x, thmc), submcs) | `Abstract -> env in let th = cth in let topmc = Mip.find (IPPath rootnm) env.env_comps in let topmc = MC._up_theory false topmc x (IPPath thpath, th) in let topmc = MC._up_mc false topmc (IPPath thpath) in let current = env.env_current in let current = MC._up_theory true current x (IPPath thpath, th) in let current = MC._up_mc true current (IPPath thpath) in let comps = env.env_comps in let comps = Mip.add (IPPath rootnm) topmc comps in let env = { env with env_current = current; env_comps = comps; } in match cth.cth_mode with | `Abstract -> env | `Concrete -> { env with env_tci = bind_instance_th thpath env.env_tci cth.cth_items; env_tc = bind_tc_th thpath env.env_tc cth.cth_items; env_rwbase = bind_br_th thpath env.env_rwbase cth.cth_items; env_atbase = bind_at_th thpath env.env_atbase cth.cth_items; env_ntbase = bind_nt_th thpath env.env_ntbase cth.cth_items; env_redbase = bind_rd_th thpath env.env_redbase cth.cth_items; } end let initial gstate = empty gstate type ebinding = [ | `Variable of EcTypes.ty | `Function of function_ | `Module of module_expr | `ModType of module_sig ] let bind1 ((x, eb) : symbol * ebinding) (env : env) = match eb with | `Variable ty -> Var .bind_pvglob x ty env | `Function f -> Fun .bind x f env | `Module m -> Mod .bind x {tme_expr = m; tme_loca = `Global} env | `ModType i -> ModTy .bind x {tms_sig = i; tms_loca = `Global} env let bindall (items : (symbol * ebinding) list) (env : env) = List.fold_left ((^~) bind1) env items module LDecl = struct type error = | InvalidKind of EcIdent.t * [`Variable | `Hypothesis] | CannotClear of EcIdent.t * EcIdent.t | NameClash of [`Ident of EcIdent.t | `Symbol of symbol] | LookupError of [`Ident of EcIdent.t | `Symbol of symbol] exception LdeclError of error let pp_error fmt (exn : error) = match exn with | LookupError (`Symbol s) -> Format.fprintf fmt "unknown symbol %s" s | NameClash (`Symbol s) -> Format.fprintf fmt "an hypothesis or variable named `%s` already exists" s | InvalidKind (x, `Variable) -> Format.fprintf fmt "`%s` is not a variable" (EcIdent.name x) | InvalidKind (x, `Hypothesis) -> Format.fprintf fmt "`%s` is not an hypothesis" (EcIdent.name x) | CannotClear (id1,id2) -> Format.fprintf fmt "cannot clear %s as it is used in %s" (EcIdent.name id1) (EcIdent.name id2) | LookupError (`Ident id) -> Format.fprintf fmt "unknown identifier `%s`, please report" (EcIdent.tostring id) | NameClash (`Ident id) -> Format.fprintf fmt "name clash for `%s`, please report" (EcIdent.tostring id) let _ = EcPException.register (fun fmt exn -> match exn with | LdeclError e -> pp_error fmt e | _ -> raise exn) let error e = raise (LdeclError e) let ld_subst s ld = match ld with | LD_var (ty, body) -> LD_var (s.fs_ty ty, body |> omap (Fsubst.f_subst s)) | LD_mem mt -> let mt = EcMemory.mt_subst s.fs_ty mt in LD_mem mt | LD_modty p -> let p = gty_as_mod (Fsubst.subst_gty s (GTmodty p)) in LD_modty p | LD_hyp f -> LD_hyp (Fsubst.f_subst s f) FIXME assert false let ld_fv = function | LD_var (ty, None) -> ty.ty_fv | LD_var (ty,Some f) -> EcIdent.fv_union ty.ty_fv f.f_fv | LD_mem mt -> EcMemory.mt_fv mt | LD_hyp f -> f.f_fv | LD_modty p -> gty_fv (GTmodty p) | LD_abs_st us -> let add fv (x,_) = match x with | PVglob x -> EcPath.x_fv fv x | PVloc _ -> fv in let fv = Mid.empty in let fv = List.fold_left add fv us.aus_reads in let fv = List.fold_left add fv us.aus_writes in List.fold_left EcPath.x_fv fv us.aus_calls let by_name s hyps = match List.ofind ((=) s |- EcIdent.name |- fst) hyps.h_local with | None -> error (LookupError (`Symbol s)) | Some h -> h let by_id id hyps = match List.ofind (EcIdent.id_equal id |- fst) hyps.h_local with | None -> error (LookupError (`Ident id)) | Some x -> snd x let as_hyp = function | (id, LD_hyp f) -> (id, f) | (id, _) -> error (InvalidKind (id, `Hypothesis)) let as_var = function | (id, LD_var (ty, _)) -> (id, ty) | (id, _) -> error (InvalidKind (id, `Variable)) let hyp_by_name s hyps = as_hyp (by_name s hyps) let var_by_name s hyps = as_var (by_name s hyps) let hyp_by_id x hyps = as_hyp (x, by_id x hyps) let var_by_id x hyps = as_var (x, by_id x hyps) let has_gen dcast s hyps = try ignore (dcast (by_name s hyps)); true with LdeclError (InvalidKind _ | LookupError _) -> false let hyp_exists s hyps = has_gen as_hyp s hyps let var_exists s hyps = has_gen as_var s hyps let has_id x hyps = try ignore (by_id x hyps); true with LdeclError (LookupError _) -> false let has_inld s = function | LD_mem mt -> is_bound s mt | _ -> false let has_name ?(dep = false) s hyps = let test (id, k) = EcIdent.name id = s || (dep && has_inld s k) in List.exists test hyps.h_local let can_unfold id hyps = try match by_id id hyps with LD_var (_, Some _) -> true | _ -> false with LdeclError _ -> false let unfold id hyps = try match by_id id hyps with | LD_var (_, Some f) -> f | _ -> raise NotReducible with LdeclError _ -> raise NotReducible let check_name_clash id hyps = if has_id id hyps then error (NameClash (`Ident id)) else let s = EcIdent.name id in if s <> "_" && has_name ~dep:false s hyps then error (NameClash (`Symbol s)) let add_local id ld hyps = check_name_clash id hyps; { hyps with h_local = (id, ld) :: hyps.h_local } let fresh_id hyps s = let s = if s = "_" || not (has_name ~dep:true s hyps) then s else let rec aux n = let s = Printf.sprintf "%s%d" s n in if has_name ~dep:true s hyps then aux (n+1) else s in aux 0 in EcIdent.create s let fresh_ids hyps names = let do1 hyps s = let id = fresh_id hyps s in (add_local id (LD_var (tbool, None)) hyps, id) in List.map_fold do1 hyps names type hyps = { le_init : env; le_env : env; le_hyps : EcBaseLogic.hyps; } let tohyps lenv = lenv.le_hyps let toenv lenv = lenv.le_env let baseenv lenv = lenv.le_init let add_local_env x k env = match k with | LD_var (ty, _) -> Var.bind_local x ty env | LD_mem mt -> Memory.push (x, mt) env | LD_modty i -> Mod.bind_local x i env | LD_hyp _ -> env | LD_abs_st us -> AbsStmt.bind x us env let add_local x k h = let le_hyps = add_local x k (tohyps h) in let le_env = add_local_env x k h.le_env in { h with le_hyps; le_env; } let init env ?(locals = []) tparams = let buildenv env = List.fold_right (fun (x, k) env -> add_local_env x k env) locals env in { le_init = env; le_env = buildenv env; le_hyps = { h_tvar = tparams; h_local = locals; }; } let clear ?(leniant = false) ids hyps = let rec filter ids hyps = match hyps with [] -> [] | ((id, lk) as bd) :: hyps -> let ids, bd = if EcIdent.Sid.mem id ids then (ids, None) else let fv = ld_fv lk in if Mid.set_disjoint ids fv then (ids, Some bd) else if leniant then (Mid.set_diff ids fv, Some bd) else let inter = Mid.set_inter ids fv in error (CannotClear (Sid.choose inter, id)) in List.ocons bd (filter ids hyps) in let locals = filter ids hyps.le_hyps.h_local in init hyps.le_init ~locals hyps.le_hyps.h_tvar let hyp_convert x check hyps = let module E = struct exception NoOp end in let init locals = init hyps.le_init ~locals hyps.le_hyps.h_tvar in let rec doit locals = match locals with | (y, LD_hyp fp) :: locals when EcIdent.id_equal x y -> begin let fp' = check (lazy (init locals)) fp in if fp == fp' then raise E.NoOp else (x, LD_hyp fp') :: locals end | [] -> error (LookupError (`Ident x)) | ld :: locals -> ld :: (doit locals) in (try Some (doit hyps.le_hyps.h_local) with E.NoOp -> None) |> omap init let local_hyps x hyps = let rec doit locals = match locals with | (y, _) :: locals -> if EcIdent.id_equal x y then locals else doit locals | [] -> error (LookupError (`Ident x)) in let locals = doit hyps.le_hyps.h_local in init hyps.le_init ~locals hyps.le_hyps.h_tvar let by_name s hyps = by_name s (tohyps hyps) let by_id x hyps = by_id x (tohyps hyps) let has_name s hyps = has_name ~dep:false s (tohyps hyps) let has_id x hyps = has_id x (tohyps hyps) let hyp_by_name s hyps = hyp_by_name s (tohyps hyps) let hyp_exists s hyps = hyp_exists s (tohyps hyps) let hyp_by_id x hyps = snd (hyp_by_id x (tohyps hyps)) let var_by_name s hyps = var_by_name s (tohyps hyps) let var_exists s hyps = var_exists s (tohyps hyps) let var_by_id x hyps = snd (var_by_id x (tohyps hyps)) let can_unfold x hyps = can_unfold x (tohyps hyps) let unfold x hyps = unfold x (tohyps hyps) let fresh_id hyps s = fresh_id (tohyps hyps) s let fresh_ids hyps s = snd (fresh_ids (tohyps hyps) s) let push_active m lenv = { lenv with le_env = Memory.push_active m lenv.le_env } let push_all l lenv = { lenv with le_env = Memory.push_all l lenv.le_env } let hoareF xp lenv = let env1, env2 = Fun.hoareF xp lenv.le_env in { lenv with le_env = env1}, {lenv with le_env = env2 } let equivF xp1 xp2 lenv = let env1, env2 = Fun.equivF xp1 xp2 lenv.le_env in { lenv with le_env = env1}, {lenv with le_env = env2 } let inv_memenv lenv = { lenv with le_env = Fun.inv_memenv lenv.le_env } let inv_memenv1 lenv = { lenv with le_env = Fun.inv_memenv1 lenv.le_env } end let pp_debug_form = ref (fun _env _fmt _f -> assert false)
87a927e2403a2b7cf7f21775a479ec68cec039c59e816d0dbff8ab7de9314e8b
e-bigmoon/haskell-blog
Example2.hs
#!/usr/bin/env stack -- stack script --resolver lts-17.3 {-# LANGUAGE OverloadedStrings #-} import Network.HTTP.Client import Network.HTTP.Client.TLS import Text.HTML.DOM import Data.Conduit ((.|), runConduit, runConduitRes, ConduitT) import Conduit (runResourceT) import Network.HTTP.Client.Conduit (bodyReaderSource) import Network.Connection (TLSSettings(TLSSettingsSimple)) import qualified System.IO as SI (readFile) import Text.HTML.DOM import Network.HTTP.Types import Text.XML import Data.Text (Text) import qualified Data.Map.Strict as DMS import Data.Maybe import Prelude hiding (readFile) import Text.XML import Text.XML.Cursor import qualified Data.Text as T import Text.HTML.DOM (readFile) -- main :: IO () -- main = do -- --doc <- readFile def "test4.xml" -- doc <- Text.HTML.DOM.readFile "test4.html" -- let cursor = fromDocument doc -- print $ T.concat $ -- cursor $// element "body" -- -- >=> attributeIs "class" "bar" -- &// attribute "href" main :: IO () main = do filecontent <- SI.readFile "urls.txt" let urls = map parseRequest_ $ lines filecontent settings = mkManagerSettings (TLSSettingsSimple True False False) Nothing manager <- newManager settings _ <- mapM (doSomething manager) urls pure () doSomething :: Manager -> Request -> IO () doSomething manager request = do withResponse request manager $ \response -> do valueDoc <- runConduit $ bodyReaderSource (responseBody response) .| Text.HTML.DOM.sinkDoc print $ takeUrl valueDoc takeUrl :: Document -> Text takeUrl doc = T.concat $ fromDocument doc $// element "body" &// attribute "href"
null
https://raw.githubusercontent.com/e-bigmoon/haskell-blog/5c9e7c25f31ea6856c5d333e8e991dbceab21c56/sample-code/yesod/appendix/ap5/Example2.hs
haskell
stack script --resolver lts-17.3 # LANGUAGE OverloadedStrings # main :: IO () main = do --doc <- readFile def "test4.xml" doc <- Text.HTML.DOM.readFile "test4.html" let cursor = fromDocument doc print $ T.concat $ cursor $// element "body" -- >=> attributeIs "class" "bar" &// attribute "href"
#!/usr/bin/env stack import Network.HTTP.Client import Network.HTTP.Client.TLS import Text.HTML.DOM import Data.Conduit ((.|), runConduit, runConduitRes, ConduitT) import Conduit (runResourceT) import Network.HTTP.Client.Conduit (bodyReaderSource) import Network.Connection (TLSSettings(TLSSettingsSimple)) import qualified System.IO as SI (readFile) import Text.HTML.DOM import Network.HTTP.Types import Text.XML import Data.Text (Text) import qualified Data.Map.Strict as DMS import Data.Maybe import Prelude hiding (readFile) import Text.XML import Text.XML.Cursor import qualified Data.Text as T import Text.HTML.DOM (readFile) main :: IO () main = do filecontent <- SI.readFile "urls.txt" let urls = map parseRequest_ $ lines filecontent settings = mkManagerSettings (TLSSettingsSimple True False False) Nothing manager <- newManager settings _ <- mapM (doSomething manager) urls pure () doSomething :: Manager -> Request -> IO () doSomething manager request = do withResponse request manager $ \response -> do valueDoc <- runConduit $ bodyReaderSource (responseBody response) .| Text.HTML.DOM.sinkDoc print $ takeUrl valueDoc takeUrl :: Document -> Text takeUrl doc = T.concat $ fromDocument doc $// element "body" &// attribute "href"
284059281eaa3e60630b6a35a6ec9e267cb30bd3e9fc5c1d31973781dfb44d7b
sondresl/AdventOfCode
Day10.hs
module Day10 where import Control.Lens import Lib import Data.List.Extra import Text.ParserCombinators.Parsec import qualified Data.Map as Map import Data.Map (Map, (!)) data Bot = Bot Int | Output Int deriving (Show, Eq, Ord) type Bots = Map Bot [Int] data Instruction = Init Bot Int | Move Bot Bot Bot deriving Show makeMap :: [Instruction] -> Bots makeMap ins = result where result :: Bots result = foldl insert Map.empty ins insert :: Bots -> Instruction -> Bots insert acc (Init n value) = Map.insertWith (++) n [value] acc insert acc (Move bot low high) = let curr = (Map.!) result bot in Map.insertWith (++) low [minimum curr] $ Map.insertWith (++) high [maximum curr] acc part1 :: [Instruction] -> Maybe Bot part1 = (fst <$>) . find ((== [17, 61]) . sort . snd) . Map.toList . makeMap part2 :: [Instruction] -> Int part2 = product . prod . makeMap where prod mp = concat [mp ! Output 0, mp ! Output 1, mp ! Output 2] main :: IO () main = do let run file = do input <- parseInput <$> readFile file putStrLn ("\nInput file: " ++ show file ++ "\n") -- mapM_ print input print $ part1 input print $ part2 input run "../data/test" run "../data/day10.in" Just ( Bot 101 ) 37789 parseInput :: String -> [Instruction] parseInput = map (parseBots . words) . lines where parseBots ["value", n, _, _, _, bot] = Init (Bot (read bot)) (read n) parseBots ["bot",n,_,"low", _,"bot",low,_,_,_,"bot",high] = Move (Bot (read n)) (Bot (read low)) (Bot (read high)) parseBots ["bot",n,_,"low", _,"bot",low,_,_,_,"output",high] = Move (Bot (read n)) (Bot (read low)) (Output (read high)) parseBots ["bot",n,_,"low", _,"output",low,_,_,_,"bot",high] = Move (Bot (read n)) (Output (read low)) (Bot (read high)) parseBots ["bot",n,_,"low", _,"output",low,_,_,_,"output",high] = Move (Bot (read n)) (Output (read low)) (Output (read high)) parseBots n = error (show n)
null
https://raw.githubusercontent.com/sondresl/AdventOfCode/224cf59354c7c1c31821f36884fe8909c5fdf9a6/2016/Haskell/src/Day10.hs
haskell
mapM_ print input
module Day10 where import Control.Lens import Lib import Data.List.Extra import Text.ParserCombinators.Parsec import qualified Data.Map as Map import Data.Map (Map, (!)) data Bot = Bot Int | Output Int deriving (Show, Eq, Ord) type Bots = Map Bot [Int] data Instruction = Init Bot Int | Move Bot Bot Bot deriving Show makeMap :: [Instruction] -> Bots makeMap ins = result where result :: Bots result = foldl insert Map.empty ins insert :: Bots -> Instruction -> Bots insert acc (Init n value) = Map.insertWith (++) n [value] acc insert acc (Move bot low high) = let curr = (Map.!) result bot in Map.insertWith (++) low [minimum curr] $ Map.insertWith (++) high [maximum curr] acc part1 :: [Instruction] -> Maybe Bot part1 = (fst <$>) . find ((== [17, 61]) . sort . snd) . Map.toList . makeMap part2 :: [Instruction] -> Int part2 = product . prod . makeMap where prod mp = concat [mp ! Output 0, mp ! Output 1, mp ! Output 2] main :: IO () main = do let run file = do input <- parseInput <$> readFile file putStrLn ("\nInput file: " ++ show file ++ "\n") print $ part1 input print $ part2 input run "../data/test" run "../data/day10.in" Just ( Bot 101 ) 37789 parseInput :: String -> [Instruction] parseInput = map (parseBots . words) . lines where parseBots ["value", n, _, _, _, bot] = Init (Bot (read bot)) (read n) parseBots ["bot",n,_,"low", _,"bot",low,_,_,_,"bot",high] = Move (Bot (read n)) (Bot (read low)) (Bot (read high)) parseBots ["bot",n,_,"low", _,"bot",low,_,_,_,"output",high] = Move (Bot (read n)) (Bot (read low)) (Output (read high)) parseBots ["bot",n,_,"low", _,"output",low,_,_,_,"bot",high] = Move (Bot (read n)) (Output (read low)) (Bot (read high)) parseBots ["bot",n,_,"low", _,"output",low,_,_,_,"output",high] = Move (Bot (read n)) (Output (read low)) (Output (read high)) parseBots n = error (show n)
2946e961095e4eb464019f2e810fe856b06a21ad41b620e102c998c8bcd0bfa9
zhongwencool/observer_cli
observer_cli_mnesia.erl
%%% @author zhongwen <> -module(observer_cli_mnesia). %% API -export([start/1]). -export([clean/1]). -include("observer_cli.hrl"). -define(LAST_LINE, "q(quit) s(sort by size) m(sort by memory) pd/pu(page:down/up) F/B(forward/back)" " hide(switch between hide and display system table)" ). -spec start(#view_opts{}) -> any(). start( #view_opts{ db = #db{ interval = MillSecond, hide_sys = HideSys, cur_page = CurPage, attr = Attr }, auto_row = AutoRow } = HomeOpts ) -> Pid = spawn_link(fun() -> ?output(?CLEAR), render_worker(MillSecond, ?INIT_TIME_REF, HideSys, AutoRow, Attr, CurPage) end), manager(Pid, HomeOpts). -spec clean(list()) -> ok. clean(Pids) -> observer_cli_lib:exit_processes(Pids). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Private %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% manager(ChildPid, #view_opts{db = DBOpts = #db{cur_page = CurPage, hide_sys = Hide}} = HomeOpts) -> case observer_cli_lib:parse_cmd(HomeOpts, ?MODULE, [ChildPid]) of quit -> erlang:send(ChildPid, quit); {new_interval, NewMs} = Msg -> erlang:send(ChildPid, Msg), manager(ChildPid, HomeOpts#view_opts{db = DBOpts#db{interval = NewMs}}); hide -> NewHide = not Hide, erlang:send(ChildPid, {system_table, NewHide}), manager(ChildPid, HomeOpts#view_opts{db = DBOpts#db{hide_sys = NewHide}}); size -> clean([ChildPid]), start(HomeOpts#view_opts{db = DBOpts#db{attr = size}}); Home {func, proc_count, memory} -> clean([ChildPid]), start(HomeOpts#view_opts{db = DBOpts#db{attr = memory}}); page_down_top_n -> NewPage = max(CurPage + 1, 1), clean([ChildPid]), start(HomeOpts#view_opts{db = DBOpts#db{cur_page = NewPage}}); page_up_top_n -> NewPage = max(CurPage - 1, 1), clean([ChildPid]), start(HomeOpts#view_opts{db = DBOpts#db{cur_page = NewPage}}); _ -> manager(ChildPid, HomeOpts) end. render_worker(Interval, LastTimeRef, HideSystemTable, AutoRow, Attr, CurPage) -> TerminalRow = observer_cli_lib:get_terminal_rows(AutoRow), Rows = erlang:max(TerminalRow - 5, 0), Text = "Interval: " ++ integer_to_list(Interval) ++ "ms" ++ " HideSystemTable:" ++ atom_to_list(HideSystemTable), Menu = observer_cli_lib:render_menu(mnesia, Text), LastLine = observer_cli_lib:render_last_line(?LAST_LINE), case get_table_list(HideSystemTable, Attr) of {error, Reason} -> ErrInfo = io_lib:format("Mnesia Error ~p~n", [Reason]), ?output([?CURSOR_TOP, Menu, ErrInfo, LastLine]); MnesiaList -> Info = render_mnesia(MnesiaList, Attr, Rows, CurPage), ?output([?CURSOR_TOP, Menu, Info, LastLine]) end, TimeRef = observer_cli_lib:next_redraw(LastTimeRef, Interval), receive quit -> quit; {new_interval, NewInterval} -> render_worker(NewInterval, TimeRef, HideSystemTable, AutoRow, Attr, CurPage); {system_table, NewHideSystemTable} -> render_worker(Interval, TimeRef, NewHideSystemTable, AutoRow, Attr, CurPage); _ -> render_worker(Interval, TimeRef, HideSystemTable, AutoRow, Attr, CurPage) end. render_mnesia(MnesiaList, Attr, Rows, CurPage) -> {_StartPos, SortMnesia} = observer_cli_lib:sublist(MnesiaList, Rows, CurPage), {MemColor, SizeColor} = case Attr of memory -> {?RED_BG, ?GRAY_BG}; _ -> {?GRAY_BG, ?RED_BG} end, Title = ?render([ ?UNDERLINE, ?W2(?GRAY_BG, "Name", 25), ?UNDERLINE, ?W2(MemColor, " Memory ", 16), ?UNDERLINE, ?W2(SizeColor, "Size", 16), ?UNDERLINE, ?W2(?GRAY_BG, "Type", 12), ?UNDERLINE, ?W2(?GRAY_BG, "Storage", 15), ?UNDERLINE, ?W2(?GRAY_BG, "Owner", 14), ?UNDERLINE, ?W2(?GRAY_BG, "Index", 11), ?UNDERLINE, ?W2(?GRAY_BG, "Reg_name", 20) ]), View = [ begin Name = proplists:get_value(name, Mnesia), Memory = proplists:get_value(memory, Mnesia), Size = proplists:get_value(size, Mnesia), Type = proplists:get_value(type, Mnesia), RegName = proplists:get_value(reg_name, Mnesia), Index = proplists:get_value(index, Mnesia), Owner = proplists:get_value(owner, Mnesia), Storage = proplists:get_value(storage, Mnesia), ?render([ ?W(Name, 24), ?W({byte, Memory}, 14), ?W(Size, 14), ?W(Type, 10), ?W(Storage, 13), ?W(Owner, 12), ?W(Index, 9), ?W(RegName, 19) ]) end || {_, _, Mnesia} <- SortMnesia ], [Title | View]. mnesia_tables() -> [ ir_AliasDef, ir_ArrayDef, ir_AttributeDef, ir_ConstantDef, ir_Contained, ir_Container, ir_EnumDef, ir_ExceptionDef, ir_IDLType, ir_IRObject, ir_InterfaceDef, ir_ModuleDef, ir_ORB, ir_OperationDef, ir_PrimitiveDef, ir_Repository, ir_SequenceDef, ir_StringDef, ir_StructDef, ir_TypedefDef, ir_UnionDef, logTable, logTransferTable, mesh_meas, mesh_type, mnesia_clist, orber_CosNaming, orber_objkeys, user ]. get_table_list(HideSys, Attr) -> Owner = ets:info(schema, owner), case Owner of undefined -> {error, "Mnesia is not running on: " ++ atom_to_list(node())}; _ -> get_table_list2(Owner, HideSys, Attr) end. get_table_list2(Owner, HideSys, Attr) -> {registered_name, RegName} = process_info(Owner, registered_name), WordSize = erlang:system_info(wordsize), CollectFun = fun(Id, Acc) -> case HideSys andalso ordsets:is_element(Id, mnesia_tables()) orelse Id =:= schema of %% ignore system table true -> Acc; false -> Storage = mnesia:table_info(Id, storage_type), Size = mnesia:table_info(Id, size), Memory = mnesia:table_info(Id, memory) * WordSize, Tab0 = [ {name, Id}, {owner, Owner}, {size, Size}, {reg_name, RegName}, {type, mnesia:table_info(Id, type)}, {memory, Memory}, {storage, Storage}, {index, mnesia:table_info(Id, index)} ], Tab = case Storage of _ when Storage =:= ram_copies orelse Storage =:= disc_copies -> [ {fixed, ets:info(Id, fixed)}, {compressed, ets:info(Id, compressed)} | Tab0 ]; disc_only_copies -> [{fixed, dets:info(Id, safe_fixed)} | Tab0]; _ -> Tab0 end, [{0, proplists:get_value(Attr, Tab), Tab} | Acc] end end, lists:foldl(CollectFun, [], mnesia:system_info(tables)).
null
https://raw.githubusercontent.com/zhongwencool/observer_cli/52933b97c7d6b09ed8af9dc8419863d79e0ee306/src/observer_cli_mnesia.erl
erlang
@author zhongwen <> API Private ignore system table
-module(observer_cli_mnesia). -export([start/1]). -export([clean/1]). -include("observer_cli.hrl"). -define(LAST_LINE, "q(quit) s(sort by size) m(sort by memory) pd/pu(page:down/up) F/B(forward/back)" " hide(switch between hide and display system table)" ). -spec start(#view_opts{}) -> any(). start( #view_opts{ db = #db{ interval = MillSecond, hide_sys = HideSys, cur_page = CurPage, attr = Attr }, auto_row = AutoRow } = HomeOpts ) -> Pid = spawn_link(fun() -> ?output(?CLEAR), render_worker(MillSecond, ?INIT_TIME_REF, HideSys, AutoRow, Attr, CurPage) end), manager(Pid, HomeOpts). -spec clean(list()) -> ok. clean(Pids) -> observer_cli_lib:exit_processes(Pids). manager(ChildPid, #view_opts{db = DBOpts = #db{cur_page = CurPage, hide_sys = Hide}} = HomeOpts) -> case observer_cli_lib:parse_cmd(HomeOpts, ?MODULE, [ChildPid]) of quit -> erlang:send(ChildPid, quit); {new_interval, NewMs} = Msg -> erlang:send(ChildPid, Msg), manager(ChildPid, HomeOpts#view_opts{db = DBOpts#db{interval = NewMs}}); hide -> NewHide = not Hide, erlang:send(ChildPid, {system_table, NewHide}), manager(ChildPid, HomeOpts#view_opts{db = DBOpts#db{hide_sys = NewHide}}); size -> clean([ChildPid]), start(HomeOpts#view_opts{db = DBOpts#db{attr = size}}); Home {func, proc_count, memory} -> clean([ChildPid]), start(HomeOpts#view_opts{db = DBOpts#db{attr = memory}}); page_down_top_n -> NewPage = max(CurPage + 1, 1), clean([ChildPid]), start(HomeOpts#view_opts{db = DBOpts#db{cur_page = NewPage}}); page_up_top_n -> NewPage = max(CurPage - 1, 1), clean([ChildPid]), start(HomeOpts#view_opts{db = DBOpts#db{cur_page = NewPage}}); _ -> manager(ChildPid, HomeOpts) end. render_worker(Interval, LastTimeRef, HideSystemTable, AutoRow, Attr, CurPage) -> TerminalRow = observer_cli_lib:get_terminal_rows(AutoRow), Rows = erlang:max(TerminalRow - 5, 0), Text = "Interval: " ++ integer_to_list(Interval) ++ "ms" ++ " HideSystemTable:" ++ atom_to_list(HideSystemTable), Menu = observer_cli_lib:render_menu(mnesia, Text), LastLine = observer_cli_lib:render_last_line(?LAST_LINE), case get_table_list(HideSystemTable, Attr) of {error, Reason} -> ErrInfo = io_lib:format("Mnesia Error ~p~n", [Reason]), ?output([?CURSOR_TOP, Menu, ErrInfo, LastLine]); MnesiaList -> Info = render_mnesia(MnesiaList, Attr, Rows, CurPage), ?output([?CURSOR_TOP, Menu, Info, LastLine]) end, TimeRef = observer_cli_lib:next_redraw(LastTimeRef, Interval), receive quit -> quit; {new_interval, NewInterval} -> render_worker(NewInterval, TimeRef, HideSystemTable, AutoRow, Attr, CurPage); {system_table, NewHideSystemTable} -> render_worker(Interval, TimeRef, NewHideSystemTable, AutoRow, Attr, CurPage); _ -> render_worker(Interval, TimeRef, HideSystemTable, AutoRow, Attr, CurPage) end. render_mnesia(MnesiaList, Attr, Rows, CurPage) -> {_StartPos, SortMnesia} = observer_cli_lib:sublist(MnesiaList, Rows, CurPage), {MemColor, SizeColor} = case Attr of memory -> {?RED_BG, ?GRAY_BG}; _ -> {?GRAY_BG, ?RED_BG} end, Title = ?render([ ?UNDERLINE, ?W2(?GRAY_BG, "Name", 25), ?UNDERLINE, ?W2(MemColor, " Memory ", 16), ?UNDERLINE, ?W2(SizeColor, "Size", 16), ?UNDERLINE, ?W2(?GRAY_BG, "Type", 12), ?UNDERLINE, ?W2(?GRAY_BG, "Storage", 15), ?UNDERLINE, ?W2(?GRAY_BG, "Owner", 14), ?UNDERLINE, ?W2(?GRAY_BG, "Index", 11), ?UNDERLINE, ?W2(?GRAY_BG, "Reg_name", 20) ]), View = [ begin Name = proplists:get_value(name, Mnesia), Memory = proplists:get_value(memory, Mnesia), Size = proplists:get_value(size, Mnesia), Type = proplists:get_value(type, Mnesia), RegName = proplists:get_value(reg_name, Mnesia), Index = proplists:get_value(index, Mnesia), Owner = proplists:get_value(owner, Mnesia), Storage = proplists:get_value(storage, Mnesia), ?render([ ?W(Name, 24), ?W({byte, Memory}, 14), ?W(Size, 14), ?W(Type, 10), ?W(Storage, 13), ?W(Owner, 12), ?W(Index, 9), ?W(RegName, 19) ]) end || {_, _, Mnesia} <- SortMnesia ], [Title | View]. mnesia_tables() -> [ ir_AliasDef, ir_ArrayDef, ir_AttributeDef, ir_ConstantDef, ir_Contained, ir_Container, ir_EnumDef, ir_ExceptionDef, ir_IDLType, ir_IRObject, ir_InterfaceDef, ir_ModuleDef, ir_ORB, ir_OperationDef, ir_PrimitiveDef, ir_Repository, ir_SequenceDef, ir_StringDef, ir_StructDef, ir_TypedefDef, ir_UnionDef, logTable, logTransferTable, mesh_meas, mesh_type, mnesia_clist, orber_CosNaming, orber_objkeys, user ]. get_table_list(HideSys, Attr) -> Owner = ets:info(schema, owner), case Owner of undefined -> {error, "Mnesia is not running on: " ++ atom_to_list(node())}; _ -> get_table_list2(Owner, HideSys, Attr) end. get_table_list2(Owner, HideSys, Attr) -> {registered_name, RegName} = process_info(Owner, registered_name), WordSize = erlang:system_info(wordsize), CollectFun = fun(Id, Acc) -> case HideSys andalso ordsets:is_element(Id, mnesia_tables()) orelse Id =:= schema of true -> Acc; false -> Storage = mnesia:table_info(Id, storage_type), Size = mnesia:table_info(Id, size), Memory = mnesia:table_info(Id, memory) * WordSize, Tab0 = [ {name, Id}, {owner, Owner}, {size, Size}, {reg_name, RegName}, {type, mnesia:table_info(Id, type)}, {memory, Memory}, {storage, Storage}, {index, mnesia:table_info(Id, index)} ], Tab = case Storage of _ when Storage =:= ram_copies orelse Storage =:= disc_copies -> [ {fixed, ets:info(Id, fixed)}, {compressed, ets:info(Id, compressed)} | Tab0 ]; disc_only_copies -> [{fixed, dets:info(Id, safe_fixed)} | Tab0]; _ -> Tab0 end, [{0, proplists:get_value(Attr, Tab), Tab} | Acc] end end, lists:foldl(CollectFun, [], mnesia:system_info(tables)).
942e6fab01980824dfdb7d0655fddb4c0e1b17306eed1a0f9ba32dcc142b1d13
sdiehl/elliptic-curve
Types.hs
module Generate.Binary.Types ( module Generate.Binary.Types , module Generate.Types ) where import Protolude import GHC.Natural (Natural) import Generate.Types ------------------------------------------------------------------------------- -- Types ------------------------------------------------------------------------------- data Curve = Curve { name :: Text , types :: Types , parameters :: Parameters } data Parameters = Parameters { a :: Element , b :: Element , h :: Natural , p :: Natural , r :: Natural , x :: Element , y :: Element }
null
https://raw.githubusercontent.com/sdiehl/elliptic-curve/445e196a550e36e0f25bd4d9d6a38676b4cf2be8/generate/Generate/Binary/Types.hs
haskell
----------------------------------------------------------------------------- Types -----------------------------------------------------------------------------
module Generate.Binary.Types ( module Generate.Binary.Types , module Generate.Types ) where import Protolude import GHC.Natural (Natural) import Generate.Types data Curve = Curve { name :: Text , types :: Types , parameters :: Parameters } data Parameters = Parameters { a :: Element , b :: Element , h :: Natural , p :: Natural , r :: Natural , x :: Element , y :: Element }
81153d77da25253729f255ac682b2d8d7b7797a74c6de5d40a1983aa7a64af63
geophf/1HaskellADay
Exercise.hs
module Y2017.M02.D17.Exercise where import Data.Map (Map) import qualified Data.Map as Map below imports available via 1HaskellADay git repository import Data.Probability import Rosalind.Genotypes - Okay , yesterday we looked at a single characteristic / just one genotype . Of course , organisms have multiple genotypes , so what characteristics do offspring inherit from their parents and how when there are multiple genotypes to consider ? That is today 's problem . Let 's say several genotypes define the traits of an organism Something like : ... kinda Traits = Genotypes [ Genotype ] deriving ( Eq , Ord , Show ) Of course , the traits are not simply an arbitrary list of genotypes , because a genotype is paired only with the genotype of the same characteristic ... so ... typed genotypes ? Ugh . I mean , that certainly is a compile - time guarantee that the conjugation of genotypes will work , but that seems like an awefully lot of coding / housekeeping work to make that guarantee . ( the crowd may , or may not , disagree with me ) How about , instead , this : - Okay, yesterday we looked at a single characteristic/just one genotype. Of course, organisms have multiple genotypes, so what characteristics do offspring inherit from their parents and how when there are multiple genotypes to consider? That is today's Haskell problem. Let's say several genotypes define the traits of an organism Something like: ... kinda Traits = Genotypes [Genotype] deriving (Eq, Ord, Show) Of course, the traits are not simply an arbitrary list of genotypes, because a genotype is paired only with the genotype of the same characteristic ... so ... typed genotypes? Ugh. I mean, that certainly is a compile-time guarantee that the conjugation of genotypes will work, but that seems like an awefully lot of coding/housekeeping work to make that guarantee. (the Idris crowd may, or may not, disagree with me) How about, instead, this: --} type Characteristic = Char data Traits = Genotypes { traits :: Map Characteristic Genotype } deriving (Eq, Ord, Show) -- This way, we can guarantee our parents have the same signature by type Signature = String signature :: Traits -> Signature signature trait = undefined -- And we also guarantee that a genotype crosses with a genotype of the same -- characteristic. How? We'll develop that below. -- 'Below' meaning now. Given two parents each with a set of traits , write a function that proves -- they both have the same signature sameSignature :: Traits -> Traits -> Bool sameSignature parentA parentB = undefined -- Once we determine that the parents have the same set of genotype (signatures) -- find the (probability) distribution of the set of traits of their offspring -- But what's that? Well, we've seen that matching the primary and secondary -- phenotype in the genotype are independent, so the resulting genotype is the -- matches of the primaries combined with the matches of the secondaries. -- Similarly , we already have in . Genotypes matching for genotypes , so -- we just combine all the paired independent geotype matches. Let's do that match :: Traits -> Traits -> Prob Traits match parentA parentB = undefined -- Let's try it out. What are the possible traits of a child of parents A and B? parentA, parentB :: Traits parentA = Genotypes . Map.fromList . zip "ab" . map mkgene $ words "Aa Bb" parentB = parentA -- parent B has the same traits as parent A. -- Hint: look to flipThree for combining genotypes into a new set of traits One of the possible children will have the traits " Aa Bb " ... what is the -- probability of a child having parent A's traits? traitsOf :: Prob Traits -> Traits -> Float traitsOf distribution traits = undefined -- note: the return type is intentionally float even though the probabilities -- are Rational values. How do we get the returned value to be Float? - BONUS ----------------------------------------------------------------- Meet Thom and his . - Meet Thom and his waifu-chan. --} thomandwaifu :: (Traits, Traits) thomandwaifu = (parentA, parentB) thom and have have two boys . What are their traits , probably ? twoboys :: (Traits, Traits) -> (Prob Traits, Prob Traits) twoboys (fromthom, andwaifu) = undefined The boys marry girls just like mom and have two boys each , respectively . -- What are the boys' children's traits? grandsons :: (Prob Traits, Prob Traits) -> Prob Traits grandsons (boy, girl) = undefined What is the probability of atLeast 1 grandson is " Aa Bb " just like dear old -- Mom and Dad? justlikemom :: Prob Traits -> Float justlikemom distribution = undefined More generally , for generation n , where each member marries an " Aa Bb " wife and has two boys , what is the probability that there are k " Aa Bb " offspring ? moregenerally :: Prob Traits -> Int -> Int -> Float moregenerally distribution n k = undefined incidentally , the bonus question answers
null
https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2017/M02/D17/Exercise.hs
haskell
} This way, we can guarantee our parents have the same signature by And we also guarantee that a genotype crosses with a genotype of the same characteristic. How? We'll develop that below. 'Below' meaning now. they both have the same signature Once we determine that the parents have the same set of genotype (signatures) find the (probability) distribution of the set of traits of their offspring But what's that? Well, we've seen that matching the primary and secondary phenotype in the genotype are independent, so the resulting genotype is the matches of the primaries combined with the matches of the secondaries. we just combine all the paired independent geotype matches. Let's do that Let's try it out. What are the possible traits of a child of parents A and B? parent B has the same traits as parent A. Hint: look to flipThree for combining genotypes into a new set of traits probability of a child having parent A's traits? note: the return type is intentionally float even though the probabilities are Rational values. How do we get the returned value to be Float? --------------------------------------------------------------- } What are the boys' children's traits? Mom and Dad?
module Y2017.M02.D17.Exercise where import Data.Map (Map) import qualified Data.Map as Map below imports available via 1HaskellADay git repository import Data.Probability import Rosalind.Genotypes - Okay , yesterday we looked at a single characteristic / just one genotype . Of course , organisms have multiple genotypes , so what characteristics do offspring inherit from their parents and how when there are multiple genotypes to consider ? That is today 's problem . Let 's say several genotypes define the traits of an organism Something like : ... kinda Traits = Genotypes [ Genotype ] deriving ( Eq , Ord , Show ) Of course , the traits are not simply an arbitrary list of genotypes , because a genotype is paired only with the genotype of the same characteristic ... so ... typed genotypes ? Ugh . I mean , that certainly is a compile - time guarantee that the conjugation of genotypes will work , but that seems like an awefully lot of coding / housekeeping work to make that guarantee . ( the crowd may , or may not , disagree with me ) How about , instead , this : - Okay, yesterday we looked at a single characteristic/just one genotype. Of course, organisms have multiple genotypes, so what characteristics do offspring inherit from their parents and how when there are multiple genotypes to consider? That is today's Haskell problem. Let's say several genotypes define the traits of an organism Something like: ... kinda Traits = Genotypes [Genotype] deriving (Eq, Ord, Show) Of course, the traits are not simply an arbitrary list of genotypes, because a genotype is paired only with the genotype of the same characteristic ... so ... typed genotypes? Ugh. I mean, that certainly is a compile-time guarantee that the conjugation of genotypes will work, but that seems like an awefully lot of coding/housekeeping work to make that guarantee. (the Idris crowd may, or may not, disagree with me) How about, instead, this: type Characteristic = Char data Traits = Genotypes { traits :: Map Characteristic Genotype } deriving (Eq, Ord, Show) type Signature = String signature :: Traits -> Signature signature trait = undefined Given two parents each with a set of traits , write a function that proves sameSignature :: Traits -> Traits -> Bool sameSignature parentA parentB = undefined Similarly , we already have in . Genotypes matching for genotypes , so match :: Traits -> Traits -> Prob Traits match parentA parentB = undefined parentA, parentB :: Traits parentA = Genotypes . Map.fromList . zip "ab" . map mkgene $ words "Aa Bb" One of the possible children will have the traits " Aa Bb " ... what is the traitsOf :: Prob Traits -> Traits -> Float traitsOf distribution traits = undefined Meet Thom and his . - Meet Thom and his waifu-chan. thomandwaifu :: (Traits, Traits) thomandwaifu = (parentA, parentB) thom and have have two boys . What are their traits , probably ? twoboys :: (Traits, Traits) -> (Prob Traits, Prob Traits) twoboys (fromthom, andwaifu) = undefined The boys marry girls just like mom and have two boys each , respectively . grandsons :: (Prob Traits, Prob Traits) -> Prob Traits grandsons (boy, girl) = undefined What is the probability of atLeast 1 grandson is " Aa Bb " just like dear old justlikemom :: Prob Traits -> Float justlikemom distribution = undefined More generally , for generation n , where each member marries an " Aa Bb " wife and has two boys , what is the probability that there are k " Aa Bb " offspring ? moregenerally :: Prob Traits -> Int -> Int -> Float moregenerally distribution n k = undefined incidentally , the bonus question answers
dd7fa51187ff9f17a3ea325f84343ec2f85a750e028f956c7218be1288f17eb4
kronusaturn/lw2-viewer
push-notifications.lisp
(in-package #:lw2.backend) (define-cache-database 'backend-push-notifications "push-subscriptions") (export 'make-subscription) (defun make-subscription (auth-token endpoint expires) (cache-put "push-subscriptions" auth-token (alist :endpoint endpoint :expires expires) :value-type :json)) (export 'find-subscription) (defun find-subscription (auth-token) (cache-get "push-subscriptions" auth-token :value-type :json)) (export 'delete-subscription) (defun delete-subscription (auth-token) (cache-del "push-subscriptions" auth-token)) (export 'send-all-notifications) (define-backend-function send-all-notifications () (backend-push-notifications (let* ((all-subscriptions (with-collector (col) (call-with-cursor "push-subscriptions" (lambda (db cursor) (declare (ignore db)) (multiple-value-bind (value key) (cursor-get cursor :first) (loop while key do (col (cons key value)) (multiple-value-setq (value key) (cursor-get cursor :next))))) :read-only t) (col))) (current-time (local-time:now)) (current-time-unix (local-time:timestamp-to-unix current-time))) (loop for (auth-token . subscription-json) in all-subscriptions do (log-and-ignore-errors (let* ((subscription (json:decode-json-from-string subscription-json)) (last-check-cons (or (assoc :last-check subscription) (cons :last-check nil))) (since (if-let (unix (cdr last-check-cons)) (local-time:unix-to-timestamp unix)))) (cond ((let ((expires (cdr (assoc :expires subscription)))) (and expires (> current-time-unix expires))) (delete-subscription auth-token)) ((sb-sys:with-deadline (:seconds 30) (check-notifications (cache-get "auth-token-to-userid" auth-token) auth-token :since since)) (handler-case (sb-sys:with-deadline (:seconds 30) (send-notification (cdr (assoc :endpoint subscription)))) (dex:http-request-gone () (delete-subscription auth-token)) (:no-error (&rest args) (declare (ignore args)) (setf (cdr last-check-cons) (local-time:timestamp-to-unix current-time)) (cache-put "push-subscriptions" auth-token (adjoin last-check-cons subscription) :value-type :json)))))))))) (backend-base nil))
null
https://raw.githubusercontent.com/kronusaturn/lw2-viewer/ce8978034d60eff1b15fb78e87028adbec429965/src/push-notifications.lisp
lisp
(in-package #:lw2.backend) (define-cache-database 'backend-push-notifications "push-subscriptions") (export 'make-subscription) (defun make-subscription (auth-token endpoint expires) (cache-put "push-subscriptions" auth-token (alist :endpoint endpoint :expires expires) :value-type :json)) (export 'find-subscription) (defun find-subscription (auth-token) (cache-get "push-subscriptions" auth-token :value-type :json)) (export 'delete-subscription) (defun delete-subscription (auth-token) (cache-del "push-subscriptions" auth-token)) (export 'send-all-notifications) (define-backend-function send-all-notifications () (backend-push-notifications (let* ((all-subscriptions (with-collector (col) (call-with-cursor "push-subscriptions" (lambda (db cursor) (declare (ignore db)) (multiple-value-bind (value key) (cursor-get cursor :first) (loop while key do (col (cons key value)) (multiple-value-setq (value key) (cursor-get cursor :next))))) :read-only t) (col))) (current-time (local-time:now)) (current-time-unix (local-time:timestamp-to-unix current-time))) (loop for (auth-token . subscription-json) in all-subscriptions do (log-and-ignore-errors (let* ((subscription (json:decode-json-from-string subscription-json)) (last-check-cons (or (assoc :last-check subscription) (cons :last-check nil))) (since (if-let (unix (cdr last-check-cons)) (local-time:unix-to-timestamp unix)))) (cond ((let ((expires (cdr (assoc :expires subscription)))) (and expires (> current-time-unix expires))) (delete-subscription auth-token)) ((sb-sys:with-deadline (:seconds 30) (check-notifications (cache-get "auth-token-to-userid" auth-token) auth-token :since since)) (handler-case (sb-sys:with-deadline (:seconds 30) (send-notification (cdr (assoc :endpoint subscription)))) (dex:http-request-gone () (delete-subscription auth-token)) (:no-error (&rest args) (declare (ignore args)) (setf (cdr last-check-cons) (local-time:timestamp-to-unix current-time)) (cache-put "push-subscriptions" auth-token (adjoin last-check-cons subscription) :value-type :json)))))))))) (backend-base nil))
9b9e38ef86e9d89593c14d03583de2624bb4075671711b5d20a5f727f2b367bc
Autodesk-AutoCAD/AutoLispExt
pdfMarkups.lsp
; random sample file (defun sampleFunc (x y / a b c d) (setq a (list 1 2 3 4) ; does this screw it all up? d (setq b 0) b (mapcar '+ a)) (foreach x a (setq d (1+ d)) ) (defun SymPtrOnly () (setq gv 32) ) (defun c (a b / q) (defun q (r j / z) (setq z (* r j)) ) (q a b) ) ) @Global does this trip ? global (list "variables" "to" "test") with (vl-sort '(lambda(a b) (setq c (< a b))) global) ) (foreach rando global (setq some (strcat some " " rando)) ) (defun DumpPidMarkups (/ path pdfList pdfMarkups lineList compList equpList chckList textList resp contractDrawings downloadPdfs downloadPath badFiles noMarkups) (defun collectMarkups ( file / pchckList pcompList pequpList plineList ptextList markups fixAnno ret ) (setq ret nil) Hard code page 1 (if (> (length markups) 0) (progn (setq markups (vl-remove-if '(lambda (a) (or (/= (type a) 'LIST) (/= (strcase (nth 3 a)) "FREETEXT") (null (nth 5 a)) (= (nth 5 a) ""))) markups)) (setq markups (mapcar '(lambda (a) (list (vl-filename-base file) (nth 4 a) (nth 5 a) (nth 6 a))) markups)) (if (> (length markups) 0) (progn (foreach anno markups (setq fixAnno (mapcar '(lambda (l) (if (= (type l) 'STR) (acet-str-replace "\r" "-" (vl-string-trim " " (vl-string-trim (chr 9) l))) l)) anno)) (cond ((vl-string-search "LINENUMBER" (strcase (nth 1 fixAnno))) (setq plineList (cons fixAnno plineList))) ((vl-string-search "COMPONENT" (strcase (nth 1 fixAnno))) (setq pcompList (cons fixAnno pcompList))) ((vl-string-search "EQUIPMENT" (strcase (nth 1 fixAnno))) (setq pequpList (cons fixAnno pequpList))) ((and (null (vl-string-search "NOT IN SCOPE" (nth 2 fixAnno)))(>= (- (strlen (nth 2 fixAnno)) (strlen (acet-str-replace "-" "" (nth 2 fixAnno)))) 3)) (setq pchckList (cons fixAnno pchckList))) (t (setq ptextList (cons fixAnno ptextList))) ) ) (setq ret (list plineList pcompList pequpList pchckList ptextList)) ) ) ) ) (setq ret (vl-filename-base file)) ) ret ) (defun getPdfList ( pth / retList ) (setq retList (cadr (NS:ACAD:FilePicker "Select P&IDs to export markups" "Select files" GV:ProjPath "*.pdf"))) (cond ((null retList) (exit)) ((and (vl-consp retList) (= (length retList) 1) (= (car retList) "")) (setq retList getPdfList)) ((and (vl-consp retList) (> (length retList) 1) (vl-every 'findfile retList)) (terpri) (prompt (strcat (itoa (length retList)) " PDFs selected for processing"))) ) retList ) (if (null GV:ProjIni) (progn (NS:ACAD:MessageBox *GV:ProjIni* "Project.ini error" 0 16)(exit))) (setq resp (car (NS:ACAD:MessageBox "Do you want to download drawings?" "P&ID Download and Export" 3 32))) (cond Cancel (terpri) (prompt "P&ID Markup Export Terminated") (exit) ) ((= resp 6) ; Yes (setq contractDrawings (vl-catch-all-apply 'NS:Sharepoint:Read (list t GV:ExePath GV:ProjUrl "Contract Drawings" "ID" "Name"))) (if (vl-catch-all-error-p contractDrawings) (progn (alert "Error reading from Sharepoint") (exit))) (setq contractDrawings (vl-remove-if '(lambda (d) (null (vl-string-search ".pdf" (car d)))) (mapcar 'reverse contractDrawings)) downloadPdfs (cadr (NS:ACAD:ListBox "Select PDFs to Download" "Download Drawings" (acad_strlsort (mapcar 'car contractDrawings)) t))) (if (null downloadPdfs) (exit)) (setq downloadPath (caadr (NS:ACAD:DirPicker "Select Download Path" "Download files" GV:ProjPath))) (if (null downloadPath) (exit)) (foreach pdf downloadPdfs (setq downloadIds (cons (cadr (assoc pdf contractDrawings)) downloadIds)) ) (NS:SharePoint:Download GV:ExePath (cadr(assoc "SITE" GV:ProjIni)) "Contract Drawings" "ID" (mapcar 'itoa downloadIds) downloadPath) (setq defaultPath downloadPath) ) ((= resp 7) ; No (setq defaultPath GV:ProjPath)) ) (setq pdfList (getPdfList defaultPath)) (if (and pdfList (> (length pdfList) 0)) (foreach pdf pdfList (setq pdfMarkups (collectMarkups pdf)) (cond ((null pdfMarkups) (setq noMarkups (cons (vl-filename-base pdf) noMarkups))) ((= (type pdfMarkups) 'STR) (setq badFiles (cons pdfMarkups badFiles))) ((listp pdfMarkups) (if (nth 0 pdfMarkups) (setq lineList (append (nth 0 pdfMarkups) lineList))) (if (nth 1 pdfMarkups) (setq compList (append (nth 1 pdfMarkups) compList))) (if (nth 2 pdfMarkups) (setq equpList (append (nth 2 pdfMarkups) equpList))) (if (nth 3 pdfMarkups) (setq chckList (append (nth 3 pdfMarkups) chckList))) (if (nth 4 pdfMarkups) (setq textList (append (nth 4 pdfMarkups) textList)))) ) ) ) (if lineList (IO:WriteLines (cons (list "Page" "Subject" "LineTag" "Author") lineList) (strcat (vl-filename-directory (car pdfList)) "\\Linenumber List.csv"))) (if compList (IO:WriteLines (cons (list "Page" "Subject" "ComponentTag" "Author") compList) (strcat (vl-filename-directory (car pdfList)) "\\Components List.csv"))) (if equpList (IO:WriteLines (cons (list "Page" "Subject" "EquipmentTag" "Author") equpList) (strcat (vl-filename-directory (car pdfList)) "\\Equipment List.csv"))) (if chckList (IO:WriteLines (cons (list "Page" "Subject" "Contents" "Author") chckList) (strcat (vl-filename-directory (car pdfList)) "\\Review Required List.csv"))) (if textList (IO:WriteLines (cons (list "Page" "Subject" "Contents" "Author") textList) (strcat (vl-filename-directory (car pdfList)) "\\FreeText List.csv"))) (if badFiles (NS:ACAD:ListBox "Error reading the following files" "File Errors" (acad_strlsort badFiles) t)) (if noMarkups (NS:ACAD:ListBox "There were no markups on the following files" "No markups" (acad_strlsort noMarkups) t)) (terpri) (prompt "P&ID Markup Export Complete") (princ) ) (defun doStuff (pth / retList) (setq retList (cadr (NS:ACAD:FilePicker "Select P&IDs to export markups" "Select files" GV:ProjPath "*.pdf" ))) (cond ((null retList) (exit)) ((and (vl-consp retList) (= (length retList) 1) (= (car retList) "")) (setq retList getPdfList) ) ((and (vl-consp retList) (> (length retList) 1) (vl-every 'findfile retList)) (terpri) (prompt (strcat (itoa (length retList)) " PDFs selected for processing")) ) ) retList )
null
https://raw.githubusercontent.com/Autodesk-AutoCAD/AutoLispExt/1acd741d5d825445d42753d3bfe5d0a77d6eefbe/extension/src/test/SourceFile/test_case/pdfMarkups.lsp
lisp
random sample file does this screw it all up? Yes No
(defun sampleFunc (x y / a b c d) d (setq b 0) b (mapcar '+ a)) (foreach x a (setq d (1+ d)) ) (defun SymPtrOnly () (setq gv 32) ) (defun c (a b / q) (defun q (r j / z) (setq z (* r j)) ) (q a b) ) ) @Global does this trip ? global (list "variables" "to" "test") with (vl-sort '(lambda(a b) (setq c (< a b))) global) ) (foreach rando global (setq some (strcat some " " rando)) ) (defun DumpPidMarkups (/ path pdfList pdfMarkups lineList compList equpList chckList textList resp contractDrawings downloadPdfs downloadPath badFiles noMarkups) (defun collectMarkups ( file / pchckList pcompList pequpList plineList ptextList markups fixAnno ret ) (setq ret nil) Hard code page 1 (if (> (length markups) 0) (progn (setq markups (vl-remove-if '(lambda (a) (or (/= (type a) 'LIST) (/= (strcase (nth 3 a)) "FREETEXT") (null (nth 5 a)) (= (nth 5 a) ""))) markups)) (setq markups (mapcar '(lambda (a) (list (vl-filename-base file) (nth 4 a) (nth 5 a) (nth 6 a))) markups)) (if (> (length markups) 0) (progn (foreach anno markups (setq fixAnno (mapcar '(lambda (l) (if (= (type l) 'STR) (acet-str-replace "\r" "-" (vl-string-trim " " (vl-string-trim (chr 9) l))) l)) anno)) (cond ((vl-string-search "LINENUMBER" (strcase (nth 1 fixAnno))) (setq plineList (cons fixAnno plineList))) ((vl-string-search "COMPONENT" (strcase (nth 1 fixAnno))) (setq pcompList (cons fixAnno pcompList))) ((vl-string-search "EQUIPMENT" (strcase (nth 1 fixAnno))) (setq pequpList (cons fixAnno pequpList))) ((and (null (vl-string-search "NOT IN SCOPE" (nth 2 fixAnno)))(>= (- (strlen (nth 2 fixAnno)) (strlen (acet-str-replace "-" "" (nth 2 fixAnno)))) 3)) (setq pchckList (cons fixAnno pchckList))) (t (setq ptextList (cons fixAnno ptextList))) ) ) (setq ret (list plineList pcompList pequpList pchckList ptextList)) ) ) ) ) (setq ret (vl-filename-base file)) ) ret ) (defun getPdfList ( pth / retList ) (setq retList (cadr (NS:ACAD:FilePicker "Select P&IDs to export markups" "Select files" GV:ProjPath "*.pdf"))) (cond ((null retList) (exit)) ((and (vl-consp retList) (= (length retList) 1) (= (car retList) "")) (setq retList getPdfList)) ((and (vl-consp retList) (> (length retList) 1) (vl-every 'findfile retList)) (terpri) (prompt (strcat (itoa (length retList)) " PDFs selected for processing"))) ) retList ) (if (null GV:ProjIni) (progn (NS:ACAD:MessageBox *GV:ProjIni* "Project.ini error" 0 16)(exit))) (setq resp (car (NS:ACAD:MessageBox "Do you want to download drawings?" "P&ID Download and Export" 3 32))) (cond Cancel (terpri) (prompt "P&ID Markup Export Terminated") (exit) ) (setq contractDrawings (vl-catch-all-apply 'NS:Sharepoint:Read (list t GV:ExePath GV:ProjUrl "Contract Drawings" "ID" "Name"))) (if (vl-catch-all-error-p contractDrawings) (progn (alert "Error reading from Sharepoint") (exit))) (setq contractDrawings (vl-remove-if '(lambda (d) (null (vl-string-search ".pdf" (car d)))) (mapcar 'reverse contractDrawings)) downloadPdfs (cadr (NS:ACAD:ListBox "Select PDFs to Download" "Download Drawings" (acad_strlsort (mapcar 'car contractDrawings)) t))) (if (null downloadPdfs) (exit)) (setq downloadPath (caadr (NS:ACAD:DirPicker "Select Download Path" "Download files" GV:ProjPath))) (if (null downloadPath) (exit)) (foreach pdf downloadPdfs (setq downloadIds (cons (cadr (assoc pdf contractDrawings)) downloadIds)) ) (NS:SharePoint:Download GV:ExePath (cadr(assoc "SITE" GV:ProjIni)) "Contract Drawings" "ID" (mapcar 'itoa downloadIds) downloadPath) (setq defaultPath downloadPath) ) (setq defaultPath GV:ProjPath)) ) (setq pdfList (getPdfList defaultPath)) (if (and pdfList (> (length pdfList) 0)) (foreach pdf pdfList (setq pdfMarkups (collectMarkups pdf)) (cond ((null pdfMarkups) (setq noMarkups (cons (vl-filename-base pdf) noMarkups))) ((= (type pdfMarkups) 'STR) (setq badFiles (cons pdfMarkups badFiles))) ((listp pdfMarkups) (if (nth 0 pdfMarkups) (setq lineList (append (nth 0 pdfMarkups) lineList))) (if (nth 1 pdfMarkups) (setq compList (append (nth 1 pdfMarkups) compList))) (if (nth 2 pdfMarkups) (setq equpList (append (nth 2 pdfMarkups) equpList))) (if (nth 3 pdfMarkups) (setq chckList (append (nth 3 pdfMarkups) chckList))) (if (nth 4 pdfMarkups) (setq textList (append (nth 4 pdfMarkups) textList)))) ) ) ) (if lineList (IO:WriteLines (cons (list "Page" "Subject" "LineTag" "Author") lineList) (strcat (vl-filename-directory (car pdfList)) "\\Linenumber List.csv"))) (if compList (IO:WriteLines (cons (list "Page" "Subject" "ComponentTag" "Author") compList) (strcat (vl-filename-directory (car pdfList)) "\\Components List.csv"))) (if equpList (IO:WriteLines (cons (list "Page" "Subject" "EquipmentTag" "Author") equpList) (strcat (vl-filename-directory (car pdfList)) "\\Equipment List.csv"))) (if chckList (IO:WriteLines (cons (list "Page" "Subject" "Contents" "Author") chckList) (strcat (vl-filename-directory (car pdfList)) "\\Review Required List.csv"))) (if textList (IO:WriteLines (cons (list "Page" "Subject" "Contents" "Author") textList) (strcat (vl-filename-directory (car pdfList)) "\\FreeText List.csv"))) (if badFiles (NS:ACAD:ListBox "Error reading the following files" "File Errors" (acad_strlsort badFiles) t)) (if noMarkups (NS:ACAD:ListBox "There were no markups on the following files" "No markups" (acad_strlsort noMarkups) t)) (terpri) (prompt "P&ID Markup Export Complete") (princ) ) (defun doStuff (pth / retList) (setq retList (cadr (NS:ACAD:FilePicker "Select P&IDs to export markups" "Select files" GV:ProjPath "*.pdf" ))) (cond ((null retList) (exit)) ((and (vl-consp retList) (= (length retList) 1) (= (car retList) "")) (setq retList getPdfList) ) ((and (vl-consp retList) (> (length retList) 1) (vl-every 'findfile retList)) (terpri) (prompt (strcat (itoa (length retList)) " PDFs selected for processing")) ) ) retList )
daa48dd0cb61363c7bf389dd529efe5448d1318f0d790fabc194898d89ea3791
anishathalye/knox
driver-lang.rkt
#lang racket/base (require racket/provide racket/stxparam (prefix-in @ rosette/safe) (for-syntax racket/base racket/syntax syntax/parse) "../driver.rkt" (only-in "interpreter.rkt" basic-value? closure make-assoc assoc-extend make-interpreter)) (provide (rename-out [$#%module-begin #%module-begin]) #%top-interaction #%app #%datum #%datum #%top (rename-out [$define define]) ;; some of the simple builtins from interpreter void void? printf println equal? cons car cdr null? list? list length reverse not + - * quotient modulo zero? add1 sub1 abs max min < <= > >= expt integer? (filtered-out (lambda (name) (substring name 1)) (combine-out @bv @bv? @bveq @bvslt @bvult @bvsle @bvule @bvsgt @bvugt @bvsge @bvuge @bvnot @bvand @bvor @bvxor @bvshl @bvlshr @bvashr @bvneg @bvadd @bvsub @bvmul @bvsdiv @bvudiv @bvsrem @bvurem @bvsmod @concat @extract @sign-extend @zero-extend @bitvector->integer @bitvector->natural @integer->bitvector @bit @lsb @msb @bvzero? @bvadd1 @bvsub1 @bvsmin @bvumin @bvsmax @bvumax @bvrol @bvror @rotate-left @rotate-right @bitvector->bits @bitvector->bool @bool->bitvector))) (define-syntax-parameter $define (lambda (stx) (raise-syntax-error #f "use of a define outside the top-level" stx))) (define-syntax (process-defines stx) (syntax-parse stx [(_ global-bindings:id) #'(begin global-bindings)] [(_ global-bindings:id ((~literal $define) value-name:id body:expr) form ...) #'(let* ([value-name body] [global-bindings (assoc-extend global-bindings 'value-name value-name)]) (process-defines global-bindings form ...))] [(_ global-bindings:id ((~literal $define) (value-name:id formals:id ...) body:expr ...+) form ...) #'(let* ([value-name (closure '(lambda (formals ...) body ...) (make-assoc))] [global-bindings (assoc-extend global-bindings 'value-name value-name)]) (process-defines global-bindings form ...))] [(_ global-bindings:id ((~literal $define) (value-name:id . rest-arg:id) body:expr ...+) form ...) #'(let* ([value-name (closure '(lambda rest-arg body ...) (make-assoc))] [global-bindings (assoc-extend global-bindings 'value-name value-name)]) (process-defines global-bindings form ...))])) (define-syntax ($#%module-begin stx) (syntax-parse stx [(_ #:idle [(~seq signal-name:id signal-value:expr) ...] form ...) #:with driver (format-id stx "driver") #'(#%module-begin (define global-bindings (let ([global-bindings (make-assoc)]) (process-defines global-bindings form ...))) (define driver (make-driver global-bindings (list (cons 'signal-name signal-value) ...))) (provide driver))]))
null
https://raw.githubusercontent.com/anishathalye/knox/161cda3e5274cc69012830f477749954ddcf736d/knox/driver/driver-lang.rkt
racket
some of the simple builtins from interpreter
#lang racket/base (require racket/provide racket/stxparam (prefix-in @ rosette/safe) (for-syntax racket/base racket/syntax syntax/parse) "../driver.rkt" (only-in "interpreter.rkt" basic-value? closure make-assoc assoc-extend make-interpreter)) (provide (rename-out [$#%module-begin #%module-begin]) #%top-interaction #%app #%datum #%datum #%top (rename-out [$define define]) void void? printf println equal? cons car cdr null? list? list length reverse not + - * quotient modulo zero? add1 sub1 abs max min < <= > >= expt integer? (filtered-out (lambda (name) (substring name 1)) (combine-out @bv @bv? @bveq @bvslt @bvult @bvsle @bvule @bvsgt @bvugt @bvsge @bvuge @bvnot @bvand @bvor @bvxor @bvshl @bvlshr @bvashr @bvneg @bvadd @bvsub @bvmul @bvsdiv @bvudiv @bvsrem @bvurem @bvsmod @concat @extract @sign-extend @zero-extend @bitvector->integer @bitvector->natural @integer->bitvector @bit @lsb @msb @bvzero? @bvadd1 @bvsub1 @bvsmin @bvumin @bvsmax @bvumax @bvrol @bvror @rotate-left @rotate-right @bitvector->bits @bitvector->bool @bool->bitvector))) (define-syntax-parameter $define (lambda (stx) (raise-syntax-error #f "use of a define outside the top-level" stx))) (define-syntax (process-defines stx) (syntax-parse stx [(_ global-bindings:id) #'(begin global-bindings)] [(_ global-bindings:id ((~literal $define) value-name:id body:expr) form ...) #'(let* ([value-name body] [global-bindings (assoc-extend global-bindings 'value-name value-name)]) (process-defines global-bindings form ...))] [(_ global-bindings:id ((~literal $define) (value-name:id formals:id ...) body:expr ...+) form ...) #'(let* ([value-name (closure '(lambda (formals ...) body ...) (make-assoc))] [global-bindings (assoc-extend global-bindings 'value-name value-name)]) (process-defines global-bindings form ...))] [(_ global-bindings:id ((~literal $define) (value-name:id . rest-arg:id) body:expr ...+) form ...) #'(let* ([value-name (closure '(lambda rest-arg body ...) (make-assoc))] [global-bindings (assoc-extend global-bindings 'value-name value-name)]) (process-defines global-bindings form ...))])) (define-syntax ($#%module-begin stx) (syntax-parse stx [(_ #:idle [(~seq signal-name:id signal-value:expr) ...] form ...) #:with driver (format-id stx "driver") #'(#%module-begin (define global-bindings (let ([global-bindings (make-assoc)]) (process-defines global-bindings form ...))) (define driver (make-driver global-bindings (list (cons 'signal-name signal-value) ...))) (provide driver))]))
e048cb479af1ebc096714902ace178bfbf8ab67a3a84b3a8adc31046409db322
nniclausse/manderlbot
mdb_bhv_google.erl
%%% File : mdb_bhv_google.erl Author : < > Purpose : ask google for the first match of a given keyword Created : 16 Jul 2002 by < > %%%---------------------------------------------------------------------- %%% This file is part of Manderlbot . %%% Manderlbot 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. %%% Manderlbot 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. %%% %%% See LICENSE for detailled license %%% %%% In addition, as a special exception, you have the permission to %%% link the code of this program with any library released under the EPL license and distribute linked combinations including the two . If you modify this file , you may extend this exception %%% to your version of the file, but you are not obligated to do %%% so. If you do not wish to do so, delete this exception %%% statement from your version. %%% %%%---------------------------------------------------------------------- -module(mdb_bhv_google). -author(''). -revision(' $Id$ '). -vsn(' $Revision$ '). -export([behaviour/5]). % MDB behaviour API -export([search/5, parse/1, set_request/1]). -include("mdb.hrl"). -include("log.hrl"). -define(google_name, "www.google.com"). -define(google_port, 80). -define(notfound, "<br><br>Aucun document ne correspond"). -define(CR, "\n"). %%%---------------------------------------------------------------------- %%% Function: behaviour/5 Purpose : ask google and give the first response %%%---------------------------------------------------------------------- behaviour(Input, BotName, Data, BotPid, Channel) -> mdb_logger:debug("GOOGLE input: ~p~n", [Input#data.body]), [Key | Args] = string:tokens(Input#data.body," "), Criteria= misc_tools:join("+", Args), mdb_logger:debug("GOOGLE criteria: ~p~n", [Criteria]), search(Criteria, Input, BotPid, BotName, Channel). search(Keywords, Input, BotPid, BotName, Channel) -> mdb_search:search({Keywords, Input, BotPid, BotName, Channel, #search_param{type = ?MODULE, server = ?google_name, port = ?google_port } }). %%---------------------------------------------------------------------- %% Func: parse/1 Purpose : data %% Returns: {stop, Result} | {stop} | {continue} | {continue, Result} %% continue -> continue parsing of incoming data %% stop -> stop parsing of incoming data %% Result -> String to be printed by mdb %%---------------------------------------------------------------------- parse("Location: " ++ URL) -> {stop, URL }; parse(?notfound ++ _Data) -> {stop, "not found"}; parse(Data) -> {continue}. %%---------------------------------------------------------------------- %% Func: set_request/1 %% Purpose: Set the request given Keywords %% Returns: String %%---------------------------------------------------------------------- set_request(Keywords) -> "GET /search?q=" ++ Keywords ++"&hl=fr&btnI=J%27ai+de+la+chance HTTP/1.0" ++ ?CR ++ ?CR.
null
https://raw.githubusercontent.com/nniclausse/manderlbot/a65cfffc50801c09551b70d6bbd7a19e6b2c57dd/src/mdb_bhv_google.erl
erlang
File : mdb_bhv_google.erl ---------------------------------------------------------------------- (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. See LICENSE for detailled license In addition, as a special exception, you have the permission to link the code of this program with any library released under to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. ---------------------------------------------------------------------- MDB behaviour API ---------------------------------------------------------------------- Function: behaviour/5 ---------------------------------------------------------------------- ---------------------------------------------------------------------- Func: parse/1 Returns: {stop, Result} | {stop} | {continue} | {continue, Result} continue -> continue parsing of incoming data stop -> stop parsing of incoming data Result -> String to be printed by mdb ---------------------------------------------------------------------- ---------------------------------------------------------------------- Func: set_request/1 Purpose: Set the request given Keywords Returns: String ----------------------------------------------------------------------
Author : < > Purpose : ask google for the first match of a given keyword Created : 16 Jul 2002 by < > This file is part of Manderlbot . Manderlbot 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 Manderlbot is distributed in the hope that it will be useful , the EPL license and distribute linked combinations including the two . If you modify this file , you may extend this exception -module(mdb_bhv_google). -author(''). -revision(' $Id$ '). -vsn(' $Revision$ '). -export([search/5, parse/1, set_request/1]). -include("mdb.hrl"). -include("log.hrl"). -define(google_name, "www.google.com"). -define(google_port, 80). -define(notfound, "<br><br>Aucun document ne correspond"). -define(CR, "\n"). Purpose : ask google and give the first response behaviour(Input, BotName, Data, BotPid, Channel) -> mdb_logger:debug("GOOGLE input: ~p~n", [Input#data.body]), [Key | Args] = string:tokens(Input#data.body," "), Criteria= misc_tools:join("+", Args), mdb_logger:debug("GOOGLE criteria: ~p~n", [Criteria]), search(Criteria, Input, BotPid, BotName, Channel). search(Keywords, Input, BotPid, BotName, Channel) -> mdb_search:search({Keywords, Input, BotPid, BotName, Channel, #search_param{type = ?MODULE, server = ?google_name, port = ?google_port } }). Purpose : data parse("Location: " ++ URL) -> {stop, URL }; parse(?notfound ++ _Data) -> {stop, "not found"}; parse(Data) -> {continue}. set_request(Keywords) -> "GET /search?q=" ++ Keywords ++"&hl=fr&btnI=J%27ai+de+la+chance HTTP/1.0" ++ ?CR ++ ?CR.
b04648c7a6c8236d83cce9a29f0cc381bb68bf38b93822ca88dfdf3e13f708f2
elldritch/hipsterfy
Main.hs
module Main (main) where import Hipsterfy.Spotify.Auth (SpotifyCredentials (..)) import Hipsterfy.Spotify.Spec (testGetAlbums) import Options.Applicative ( ParserInfo, briefDesc, execParser, helper, info, long, progDesc, strOption, ) import Relude import System.Environment (withArgs) import Test.Hspec (hspec) newtype Options = Options { accessToken :: Text } opts :: ParserInfo Options opts = info (options <**> helper) (briefDesc <> progDesc "Hipsterfy automated test") where options = Options <$> strOption (long "access_token") main :: IO () main = do Options {accessToken} <- execParser opts let creds = SpotifyCredentials { accessToken, refreshToken = error "impossible: refreshToken never used", expiration = error "impossible: expiration never used" } withArgs [] $ hspec $ do testGetAlbums creds
null
https://raw.githubusercontent.com/elldritch/hipsterfy/7d455697c1146d89fc6b2f78effe6694efe69120/test/Main.hs
haskell
module Main (main) where import Hipsterfy.Spotify.Auth (SpotifyCredentials (..)) import Hipsterfy.Spotify.Spec (testGetAlbums) import Options.Applicative ( ParserInfo, briefDesc, execParser, helper, info, long, progDesc, strOption, ) import Relude import System.Environment (withArgs) import Test.Hspec (hspec) newtype Options = Options { accessToken :: Text } opts :: ParserInfo Options opts = info (options <**> helper) (briefDesc <> progDesc "Hipsterfy automated test") where options = Options <$> strOption (long "access_token") main :: IO () main = do Options {accessToken} <- execParser opts let creds = SpotifyCredentials { accessToken, refreshToken = error "impossible: refreshToken never used", expiration = error "impossible: expiration never used" } withArgs [] $ hspec $ do testGetAlbums creds
ca1aa3397513904f19e23baec12cb4be15228e0f2359068aeeef7e23b49ba38d
kototama/clojure-semantic
mini.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 ^{:doc "The core Clojure language." :author "Rich Hickey"} kklojure.core) (def unquote2 12) (def ^{:a o} unquote-splicing2) (defn aa [b c] ()) (defn ^:private ^:static kreduce ([f coll] (let [s (seq coll)] (if s (reduce1 f (first s) (next s)) (f)))) ([f val coll] (let [s (seq coll)] (if s (if (chunked-seq? s) (recur f (.reduce (chunk-first s) f val) (chunk-next s)) (recur f (f val (first s)) (next s))) val)))) (defn ^:string kcheck4 "Detects and rejects non-trivial cyclic load dependencies. The exception message shows the dependency chain with the cycle highlighted. Ignores the trivial case of a file attempting to load itself because that can occur when a gen-class'd class loads its implementation." [path] (when (some #{path} (rest *pending-paths*)) (let [pending (map #(if (= % path) (str "[ " % " ]") %) (cons path *pending-paths*)) chain (apply str (interpose "->" pending))] (throw (Exception. (str "Cyclic load dependency: " chain)))))) (defn- ^:string check2 "Detects and rejects non-trivial cyclic load dependencies. The exception message shows the dependency chain with the cycle highlighted. Ignores the trivial case of a file attempting to load itself because that can occur when a gen-class'd class loads its implementation." [path] (when (some #{path} (rest *pending-paths*)) (let [pending (map #(if (= % path) (str "[ " % " ]") %) (cons path *pending-paths*)) chain (apply str (interpose "->" pending))] (throw (Exception. (str "Cyclic load dependency: " chain)))))) (def ^:dynamic ^{:doc "bound in a repl thread to the second most recent value printed" :added "1.0"} *2) (defn ^:static ^clojure.lang.ChunkBuffer kchunk-buffer ^clojure.lang.ChunkBuffer [capacity] (clojure.lang.ChunkBuffer. capacity)) (defn ^:static kchunk-append [^clojure.lang.ChunkBuffer b x] (.add b x))
null
https://raw.githubusercontent.com/kototama/clojure-semantic/580c8c6629b9a42ce0d6ab14bf44597685a473d3/tests/mini.clj
clojure
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.
Copyright ( c ) . All rights reserved . (ns ^{:doc "The core Clojure language." :author "Rich Hickey"} kklojure.core) (def unquote2 12) (def ^{:a o} unquote-splicing2) (defn aa [b c] ()) (defn ^:private ^:static kreduce ([f coll] (let [s (seq coll)] (if s (reduce1 f (first s) (next s)) (f)))) ([f val coll] (let [s (seq coll)] (if s (if (chunked-seq? s) (recur f (.reduce (chunk-first s) f val) (chunk-next s)) (recur f (f val (first s)) (next s))) val)))) (defn ^:string kcheck4 "Detects and rejects non-trivial cyclic load dependencies. The exception message shows the dependency chain with the cycle highlighted. Ignores the trivial case of a file attempting to load itself because that can occur when a gen-class'd class loads its implementation." [path] (when (some #{path} (rest *pending-paths*)) (let [pending (map #(if (= % path) (str "[ " % " ]") %) (cons path *pending-paths*)) chain (apply str (interpose "->" pending))] (throw (Exception. (str "Cyclic load dependency: " chain)))))) (defn- ^:string check2 "Detects and rejects non-trivial cyclic load dependencies. The exception message shows the dependency chain with the cycle highlighted. Ignores the trivial case of a file attempting to load itself because that can occur when a gen-class'd class loads its implementation." [path] (when (some #{path} (rest *pending-paths*)) (let [pending (map #(if (= % path) (str "[ " % " ]") %) (cons path *pending-paths*)) chain (apply str (interpose "->" pending))] (throw (Exception. (str "Cyclic load dependency: " chain)))))) (def ^:dynamic ^{:doc "bound in a repl thread to the second most recent value printed" :added "1.0"} *2) (defn ^:static ^clojure.lang.ChunkBuffer kchunk-buffer ^clojure.lang.ChunkBuffer [capacity] (clojure.lang.ChunkBuffer. capacity)) (defn ^:static kchunk-append [^clojure.lang.ChunkBuffer b x] (.add b x))
0698d2d0cbc78c4dfb294098ec5a767e7d5b70ac4a40940ab07e1d7ae9fc65d2
simonmar/par-tutorial
kmeans-seq.hs
K - Means sample from " Parallel and Concurrent Programming in Haskell " -- -- Usage (sequential): -- $ ./kmeans-par seq import System.IO import KMeansCommon import Data.Array import Text.Printf import Data.List import Data.Function import Data.Binary (decodeFile) import Debug.Trace import Control.DeepSeq import System.Environment import Data.Time.Clock import Control.Exception main = do points <- decodeFile "points.bin" clusters <- getClusters "clusters" let nclusters = length clusters args <- getArgs evaluate (length points) t0 <- getCurrentTime final_clusters <- case args of ["seq"] -> [ " par",n ] - > kmeans_par ( read n ) nclusters points clusters _other -> error "args" t1 <- getCurrentTime print final_clusters printf "Total time: %.2f\n" (realToFrac (diffUTCTime t1 t0) :: Double) -- ----------------------------------------------------------------------------- -- K-Means: repeatedly step until convergence kmeans_seq :: Int -> [Vector] -> [Cluster] -> IO [Cluster] kmeans_seq nclusters points clusters = do let loop :: Int -> [Cluster] -> IO [Cluster] loop n clusters | n > tooMany = do printf "giving up."; return clusters loop n clusters = do hPrintf stderr "iteration %d\n" n hPutStr stderr (unlines (map show clusters)) let clusters' = step nclusters clusters points if clusters' == clusters then return clusters else loop (n+1) clusters' -- loop 0 clusters kmeans_par :: Int -> Int -> [Vector] -> [Cluster] -> IO [Cluster] kmeans_par n nclusters points clusters = error "kmeans_par not defined!" hint : one approach is to divide the points into n sets , call -- step on the sets in parallel and combine the results using -- 'reduce', below. tooMany = 50 -- ----------------------------------------------------------------------------- Perform one step of the K - Means algorithm step :: Int -> [Cluster] -> [Vector] -> [Cluster] step nclusters clusters points = makeNewClusters (assign nclusters clusters points) -- assign each vector to the nearest cluster centre assign :: Int -> [Cluster] -> [Vector] -> Array Int [Vector] assign nclusters clusters points = accumArray (flip (:)) [] (0, nclusters-1) [ (clId (nearest p), p) | p <- points ] where nearest p = fst $ minimumBy (compare `on` snd) [ (c, sqDistance (clCent c) p) | c <- clusters ] makeNewClusters :: Array Int [Vector] -> [Cluster] makeNewClusters arr = filter ((>0) . clCount) $ [ makeCluster i ps | (i,ps) <- assocs arr ] -- v. important: filter out any clusters that have -- no points. This can happen when a cluster is not -- close to any points. If we leave these in, then the NaNs mess up all the future calculations . -- Takes the number of clusters, N, and a list of lists of clusters -- (each list is length N), and combines the lists to produce a final -- list of N clusters. -- -- Useful for parallelising the algorithm! -- reduce :: Int -> [[Cluster]] -> [Cluster] reduce nclusters css = concatMap combine $ elems $ accumArray (flip (:)) [] (0,nclusters) [ (clId c, c) | c <- concat css] where combine [] = [] combine (c:cs) = [foldr combineClusters c cs]
null
https://raw.githubusercontent.com/simonmar/par-tutorial/f9061ea177800eb4ed9660bcabc8d8d836e1c73c/code/kmeans/kmeans-seq.hs
haskell
Usage (sequential): $ ./kmeans-par seq ----------------------------------------------------------------------------- K-Means: repeatedly step until convergence step on the sets in parallel and combine the results using 'reduce', below. ----------------------------------------------------------------------------- assign each vector to the nearest cluster centre v. important: filter out any clusters that have no points. This can happen when a cluster is not close to any points. If we leave these in, then Takes the number of clusters, N, and a list of lists of clusters (each list is length N), and combines the lists to produce a final list of N clusters. Useful for parallelising the algorithm!
K - Means sample from " Parallel and Concurrent Programming in Haskell " import System.IO import KMeansCommon import Data.Array import Text.Printf import Data.List import Data.Function import Data.Binary (decodeFile) import Debug.Trace import Control.DeepSeq import System.Environment import Data.Time.Clock import Control.Exception main = do points <- decodeFile "points.bin" clusters <- getClusters "clusters" let nclusters = length clusters args <- getArgs evaluate (length points) t0 <- getCurrentTime final_clusters <- case args of ["seq"] -> [ " par",n ] - > kmeans_par ( read n ) nclusters points clusters _other -> error "args" t1 <- getCurrentTime print final_clusters printf "Total time: %.2f\n" (realToFrac (diffUTCTime t1 t0) :: Double) kmeans_seq :: Int -> [Vector] -> [Cluster] -> IO [Cluster] kmeans_seq nclusters points clusters = do let loop :: Int -> [Cluster] -> IO [Cluster] loop n clusters | n > tooMany = do printf "giving up."; return clusters loop n clusters = do hPrintf stderr "iteration %d\n" n hPutStr stderr (unlines (map show clusters)) let clusters' = step nclusters clusters points if clusters' == clusters then return clusters else loop (n+1) clusters' loop 0 clusters kmeans_par :: Int -> Int -> [Vector] -> [Cluster] -> IO [Cluster] kmeans_par n nclusters points clusters = error "kmeans_par not defined!" hint : one approach is to divide the points into n sets , call tooMany = 50 Perform one step of the K - Means algorithm step :: Int -> [Cluster] -> [Vector] -> [Cluster] step nclusters clusters points = makeNewClusters (assign nclusters clusters points) assign :: Int -> [Cluster] -> [Vector] -> Array Int [Vector] assign nclusters clusters points = accumArray (flip (:)) [] (0, nclusters-1) [ (clId (nearest p), p) | p <- points ] where nearest p = fst $ minimumBy (compare `on` snd) [ (c, sqDistance (clCent c) p) | c <- clusters ] makeNewClusters :: Array Int [Vector] -> [Cluster] makeNewClusters arr = filter ((>0) . clCount) $ [ makeCluster i ps | (i,ps) <- assocs arr ] the NaNs mess up all the future calculations . reduce :: Int -> [[Cluster]] -> [Cluster] reduce nclusters css = concatMap combine $ elems $ accumArray (flip (:)) [] (0,nclusters) [ (clId c, c) | c <- concat css] where combine [] = [] combine (c:cs) = [foldr combineClusters c cs]
b3eb7b8be7c2aefd9e00412f63737e23584f6fa254ff5df9f74bdc69b97e0152
clojurewerkz/archimedes
io.clj
(ns clojurewerkz.archimedes.io (:require [clojure.java.io :as io] [clojurewerkz.archimedes.graph :as g]) (:import [com.tinkerpop.blueprints.util.io.graphml GraphMLWriter GraphMLReader] [com.tinkerpop.blueprints.util.io.gml GMLWriter GMLReader] [com.tinkerpop.blueprints.util.io.graphson GraphSONWriter GraphSONReader GraphSONMode])) (defn- load-graph-with-reader [reader g string-or-file] (let [in-stream (io/input-stream string-or-file)] (reader g in-stream))) (defn- write-graph-with-writer [writer g string-or-file] (if (not (g/get-feature g "supportsVertexIteration")) (throw (Exception. "Cannot write a graph that does not support vertex iteration."))) (let [out-stream (io/output-stream string-or-file)] (writer g out-stream))) GML (def load-graph-gml (partial load-graph-with-reader #(GMLReader/inputGraph %1 %2))) (def write-graph-gml (partial write-graph-with-writer #(GMLWriter/outputGraph %1 %2))) ;; GraphML (def load-graph-graphml (partial load-graph-with-reader #(GraphMLReader/inputGraph %1 %2))) (def write-graph-graphml (partial write-graph-with-writer #(GraphMLWriter/outputGraph %1 %2))) GraphSON (def load-graph-graphson (partial load-graph-with-reader #(GraphSONReader/inputGraph %1 %2))) write - graph - graphson can take an optional 2nd argument : ;; show-types - determines if types are written explicitly to the JSON Note that for Titan Graphs with types , you will want show - types = true . ;; See -Reader-and-Writer-Library (defn write-graph-graphson [g string-or-file & [ show-types ]] (let [graphSON-mode (if show-types GraphSONMode/EXTENDED GraphSONMode/NORMAL)] (write-graph-with-writer #(GraphSONWriter/outputGraph %1 %2 graphSON-mode) g string-or-file)))
null
https://raw.githubusercontent.com/clojurewerkz/archimedes/f3300d3d71d35534acf7cc6f010e3fa503be0fba/src/clojure/clojurewerkz/archimedes/io.clj
clojure
GraphML show-types - determines if types are written explicitly to the JSON See -Reader-and-Writer-Library
(ns clojurewerkz.archimedes.io (:require [clojure.java.io :as io] [clojurewerkz.archimedes.graph :as g]) (:import [com.tinkerpop.blueprints.util.io.graphml GraphMLWriter GraphMLReader] [com.tinkerpop.blueprints.util.io.gml GMLWriter GMLReader] [com.tinkerpop.blueprints.util.io.graphson GraphSONWriter GraphSONReader GraphSONMode])) (defn- load-graph-with-reader [reader g string-or-file] (let [in-stream (io/input-stream string-or-file)] (reader g in-stream))) (defn- write-graph-with-writer [writer g string-or-file] (if (not (g/get-feature g "supportsVertexIteration")) (throw (Exception. "Cannot write a graph that does not support vertex iteration."))) (let [out-stream (io/output-stream string-or-file)] (writer g out-stream))) GML (def load-graph-gml (partial load-graph-with-reader #(GMLReader/inputGraph %1 %2))) (def write-graph-gml (partial write-graph-with-writer #(GMLWriter/outputGraph %1 %2))) (def load-graph-graphml (partial load-graph-with-reader #(GraphMLReader/inputGraph %1 %2))) (def write-graph-graphml (partial write-graph-with-writer #(GraphMLWriter/outputGraph %1 %2))) GraphSON (def load-graph-graphson (partial load-graph-with-reader #(GraphSONReader/inputGraph %1 %2))) write - graph - graphson can take an optional 2nd argument : Note that for Titan Graphs with types , you will want show - types = true . (defn write-graph-graphson [g string-or-file & [ show-types ]] (let [graphSON-mode (if show-types GraphSONMode/EXTENDED GraphSONMode/NORMAL)] (write-graph-with-writer #(GraphSONWriter/outputGraph %1 %2 graphSON-mode) g string-or-file)))
6015163168521763688ba3f6359d9eddc6011bcb8b11fe2ef4ad790f24627cb0
haroldcarr/learn-haskell-coq-ml-etc
Tutorial1.hs
# LANGUAGE NoMonomorphismRestriction # # LANGUAGE FlexibleInstances , FlexibleContexts # {-# LANGUAGE GADTs #-} -- ** `Practical' denotational semantics module Tutorial1 where Consider a small subset of Haskell -- (or a pure functional subset of other suitable language) -- as an `executable Math' -- How to deal with side-effects, like input? -- Simple sub-language of effectful integer expressions , embedded in Haskell -- Define by denotational semantics: giving meaning to each -- expression and how to compose them -- Don't commit to a particular domain yet class ReaderLang d where int :: Int -> d -- Int literals add :: d -> d -> d ask :: d -- Sample expression rlExp = add ask (add ask (int 1)) -- What should be that d? EDLS , pp 2 and 6 EDLS , p7 -- * Implementing Math data CRead = CRVal Int | Get0 (Int -> CRead) instance ReaderLang CRead where int x = CRVal x ask = Get0 CRVal -- t1 = ask + ask -- p9 add (CRVal x) (CRVal y) = CRVal (x+y) add (Get0 k) y = Get0 (\x -> add (k x) y) add x (Get0 k) = Get0 (\y -> add x (k y)) -- The meaning of rlExp in that domain _ = rlExp :: CRead -- Need authority (admin)! p 11 runReader0 :: Int -> CRead -> Int runReader0 e (CRVal x) = x runReader0 e (Get0 k) = runReader0 e $ k e _ = runReader0 2 rlExp -- CRead is too particular semantic domain: nothing but Int value -- (computations) -- Need something more general -- Again, p7 data Comp req a where Val :: a -> Comp req a E :: req x -> (x -> Comp req a) -> Comp req a -- Effect signature data Get x where Get :: Get Int instance ReaderLang (Comp Get Int) where int x = Val x ask = E Get Val add (Val x) (Val y) = Val (x+y) add (E r k) y = E r (\x -> add (k x) y) add x (E r k) = E r (\y -> add x (k y)) -- How to extend to other types of env? runReader :: Int -> Comp Get a -> a runReader e (Val x) = x runReader e (E Get k) = runReader e $ k e _ = runReader 2 rlExp :: Int If we need subtraction , should we write the last two clauses -- over again? -- Generalizing even more p7 , Fig 3 inV :: a -> Comp req a inV = Val bind :: Comp req a -> (a -> Comp req b) -> Comp req b bind (Val x) f = f x bind (E r k) f = E r (\x -> bind (k x) f) -- We can easily write even richer Reader languages, uniformly rlExp2 = bind ask $ \x -> bind ask $ \y -> Val (x + y + 1) -- with multiplication, subtraction, end re-using previous expressions rlExp3 = bind rlExp2 $ \x -> bind ask $ \y -> Val (x * y - 1) _ = runReader 2 rlExp3 :: Int
null
https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/conference/2017-09-cufp-effects/src/Tutorial1.hs
haskell
# LANGUAGE GADTs # ** `Practical' denotational semantics (or a pure functional subset of other suitable language) as an `executable Math' How to deal with side-effects, like input? Simple sub-language of effectful integer Define by denotational semantics: giving meaning to each expression and how to compose them Don't commit to a particular domain yet Int literals Sample expression What should be that d? * Implementing Math t1 = ask + ask p9 The meaning of rlExp in that domain Need authority (admin)! CRead is too particular semantic domain: nothing but Int value (computations) Need something more general Again, p7 Effect signature How to extend to other types of env? over again? Generalizing even more We can easily write even richer Reader languages, uniformly with multiplication, subtraction, end re-using previous expressions
# LANGUAGE NoMonomorphismRestriction # # LANGUAGE FlexibleInstances , FlexibleContexts # module Tutorial1 where Consider a small subset of Haskell expressions , embedded in Haskell class ReaderLang d where add :: d -> d -> d ask :: d rlExp = add ask (add ask (int 1)) EDLS , pp 2 and 6 EDLS , p7 data CRead = CRVal Int | Get0 (Int -> CRead) instance ReaderLang CRead where int x = CRVal x ask = Get0 CRVal add (CRVal x) (CRVal y) = CRVal (x+y) add (Get0 k) y = Get0 (\x -> add (k x) y) add x (Get0 k) = Get0 (\y -> add x (k y)) _ = rlExp :: CRead p 11 runReader0 :: Int -> CRead -> Int runReader0 e (CRVal x) = x runReader0 e (Get0 k) = runReader0 e $ k e _ = runReader0 2 rlExp data Comp req a where Val :: a -> Comp req a E :: req x -> (x -> Comp req a) -> Comp req a data Get x where Get :: Get Int instance ReaderLang (Comp Get Int) where int x = Val x ask = E Get Val add (Val x) (Val y) = Val (x+y) add (E r k) y = E r (\x -> add (k x) y) add x (E r k) = E r (\y -> add x (k y)) runReader :: Int -> Comp Get a -> a runReader e (Val x) = x runReader e (E Get k) = runReader e $ k e _ = runReader 2 rlExp :: Int If we need subtraction , should we write the last two clauses p7 , Fig 3 inV :: a -> Comp req a inV = Val bind :: Comp req a -> (a -> Comp req b) -> Comp req b bind (Val x) f = f x bind (E r k) f = E r (\x -> bind (k x) f) rlExp2 = bind ask $ \x -> bind ask $ \y -> Val (x + y + 1) rlExp3 = bind rlExp2 $ \x -> bind ask $ \y -> Val (x * y - 1) _ = runReader 2 rlExp3 :: Int
d6959d4ed525ed8eeac1876c0674cb05de0df7db8cf7f26acbab4195f943fc16
hongchangwu/ocaml-type-classes
num.mli
module type S = sig type t val ( + ) : t -> t -> t val ( - ) : t -> t -> t val ( * ) : t -> t -> t val negate : t -> t val abs : t -> t val from_int : int -> t end val int : (module S with type t = int) val float : (module S with type t = float)
null
https://raw.githubusercontent.com/hongchangwu/ocaml-type-classes/17b11af26008f42a88aec85001a94ba18584ea72/lib/num.mli
ocaml
module type S = sig type t val ( + ) : t -> t -> t val ( - ) : t -> t -> t val ( * ) : t -> t -> t val negate : t -> t val abs : t -> t val from_int : int -> t end val int : (module S with type t = int) val float : (module S with type t = float)
c57897a076d7d9d90497bae1a7966469c66da1f7dd1e63048df25c16c6125c64
emilypi/higher-functors
Higher.hs
# language PolyKinds # # language KindSignatures # # language RoleAnnotations # # language GADTs # # language StandaloneKindSignatures # # language TypeOperators # # language RankNTypes # module Data.Function.Higher ( -- * Natural Transformations NT(..) , NIso(..) , Nop(..) -- * Type synonyms , type (~>) , type (<~) , type (<~>) -- * Combinators , ($$-) , (-$$) ) where import Data.Kind (Type) infixr 0 ~>, <~>, <~, $$-, -$$ -- | A synonym for 'NT'. -- type (~>) (f :: k -> Type) (g :: k -> Type) = forall a. f a -> g a -- | A synonym for 'Nop'. The pun here is "natural 'Op'" -- type (<~) (f :: k -> Type) (g :: k -> Type) = forall a. g a -> f a | A synonym for ' NIso ' -- type (<~>) (f :: k -> Type) (g :: k -> Type) = (f ~> g) -> (g ~> f) -- | The type of natural transformations. Note that in general -- this is a stronger condition than naturality due to the presence -- of parametricity. -- type NT :: (k -> Type) -> (k -> Type) -> k -> Type type role NT nominal nominal nominal newtype NT f g a where NT :: { runNT :: (f ~> g) } -> NT f g a -- | The type of natural isomorphisms. -- type NIso :: (i -> Type) -> (j -> Type) -> k -> Type type role NIso nominal nominal nominal data NIso f g a where NIso :: { runNTIso :: (f <~> g) } -> NIso f g a -- | The type of natural transformations in the opposite functor category . is to ' NT ' as ' Op ' is to ' Nop ' -- type Nop :: (i -> Type) -> (i -> Type) -> i -> Type type role Nop nominal nominal nominal newtype Nop f g a where Nop :: { runNop :: (f <~ g) } -> Nop f g a -- | Evaluate a component of a natural transformation of functors -- with common polarity at some concrete value. -- ($$-) :: NT f g a -> f a -> g a NT fg $$- f = fg f -- | Evaluate a component of a natural transformation of functors -- with mixed polarity at some concrete value. -- (-$$) :: Nop f g a -> g a -> f a Nop gf -$$ g = gf g
null
https://raw.githubusercontent.com/emilypi/higher-functors/41f8858983f706177b88e6f2ec78e6f5f59dd58c/src/Data/Function/Higher.hs
haskell
* Natural Transformations * Type synonyms * Combinators | A synonym for 'NT'. | A synonym for 'Nop'. The pun here is "natural 'Op'" | The type of natural transformations. Note that in general this is a stronger condition than naturality due to the presence of parametricity. | The type of natural isomorphisms. | The type of natural transformations in the opposite | Evaluate a component of a natural transformation of functors with common polarity at some concrete value. | Evaluate a component of a natural transformation of functors with mixed polarity at some concrete value.
# language PolyKinds # # language KindSignatures # # language RoleAnnotations # # language GADTs # # language StandaloneKindSignatures # # language TypeOperators # # language RankNTypes # module Data.Function.Higher NT(..) , NIso(..) , Nop(..) , type (~>) , type (<~) , type (<~>) , ($$-) , (-$$) ) where import Data.Kind (Type) infixr 0 ~>, <~>, <~, $$-, -$$ type (~>) (f :: k -> Type) (g :: k -> Type) = forall a. f a -> g a type (<~) (f :: k -> Type) (g :: k -> Type) = forall a. g a -> f a | A synonym for ' NIso ' type (<~>) (f :: k -> Type) (g :: k -> Type) = (f ~> g) -> (g ~> f) type NT :: (k -> Type) -> (k -> Type) -> k -> Type type role NT nominal nominal nominal newtype NT f g a where NT :: { runNT :: (f ~> g) } -> NT f g a type NIso :: (i -> Type) -> (j -> Type) -> k -> Type type role NIso nominal nominal nominal data NIso f g a where NIso :: { runNTIso :: (f <~> g) } -> NIso f g a functor category . is to ' NT ' as ' Op ' is to ' Nop ' type Nop :: (i -> Type) -> (i -> Type) -> i -> Type type role Nop nominal nominal nominal newtype Nop f g a where Nop :: { runNop :: (f <~ g) } -> Nop f g a ($$-) :: NT f g a -> f a -> g a NT fg $$- f = fg f (-$$) :: Nop f g a -> g a -> f a Nop gf -$$ g = gf g
a36555514b901207c1eb87118a277dad8234211b1c34397e1824941a8b43ed13
Z572/gwwm
client.scm
(define-module (gwwm client) #:autoload (gwwm) (fullscreen-layer float-layer tile-layer overlay-layer top-layer bottom-layer background-layer gwwm-seat arrangelayers) #:autoload (gwwm commands) (arrange) #:autoload (gwwm config) (gwwm-borderpx g-config) #:duplicates (merge-generics replace warn-override-core warn last) #:use-module (srfi srfi-1) #:use-module (srfi srfi-2) #:use-module (srfi srfi-26) #:use-module (srfi srfi-71) #:use-module (srfi srfi-189) #:use-module (gwwm utils srfi-215) #:use-module (wlroots types scene) #:use-module (wlroots types compositor) #:use-module (wlroots types subcompositor) #:use-module (wlroots types layer-shell) #:use-module (wlroots time) #:use-module (ice-9 q) #:use-module (ice-9 control) #:use-module (ice-9 format) #:use-module (gwwm utils) #:use-module (util572 color) #:use-module (wlroots xwayland) #:use-module (gwwm monitor) #:use-module (gwwm hooks) #:use-module (wayland listener) #:use-module (wayland list) #:use-module (wlroots types seat) #:use-module (wlroots util box) #:use-module (util572 box) #:use-module (wlroots types xdg-shell) #:use-module (wlroots types cursor) #:use-module (gwwm listener) #:use-module (gwwm i18n) #:use-module (oop goops) #:use-module (oop goops describe) #:export (visibleon current-client client-get-geometry client-floating? client-fullscreen? client-urgent? client-list client-get-appid client-get-title client-alive? client-at client=? client-get-parent client-is-x11? client-is-unmanaged? client-is-float-type? client-send-close client-set-tiled client-resize client-set-resizing! client-title client-appid client-scene client-set-scene! client-monitor client-border-width client-get-size-hints client-tags client-surface client-super-surface client-geom client-prev-geom client-mapped? client-wants-fullscreen? client-do-set-fullscreen client-do-set-floating client-resize-configure-serial client-init-border client-set-border-color client-restack-surface client-from-wlr-surface super-surface->client super-surface->scene scene-node->client client-set-title-notify client-commit-notify client-destroy-notify surface->scene client-scene-set-enabled client-scene-move client-scene-move/relatively client-scene-raise-to-top %fstack %clients %layer-clients <gwwm-base-client> <gwwm-client> <gwwm-x-client> <gwwm-xdg-client> <gwwm-layer-client>)) (define %layer-clients (make-parameter (make-q) (lambda (o) (if (q? o) o (error "not a q! ~A" o))))) (define %fstack (make-parameter (make-q) (lambda (o) (if (q? o) o (error "not a q! ~A" o))))) (eval-when (expand load eval) (load-extension "libgwwm" "scm_init_gwwm_client")) (define-method (client-set-border-color c (color <rgba-color>)) #t) (define-once visibleon-functions (list (lambda (c m) (equal? (client-tags c) (list-ref (slot-ref m 'tagset) (slot-ref m 'seltags)))))) (define (visibleon c m) (and m (equal? (client-monitor c) m) (and-map (lambda (v) (v c m)) visibleon-functions))) (define-class <gwwm-base-client> () (geom #:accessor client-geom #:init-thunk (lambda () (make <wlr-box>))) (monitor #:init-value #f #:accessor client-monitor #:init-keyword #:monitor) (super-surface #:init-value #f #:accessor client-super-surface #:init-keyword #:super-surface) (surface #:allocation #:virtual #:slot-ref (lambda (obj) (.surface (slot-ref obj 'super-surface))) #:slot-set! (const #f) #:getter client-surface) (scene #:init-value #f #:accessor client-scene #:setter client-set-scene! #:init-keyword #:scene) (alive? #:init-value #t #:accessor client-alive?) #:metaclass <redefinable-class>) (define-class <gwwm-client> (<gwwm-base-client>) (appid #:accessor client-appid) (floating? #:init-value #f #:accessor client-floating?) (fullscreen? #:init-value #f #:accessor client-fullscreen?) (urgent? #:init-value #f #:accessor client-urgent?) (title #:accessor client-title) (tags #:init-value 0 #:accessor client-tags) (border-width #:init-value 1 #:accessor client-border-width) (prev-geom #:accessor client-prev-geom) (resize-configure-serial #:accessor client-resize-configure-serial #:init-value #f)) (define-once super-surface->client (make-object-property)) (define-once super-surface->scene (make-object-property)) (let-syntax ((def (lambda (x) (syntax-case x () ((_ n %n f s) #'(begin (define-once %n (make-hash-table 500)) (define-method (n (o f)) (hashq-ref %n o)) (define-method ((setter n) (o f) (o2 s)) (hashq-set! %n o o2)) (export n))))))) (def surface->scene %surface->scene <wlr-surface> <wlr-scene-tree>) (def scene-node->client %scene-node->client <wlr-scene-node> <gwwm-base-client>)) (define-once client-borders (make-object-property)) (define-method (client-set-border-color (c <gwwm-client>) (color <rgba-color>)) (for-each (lambda (b) (wlr-scene-rect-set-color b color)) (or (client-borders c) '()))) (define-class <gwwm-layer-client> (<gwwm-base-client>) (scene-layer-surface #:init-keyword #:scene-layer-surface)) (define-class <gwwm-x-client> (<gwwm-client>)) (define-class <gwwm-xdg-client> (<gwwm-client>)) (define-method (initialize (c <gwwm-base-client>) initargs) (next-method) (set! (super-surface->client (client-super-surface c)) c)) (define-method (initialize (c <gwwm-client>) initargs) (next-method) (set! (client-appid c) (client-get-appid c)) (set! (client-title c) (client-get-title c))) (define-method (initialize (c <gwwm-layer-client>) initargs) (next-method) (q-push! (%layer-clients) c)) (define-method (client-mapped? (c <gwwm-xdg-client>)) (.mapped (client-super-surface c))) (define-method (client-mapped? (c <gwwm-x-client>)) (wlr-xwayland-surface-mapped? (client-super-surface c))) (define-method (client-init-border (c <gwwm-client>)) (send-log DEBUG (G_ "client init border") 'c c) (define scene (client-scene c)) (define (create) (let ((rect (wlr-scene-rect-create scene 0 0 (make-rgba-color 0 0 0 0)))) rect)) (set! (client-borders c) (list (create) (create) (create) (create))) (client-set-tiled c (list 1 2 4 8)) (modify-instance* (client-geom c) (width (+ width (* 2 (gwwm-borderpx)))) (height (+ height (* 2 (gwwm-borderpx)))))) (define-method (describe (c <gwwm-base-client>)) (if (client-alive? c) (next-method) (begin (format #t (G_ "~S is a *deaded* client.~%") c) *unspecified*))) (define-once %clients (make-parameter (make-q) (lambda (o) (if (q? o) o (error "not a q! ~A" o))))) (define-method (client-wants-fullscreen? (c <gwwm-xdg-client>)) (.fullscreen (.requested (wlr-xdg-surface-toplevel (client-super-surface c))))) (define-method (client-wants-fullscreen? (c <gwwm-x-client>)) (.fullscreen (client-super-surface c))) (define-method (client-do-set-fullscreen (c <gwwm-client>)) (client-do-set-fullscreen c (client-fullscreen? c))) (define-method (client-do-set-fullscreen (c <gwwm-client>) fullscreen?) (send-log DEBUG (G_ "client do fullscreen") 'client c 'fullscreen? fullscreen?) (let ((fullscreen? (->bool fullscreen?))) (set! (client-fullscreen? c) fullscreen?) (set! (client-border-width c) (if fullscreen? 0 (gwwm-borderpx))) (if fullscreen? (begin (set! (client-prev-geom c) (shallow-clone (client-geom c))) (client-resize c (shallow-clone (monitor-area (client-monitor c))) #f)) (client-resize c (shallow-clone (client-prev-geom c)))) (run-hook client-fullscreen-hook c fullscreen?) (arrange (client-monitor c)))) (define-method (client-do-set-fullscreen (client <gwwm-xdg-client>) fullscreen?) (next-method) (wlr-xdg-toplevel-set-fullscreen (wlr-xdg-surface-toplevel (client-super-surface client)) fullscreen?)) (define-method (client-do-set-fullscreen (c <gwwm-x-client>) fullscreen?) (next-method) (wlr-xwayland-surface-set-fullscreen (client-super-surface c) fullscreen?)) (define-method (client-do-set-floating (c <gwwm-client>) floating?) (send-log DEBUG (G_ "client do floating") 'client c ) (when (client-fullscreen? c) (client-do-set-fullscreen c #f)) (set! (client-floating? c) floating?) (arrange (client-monitor c))) (define-method (write (client <gwwm-client>) port) (format port "#<~s ~a ~x>" (class-name (class-of client)) (if (client-alive? client) (client-get-appid client) "*deaded*") (object-address client))) (define-method (client-get-parent (c <gwwm-xdg-client>)) (and=> (.parent (wlr-xdg-surface-toplevel (client-super-surface c))) (lambda (x) (client-from-wlr-surface (.surface x))))) (define-method (client-get-parent (c <gwwm-x-client>)) (and=> (.parent (client-super-surface c)) (lambda (x) (client-from-wlr-surface (.surface x))))) (define-method (client-get-appid (c <gwwm-xdg-client>)) (or (and=> (client-super-surface c) (lambda (o) (.app-id (wlr-xdg-surface-toplevel o)))) "*unknow*")) (define-method (client-get-appid (c <gwwm-x-client>)) (or (and=> (client-super-surface c) wlr-xwayland-surface-class) "*unknow*")) (define-method (client-get-title (c <gwwm-xdg-client>)) (.title (wlr-xdg-surface-toplevel (client-super-surface c)))) (define-method (client-get-title (c <gwwm-x-client>)) (wlr-xwayland-surface-title (client-super-surface c))) (define-method (client-send-close (c <gwwm-xdg-client>)) (wlr-xdg-toplevel-send-close (wlr-xdg-surface-toplevel(client-super-surface c)))) (define-method (client-send-close (c <gwwm-x-client>)) (wlr-xwayland-surface-close (client-super-surface c))) (define (client-is-x11? client) (is-a? client <gwwm-x-client>)) (define-method (client-is-unmanaged? client) #f) (define-method (client-is-unmanaged? (client <gwwm-x-client>)) (wlr-xwayland-surface-override-redirect (client-super-surface client))) (define* (client-list #:optional (m #f)) "return all clients. if provide M, return M's clients." (let ((clients (car (%clients)))) (if m (filter (lambda (c) (eq? (client-monitor c) m)) clients) clients))) (define (current-client) "return current client or #f." (and=> (.focused-surface (.keyboard-state (gwwm-seat))) client-from-wlr-surface)) (define-method (client-set-resizing! (c <gwwm-xdg-client>) resizing?) (wlr-xdg-toplevel-set-resizing (wlr-xdg-surface-toplevel (client-super-surface c)) resizing?)) (define-method (client-set-resizing! (c <gwwm-x-client>) resizing?) *unspecified*) (define-method (client-at x y) (or (any (lambda (layer) (let* ((node p (wlr-scene-node-at (.node layer) x y))) (if node (let loop ((node* node)) (or (let ((o (scene-node->client node*))) (and ((negate (cut is-a? <> <gwwm-layer-client>)) o) o (just o (and=> (wlr-scene-object-from-node node) (lambda (o) (and (wlr-scene-surface? o) (.surface o)))) (car p) (cdr p)))) (and=> (and=> (.parent node*) .node) loop))) #f))) (list overlay-layer top-layer float-layer fullscreen-layer tile-layer bottom-layer background-layer)) (nothing))) (define-method (client-at (cursor <wlr-cursor>)) (client-at (.x cursor) (.y cursor))) (define (%get-size-hints-helper o) (define boxs (list (make <wlr-box>) (make <wlr-box>))) (and=> o (lambda (o) (let-slots o (max-width max-height min-width min-height) (modify-instance* (first boxs) (width max-width) (height max-height)) (modify-instance* (second boxs) (width min-width) (height min-height))))) (unlist boxs)) (define-method (client-get-size-hints (c <gwwm-xdg-client>)) (%get-size-hints-helper (.current (wlr-xdg-surface-toplevel (client-super-surface c))))) (define-method (client-get-size-hints (c <gwwm-x-client>)) (%get-size-hints-helper (.size-hints (client-super-surface c)))) (define-method (client-set-tiled c (edges <list>)) (client-set-tiled c (apply logior edges))) (define-method (client-set-tiled (c <gwwm-xdg-client>) (edges <integer>)) (wlr-xdg-toplevel-set-tiled (wlr-xdg-surface-toplevel (client-super-surface c)) edges)) (define-method (client-restack-surface c) *unspecified*) (define-method (client-restack-surface (c <gwwm-x-client>)) (wlr-xwayland-surface-restack (client-super-surface c) #f 0)) (define-method (client-set-tiled (c <gwwm-x-client>) edges) *unspecified*) (define (client-from-wlr-surface s) (and s (or (and-let* (((wlr-surface-is-xdg-surface s)) (super-surface (wlr-xdg-surface-from-wlr-surface s)) ((eq? (.role super-surface) 'WLR_XDG_SURFACE_ROLE_TOPLEVEL))) (super-surface->client super-surface)) (and-let* (((wlr-surface-is-xwayland-surface s)) (super-surface (wlr-xwayland-surface-from-wlr-surface s))) (super-surface->client super-surface)) (if (wlr-surface-is-subsurface s) (client-from-wlr-surface (wlr-surface-get-root-surface s)) #f)))) (define-method (client-get-geometry (c <gwwm-xdg-client>)) (wlr-xdg-surface-get-geometry (client-super-surface c))) (define-method (client-get-geometry (c <gwwm-x-client>)) (let ((s (client-super-surface c))) (make-wlr-box (wlr-xwayland-surface-x s) (wlr-xwayland-surface-y s) (wlr-xwayland-surface-width s) (wlr-xwayland-surface-height s)))) (define-method (applybounds (c <gwwm-client>) geom) (unless (client-fullscreen? c) (let ((_ min* (client-get-size-hints c)) (bw (client-border-width c)) (box (client-geom c))) (modify-instance* box (width (max width (+ (box-width min*) (* 2 bw)) )) (height (max height (+ (box-height min*) (* 2 bw)) ))) (let-slots geom ((x xx) (y yy) (height hh) (width ww)) (let-slots box (x y height width) (if (>= x (+ xx ww)) (set! (box-x box) (- (+ xx ww) width))) (if (>= y (+ yy hh)) (set! (box-y box) (- (+ yy hh) height))) (if (<= (+ x width (* 2 bw)) xx) (set! (box-x box) xx)) (if (<= (+ y height (* 2 bw)) y) (set! (box-x box) yy))))))) (define-method (client-set-size! (c <gwwm-xdg-client>) width height) (wlr-xdg-toplevel-set-size (wlr-xdg-surface-toplevel (client-super-surface c)) width height)) (define-method (client-set-size! (c <gwwm-x-client>) width height) (wlr-xwayland-surface-configure (client-super-surface c) (box-x (client-geom c)) (box-y (client-geom c)) width height) 0) (define-method (client-resize-border (c <gwwm-client>)) (and-let* ((borders (client-borders c)) ((not (null-list? borders))) (bw (client-border-width c)) (geom (client-geom c)) (heigh (box-height geom)) (width (box-width geom))) (wlr-scene-rect-set-size (list-ref borders 0) width bw) (wlr-scene-node-set-position (.node (list-ref borders 0)) (- bw) (- bw)) (wlr-scene-rect-set-size (list-ref borders 1) width bw) (wlr-scene-node-set-position (.node (list-ref borders 1)) (- bw) (- heigh bw bw )) (wlr-scene-rect-set-size (list-ref borders 2) bw heigh) (wlr-scene-node-set-position (.node (list-ref borders 2)) (- bw) (- bw ) ) (wlr-scene-rect-set-size (list-ref borders 3) bw heigh) (wlr-scene-node-set-position (.node (list-ref borders 3)) (- width bw bw) (- bw)))) (define-method (client-scene-raise-to-top (c <gwwm-base-client>)) (wlr-scene-node-raise-to-top (.node (client-scene c)))) (define-method (client-scene-set-enabled (c <gwwm-base-client>) n) (wlr-scene-node-set-enabled (.node (client-scene c)) n)) (define-method (client-scene-move (c <gwwm-base-client>) x y) (wlr-scene-node-set-position (.node (client-scene c)) x y)) (define-method (client-scene-move (c <gwwm-client>) x y) (let ((bw (client-border-width c))) (next-method c (+ bw x) (+ bw y)))) (define-method (client-scene-move/relatively (c <gwwm-base-client>) x y) (let ((node (.node (client-scene c)))) (wlr-scene-node-set-position (.node (client-scene c)) (+ (.x node) x) (+ (.y node) y)))) (define-method (client-resize (c <gwwm-client>) geo (interact? <boolean>)) (set! (client-geom c) geo) (applybounds c (if interact? ((@ (gwwm) entire-layout-box)) (monitor-window-area (client-monitor c)))) (let* ((bw (client-border-width c)) (geom (client-geom c)) (heigh (box-height geom)) (width (box-width geom))) (set! (client-resize-configure-serial c) (client-set-size! c (- width (* 2 bw)) (- heigh (* 2 bw)))) (client-resize-border c) (client-scene-move c (box-x geo) (box-y geo)))) (define-method (client-resize (c <gwwm-client>) geo) (client-resize c geo #f)) (define-method (client-destroy-notify (c <gwwm-base-client>)) (lambda (listener data) (send-log DEBUG "client destroy" 'client c) (run-hook client-destroy-hook c) ;; mark it destroyed. (set! (client-alive? c) #f))) (define-method (client-destroy-notify (c <gwwm-client>)) (let ((next (next-method c))) (lambda (listener data) (next listener data) (set! (client-scene c) #f)))) (define-method (client-destroy-notify (c <gwwm-layer-client>)) (let ((next (next-method c))) (lambda (listener data) (q-remove! (%layer-clients) c) (for-each (cut q-remove! <> c) (slot-ref (client-monitor c) 'layers)) (next listener data) (and=> (client-monitor c) arrangelayers)))) (define-method (client-set-title-notify (c <gwwm-client>)) (lambda (listener data) (let ((title (client-title c)) (new (client-get-title c))) (set! (client-title c) new) (run-hook update-title-hook c title new) (send-log DEBUG (G_ "Client change title.") 'client c 'old title 'new (client-title c))))) (define-method (client-commit-notify (c <gwwm-client>)) (lambda (a b) ;;(send-log DEBUG "client commit" 'client c) (let ((box (client-get-geometry c)) (m (client-monitor c))) (when (and m (not (box-empty? box)) (or (not (= (box-width box) (- (box-width (client-geom c)) (* 2 (client-border-width c))))) (not (= (box-height box) (- (box-height (client-geom c)) (* 2 (client-border-width c))))))) (arrange m))) (run-hook surface-commit-event-hook c))) (define-method (client-commit-notify (c <gwwm-xdg-client>)) (let ((next (next-method c))) (lambda (listener data) (next listener data) (let ((serial (client-resize-configure-serial c)) (current (.current (client-super-surface c))) (pending (.pending (client-super-surface c)))) (when (and (not (zero? serial)) (or (<= serial (.configure-serial current)) (and (= (box-width (.geometry current)) (box-width (.geometry pending))) (= (box-height (.geometry current)) (box-height (.geometry pending)))))) (set! (client-resize-configure-serial c) 0))))))
null
https://raw.githubusercontent.com/Z572/gwwm/cf2dfea760a11b430892d2e883344c05d6fe73df/gwwm/client.scm
scheme
mark it destroyed. (send-log DEBUG "client commit" 'client c)
(define-module (gwwm client) #:autoload (gwwm) (fullscreen-layer float-layer tile-layer overlay-layer top-layer bottom-layer background-layer gwwm-seat arrangelayers) #:autoload (gwwm commands) (arrange) #:autoload (gwwm config) (gwwm-borderpx g-config) #:duplicates (merge-generics replace warn-override-core warn last) #:use-module (srfi srfi-1) #:use-module (srfi srfi-2) #:use-module (srfi srfi-26) #:use-module (srfi srfi-71) #:use-module (srfi srfi-189) #:use-module (gwwm utils srfi-215) #:use-module (wlroots types scene) #:use-module (wlroots types compositor) #:use-module (wlroots types subcompositor) #:use-module (wlroots types layer-shell) #:use-module (wlroots time) #:use-module (ice-9 q) #:use-module (ice-9 control) #:use-module (ice-9 format) #:use-module (gwwm utils) #:use-module (util572 color) #:use-module (wlroots xwayland) #:use-module (gwwm monitor) #:use-module (gwwm hooks) #:use-module (wayland listener) #:use-module (wayland list) #:use-module (wlroots types seat) #:use-module (wlroots util box) #:use-module (util572 box) #:use-module (wlroots types xdg-shell) #:use-module (wlroots types cursor) #:use-module (gwwm listener) #:use-module (gwwm i18n) #:use-module (oop goops) #:use-module (oop goops describe) #:export (visibleon current-client client-get-geometry client-floating? client-fullscreen? client-urgent? client-list client-get-appid client-get-title client-alive? client-at client=? client-get-parent client-is-x11? client-is-unmanaged? client-is-float-type? client-send-close client-set-tiled client-resize client-set-resizing! client-title client-appid client-scene client-set-scene! client-monitor client-border-width client-get-size-hints client-tags client-surface client-super-surface client-geom client-prev-geom client-mapped? client-wants-fullscreen? client-do-set-fullscreen client-do-set-floating client-resize-configure-serial client-init-border client-set-border-color client-restack-surface client-from-wlr-surface super-surface->client super-surface->scene scene-node->client client-set-title-notify client-commit-notify client-destroy-notify surface->scene client-scene-set-enabled client-scene-move client-scene-move/relatively client-scene-raise-to-top %fstack %clients %layer-clients <gwwm-base-client> <gwwm-client> <gwwm-x-client> <gwwm-xdg-client> <gwwm-layer-client>)) (define %layer-clients (make-parameter (make-q) (lambda (o) (if (q? o) o (error "not a q! ~A" o))))) (define %fstack (make-parameter (make-q) (lambda (o) (if (q? o) o (error "not a q! ~A" o))))) (eval-when (expand load eval) (load-extension "libgwwm" "scm_init_gwwm_client")) (define-method (client-set-border-color c (color <rgba-color>)) #t) (define-once visibleon-functions (list (lambda (c m) (equal? (client-tags c) (list-ref (slot-ref m 'tagset) (slot-ref m 'seltags)))))) (define (visibleon c m) (and m (equal? (client-monitor c) m) (and-map (lambda (v) (v c m)) visibleon-functions))) (define-class <gwwm-base-client> () (geom #:accessor client-geom #:init-thunk (lambda () (make <wlr-box>))) (monitor #:init-value #f #:accessor client-monitor #:init-keyword #:monitor) (super-surface #:init-value #f #:accessor client-super-surface #:init-keyword #:super-surface) (surface #:allocation #:virtual #:slot-ref (lambda (obj) (.surface (slot-ref obj 'super-surface))) #:slot-set! (const #f) #:getter client-surface) (scene #:init-value #f #:accessor client-scene #:setter client-set-scene! #:init-keyword #:scene) (alive? #:init-value #t #:accessor client-alive?) #:metaclass <redefinable-class>) (define-class <gwwm-client> (<gwwm-base-client>) (appid #:accessor client-appid) (floating? #:init-value #f #:accessor client-floating?) (fullscreen? #:init-value #f #:accessor client-fullscreen?) (urgent? #:init-value #f #:accessor client-urgent?) (title #:accessor client-title) (tags #:init-value 0 #:accessor client-tags) (border-width #:init-value 1 #:accessor client-border-width) (prev-geom #:accessor client-prev-geom) (resize-configure-serial #:accessor client-resize-configure-serial #:init-value #f)) (define-once super-surface->client (make-object-property)) (define-once super-surface->scene (make-object-property)) (let-syntax ((def (lambda (x) (syntax-case x () ((_ n %n f s) #'(begin (define-once %n (make-hash-table 500)) (define-method (n (o f)) (hashq-ref %n o)) (define-method ((setter n) (o f) (o2 s)) (hashq-set! %n o o2)) (export n))))))) (def surface->scene %surface->scene <wlr-surface> <wlr-scene-tree>) (def scene-node->client %scene-node->client <wlr-scene-node> <gwwm-base-client>)) (define-once client-borders (make-object-property)) (define-method (client-set-border-color (c <gwwm-client>) (color <rgba-color>)) (for-each (lambda (b) (wlr-scene-rect-set-color b color)) (or (client-borders c) '()))) (define-class <gwwm-layer-client> (<gwwm-base-client>) (scene-layer-surface #:init-keyword #:scene-layer-surface)) (define-class <gwwm-x-client> (<gwwm-client>)) (define-class <gwwm-xdg-client> (<gwwm-client>)) (define-method (initialize (c <gwwm-base-client>) initargs) (next-method) (set! (super-surface->client (client-super-surface c)) c)) (define-method (initialize (c <gwwm-client>) initargs) (next-method) (set! (client-appid c) (client-get-appid c)) (set! (client-title c) (client-get-title c))) (define-method (initialize (c <gwwm-layer-client>) initargs) (next-method) (q-push! (%layer-clients) c)) (define-method (client-mapped? (c <gwwm-xdg-client>)) (.mapped (client-super-surface c))) (define-method (client-mapped? (c <gwwm-x-client>)) (wlr-xwayland-surface-mapped? (client-super-surface c))) (define-method (client-init-border (c <gwwm-client>)) (send-log DEBUG (G_ "client init border") 'c c) (define scene (client-scene c)) (define (create) (let ((rect (wlr-scene-rect-create scene 0 0 (make-rgba-color 0 0 0 0)))) rect)) (set! (client-borders c) (list (create) (create) (create) (create))) (client-set-tiled c (list 1 2 4 8)) (modify-instance* (client-geom c) (width (+ width (* 2 (gwwm-borderpx)))) (height (+ height (* 2 (gwwm-borderpx)))))) (define-method (describe (c <gwwm-base-client>)) (if (client-alive? c) (next-method) (begin (format #t (G_ "~S is a *deaded* client.~%") c) *unspecified*))) (define-once %clients (make-parameter (make-q) (lambda (o) (if (q? o) o (error "not a q! ~A" o))))) (define-method (client-wants-fullscreen? (c <gwwm-xdg-client>)) (.fullscreen (.requested (wlr-xdg-surface-toplevel (client-super-surface c))))) (define-method (client-wants-fullscreen? (c <gwwm-x-client>)) (.fullscreen (client-super-surface c))) (define-method (client-do-set-fullscreen (c <gwwm-client>)) (client-do-set-fullscreen c (client-fullscreen? c))) (define-method (client-do-set-fullscreen (c <gwwm-client>) fullscreen?) (send-log DEBUG (G_ "client do fullscreen") 'client c 'fullscreen? fullscreen?) (let ((fullscreen? (->bool fullscreen?))) (set! (client-fullscreen? c) fullscreen?) (set! (client-border-width c) (if fullscreen? 0 (gwwm-borderpx))) (if fullscreen? (begin (set! (client-prev-geom c) (shallow-clone (client-geom c))) (client-resize c (shallow-clone (monitor-area (client-monitor c))) #f)) (client-resize c (shallow-clone (client-prev-geom c)))) (run-hook client-fullscreen-hook c fullscreen?) (arrange (client-monitor c)))) (define-method (client-do-set-fullscreen (client <gwwm-xdg-client>) fullscreen?) (next-method) (wlr-xdg-toplevel-set-fullscreen (wlr-xdg-surface-toplevel (client-super-surface client)) fullscreen?)) (define-method (client-do-set-fullscreen (c <gwwm-x-client>) fullscreen?) (next-method) (wlr-xwayland-surface-set-fullscreen (client-super-surface c) fullscreen?)) (define-method (client-do-set-floating (c <gwwm-client>) floating?) (send-log DEBUG (G_ "client do floating") 'client c ) (when (client-fullscreen? c) (client-do-set-fullscreen c #f)) (set! (client-floating? c) floating?) (arrange (client-monitor c))) (define-method (write (client <gwwm-client>) port) (format port "#<~s ~a ~x>" (class-name (class-of client)) (if (client-alive? client) (client-get-appid client) "*deaded*") (object-address client))) (define-method (client-get-parent (c <gwwm-xdg-client>)) (and=> (.parent (wlr-xdg-surface-toplevel (client-super-surface c))) (lambda (x) (client-from-wlr-surface (.surface x))))) (define-method (client-get-parent (c <gwwm-x-client>)) (and=> (.parent (client-super-surface c)) (lambda (x) (client-from-wlr-surface (.surface x))))) (define-method (client-get-appid (c <gwwm-xdg-client>)) (or (and=> (client-super-surface c) (lambda (o) (.app-id (wlr-xdg-surface-toplevel o)))) "*unknow*")) (define-method (client-get-appid (c <gwwm-x-client>)) (or (and=> (client-super-surface c) wlr-xwayland-surface-class) "*unknow*")) (define-method (client-get-title (c <gwwm-xdg-client>)) (.title (wlr-xdg-surface-toplevel (client-super-surface c)))) (define-method (client-get-title (c <gwwm-x-client>)) (wlr-xwayland-surface-title (client-super-surface c))) (define-method (client-send-close (c <gwwm-xdg-client>)) (wlr-xdg-toplevel-send-close (wlr-xdg-surface-toplevel(client-super-surface c)))) (define-method (client-send-close (c <gwwm-x-client>)) (wlr-xwayland-surface-close (client-super-surface c))) (define (client-is-x11? client) (is-a? client <gwwm-x-client>)) (define-method (client-is-unmanaged? client) #f) (define-method (client-is-unmanaged? (client <gwwm-x-client>)) (wlr-xwayland-surface-override-redirect (client-super-surface client))) (define* (client-list #:optional (m #f)) "return all clients. if provide M, return M's clients." (let ((clients (car (%clients)))) (if m (filter (lambda (c) (eq? (client-monitor c) m)) clients) clients))) (define (current-client) "return current client or #f." (and=> (.focused-surface (.keyboard-state (gwwm-seat))) client-from-wlr-surface)) (define-method (client-set-resizing! (c <gwwm-xdg-client>) resizing?) (wlr-xdg-toplevel-set-resizing (wlr-xdg-surface-toplevel (client-super-surface c)) resizing?)) (define-method (client-set-resizing! (c <gwwm-x-client>) resizing?) *unspecified*) (define-method (client-at x y) (or (any (lambda (layer) (let* ((node p (wlr-scene-node-at (.node layer) x y))) (if node (let loop ((node* node)) (or (let ((o (scene-node->client node*))) (and ((negate (cut is-a? <> <gwwm-layer-client>)) o) o (just o (and=> (wlr-scene-object-from-node node) (lambda (o) (and (wlr-scene-surface? o) (.surface o)))) (car p) (cdr p)))) (and=> (and=> (.parent node*) .node) loop))) #f))) (list overlay-layer top-layer float-layer fullscreen-layer tile-layer bottom-layer background-layer)) (nothing))) (define-method (client-at (cursor <wlr-cursor>)) (client-at (.x cursor) (.y cursor))) (define (%get-size-hints-helper o) (define boxs (list (make <wlr-box>) (make <wlr-box>))) (and=> o (lambda (o) (let-slots o (max-width max-height min-width min-height) (modify-instance* (first boxs) (width max-width) (height max-height)) (modify-instance* (second boxs) (width min-width) (height min-height))))) (unlist boxs)) (define-method (client-get-size-hints (c <gwwm-xdg-client>)) (%get-size-hints-helper (.current (wlr-xdg-surface-toplevel (client-super-surface c))))) (define-method (client-get-size-hints (c <gwwm-x-client>)) (%get-size-hints-helper (.size-hints (client-super-surface c)))) (define-method (client-set-tiled c (edges <list>)) (client-set-tiled c (apply logior edges))) (define-method (client-set-tiled (c <gwwm-xdg-client>) (edges <integer>)) (wlr-xdg-toplevel-set-tiled (wlr-xdg-surface-toplevel (client-super-surface c)) edges)) (define-method (client-restack-surface c) *unspecified*) (define-method (client-restack-surface (c <gwwm-x-client>)) (wlr-xwayland-surface-restack (client-super-surface c) #f 0)) (define-method (client-set-tiled (c <gwwm-x-client>) edges) *unspecified*) (define (client-from-wlr-surface s) (and s (or (and-let* (((wlr-surface-is-xdg-surface s)) (super-surface (wlr-xdg-surface-from-wlr-surface s)) ((eq? (.role super-surface) 'WLR_XDG_SURFACE_ROLE_TOPLEVEL))) (super-surface->client super-surface)) (and-let* (((wlr-surface-is-xwayland-surface s)) (super-surface (wlr-xwayland-surface-from-wlr-surface s))) (super-surface->client super-surface)) (if (wlr-surface-is-subsurface s) (client-from-wlr-surface (wlr-surface-get-root-surface s)) #f)))) (define-method (client-get-geometry (c <gwwm-xdg-client>)) (wlr-xdg-surface-get-geometry (client-super-surface c))) (define-method (client-get-geometry (c <gwwm-x-client>)) (let ((s (client-super-surface c))) (make-wlr-box (wlr-xwayland-surface-x s) (wlr-xwayland-surface-y s) (wlr-xwayland-surface-width s) (wlr-xwayland-surface-height s)))) (define-method (applybounds (c <gwwm-client>) geom) (unless (client-fullscreen? c) (let ((_ min* (client-get-size-hints c)) (bw (client-border-width c)) (box (client-geom c))) (modify-instance* box (width (max width (+ (box-width min*) (* 2 bw)) )) (height (max height (+ (box-height min*) (* 2 bw)) ))) (let-slots geom ((x xx) (y yy) (height hh) (width ww)) (let-slots box (x y height width) (if (>= x (+ xx ww)) (set! (box-x box) (- (+ xx ww) width))) (if (>= y (+ yy hh)) (set! (box-y box) (- (+ yy hh) height))) (if (<= (+ x width (* 2 bw)) xx) (set! (box-x box) xx)) (if (<= (+ y height (* 2 bw)) y) (set! (box-x box) yy))))))) (define-method (client-set-size! (c <gwwm-xdg-client>) width height) (wlr-xdg-toplevel-set-size (wlr-xdg-surface-toplevel (client-super-surface c)) width height)) (define-method (client-set-size! (c <gwwm-x-client>) width height) (wlr-xwayland-surface-configure (client-super-surface c) (box-x (client-geom c)) (box-y (client-geom c)) width height) 0) (define-method (client-resize-border (c <gwwm-client>)) (and-let* ((borders (client-borders c)) ((not (null-list? borders))) (bw (client-border-width c)) (geom (client-geom c)) (heigh (box-height geom)) (width (box-width geom))) (wlr-scene-rect-set-size (list-ref borders 0) width bw) (wlr-scene-node-set-position (.node (list-ref borders 0)) (- bw) (- bw)) (wlr-scene-rect-set-size (list-ref borders 1) width bw) (wlr-scene-node-set-position (.node (list-ref borders 1)) (- bw) (- heigh bw bw )) (wlr-scene-rect-set-size (list-ref borders 2) bw heigh) (wlr-scene-node-set-position (.node (list-ref borders 2)) (- bw) (- bw ) ) (wlr-scene-rect-set-size (list-ref borders 3) bw heigh) (wlr-scene-node-set-position (.node (list-ref borders 3)) (- width bw bw) (- bw)))) (define-method (client-scene-raise-to-top (c <gwwm-base-client>)) (wlr-scene-node-raise-to-top (.node (client-scene c)))) (define-method (client-scene-set-enabled (c <gwwm-base-client>) n) (wlr-scene-node-set-enabled (.node (client-scene c)) n)) (define-method (client-scene-move (c <gwwm-base-client>) x y) (wlr-scene-node-set-position (.node (client-scene c)) x y)) (define-method (client-scene-move (c <gwwm-client>) x y) (let ((bw (client-border-width c))) (next-method c (+ bw x) (+ bw y)))) (define-method (client-scene-move/relatively (c <gwwm-base-client>) x y) (let ((node (.node (client-scene c)))) (wlr-scene-node-set-position (.node (client-scene c)) (+ (.x node) x) (+ (.y node) y)))) (define-method (client-resize (c <gwwm-client>) geo (interact? <boolean>)) (set! (client-geom c) geo) (applybounds c (if interact? ((@ (gwwm) entire-layout-box)) (monitor-window-area (client-monitor c)))) (let* ((bw (client-border-width c)) (geom (client-geom c)) (heigh (box-height geom)) (width (box-width geom))) (set! (client-resize-configure-serial c) (client-set-size! c (- width (* 2 bw)) (- heigh (* 2 bw)))) (client-resize-border c) (client-scene-move c (box-x geo) (box-y geo)))) (define-method (client-resize (c <gwwm-client>) geo) (client-resize c geo #f)) (define-method (client-destroy-notify (c <gwwm-base-client>)) (lambda (listener data) (send-log DEBUG "client destroy" 'client c) (run-hook client-destroy-hook c) (set! (client-alive? c) #f))) (define-method (client-destroy-notify (c <gwwm-client>)) (let ((next (next-method c))) (lambda (listener data) (next listener data) (set! (client-scene c) #f)))) (define-method (client-destroy-notify (c <gwwm-layer-client>)) (let ((next (next-method c))) (lambda (listener data) (q-remove! (%layer-clients) c) (for-each (cut q-remove! <> c) (slot-ref (client-monitor c) 'layers)) (next listener data) (and=> (client-monitor c) arrangelayers)))) (define-method (client-set-title-notify (c <gwwm-client>)) (lambda (listener data) (let ((title (client-title c)) (new (client-get-title c))) (set! (client-title c) new) (run-hook update-title-hook c title new) (send-log DEBUG (G_ "Client change title.") 'client c 'old title 'new (client-title c))))) (define-method (client-commit-notify (c <gwwm-client>)) (lambda (a b) (let ((box (client-get-geometry c)) (m (client-monitor c))) (when (and m (not (box-empty? box)) (or (not (= (box-width box) (- (box-width (client-geom c)) (* 2 (client-border-width c))))) (not (= (box-height box) (- (box-height (client-geom c)) (* 2 (client-border-width c))))))) (arrange m))) (run-hook surface-commit-event-hook c))) (define-method (client-commit-notify (c <gwwm-xdg-client>)) (let ((next (next-method c))) (lambda (listener data) (next listener data) (let ((serial (client-resize-configure-serial c)) (current (.current (client-super-surface c))) (pending (.pending (client-super-surface c)))) (when (and (not (zero? serial)) (or (<= serial (.configure-serial current)) (and (= (box-width (.geometry current)) (box-width (.geometry pending))) (= (box-height (.geometry current)) (box-height (.geometry pending)))))) (set! (client-resize-configure-serial c) 0))))))
de0ddc90558bcb424d66ba10a29d652d20553a77022fa3eff0767d5a1b7b6762
mishoo/queen.lisp
stream.lisp
(in-package #:queen) (defparameter *has-letter-prop* (cl-unicode:property-test "Letter")) (defmacro with-parse-stream (input &body body) (let ((pos (gensym "pos")) (line (gensym "line")) (col (gensym "col")) (log (gensym "log")) (-next (gensym "-next"))) `(let ((,pos 0) (,line 1) (,col 0) (,log nil)) (labels ((,-next () (if ,log (pop ,log) (read-char ,input nil 'EOF))) (unget (ch) (push ch ,log)) (peek () (if ,log (car ,log) (peek-char nil ,input nil nil))) (next () (let ((ch (,-next))) (when (and (eql ch #\Return) (eql (peek) #\Newline)) (incf ,pos) (setf ch (,-next))) (case ch (EOF nil) (#\Newline (setf ,col 0) (incf ,line) (incf ,pos) ch) (otherwise (incf ,col) (incf ,pos) ch)))) (eof? () (not (peek))) (croak (msg &rest args) (when args (setf msg (apply #'format nil msg args))) (error "ERROR: ~A (~A:~A)" msg ,line ,col)) (read-while (pred) (with-output-to-string (out) (loop for ch = (peek) while (and ch (funcall pred ch)) do (write-char (next) out)))) (whitespace? (ch) (case (char-code ch) ((32 10 13 9 #xA0 #xFEFF) t))) (non-whitespace? (ch) (not (whitespace? ch))) (digit? (ch) (digit-char-p ch)) (letter? (ch) (funcall *has-letter-prop* ch)) (alnum? (ch) (or (digit? ch) (letter? ch))) (look-ahead (len func) (let ((savepos ,pos) (saveline ,line) (savecol ,col)) (let ((chars (loop repeat len collect (next)))) (or (funcall func chars) (progn (setf ,pos savepos ,line saveline ,col savecol ,log (nconc chars ,log)) nil))))) (skip (ch &optional no-error) (cond ((characterp ch) (let ((curr (next))) (if (eql ch curr) curr (unless no-error (croak "Expected ~A but found ~A" ch curr))))) ((stringp ch) (let ((match (look-ahead (length ch) (lambda (chars) (unless (member nil chars) (string= ch (coerce chars 'string))))))) (if match match (unless no-error (croak "Expected ~A ch"))))) (t (error "Unknown token in `skip'")))) (read-number () (let (n d ch) (tagbody next (setq ch (next)) (unless ch (go finish)) (setq d (digit? ch)) (unless d (go finish)) (setf n (+ d (* (or n 0) 10))) (go next) finish (when ch (unget ch))) n)) (read-string (&optional (quote #\") (esc #\\)) (skip quote) (let* ((escaped nil)) (prog1 (read-while (lambda (ch) (cond (escaped (setf escaped nil) t) ((eql ch quote) nil) ((eql ch esc) (next) (setf escaped t) t) (t t)))) (skip quote)))) (skip-whitespace () (read-while #'whitespace?))) (declare (ignorable #'peek #'next #'unget #'eof? #'croak #'read-while #'whitespace? #'non-whitespace? #'digit? #'letter? #'alnum? #'skip #'read-string #'skip-whitespace #'look-ahead #'read-number)) (unwind-protect (progn ,@body) (when ,log (unread-char (car ,log) ,input)))))))
null
https://raw.githubusercontent.com/mishoo/queen.lisp/395535fcbd24fa463b32e17a35a4c12fdc7e2277/stream.lisp
lisp
(in-package #:queen) (defparameter *has-letter-prop* (cl-unicode:property-test "Letter")) (defmacro with-parse-stream (input &body body) (let ((pos (gensym "pos")) (line (gensym "line")) (col (gensym "col")) (log (gensym "log")) (-next (gensym "-next"))) `(let ((,pos 0) (,line 1) (,col 0) (,log nil)) (labels ((,-next () (if ,log (pop ,log) (read-char ,input nil 'EOF))) (unget (ch) (push ch ,log)) (peek () (if ,log (car ,log) (peek-char nil ,input nil nil))) (next () (let ((ch (,-next))) (when (and (eql ch #\Return) (eql (peek) #\Newline)) (incf ,pos) (setf ch (,-next))) (case ch (EOF nil) (#\Newline (setf ,col 0) (incf ,line) (incf ,pos) ch) (otherwise (incf ,col) (incf ,pos) ch)))) (eof? () (not (peek))) (croak (msg &rest args) (when args (setf msg (apply #'format nil msg args))) (error "ERROR: ~A (~A:~A)" msg ,line ,col)) (read-while (pred) (with-output-to-string (out) (loop for ch = (peek) while (and ch (funcall pred ch)) do (write-char (next) out)))) (whitespace? (ch) (case (char-code ch) ((32 10 13 9 #xA0 #xFEFF) t))) (non-whitespace? (ch) (not (whitespace? ch))) (digit? (ch) (digit-char-p ch)) (letter? (ch) (funcall *has-letter-prop* ch)) (alnum? (ch) (or (digit? ch) (letter? ch))) (look-ahead (len func) (let ((savepos ,pos) (saveline ,line) (savecol ,col)) (let ((chars (loop repeat len collect (next)))) (or (funcall func chars) (progn (setf ,pos savepos ,line saveline ,col savecol ,log (nconc chars ,log)) nil))))) (skip (ch &optional no-error) (cond ((characterp ch) (let ((curr (next))) (if (eql ch curr) curr (unless no-error (croak "Expected ~A but found ~A" ch curr))))) ((stringp ch) (let ((match (look-ahead (length ch) (lambda (chars) (unless (member nil chars) (string= ch (coerce chars 'string))))))) (if match match (unless no-error (croak "Expected ~A ch"))))) (t (error "Unknown token in `skip'")))) (read-number () (let (n d ch) (tagbody next (setq ch (next)) (unless ch (go finish)) (setq d (digit? ch)) (unless d (go finish)) (setf n (+ d (* (or n 0) 10))) (go next) finish (when ch (unget ch))) n)) (read-string (&optional (quote #\") (esc #\\)) (skip quote) (let* ((escaped nil)) (prog1 (read-while (lambda (ch) (cond (escaped (setf escaped nil) t) ((eql ch quote) nil) ((eql ch esc) (next) (setf escaped t) t) (t t)))) (skip quote)))) (skip-whitespace () (read-while #'whitespace?))) (declare (ignorable #'peek #'next #'unget #'eof? #'croak #'read-while #'whitespace? #'non-whitespace? #'digit? #'letter? #'alnum? #'skip #'read-string #'skip-whitespace #'look-ahead #'read-number)) (unwind-protect (progn ,@body) (when ,log (unread-char (car ,log) ,input)))))))
eb92c36b70d93db177fc33266ab1b94221c3194e50d998a863d91b13c7b441d3
soulomoon/SICP
Exercise 2.24.scm
Exercise 2.24 : Suppose we evaluate the expression ( list 1 ( list 2 ( list 3 4 ) ) ) . Give the result printed by the interpreter , the corresponding box - and - pointer structure , and the interpretation of this as a tree ( as in Figure 2.6 ) . (list 1 (list 2 (list 3 4))) Welcome to DrRacket, version 6.7 [3m]. memory limit : 128 MB . {mcons 1 {mcons {mcons 2 {mcons {mcons 3 {mcons 4 '()}} '()}} '()}} >
null
https://raw.githubusercontent.com/soulomoon/SICP/1c6cbf5ecf6397eaeb990738a938d48c193af1bb/Chapter2/Exercise%202.24.scm
scheme
Exercise 2.24 : Suppose we evaluate the expression ( list 1 ( list 2 ( list 3 4 ) ) ) . Give the result printed by the interpreter , the corresponding box - and - pointer structure , and the interpretation of this as a tree ( as in Figure 2.6 ) . (list 1 (list 2 (list 3 4))) Welcome to DrRacket, version 6.7 [3m]. memory limit : 128 MB . {mcons 1 {mcons {mcons 2 {mcons {mcons 3 {mcons 4 '()}} '()}} '()}} >
c0de35b7009f6c6b2bc3ce255b9da9d3e80b488efc47a4d153af0a94a5eb6bee
anoma/juvix
Serialization.hs
module Juvix.Compiler.Backend.C.Extra.Serialization where import Juvix.Compiler.Backend.C.Language import Juvix.Extra.Strings qualified as Str import Juvix.Prelude hiding (Binary, Unary) import Language.C qualified as C import Language.C.Data.Ident qualified as C import Language.C.Pretty qualified as P import Language.C.Syntax import Text.PrettyPrint.HughesPJ qualified as HP encAngles :: HP.Doc -> HP.Doc encAngles p = HP.char '<' HP.<> p HP.<> HP.char '>' prettyText :: Text -> HP.Doc prettyText = HP.text . unpack prettyCpp :: Cpp -> HP.Doc prettyCpp = \case CppIncludeFile i -> "#include" HP.<+> HP.doubleQuotes (prettyText i) CppIncludeSystem i -> "#include" HP.<+> encAngles (prettyText i) CppDefine Define {..} -> prettyDefine _defineName (prettyDefineBody _defineBody) CppDefineParens Define {..} -> prettyDefine _defineName (HP.parens (prettyDefineBody _defineBody)) where prettyDefineBody :: Expression -> HP.Doc prettyDefineBody e = P.pretty (mkCExpr e) prettyDefine :: Text -> HP.Doc -> HP.Doc prettyDefine n body = "#define" HP.<+> prettyText n HP.<+> body prettyAttribute :: Attribute -> HP.Doc prettyAttribute = \case ExportName n -> attr "export_name" n ImportName n -> attr "import_name" n where attr :: Text -> Text -> HP.Doc attr n v = "__attribute__" HP.<> HP.parens (HP.parens (prettyText n HP.<> HP.parens (HP.doubleQuotes (prettyText v)))) prettyCCode :: CCode -> HP.Doc prettyCCode = \case ExternalDecl decl -> P.pretty (CDeclExt (mkCDecl decl)) ExternalAttribute a -> prettyAttribute a ExternalFuncSig funSig -> P.pretty (CDeclExt (mkCFunSig funSig)) ExternalFunc fun -> P.pretty (CFDefExt (mkCFunDef fun)) ExternalMacro m -> prettyCpp m Verbatim t -> prettyText t serialize :: CCodeUnit -> Text serialize = show . codeUnitDoc where codeUnitDoc :: CCodeUnit -> HP.Doc codeUnitDoc c = HP.vcat (map prettyCCode (c ^. ccodeCode)) goTypeDecl' :: CDeclType -> Declaration goTypeDecl' CDeclType {..} = Declaration { _declType = _typeDeclType, _declIsPtr = _typeIsPtr, _declName = Nothing, _declInitializer = Nothing } mkCDecl :: Declaration -> CDecl mkCDecl Declaration {..} = case _declType of DeclFunPtr FunPtr {..} -> CDecl (mkDeclSpecifier _funPtrReturnType) [(Just declr, Nothing, Nothing)] C.undefNode where declr :: CDeclr declr = CDeclr (mkIdent <$> _declName) derivedDeclr Nothing [] C.undefNode derivedDeclr :: [CDerivedDeclr] derivedDeclr = CPtrDeclr [] C.undefNode : (funDerDeclr <> ptrDeclr) ptrDeclr :: [CDerivedDeclr] ptrDeclr = [CPtrDeclr [] C.undefNode | _funPtrIsPtr] funDerDeclr :: [CDerivedDeclr] funDerDeclr = [CFunDeclr (Right (funArgs, False)) [] C.undefNode] funArgs :: [CDecl] funArgs = mkCDecl . goTypeDecl' <$> _funPtrArgs DeclArray Array {..} -> CDecl (CStorageSpec (CStatic C.undefNode) : mkDeclSpecifier _arrayType) [(Just declr, initializer, Nothing)] C.undefNode where declr :: CDeclr declr = CDeclr (mkIdent <$> _declName) derivedDeclr Nothing [] C.undefNode derivedDeclr :: [CDerivedDeclr] derivedDeclr = [CArrDeclr [] (CArrSize False (CConst (CIntConst (cInteger _arraySize) C.undefNode))) C.undefNode] initializer :: Maybe CInit initializer = mkCInit <$> _declInitializer _ -> CDecl (mkDeclSpecifier _declType) [(Just declrName, initializer, Nothing)] C.undefNode where declrName :: CDeclr declrName = CDeclr (mkIdent <$> _declName) ptrDeclr Nothing [] C.undefNode ptrDeclr :: [CDerivedDeclarator C.NodeInfo] ptrDeclr = [CPtrDeclr [] C.undefNode | _declIsPtr] initializer :: Maybe CInit initializer = mkCInit <$> _declInitializer mkCInit :: Initializer -> CInit mkCInit = \case ExprInitializer e -> CInitExpr (mkCExpr e) C.undefNode ListInitializer l -> CInitList (map (\i -> ([], mkCInit i)) l) C.undefNode DesignatorInitializer ds -> CInitList (f <$> ds) C.undefNode where f :: DesigInit -> ([CDesignator], CInit) f DesigInit {..} = ([CMemberDesig (mkIdent _desigDesignator) C.undefNode], mkCInit _desigInitializer) mkFunCommon :: FunctionSig -> ([CDeclSpec], CDeclr) mkFunCommon FunctionSig {..} = (declSpec, declr) where declr :: CDeclr declr = CDeclr (Just (mkIdent _funcName)) derivedDeclr Nothing [] C.undefNode declSpec :: [CDeclSpec] declSpec = qualifier <> mkDeclSpecifier _funcReturnType qualifier :: [CDeclSpec] qualifier = if _funcQualifier == StaticInline then [CStorageSpec (CStatic C.undefNode), CFunSpec (CInlineQual C.undefNode)] else [] derivedDeclr :: [CDerivedDeclr] derivedDeclr = funDerDeclr <> ptrDeclr ptrDeclr :: [CDerivedDeclr] ptrDeclr = [CPtrDeclr [] C.undefNode | _funcIsPtr] funDerDeclr :: [CDerivedDeclr] funDerDeclr = [CFunDeclr (Right (funArgs, False)) [] C.undefNode] funArgs :: [CDecl] funArgs = mkCDecl <$> _funcArgs mkCFunSig :: FunctionSig -> CDecl mkCFunSig s = let (declSpec, declr) = mkFunCommon s in CDecl declSpec [(Just declr, Nothing, Nothing)] C.undefNode mkCFunDef :: Function -> CFunDef mkCFunDef Function {..} = let (declSpec, declr) = mkFunCommon _funcSig in CFunDef declSpec declr [] statement C.undefNode where statement :: CStat statement = CCompound [] block C.undefNode block :: [CBlockItem] block = mkBlockItem <$> _funcBody mkBlockItem :: BodyItem -> CBlockItem mkBlockItem = \case BodyStatement s -> CBlockStmt (mkCStat s) BodyDecl d -> CBlockDecl (mkCDecl d) mkCExpr :: Expression -> CExpr mkCExpr = \case ExpressionAssign Assign {..} -> CAssign CAssignOp (mkCExpr _assignLeft) (mkCExpr _assignRight) C.undefNode ExpressionCast Cast {..} -> CCast (mkCDecl _castDecl) (mkCExpr _castExpression) C.undefNode ExpressionCall Call {..} -> CCall (mkCExpr _callCallee) (mkCExpr <$> _callArgs) C.undefNode ExpressionLiteral l -> case l of LiteralInt i -> CConst (CIntConst (cInteger i) C.undefNode) LiteralChar c -> CConst (CCharConst (cChar c) C.undefNode) LiteralString s -> CConst (CStrConst (cString (unpack s)) C.undefNode) ExpressionVar n -> CVar (mkIdent n) C.undefNode ExpressionBinary Binary {..} -> CBinary (mkBinaryOp _binaryOp) (mkCExpr _binaryLeft) (mkCExpr _binaryRight) C.undefNode ExpressionUnary Unary {..} -> CUnary (mkUnaryOp _unaryOp) (mkCExpr _unarySubject) C.undefNode ExpressionMember MemberAccess {..} -> CMember (mkCExpr _memberSubject) (mkIdent _memberField) (_memberOp == Pointer) C.undefNode ExpressionStatement stmt -> CStatExpr (mkCStat stmt) C.undefNode mkCStat :: Statement -> CStat mkCStat = \case StatementReturn me -> CReturn (mkCExpr <$> me) C.undefNode StatementIf If {..} -> CIf (mkCExpr _ifCondition) (mkCStat _ifThen) (mkCStat <$> _ifElse) C.undefNode StatementSwitch Switch {..} -> CSwitch (mkCExpr _switchCondition) (CCompound [] (map CBlockStmt (caseStmts ++ caseDefault)) C.undefNode) C.undefNode where caseStmts = map ( \Case {..} -> CCase (mkCExpr _caseValue) ( CCompound [] [ CBlockStmt (mkCStat _caseCode), CBlockStmt (CBreak C.undefNode) ] C.undefNode ) C.undefNode ) _switchCases caseDefault = maybe [CDefault (mkCStat (StatementExpr (macroVar "UNREACHABLE"))) C.undefNode] (\x -> [CDefault (mkCStat x) C.undefNode]) _switchDefault StatementLabel Label {..} -> CLabel (mkIdent _labelName) (mkCStat _labelCode) [] C.undefNode StatementGoto Goto {..} -> CGoto (mkIdent _gotoLabel) C.undefNode StatementExpr e -> CExpr (Just (mkCExpr e)) C.undefNode StatementCompound ss -> CCompound [] (CBlockStmt . mkCStat <$> ss) C.undefNode mkBinaryOp :: BinaryOp -> CBinaryOp mkBinaryOp = \case Eq -> CEqOp Neq -> CNeqOp And -> CLndOp Or -> CLorOp Plus -> CAddOp mkUnaryOp :: UnaryOp -> CUnaryOp mkUnaryOp = \case Address -> CAdrOp Indirection -> CIndOp Negation -> CNegOp mkDeclSpecifier :: DeclType -> [CDeclSpec] mkDeclSpecifier = \case DeclTypeDefType typeDefName -> mkTypeDefTypeSpec typeDefName DeclTypeDef typ -> CStorageSpec (CTypedef C.undefNode) : mkDeclSpecifier typ DeclStructUnion StructUnion {..} -> mkStructUnionTypeSpec _structUnionTag _structUnionName _structMembers DeclEnum Enum {..} -> mkEnumSpec _enumName _enumMembers DeclJuvixClosure -> mkTypeDefTypeSpec Str.juvixFunctionT BoolType -> [CTypeSpec (CBoolType C.undefNode)] DeclFunPtr {} -> [] DeclArray {} -> [] mkEnumSpec :: Maybe Text -> Maybe [Text] -> [CDeclSpec] mkEnumSpec name members = [CTypeSpec (CEnumType enum C.undefNode)] where enum :: CEnum enum = CEnum (mkIdent <$> name) (fmap (map (\m -> (mkIdent m, Nothing))) members) [] C.undefNode mkTypeDefTypeSpec :: Text -> [CDeclSpec] mkTypeDefTypeSpec name = [CTypeSpec (CTypeDef (mkIdent name) C.undefNode)] mkStructUnionTypeSpec :: StructUnionTag -> Maybe Text -> Maybe [Declaration] -> [CDeclSpec] mkStructUnionTypeSpec tag name members = [CTypeSpec (CSUType struct C.undefNode)] where struct :: CStructUnion struct = CStruct cStructTag (mkIdent <$> name) memberDecls [] C.undefNode memberDecls :: Maybe [CDecl] memberDecls = fmap (map mkCDecl) members cStructTag = case tag of StructTag -> CStructTag UnionTag -> CUnionTag mkIdent :: Text -> C.Ident mkIdent t = C.Ident (unpack t) 0 C.undefNode
null
https://raw.githubusercontent.com/anoma/juvix/f5de5faaefa298b608344766e7376f7e48c430b0/src/Juvix/Compiler/Backend/C/Extra/Serialization.hs
haskell
module Juvix.Compiler.Backend.C.Extra.Serialization where import Juvix.Compiler.Backend.C.Language import Juvix.Extra.Strings qualified as Str import Juvix.Prelude hiding (Binary, Unary) import Language.C qualified as C import Language.C.Data.Ident qualified as C import Language.C.Pretty qualified as P import Language.C.Syntax import Text.PrettyPrint.HughesPJ qualified as HP encAngles :: HP.Doc -> HP.Doc encAngles p = HP.char '<' HP.<> p HP.<> HP.char '>' prettyText :: Text -> HP.Doc prettyText = HP.text . unpack prettyCpp :: Cpp -> HP.Doc prettyCpp = \case CppIncludeFile i -> "#include" HP.<+> HP.doubleQuotes (prettyText i) CppIncludeSystem i -> "#include" HP.<+> encAngles (prettyText i) CppDefine Define {..} -> prettyDefine _defineName (prettyDefineBody _defineBody) CppDefineParens Define {..} -> prettyDefine _defineName (HP.parens (prettyDefineBody _defineBody)) where prettyDefineBody :: Expression -> HP.Doc prettyDefineBody e = P.pretty (mkCExpr e) prettyDefine :: Text -> HP.Doc -> HP.Doc prettyDefine n body = "#define" HP.<+> prettyText n HP.<+> body prettyAttribute :: Attribute -> HP.Doc prettyAttribute = \case ExportName n -> attr "export_name" n ImportName n -> attr "import_name" n where attr :: Text -> Text -> HP.Doc attr n v = "__attribute__" HP.<> HP.parens (HP.parens (prettyText n HP.<> HP.parens (HP.doubleQuotes (prettyText v)))) prettyCCode :: CCode -> HP.Doc prettyCCode = \case ExternalDecl decl -> P.pretty (CDeclExt (mkCDecl decl)) ExternalAttribute a -> prettyAttribute a ExternalFuncSig funSig -> P.pretty (CDeclExt (mkCFunSig funSig)) ExternalFunc fun -> P.pretty (CFDefExt (mkCFunDef fun)) ExternalMacro m -> prettyCpp m Verbatim t -> prettyText t serialize :: CCodeUnit -> Text serialize = show . codeUnitDoc where codeUnitDoc :: CCodeUnit -> HP.Doc codeUnitDoc c = HP.vcat (map prettyCCode (c ^. ccodeCode)) goTypeDecl' :: CDeclType -> Declaration goTypeDecl' CDeclType {..} = Declaration { _declType = _typeDeclType, _declIsPtr = _typeIsPtr, _declName = Nothing, _declInitializer = Nothing } mkCDecl :: Declaration -> CDecl mkCDecl Declaration {..} = case _declType of DeclFunPtr FunPtr {..} -> CDecl (mkDeclSpecifier _funPtrReturnType) [(Just declr, Nothing, Nothing)] C.undefNode where declr :: CDeclr declr = CDeclr (mkIdent <$> _declName) derivedDeclr Nothing [] C.undefNode derivedDeclr :: [CDerivedDeclr] derivedDeclr = CPtrDeclr [] C.undefNode : (funDerDeclr <> ptrDeclr) ptrDeclr :: [CDerivedDeclr] ptrDeclr = [CPtrDeclr [] C.undefNode | _funPtrIsPtr] funDerDeclr :: [CDerivedDeclr] funDerDeclr = [CFunDeclr (Right (funArgs, False)) [] C.undefNode] funArgs :: [CDecl] funArgs = mkCDecl . goTypeDecl' <$> _funPtrArgs DeclArray Array {..} -> CDecl (CStorageSpec (CStatic C.undefNode) : mkDeclSpecifier _arrayType) [(Just declr, initializer, Nothing)] C.undefNode where declr :: CDeclr declr = CDeclr (mkIdent <$> _declName) derivedDeclr Nothing [] C.undefNode derivedDeclr :: [CDerivedDeclr] derivedDeclr = [CArrDeclr [] (CArrSize False (CConst (CIntConst (cInteger _arraySize) C.undefNode))) C.undefNode] initializer :: Maybe CInit initializer = mkCInit <$> _declInitializer _ -> CDecl (mkDeclSpecifier _declType) [(Just declrName, initializer, Nothing)] C.undefNode where declrName :: CDeclr declrName = CDeclr (mkIdent <$> _declName) ptrDeclr Nothing [] C.undefNode ptrDeclr :: [CDerivedDeclarator C.NodeInfo] ptrDeclr = [CPtrDeclr [] C.undefNode | _declIsPtr] initializer :: Maybe CInit initializer = mkCInit <$> _declInitializer mkCInit :: Initializer -> CInit mkCInit = \case ExprInitializer e -> CInitExpr (mkCExpr e) C.undefNode ListInitializer l -> CInitList (map (\i -> ([], mkCInit i)) l) C.undefNode DesignatorInitializer ds -> CInitList (f <$> ds) C.undefNode where f :: DesigInit -> ([CDesignator], CInit) f DesigInit {..} = ([CMemberDesig (mkIdent _desigDesignator) C.undefNode], mkCInit _desigInitializer) mkFunCommon :: FunctionSig -> ([CDeclSpec], CDeclr) mkFunCommon FunctionSig {..} = (declSpec, declr) where declr :: CDeclr declr = CDeclr (Just (mkIdent _funcName)) derivedDeclr Nothing [] C.undefNode declSpec :: [CDeclSpec] declSpec = qualifier <> mkDeclSpecifier _funcReturnType qualifier :: [CDeclSpec] qualifier = if _funcQualifier == StaticInline then [CStorageSpec (CStatic C.undefNode), CFunSpec (CInlineQual C.undefNode)] else [] derivedDeclr :: [CDerivedDeclr] derivedDeclr = funDerDeclr <> ptrDeclr ptrDeclr :: [CDerivedDeclr] ptrDeclr = [CPtrDeclr [] C.undefNode | _funcIsPtr] funDerDeclr :: [CDerivedDeclr] funDerDeclr = [CFunDeclr (Right (funArgs, False)) [] C.undefNode] funArgs :: [CDecl] funArgs = mkCDecl <$> _funcArgs mkCFunSig :: FunctionSig -> CDecl mkCFunSig s = let (declSpec, declr) = mkFunCommon s in CDecl declSpec [(Just declr, Nothing, Nothing)] C.undefNode mkCFunDef :: Function -> CFunDef mkCFunDef Function {..} = let (declSpec, declr) = mkFunCommon _funcSig in CFunDef declSpec declr [] statement C.undefNode where statement :: CStat statement = CCompound [] block C.undefNode block :: [CBlockItem] block = mkBlockItem <$> _funcBody mkBlockItem :: BodyItem -> CBlockItem mkBlockItem = \case BodyStatement s -> CBlockStmt (mkCStat s) BodyDecl d -> CBlockDecl (mkCDecl d) mkCExpr :: Expression -> CExpr mkCExpr = \case ExpressionAssign Assign {..} -> CAssign CAssignOp (mkCExpr _assignLeft) (mkCExpr _assignRight) C.undefNode ExpressionCast Cast {..} -> CCast (mkCDecl _castDecl) (mkCExpr _castExpression) C.undefNode ExpressionCall Call {..} -> CCall (mkCExpr _callCallee) (mkCExpr <$> _callArgs) C.undefNode ExpressionLiteral l -> case l of LiteralInt i -> CConst (CIntConst (cInteger i) C.undefNode) LiteralChar c -> CConst (CCharConst (cChar c) C.undefNode) LiteralString s -> CConst (CStrConst (cString (unpack s)) C.undefNode) ExpressionVar n -> CVar (mkIdent n) C.undefNode ExpressionBinary Binary {..} -> CBinary (mkBinaryOp _binaryOp) (mkCExpr _binaryLeft) (mkCExpr _binaryRight) C.undefNode ExpressionUnary Unary {..} -> CUnary (mkUnaryOp _unaryOp) (mkCExpr _unarySubject) C.undefNode ExpressionMember MemberAccess {..} -> CMember (mkCExpr _memberSubject) (mkIdent _memberField) (_memberOp == Pointer) C.undefNode ExpressionStatement stmt -> CStatExpr (mkCStat stmt) C.undefNode mkCStat :: Statement -> CStat mkCStat = \case StatementReturn me -> CReturn (mkCExpr <$> me) C.undefNode StatementIf If {..} -> CIf (mkCExpr _ifCondition) (mkCStat _ifThen) (mkCStat <$> _ifElse) C.undefNode StatementSwitch Switch {..} -> CSwitch (mkCExpr _switchCondition) (CCompound [] (map CBlockStmt (caseStmts ++ caseDefault)) C.undefNode) C.undefNode where caseStmts = map ( \Case {..} -> CCase (mkCExpr _caseValue) ( CCompound [] [ CBlockStmt (mkCStat _caseCode), CBlockStmt (CBreak C.undefNode) ] C.undefNode ) C.undefNode ) _switchCases caseDefault = maybe [CDefault (mkCStat (StatementExpr (macroVar "UNREACHABLE"))) C.undefNode] (\x -> [CDefault (mkCStat x) C.undefNode]) _switchDefault StatementLabel Label {..} -> CLabel (mkIdent _labelName) (mkCStat _labelCode) [] C.undefNode StatementGoto Goto {..} -> CGoto (mkIdent _gotoLabel) C.undefNode StatementExpr e -> CExpr (Just (mkCExpr e)) C.undefNode StatementCompound ss -> CCompound [] (CBlockStmt . mkCStat <$> ss) C.undefNode mkBinaryOp :: BinaryOp -> CBinaryOp mkBinaryOp = \case Eq -> CEqOp Neq -> CNeqOp And -> CLndOp Or -> CLorOp Plus -> CAddOp mkUnaryOp :: UnaryOp -> CUnaryOp mkUnaryOp = \case Address -> CAdrOp Indirection -> CIndOp Negation -> CNegOp mkDeclSpecifier :: DeclType -> [CDeclSpec] mkDeclSpecifier = \case DeclTypeDefType typeDefName -> mkTypeDefTypeSpec typeDefName DeclTypeDef typ -> CStorageSpec (CTypedef C.undefNode) : mkDeclSpecifier typ DeclStructUnion StructUnion {..} -> mkStructUnionTypeSpec _structUnionTag _structUnionName _structMembers DeclEnum Enum {..} -> mkEnumSpec _enumName _enumMembers DeclJuvixClosure -> mkTypeDefTypeSpec Str.juvixFunctionT BoolType -> [CTypeSpec (CBoolType C.undefNode)] DeclFunPtr {} -> [] DeclArray {} -> [] mkEnumSpec :: Maybe Text -> Maybe [Text] -> [CDeclSpec] mkEnumSpec name members = [CTypeSpec (CEnumType enum C.undefNode)] where enum :: CEnum enum = CEnum (mkIdent <$> name) (fmap (map (\m -> (mkIdent m, Nothing))) members) [] C.undefNode mkTypeDefTypeSpec :: Text -> [CDeclSpec] mkTypeDefTypeSpec name = [CTypeSpec (CTypeDef (mkIdent name) C.undefNode)] mkStructUnionTypeSpec :: StructUnionTag -> Maybe Text -> Maybe [Declaration] -> [CDeclSpec] mkStructUnionTypeSpec tag name members = [CTypeSpec (CSUType struct C.undefNode)] where struct :: CStructUnion struct = CStruct cStructTag (mkIdent <$> name) memberDecls [] C.undefNode memberDecls :: Maybe [CDecl] memberDecls = fmap (map mkCDecl) members cStructTag = case tag of StructTag -> CStructTag UnionTag -> CUnionTag mkIdent :: Text -> C.Ident mkIdent t = C.Ident (unpack t) 0 C.undefNode
59f78032b4376da8f5b19530e3650b44100a65e6366a6daa0bc507859562370d
mejgun/haskell-tdlib
ResetPassword.hs
{-# LANGUAGE OverloadedStrings #-} -- | module TD.Query.ResetPassword where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U -- | Removes 2 - step verification password without previous password and access to recovery email address . The password ca n't be reset immediately and the request needs to be repeated after the specified time data ResetPassword = ResetPassword { } deriving (Eq) instance Show ResetPassword where show ResetPassword = "ResetPassword" ++ U.cc [] instance T.ToJSON ResetPassword where toJSON ResetPassword = A.object [ "@type" A..= T.String "resetPassword" ]
null
https://raw.githubusercontent.com/mejgun/haskell-tdlib/81516bd04c25c7371d4a9a5c972499791111c407/src/TD/Query/ResetPassword.hs
haskell
# LANGUAGE OverloadedStrings # | |
module TD.Query.ResetPassword where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U Removes 2 - step verification password without previous password and access to recovery email address . The password ca n't be reset immediately and the request needs to be repeated after the specified time data ResetPassword = ResetPassword { } deriving (Eq) instance Show ResetPassword where show ResetPassword = "ResetPassword" ++ U.cc [] instance T.ToJSON ResetPassword where toJSON ResetPassword = A.object [ "@type" A..= T.String "resetPassword" ]
f31f8627c25214be03fbdf324d2af40a4f67a1a91a5adf43e5fe61da06d716d0
JunSuzukiJapan/cl-reex
max.lisp
(in-package :cl-user) (defpackage cl-reex.operator.max (:use :cl) (:import-from :cl-reex.observer :observer :on-next :on-error :on-completed ) (:import-from :cl-reex.observable :observable :dispose :is-active :set-error :set-completed :set-disposed :subscribe ) (:import-from :cl-reex.macro.operator-table :set-zero-arg-operator ) (:import-from :cl-reex.operator :operator ) (:export :operator-max :max :make-operator-max )) (in-package :cl-reex.operator.max) (defclass operator-max (operator) ((max :initarg :max :accessor max-num )) (:documentation "Max operator") ) (defun make-operator-max (observable) (make-instance 'operator-max :observable observable )) (defmethod on-next ((op operator-max) x) (when (is-active op) (if (slot-boundp op 'max) (when (< (max-num op) x) (setf (max-num op) x) ) (setf (max-num op) x) ))) (defmethod on-error ((op operator-max) x) (when (is-active op) (on-error (observer op) x) (set-error op) )) (defmethod on-completed ((op operator-max)) (when (is-active op) (on-next (observer op) (max-num op)) (on-completed (observer op)) (set-completed op) )) (set-zero-arg-operator 'max 'make-operator-max)
null
https://raw.githubusercontent.com/JunSuzukiJapan/cl-reex/94928c7949c235b41902138d9e4a5654b92d67eb/src/operator/max.lisp
lisp
(in-package :cl-user) (defpackage cl-reex.operator.max (:use :cl) (:import-from :cl-reex.observer :observer :on-next :on-error :on-completed ) (:import-from :cl-reex.observable :observable :dispose :is-active :set-error :set-completed :set-disposed :subscribe ) (:import-from :cl-reex.macro.operator-table :set-zero-arg-operator ) (:import-from :cl-reex.operator :operator ) (:export :operator-max :max :make-operator-max )) (in-package :cl-reex.operator.max) (defclass operator-max (operator) ((max :initarg :max :accessor max-num )) (:documentation "Max operator") ) (defun make-operator-max (observable) (make-instance 'operator-max :observable observable )) (defmethod on-next ((op operator-max) x) (when (is-active op) (if (slot-boundp op 'max) (when (< (max-num op) x) (setf (max-num op) x) ) (setf (max-num op) x) ))) (defmethod on-error ((op operator-max) x) (when (is-active op) (on-error (observer op) x) (set-error op) )) (defmethod on-completed ((op operator-max)) (when (is-active op) (on-next (observer op) (max-num op)) (on-completed (observer op)) (set-completed op) )) (set-zero-arg-operator 'max 'make-operator-max)
e5d5cfc00b2b43003d0bc39ba4961a898b2acc48d951d1a5170f827e2234f037
archaelus/erms
erms_esme_connection.erl
Copyright ( C ) 2004 Peña < > %%% %%% 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 . %%% %%% 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 %%% @doc ESME Skeleton. %%% %%% <p>You may use this skeleton as the starting point to implement your %%% own ESMEs.</p> %%% 2004 @author < mpquique_at_users.sourceforge.net > %%% [/] @version 1.1 , { 6 Jul 2004 } { @time } . %%% @end -module(erms_esme_connection). -behaviour(gen_esme). %%%------------------------------------------------------------------- %%% Include files %%%------------------------------------------------------------------- -include_lib("eunit/include/eunit.hrl"). -include_lib("logging.hrl"). -include_lib("mnesia_model.hrl"). -include_lib("oserl.hrl"). -include_lib("smpp_base.hrl"). %%%------------------------------------------------------------------- %%% External exports %%%------------------------------------------------------------------- -export([start_link/1, start_link/2, stop/1, reconnect/1]). %%%------------------------------------------------------------------- %%% Internal ESME exports %%%------------------------------------------------------------------- -export([init/1, handle_outbind/3, handle_alert_notification/2, handle_enquire_link_failure/2, handle_operation/3, handle_unbind/3, handle_listen_error/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %%%------------------------------------------------------------------- Records %%%------------------------------------------------------------------- %% %@spec {state} %% % @doc Representation of the ESME server state . %% %% <dl> %% <dt>: </dt><dd> %% </dd> %% </dl> %% %@end -record(state, {conf, name, session, rules, listener, heartbeatref, parent}). -record(conf, {systemid, password, smsc, type}). -define(SYSTEM_TYPE, "InternetGW"). %%%=================================================================== %%% External functions %%%=================================================================== %% @spec start_link(Name::string()) -> Result Result = { ok , Pid } | ignore | { error , Error } Pid = pid ( ) Error = { already_started , Pid } | term ( ) %% @doc Starts the ESME server . %% %% @see gen_esme %% @see start/0 %% @end start_link(ConnectionName) -> start_link(ConnectionName, []). start_link(ConnectionName, Args) -> {ok, Pid} = gen_esme:start_link(?MODULE, [ConnectionName, self(), Args], []), Pid ! reconnect, {ok, Pid}. ( ) ) - > ok | { error , Reason::term ( ) } %% @doc Stops the named ESME connection . %% %% @see handle_call/3 %% @equiv gen_esme : call(SERVER , die , 10000 ) %% @end stop(ConnectionName) -> gen_esme:call(erms_connection_mgr:where({connection, ConnectionName}), die, 10000). reconnect(ConnectionName) -> erms_connection_mgr:where({connection, ConnectionName}) ! reconnect. %%%=================================================================== %%% Server functions %%%=================================================================== ) - > Result = term ( ) Result = { ok , State } | { ok , State , Timeout } | ignore | { stop , Reason } State = term ( ) %% Timeout = int() | infinity term ( ) %% %% @doc <a href="#init-1"> %% gen_esme - init/1</a> callback implementation. %% %% <p>Initiates the server.</p> %% @end init([ConnectionName, Parent]) -> [Conf] = erms_connection:args(ConnectionName), init([ConnectionName, Parent, Conf]); init([ConnectionName, Parent, Conf]) -> Rules = erms_connection:rx_rules(ConnectionName), process_flag(trap_exit, true), % You may start sessions and issue bind requests here. {ok, TimerRef} = timer:send_interval(timer:minutes(1), reconnect), {ok, #state{conf=Conf, name=ConnectionName, rules=Rules, heartbeatref=TimerRef, parent=Parent}}. bind(#conf{type=rx} = Conf, Session) -> Params = [{system_id, Conf#conf.systemid}, {password, Conf#conf.password}, {system_type, ?SYSTEM_TYPE}, {interface_version, ?SMPP_VERSION_3_4}], gen_esme:bind_receiver(Session, Params); bind(#conf{type=trx} = Conf, Session) -> Params = [{system_id, Conf#conf.systemid}, {password, Conf#conf.password}, {system_type, ?SYSTEM_TYPE}, {interface_version, ?SMPP_VERSION_3_4}], gen_esme:bind_transceiver(Session, Params); bind(#conf{type=tx} = Conf, Session) -> Params = [{system_id, Conf#conf.systemid}, {password, Conf#conf.password}, {system_type, ?SYSTEM_TYPE}, {interface_version, ?SMPP_VERSION_3_4}], gen_esme:bind_transceiver(Session, Params). @spec handle_outbind(Outbind , From , State ) - > Result = { outbind , Session , Pdu } %% Session = pid() Pdu = pdu ( ) %% From = term() %% State = term() Result = { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } ParamList = [ { ParamName , ParamValue } ] ParamName = atom ( ) ParamValue = term ( ) NewState = term ( ) %% Timeout = int() %% Reason = term() %% %% @doc <a href="#handle_outbind-3">gen_esme - handle_outbind/3</a> callback implementation. %% < p > Handle < i > oubind</i > requests from the peer > %% @end handle_outbind({outbind, _Session, _Pdu}, _From, State) -> ?WARN("Unexpected/wanted/supported outbind.", []), {noreply, State}. , State ) - > Result %% AlertNotification = {alert_notification, Session, Pdu} %% Session = pid() Pdu = pdu ( ) %% State = term() Result = { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } ParamList = [ { ParamName , ParamValue } ] ParamName = atom ( ) ParamValue = term ( ) NewState = term ( ) %% Timeout = int() %% Reason = term() %% %% @doc <a href="#handle_alert_notification-3">gen_esme - handle_alert_notification/3</a> callback implementation. %% < p > Handle < i > alert_notification</i > requests from the peer > %% @end handle_alert_notification({alert_notification, _Session, _Pdu}, State) -> ?INFO("Unsupported alert notification", []), {noreply, State}. , State ) - > Result EnquireLinkFailure = { enquire_link_failure , Session , CommandStatus } %% Session = pid() CommandStatus = int ( ) %% State = term() Result = { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } NewState = term ( ) %% Timeout = int() %% Reason = term() %% %% @doc <a href="#handle_alert_notification-3">gen_esme - handle_alert_notification/3</a> callback implementation. %% < p > Handle < i > alert_notification</i > requests from the peer > %% @end handle_enquire_link_failure({enquire_link_failure, _Session, CommandStatus}, State) -> ?WARN("Link status enquiry failed, cmd status ~p", [CommandStatus]), {noreply, State}. @spec handle_operation(Operation , From , State ) - > Result %% Operation = {deliver_sm, Session, Pdu} | {data_sm, Session, Pdu} %% Session = pid() Pdu = pdu ( ) %% From = term() %% State = term() %% Result = {reply, Reply, NewState} | { reply , Reply , NewState , Timeout } | { noreply , NewState } | { noreply , NewState , Timeout } | %% {stop, Reason, Reply, NewState} | { stop , , NewState } %% Reply = {ok, ParamList} | {error, Error, ParamList} ParamList = [ { ParamName , ParamValue } ] ParamName = atom ( ) ParamValue = term ( ) NewState = term ( ) %% Timeout = int() %% Reason = term() %% %% @doc <a href="#handle_operation-3">gen_esme - handle_operation/3</a> callback implementation. %% %% <p>Handle <i>deliver_sm</i> and <i>data_sm</i> operations (from the peer %% SMSCs) to the callback ESME.</p> %% %% <p>The <tt>ParamList</tt> included in the response is used to construct the response PDU . If a command_status other than ESME_ROK is to be returned by the ESME in the response PDU , the callback should return the term < tt>{error , Error , ParamList}</tt > , where < tt > Error</tt > is the desired command_status error code.</p > %% @end handle_operation({deliver_sm, _Session, Pdu}, _From, State) -> From = dict:fetch(source_addr, Pdu), To = dict:fetch(destination_addr, Pdu), Text = dict:fetch(short_message, Pdu), Msg = erms_msg:msg(From, To, Text), case erms_connection:check_rx_rules(Msg, State#state.rules) of discard -> ?WARN("Throwing away MT, no matching receive rule ~p", [From]); {Direction, Shortcode} -> Dlr = dict:fetch(registered_delivery, Pdu), if Dlr == ?REGISTERED_DELIVERY_MC_NEVER -> ok; true -> ?WARN("Unsupported DLR request ~p", [Dlr]) end, _Id = erms_msg_queue:queue(State#state.name, Shortcode, Msg, Direction) end, {reply, {ok, []}, State}; handle_operation({CmdName, _Session, Pdu}, _From, S) -> ?WARN("Unhandled operation, ~p: ~p", [CmdName, dict:to_list(Pdu)]), % Don't know how to handle CmdName {reply, {error, ?ESME_RINVCMDID, []}, S}. , From , State ) - > Result = { unbind , Session , Pdu } %% Session = pid() Pdu = pdu ( ) %% Result = {reply, Reply, NewState} | { reply , Reply , NewState , Timeout } | { noreply , NewState } | { noreply , NewState , Timeout } | %% {stop, Reason, Reply, NewState} | { stop , , NewState } %% Reply = ok | {error, Error} %% Error = int() NewState = term ( ) %% Timeout = int() %% Reason = term() %% %% @doc <a href="#handle_unbind-3">gen_esme - handle_unbind/3</a> callback implementation. %% < p > Handle < i > unbind</i > requests from the peer > %% < p > If < tt > ok</tt > returned an unbind_resp with a ESME_ROK command_status is sent to the MC and the session moves into the unbound state . When < tt>{error , Error}</tt > is returned by the ESME , the response PDU sent by the session to the MC will have an < tt > Error</tt > command_status and the session will remain on it 's current bound state ( bound_rx , or > %% @end handle_unbind({unbind, _Session, _Pdu}, _From, State) -> ?INFO("Got unbind request, probably should shutdown.", []), {reply, ok, State}. handle_listen_error(State ) - > Result %% State = term() Result = { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } NewState = term ( ) %% Timeout = int() %% Reason = term() %% @doc < a href=" / oserl / > callback implementation . %% %% <p>Handle listen failures.</p> %% @end handle_listen_error(State) -> ?WARN("Listen error.", []), {noreply, State}. , From , State ) - > Result %% Request = term() %% From = {pid(), Tag} State = term ( ) %% Result = {reply, Reply, NewState} | { reply , Reply , NewState , Timeout } | { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , Reply , NewState } | { stop , , NewState } %% Reply = term() NewState = term ( ) Timeout = int ( ) | infinity %% Reason = term() %% %% @doc <a href="#handle_call-3">gen_esme - handle_call/3</a> callback implementation. %% < p > Handling call > %% %% <ul> < li > On < tt>{stop , , Reply , NewState}</tt > %% terminate/2 is called</li> < li > On < tt>{stop , , NewState}</tt > %% terminate/2 is called</li> %% </ul> %% %% @see terminate/2 %% @end handle_call(die, _From, State) -> {stop, normal, ok, State}; handle_call(Request, From, State) -> ?WARN("Unexpected call ~p from ~p", [Request, From]), {noreply, State}. , State ) - > Result %% Request = term() Result = { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } NewState = term ( ) Timeout = int ( ) | infinity %% Reason = normal | term() %% %% @doc <a href="#handle_cast-2"> gen_esme - handle_cast/2</a> callback implementation. %% < p > Handling cast > %% %% <ul> < li > On < tt>{stop , , State}</tt > terminate/2 is called.</li > %% </ul> %% %% @see terminate/2 %% @end handle_cast(Request, State) -> ?WARN("Unexpected cast ~p", [Request]), {noreply, State}. , State ) - > Result %% Info = timeout | term() %% State = term() Result = { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } NewState = term ( ) Timeout = int ( ) | infinity %% Reason = normal | term() %% %% @doc <a href="#handle_info-2"> gen_esme - handle_info/2</a> callback implementation. %% %% <p>Handling all non call/cast messages.</p> %% %% <ul> < li > On < tt>{stop , , State}</tt > terminate/2 is called.</li > %% </ul> %% %% @see terminate/2 %% @end handle_info({'EXIT', Pid, Reason}, #state{parent=Pid} = State) -> {stop, Reason, State}; handle_info({'EXIT', Pid, _Reason}, #state{listener=Pid} = State) -> {noreply, State#state{listener=undefined}}; handle_info({'EXIT', Pid, _Reason}, #state{session=Pid} = State) -> {noreply, State#state{session=undefined}}; handle_info(reconnect, #state{session=Pid} = State) when is_pid(Pid) -> {noreply, State}; handle_info(reconnect, #state{session=undefined,conf=Conf,name=ConnectionName} = State) -> {Host, Port} = Conf#conf.smsc, case gen_esme:session_start(self(), Host, Port) of {ok, Session} -> link(Session), case bind(Conf, Session) of {ok, _Pdu} -> {noreply, State#state{session=Session, listener=listen(Conf#conf.type, Session, ConnectionName)}}; BindError -> ?ERR("Couldn't bind session, ~p", [BindError]), catch(gen_esme:session_stop(Session)), {noreply, State} end; Error -> ?ERR("Couldn't connect to the SMSC, ~p", [Error]), {noreply, State} end; handle_info(Info, State) -> ?WARN("Unexpected info ~p", [Info]), {noreply, State}. , State ) - > ok %% Reason = normal | shutdown | term() State = term ( ) %% %% @doc <a href="#terminate-2"> %% gen_esme - terminate/2</a> callback implementation. %% < p > Shutdown the ESME server.</p > %% %% <p>Return value is ignored by <tt>gen_esme</tt>.</p> %% @end terminate(Reason, #state{session=Session}) when is_pid(Session) -> if Reason == normal -> ok; Reason == shutdown -> ok; true -> ?INFO("Terminating: ~p", [Reason]) end, catch(gen_esme:session_stop(Session)), % You may stop sessions and issue unbind requests here. ok; terminate(Reason, _) -> if Reason == normal -> ok; Reason == shutdown -> ok; true -> ?INFO("Terminating: ~p", [Reason]) end, ok. , State , Extra ) - > { ok , NewState } undefined | term ( ) %% State = term() %% Extra = term NewState = term ( ) %% %% @doc <a href="#code_change-2"> gen_esme - code_change/2</a> callback implementation. %% %% <p>Convert process state when code is changed.</p> %% @end code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== Internal functions %%%=================================================================== listen(rx, _, _) -> undefined; listen(trx, Session, Name) -> listen(tx, Session, Name); listen(tx, Session, Name) -> {ok, Pid} = erms_esme_listener:start_link(Session, Name), Pid.
null
https://raw.githubusercontent.com/archaelus/erms/5dbe5e79516a16e461e7a2a345dd80fbf92ef6fa/src/erms_esme_connection.erl
erlang
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. License along with this library; if not, write to the Free Software @doc ESME Skeleton. <p>You may use this skeleton as the starting point to implement your own ESMEs.</p> [/] @end ------------------------------------------------------------------- Include files ------------------------------------------------------------------- ------------------------------------------------------------------- External exports ------------------------------------------------------------------- ------------------------------------------------------------------- Internal ESME exports ------------------------------------------------------------------- ------------------------------------------------------------------- ------------------------------------------------------------------- %@spec {state} @doc Representation of the ESME server state . <dl> <dt>: </dt><dd> </dd> </dl> %@end =================================================================== External functions =================================================================== @spec start_link(Name::string()) -> Result @see gen_esme @see start/0 @end @see handle_call/3 @end =================================================================== Server functions =================================================================== Timeout = int() | infinity @doc <a href="#init-1"> gen_esme - init/1</a> callback implementation. <p>Initiates the server.</p> @end You may start sessions and issue bind requests here. Session = pid() From = term() State = term() Timeout = int() Reason = term() @doc <a href="#handle_outbind-3">gen_esme - handle_outbind/3</a> callback implementation. @end AlertNotification = {alert_notification, Session, Pdu} Session = pid() State = term() Timeout = int() Reason = term() @doc <a href="#handle_alert_notification-3">gen_esme - handle_alert_notification/3</a> callback implementation. @end Session = pid() State = term() Timeout = int() Reason = term() @doc <a href="#handle_alert_notification-3">gen_esme - handle_alert_notification/3</a> callback implementation. @end Operation = {deliver_sm, Session, Pdu} | {data_sm, Session, Pdu} Session = pid() From = term() State = term() Result = {reply, Reply, NewState} | {stop, Reason, Reply, NewState} | Reply = {ok, ParamList} | {error, Error, ParamList} Timeout = int() Reason = term() @doc <a href="#handle_operation-3">gen_esme - handle_operation/3</a> callback implementation. <p>Handle <i>deliver_sm</i> and <i>data_sm</i> operations (from the peer SMSCs) to the callback ESME.</p> <p>The <tt>ParamList</tt> included in the response is used to construct @end Don't know how to handle CmdName Session = pid() Result = {reply, Reply, NewState} | {stop, Reason, Reply, NewState} | Reply = ok | {error, Error} Error = int() Timeout = int() Reason = term() @doc <a href="#handle_unbind-3">gen_esme - handle_unbind/3</a> callback implementation. @end State = term() Timeout = int() Reason = term() <p>Handle listen failures.</p> @end Request = term() From = {pid(), Tag} Result = {reply, Reply, NewState} | Reply = term() Reason = term() @doc <a href="#handle_call-3">gen_esme - handle_call/3</a> callback implementation. <ul> terminate/2 is called</li> terminate/2 is called</li> </ul> @see terminate/2 @end Request = term() Reason = normal | term() @doc <a href="#handle_cast-2"> gen_esme - handle_cast/2</a> callback implementation. <ul> </ul> @see terminate/2 @end Info = timeout | term() State = term() Reason = normal | term() @doc <a href="#handle_info-2"> gen_esme - handle_info/2</a> callback implementation. <p>Handling all non call/cast messages.</p> <ul> </ul> @see terminate/2 @end Reason = normal | shutdown | term() @doc <a href="#terminate-2"> gen_esme - terminate/2</a> callback implementation. <p>Return value is ignored by <tt>gen_esme</tt>.</p> @end You may stop sessions and issue unbind requests here. State = term() Extra = term @doc <a href="#code_change-2"> gen_esme - code_change/2</a> callback implementation. <p>Convert process state when code is changed.</p> @end =================================================================== ===================================================================
Copyright ( C ) 2004 Peña < > License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA 2004 @author < mpquique_at_users.sourceforge.net > @version 1.1 , { 6 Jul 2004 } { @time } . -module(erms_esme_connection). -behaviour(gen_esme). -include_lib("eunit/include/eunit.hrl"). -include_lib("logging.hrl"). -include_lib("mnesia_model.hrl"). -include_lib("oserl.hrl"). -include_lib("smpp_base.hrl"). -export([start_link/1, start_link/2, stop/1, reconnect/1]). -export([init/1, handle_outbind/3, handle_alert_notification/2, handle_enquire_link_failure/2, handle_operation/3, handle_unbind/3, handle_listen_error/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). Records -record(state, {conf, name, session, rules, listener, heartbeatref, parent}). -record(conf, {systemid, password, smsc, type}). -define(SYSTEM_TYPE, "InternetGW"). Result = { ok , Pid } | ignore | { error , Error } Pid = pid ( ) Error = { already_started , Pid } | term ( ) @doc Starts the ESME server . start_link(ConnectionName) -> start_link(ConnectionName, []). start_link(ConnectionName, Args) -> {ok, Pid} = gen_esme:start_link(?MODULE, [ConnectionName, self(), Args], []), Pid ! reconnect, {ok, Pid}. ( ) ) - > ok | { error , Reason::term ( ) } @doc Stops the named ESME connection . @equiv gen_esme : call(SERVER , die , 10000 ) stop(ConnectionName) -> gen_esme:call(erms_connection_mgr:where({connection, ConnectionName}), die, 10000). reconnect(ConnectionName) -> erms_connection_mgr:where({connection, ConnectionName}) ! reconnect. ) - > Result = term ( ) Result = { ok , State } | { ok , State , Timeout } | ignore | { stop , Reason } State = term ( ) term ( ) init([ConnectionName, Parent]) -> [Conf] = erms_connection:args(ConnectionName), init([ConnectionName, Parent, Conf]); init([ConnectionName, Parent, Conf]) -> Rules = erms_connection:rx_rules(ConnectionName), process_flag(trap_exit, true), {ok, TimerRef} = timer:send_interval(timer:minutes(1), reconnect), {ok, #state{conf=Conf, name=ConnectionName, rules=Rules, heartbeatref=TimerRef, parent=Parent}}. bind(#conf{type=rx} = Conf, Session) -> Params = [{system_id, Conf#conf.systemid}, {password, Conf#conf.password}, {system_type, ?SYSTEM_TYPE}, {interface_version, ?SMPP_VERSION_3_4}], gen_esme:bind_receiver(Session, Params); bind(#conf{type=trx} = Conf, Session) -> Params = [{system_id, Conf#conf.systemid}, {password, Conf#conf.password}, {system_type, ?SYSTEM_TYPE}, {interface_version, ?SMPP_VERSION_3_4}], gen_esme:bind_transceiver(Session, Params); bind(#conf{type=tx} = Conf, Session) -> Params = [{system_id, Conf#conf.systemid}, {password, Conf#conf.password}, {system_type, ?SYSTEM_TYPE}, {interface_version, ?SMPP_VERSION_3_4}], gen_esme:bind_transceiver(Session, Params). @spec handle_outbind(Outbind , From , State ) - > Result = { outbind , Session , Pdu } Pdu = pdu ( ) Result = { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } ParamList = [ { ParamName , ParamValue } ] ParamName = atom ( ) ParamValue = term ( ) NewState = term ( ) < p > Handle < i > oubind</i > requests from the peer > handle_outbind({outbind, _Session, _Pdu}, _From, State) -> ?WARN("Unexpected/wanted/supported outbind.", []), {noreply, State}. , State ) - > Result Pdu = pdu ( ) Result = { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } ParamList = [ { ParamName , ParamValue } ] ParamName = atom ( ) ParamValue = term ( ) NewState = term ( ) < p > Handle < i > alert_notification</i > requests from the peer > handle_alert_notification({alert_notification, _Session, _Pdu}, State) -> ?INFO("Unsupported alert notification", []), {noreply, State}. , State ) - > Result EnquireLinkFailure = { enquire_link_failure , Session , CommandStatus } CommandStatus = int ( ) Result = { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } NewState = term ( ) < p > Handle < i > alert_notification</i > requests from the peer > handle_enquire_link_failure({enquire_link_failure, _Session, CommandStatus}, State) -> ?WARN("Link status enquiry failed, cmd status ~p", [CommandStatus]), {noreply, State}. @spec handle_operation(Operation , From , State ) - > Result Pdu = pdu ( ) { reply , Reply , NewState , Timeout } | { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } ParamList = [ { ParamName , ParamValue } ] ParamName = atom ( ) ParamValue = term ( ) NewState = term ( ) the response PDU . If a command_status other than ESME_ROK is to be returned by the ESME in the response PDU , the callback should return the term < tt>{error , Error , ParamList}</tt > , where < tt > Error</tt > is the desired command_status error code.</p > handle_operation({deliver_sm, _Session, Pdu}, _From, State) -> From = dict:fetch(source_addr, Pdu), To = dict:fetch(destination_addr, Pdu), Text = dict:fetch(short_message, Pdu), Msg = erms_msg:msg(From, To, Text), case erms_connection:check_rx_rules(Msg, State#state.rules) of discard -> ?WARN("Throwing away MT, no matching receive rule ~p", [From]); {Direction, Shortcode} -> Dlr = dict:fetch(registered_delivery, Pdu), if Dlr == ?REGISTERED_DELIVERY_MC_NEVER -> ok; true -> ?WARN("Unsupported DLR request ~p", [Dlr]) end, _Id = erms_msg_queue:queue(State#state.name, Shortcode, Msg, Direction) end, {reply, {ok, []}, State}; handle_operation({CmdName, _Session, Pdu}, _From, S) -> ?WARN("Unhandled operation, ~p: ~p", [CmdName, dict:to_list(Pdu)]), {reply, {error, ?ESME_RINVCMDID, []}, S}. , From , State ) - > Result = { unbind , Session , Pdu } Pdu = pdu ( ) { reply , Reply , NewState , Timeout } | { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } NewState = term ( ) < p > Handle < i > unbind</i > requests from the peer > < p > If < tt > ok</tt > returned an unbind_resp with a ESME_ROK command_status is sent to the MC and the session moves into the unbound state . When < tt>{error , Error}</tt > is returned by the ESME , the response PDU sent by the session to the MC will have an < tt > Error</tt > command_status and the session will remain on it 's current bound state ( bound_rx , or > handle_unbind({unbind, _Session, _Pdu}, _From, State) -> ?INFO("Got unbind request, probably should shutdown.", []), {reply, ok, State}. handle_listen_error(State ) - > Result Result = { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } NewState = term ( ) @doc < a href=" / oserl / > callback implementation . handle_listen_error(State) -> ?WARN("Listen error.", []), {noreply, State}. , From , State ) - > Result State = term ( ) { reply , Reply , NewState , Timeout } | { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , Reply , NewState } | { stop , , NewState } NewState = term ( ) Timeout = int ( ) | infinity < p > Handling call > < li > On < tt>{stop , , Reply , NewState}</tt > < li > On < tt>{stop , , NewState}</tt > handle_call(die, _From, State) -> {stop, normal, ok, State}; handle_call(Request, From, State) -> ?WARN("Unexpected call ~p from ~p", [Request, From]), {noreply, State}. , State ) - > Result Result = { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } NewState = term ( ) Timeout = int ( ) | infinity < p > Handling cast > < li > On < tt>{stop , , State}</tt > terminate/2 is called.</li > handle_cast(Request, State) -> ?WARN("Unexpected cast ~p", [Request]), {noreply, State}. , State ) - > Result Result = { noreply , NewState } | { noreply , NewState , Timeout } | { stop , , NewState } NewState = term ( ) Timeout = int ( ) | infinity < li > On < tt>{stop , , State}</tt > terminate/2 is called.</li > handle_info({'EXIT', Pid, Reason}, #state{parent=Pid} = State) -> {stop, Reason, State}; handle_info({'EXIT', Pid, _Reason}, #state{listener=Pid} = State) -> {noreply, State#state{listener=undefined}}; handle_info({'EXIT', Pid, _Reason}, #state{session=Pid} = State) -> {noreply, State#state{session=undefined}}; handle_info(reconnect, #state{session=Pid} = State) when is_pid(Pid) -> {noreply, State}; handle_info(reconnect, #state{session=undefined,conf=Conf,name=ConnectionName} = State) -> {Host, Port} = Conf#conf.smsc, case gen_esme:session_start(self(), Host, Port) of {ok, Session} -> link(Session), case bind(Conf, Session) of {ok, _Pdu} -> {noreply, State#state{session=Session, listener=listen(Conf#conf.type, Session, ConnectionName)}}; BindError -> ?ERR("Couldn't bind session, ~p", [BindError]), catch(gen_esme:session_stop(Session)), {noreply, State} end; Error -> ?ERR("Couldn't connect to the SMSC, ~p", [Error]), {noreply, State} end; handle_info(Info, State) -> ?WARN("Unexpected info ~p", [Info]), {noreply, State}. , State ) - > ok State = term ( ) < p > Shutdown the ESME server.</p > terminate(Reason, #state{session=Session}) when is_pid(Session) -> if Reason == normal -> ok; Reason == shutdown -> ok; true -> ?INFO("Terminating: ~p", [Reason]) end, catch(gen_esme:session_stop(Session)), ok; terminate(Reason, _) -> if Reason == normal -> ok; Reason == shutdown -> ok; true -> ?INFO("Terminating: ~p", [Reason]) end, ok. , State , Extra ) - > { ok , NewState } undefined | term ( ) NewState = term ( ) code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions listen(rx, _, _) -> undefined; listen(trx, Session, Name) -> listen(tx, Session, Name); listen(tx, Session, Name) -> {ok, Pid} = erms_esme_listener:start_link(Session, Name), Pid.
bcbc48dfebd1407011d27adb92c75c47aada74cd6f37cdf4a7a262e9b5bd6c16
stchang/macrotypes
typedefs.rkt
#lang turnstile+/base (require turnstile/typedefs) (provide (all-from-out turnstile/typedefs))
null
https://raw.githubusercontent.com/stchang/macrotypes/05ec31f2e1fe0ddd653211e041e06c6c8071ffa6/turnstile-lib/turnstile%2B/typedefs.rkt
racket
#lang turnstile+/base (require turnstile/typedefs) (provide (all-from-out turnstile/typedefs))
904b9019ca89a9b6a8e26c2892d12dd43ec3d72fa0658c0db551652ad43e37db
fugue/fregot
Extended.hs
| Copyright : ( c ) 2020 Fugue , Inc. License : Apache License , version 2.0 Maintainer : Stability : experimental Portability : POSIX Copyright : (c) 2020 Fugue, Inc. License : Apache License, version 2.0 Maintainer : Stability : experimental Portability : POSIX -} module Data.Text.Extended ( module Data.Text , fromString ) where import Control.Lens (Iso', iso) import Data.Text fromString :: Iso' String Text fromString = iso pack unpack
null
https://raw.githubusercontent.com/fugue/fregot/c3d87f37c43558761d5f6ac758d2f1a4117adb3e/lib/Data/Text/Extended.hs
haskell
| Copyright : ( c ) 2020 Fugue , Inc. License : Apache License , version 2.0 Maintainer : Stability : experimental Portability : POSIX Copyright : (c) 2020 Fugue, Inc. License : Apache License, version 2.0 Maintainer : Stability : experimental Portability : POSIX -} module Data.Text.Extended ( module Data.Text , fromString ) where import Control.Lens (Iso', iso) import Data.Text fromString :: Iso' String Text fromString = iso pack unpack
137465e524281d714e5c9375f555ca5599a9b5c0fb387cc5fc3e857c09cf56cb
ato/lein-clojars
project.clj
(defproject lein-clojars "0.9.1" :description "Leiningen plugin for interacting with Clojars.org." :dependencies [[com.jcraft/jsch "0.1.42"]])
null
https://raw.githubusercontent.com/ato/lein-clojars/3a7485ec13b6519dfd5a69155ccc9af555c9dd25/project.clj
clojure
(defproject lein-clojars "0.9.1" :description "Leiningen plugin for interacting with Clojars.org." :dependencies [[com.jcraft/jsch "0.1.42"]])
03e2cca1d105e79fb0e29da7eeeb7155c53cb5f832586661cd55c914256a06eb
orthecreedence/cl-hash-util
hash-util.lisp
cl - hash - util is a very basic library for dealing with CL 's hash tables . The ;;; idea was spawned through working with enough JSON APIs and config files, ;;; causing a lot of headaches in the process. For instance, to get a value deep ;;; within a hash, you have to do: ( gethash " city " ( gethash " location " ( gethash " user " obj ) ) ) ;;; ;;; With cl-hash-util, you can write: ( hget obj ' ( " user " " location " " city " ) ) ;;; ;;; hget can also deal with getting elements out of lists and arrays: ( hget obj ' ( " user " " friends " 0 " name " ) ) ;;; ;;; which normally would have to be written as such: ( gethash " name " ( elt ( gethash " friends " ( gethash " user " obj ) ) 0 ) ) ;;; ;;; ...uuuugly. ;;; ;;; cl-hash-util also provides an easy way to build hash tables on the fly. ;;; Where you'd normally have to do something like: ( let ( ( ( make - hash - table : test # ' equal ) ) ) ( setf ( gethash " name " ) " andrew " ) ( setf ( gethash " location " myhash ) " santa cruz " ) ;;; myhash) ;;; ;;; You can now do: ( hash - create ' ( ( " name " " andrew " ) ( " location " " santa cruz " ) ) ) ;;; ;;; -OR- ;;; ( hash ( " name " " andrew " ) ( " location " " santa cruz " ) ) ;;; ;;; You can also do nested hashes: ;;; (hash ("name" "andrew") ( " location " ( hash ( " city " " santa cruz " ) ;;; ("state" "CA")))) ;;; ;;; This saves a lot of typing =]. ;;; ;;; The project is hosted on github: ;;; -hash-util (defpackage :cl-hash-util (:use :cl :cl-user) (:export :*error-on-nil* :hash-create :hash :hget :hash-copy :hash-keys :with-keys :collecting-hash-table :it :collect :alist->plist :plist->alist :alist->hash :plist->hash :hash->alist :hash->plist :hash-get) (:nicknames :hu)) (in-package :cl-hash-util) (defvar *error-on-nil* nil "If hget encounters a nil, error out.") (defun hash-create (pairs &key (test #'equal)) "Create a hash table with limited syntax: (hash `((\"name\" \"andrew\") (\"city\" \"santa cruz\"))) which would otherwise be: (let ((hash (make-hash-table :test #'equal))) (setf (gethash \"name\" hash) \"andrew\") (setf (gethash \"city\" hash) \"santa cruz\") hash) yuck city." (let ((hash (make-hash-table :test test))) (dolist (pair pairs) (setf (gethash (car pair) hash) (cadr pair))) hash)) (defmacro hash (&rest pairs) "Extends hash-create syntax to make it nicer." `(hash-create (list ,@(loop for pair in pairs collect (list 'list (car pair) (cadr pair)))))) (defun %hget-access (obj key) (if (hash-table-p obj) (gethash key obj) (handler-case (values (elt obj key) t) (t (e) (declare (ignore e)) (values nil nil))))) (defun %store-p (obj key) "Is the object something from which key could be fetched?" (or (hash-table-p obj) (and (numberp key) (or (listp obj) (vectorp obj))))) (defun %find-lowest-store (obj path) (let ((placeholder obj)) (loop for entries on path do (if placeholder (if (cdr entries) (if (%store-p placeholder (car entries)) (let ((next (%hget-access placeholder (car entries)))) (unless next (return-from %find-lowest-store (values placeholder entries))) ;Partial (setf placeholder next)) ;Try some more (error "Can't descend into tree. Value is not null, but is not a hash table or sequence.")) (return-from %find-lowest-store (values placeholder (last path)))) ;Total success! (return-from %find-lowest-store (values nil path)))))) ;Initial nil (defun hget (obj path &key fill-func) "Allows you to specify a path to get values out of a hash/list object. For instance, if you did: (let ((myhash (hash '(\"lol\" '(3 4 5))))) (hget myhash '(\"lol\" 1))) which would return 4 (1st index of list stored under key 'lol of the hash table). Simplifies traversing responses from decoded JSON objects by about a trillion times. The second and third values returned by hget indicate how much success it had in looking up your request. If the second value is T, everything was found, right up to the end node. When the second value is NIL, the third value is the portion of the supplied path that was missing. By setting *error-on-nil* to true, hget can be persuaded to throw an error if any of the upper part of the tree is missing . It will not throw an error if the final value is not set." (declare (ignore fill-func)) (multiple-value-bind (lstore leftover) (%find-lowest-store obj path) (let ((leftlen (length leftover))) (cond ((= 0 leftlen) (error "0 length path.")) ((= 1 leftlen) (multiple-value-bind (val sig) (%hget-access lstore (car (last path))) (if sig (values val t) (values nil nil leftover)))) (t (if *error-on-nil* (if (numberp (car leftover)) (error "NIL found instead of sequence") (error "NIL found instead of hash table")) (values nil nil leftover))))))) (defun %hget-set (store key value) (if (hash-table-p store) (setf (gethash key store) value) (setf (elt store key) value))) (defun (setf hget) (val obj path &key fill-func) "Defines a setf for the hget function. Uses hget to get all but the last item in the path, then setfs that last object (either a gethash or an elt). If any of the path aside from the last item is missing, it will throw an error. To change this behavior, supply an object construction function with the :fill-func parameter. (Setf hget) will fill out the tree up to the last path item with the objects that this function returns." (let ((path (if (listp path) path (list path)))) (multiple-value-bind (lstore leftover) (%find-lowest-store obj path) (unless lstore (error "Can't set: No fill-func and no hash-table or sequence found.")) (when (> (length leftover) 1) (if fill-func (dolist (key (butlast leftover)) (let ((stor (funcall fill-func))) (%hget-set lstore key stor) (setf lstore stor))) (error "Can't set: Missing storage objects in tree and no fill-func supplied."))) (%hget-set lstore (car (last leftover)) val)))) (setf (fdefinition 'hash-get) #'hget) (setf (fdefinition '(setf hash-get)) (fdefinition '(setf hget))) (defun hash-copy (hash &key (test #'equal)) "Performs a shallow (non-recursive) copy of a hash table." (let ((new-hash (make-hash-table :test test :size (hash-table-count hash)))) (loop for k being the hash-keys of hash for v being the hash-values of hash do (setf (gethash k new-hash) v)) new-hash)) (defun hash-keys (hash) "Grab all the hash keys of the passed hash into a list." (loop for x being the hash-keys of hash collect x))
null
https://raw.githubusercontent.com/orthecreedence/cl-hash-util/91d17d3e9208db9438b72bb60037644fd79fb497/hash-util.lisp
lisp
idea was spawned through working with enough JSON APIs and config files, causing a lot of headaches in the process. For instance, to get a value deep within a hash, you have to do: With cl-hash-util, you can write: hget can also deal with getting elements out of lists and arrays: which normally would have to be written as such: ...uuuugly. cl-hash-util also provides an easy way to build hash tables on the fly. Where you'd normally have to do something like: myhash) You can now do: -OR- You can also do nested hashes: (hash ("name" "andrew") ("state" "CA")))) This saves a lot of typing =]. The project is hosted on github: -hash-util Partial Try some more Total success! Initial nil
cl - hash - util is a very basic library for dealing with CL 's hash tables . The ( gethash " city " ( gethash " location " ( gethash " user " obj ) ) ) ( hget obj ' ( " user " " location " " city " ) ) ( hget obj ' ( " user " " friends " 0 " name " ) ) ( gethash " name " ( elt ( gethash " friends " ( gethash " user " obj ) ) 0 ) ) ( let ( ( ( make - hash - table : test # ' equal ) ) ) ( setf ( gethash " name " ) " andrew " ) ( setf ( gethash " location " myhash ) " santa cruz " ) ( hash - create ' ( ( " name " " andrew " ) ( " location " " santa cruz " ) ) ) ( hash ( " name " " andrew " ) ( " location " " santa cruz " ) ) ( " location " ( hash ( " city " " santa cruz " ) (defpackage :cl-hash-util (:use :cl :cl-user) (:export :*error-on-nil* :hash-create :hash :hget :hash-copy :hash-keys :with-keys :collecting-hash-table :it :collect :alist->plist :plist->alist :alist->hash :plist->hash :hash->alist :hash->plist :hash-get) (:nicknames :hu)) (in-package :cl-hash-util) (defvar *error-on-nil* nil "If hget encounters a nil, error out.") (defun hash-create (pairs &key (test #'equal)) "Create a hash table with limited syntax: (hash `((\"name\" \"andrew\") (\"city\" \"santa cruz\"))) which would otherwise be: (let ((hash (make-hash-table :test #'equal))) (setf (gethash \"name\" hash) \"andrew\") (setf (gethash \"city\" hash) \"santa cruz\") hash) yuck city." (let ((hash (make-hash-table :test test))) (dolist (pair pairs) (setf (gethash (car pair) hash) (cadr pair))) hash)) (defmacro hash (&rest pairs) "Extends hash-create syntax to make it nicer." `(hash-create (list ,@(loop for pair in pairs collect (list 'list (car pair) (cadr pair)))))) (defun %hget-access (obj key) (if (hash-table-p obj) (gethash key obj) (handler-case (values (elt obj key) t) (t (e) (declare (ignore e)) (values nil nil))))) (defun %store-p (obj key) "Is the object something from which key could be fetched?" (or (hash-table-p obj) (and (numberp key) (or (listp obj) (vectorp obj))))) (defun %find-lowest-store (obj path) (let ((placeholder obj)) (loop for entries on path do (if placeholder (if (cdr entries) (if (%store-p placeholder (car entries)) (let ((next (%hget-access placeholder (car entries)))) (unless next (return-from %find-lowest-store (error "Can't descend into tree. Value is not null, but is not a hash table or sequence.")) (return-from %find-lowest-store (defun hget (obj path &key fill-func) "Allows you to specify a path to get values out of a hash/list object. For instance, if you did: (let ((myhash (hash '(\"lol\" '(3 4 5))))) (hget myhash '(\"lol\" 1))) which would return 4 (1st index of list stored under key 'lol of the hash table). Simplifies traversing responses from decoded JSON objects by about a trillion times. The second and third values returned by hget indicate how much success it had in looking up your request. If the second value is T, everything was found, right up to the end node. When the second value is NIL, the third value is the portion of the supplied path that was missing. By setting *error-on-nil* to true, hget can be persuaded to throw an error if any of the upper part of the tree is missing . It will not throw an error if the final value is not set." (declare (ignore fill-func)) (multiple-value-bind (lstore leftover) (%find-lowest-store obj path) (let ((leftlen (length leftover))) (cond ((= 0 leftlen) (error "0 length path.")) ((= 1 leftlen) (multiple-value-bind (val sig) (%hget-access lstore (car (last path))) (if sig (values val t) (values nil nil leftover)))) (t (if *error-on-nil* (if (numberp (car leftover)) (error "NIL found instead of sequence") (error "NIL found instead of hash table")) (values nil nil leftover))))))) (defun %hget-set (store key value) (if (hash-table-p store) (setf (gethash key store) value) (setf (elt store key) value))) (defun (setf hget) (val obj path &key fill-func) "Defines a setf for the hget function. Uses hget to get all but the last item in the path, then setfs that last object (either a gethash or an elt). If any of the path aside from the last item is missing, it will throw an error. To change this behavior, supply an object construction function with the :fill-func parameter. (Setf hget) will fill out the tree up to the last path item with the objects that this function returns." (let ((path (if (listp path) path (list path)))) (multiple-value-bind (lstore leftover) (%find-lowest-store obj path) (unless lstore (error "Can't set: No fill-func and no hash-table or sequence found.")) (when (> (length leftover) 1) (if fill-func (dolist (key (butlast leftover)) (let ((stor (funcall fill-func))) (%hget-set lstore key stor) (setf lstore stor))) (error "Can't set: Missing storage objects in tree and no fill-func supplied."))) (%hget-set lstore (car (last leftover)) val)))) (setf (fdefinition 'hash-get) #'hget) (setf (fdefinition '(setf hash-get)) (fdefinition '(setf hget))) (defun hash-copy (hash &key (test #'equal)) "Performs a shallow (non-recursive) copy of a hash table." (let ((new-hash (make-hash-table :test test :size (hash-table-count hash)))) (loop for k being the hash-keys of hash for v being the hash-values of hash do (setf (gethash k new-hash) v)) new-hash)) (defun hash-keys (hash) "Grab all the hash keys of the passed hash into a list." (loop for x being the hash-keys of hash collect x))
d35a9d367963f2871a448abc94080ae7cc5d9b7d29d2a29204c1c14581c44a67
facebook/pyre-check
interprocedural.ml
* Copyright ( c ) Meta Platforms , Inc. and 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) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) Taint : here we expose modules for the ` pyrelib.interprocedural ` library module FixpointAnalysis = FixpointAnalysis module Target = Target module CallGraph = CallGraph module CallResolution = CallResolution module DecoratorHelper = DecoratorHelper module OverrideGraph = OverrideGraph module DependencyGraph = DependencyGraph module DependencyGraphSharedMemory = DependencyGraphSharedMemory module Error = Error module ClassHierarchyGraph = ClassHierarchyGraph module ClassInterval = ClassInterval module ClassIntervalSet = ClassIntervalSet module ClassIntervalSetGraph = ClassIntervalSetGraph module FetchCallables = FetchCallables module TargetGraph = TargetGraph module ChangedPaths = ChangedPaths module Metrics = Metrics
null
https://raw.githubusercontent.com/facebook/pyre-check/7b36197dd21e83c8d290737e9c7b52585102a4ab/source/interprocedural/interprocedural.ml
ocaml
* Copyright ( c ) Meta Platforms , Inc. and 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) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) Taint : here we expose modules for the ` pyrelib.interprocedural ` library module FixpointAnalysis = FixpointAnalysis module Target = Target module CallGraph = CallGraph module CallResolution = CallResolution module DecoratorHelper = DecoratorHelper module OverrideGraph = OverrideGraph module DependencyGraph = DependencyGraph module DependencyGraphSharedMemory = DependencyGraphSharedMemory module Error = Error module ClassHierarchyGraph = ClassHierarchyGraph module ClassInterval = ClassInterval module ClassIntervalSet = ClassIntervalSet module ClassIntervalSetGraph = ClassIntervalSetGraph module FetchCallables = FetchCallables module TargetGraph = TargetGraph module ChangedPaths = ChangedPaths module Metrics = Metrics
efb515bc46c4d4502a475750d366e3f66271e1ddd9cb1e960cb1748882bc9171
SKS-Keyserver/sks-keyserver
packet.mli
type ptype = Reserved | Public_Key_Encrypted_Session_Key_Packet | Signature_Packet | Symmetric_Key_Encrypted_Session_Key_Packet | One_Pass_Signature_Packet | Secret_Key_Packet | Public_Key_Packet | Secret_Subkey_Packet | Compressed_Data_Packet | Symmetrically_Encrypted_Data_Packet | Marker_Packet | Literal_Data_Packet | Trust_Packet | User_ID_Packet | User_Attribute_Packet | Sym_Encrypted_and_Integrity_Protected_Data_Packet | Modification_Detection_Code_Packet | Public_Subkey_Packet | Private_or_Experimental_ptype | Unexpected_ptype type packet = { content_tag : int; packet_type : ptype; packet_length : int; packet_body : string; } type sigsubpacket = { ssp_length : int; ssp_type : int; ssp_body : string; } val ssp_type_to_string : int -> string type key = packet list val sigtype_to_string : int -> string val content_tag_to_ptype : int -> ptype val ptype_to_string : ptype -> string type mpi = { mpi_bits : int; mpi_data : string; } val pubkey_algorithm_string : int -> string type pubkeyinfo = { pk_version : int; pk_ctime : int64; pk_expiration : int option; pk_alg : int; pk_keylen : int; } type sigtype = Signature_of_a_binary_document | Signature_of_a_canonical_text_document | Standalone_signature | Generic_certification_of_a_User_ID_and_Public_Key_packet | Persona_certification_of_a_User_ID_and_Public_Key_packet | Casual_certification_of_a_User_ID_and_Public_Key_packet | Positive_certification_of_a_User_ID_and_Public_Key_packet | Subkey_Binding_Signature | Signature_directly_on_a_key | Key_revocation_signature | Subkey_revocation_signature | Certification_revocation_signature | Timestamp_signature | Unexpected_sigtype type v3sig = { v3s_sigtype : int; v3s_ctime : int64; v3s_keyid : string; v3s_pk_alg : int; v3s_hash_alg : int; v3s_hash_value : string; v3s_mpis : mpi list; } type v4sig = { v4s_sigtype : int; v4s_pk_alg : int; v4s_hashed_subpackets : sigsubpacket list; v4s_unhashed_subpackets : sigsubpacket list; v4s_hash_value : string; v4s_mpis : mpi list; } type signature = V3sig of v3sig | V4sig of v4sig val int_to_sigtype : int -> sigtype val content_tag_to_string : int -> string val print_packet : packet -> unit val write_packet_new : packet -> < write_byte : int -> 'a; write_int : int -> 'b; write_string : string -> 'c; .. > -> 'c val pk_alg_to_ident : int -> string val write_packet_old : packet -> < write_byte : int -> 'a; write_int : int -> 'b; write_string : string -> 'c; .. > -> 'c val write_packet : packet -> < write_byte : int -> 'a; write_int : int -> 'b; write_string : string -> 'c; .. > -> 'c
null
https://raw.githubusercontent.com/SKS-Keyserver/sks-keyserver/a4e5267d817cddbdfee13d07a7fb38a9b94b3eee/packet.mli
ocaml
type ptype = Reserved | Public_Key_Encrypted_Session_Key_Packet | Signature_Packet | Symmetric_Key_Encrypted_Session_Key_Packet | One_Pass_Signature_Packet | Secret_Key_Packet | Public_Key_Packet | Secret_Subkey_Packet | Compressed_Data_Packet | Symmetrically_Encrypted_Data_Packet | Marker_Packet | Literal_Data_Packet | Trust_Packet | User_ID_Packet | User_Attribute_Packet | Sym_Encrypted_and_Integrity_Protected_Data_Packet | Modification_Detection_Code_Packet | Public_Subkey_Packet | Private_or_Experimental_ptype | Unexpected_ptype type packet = { content_tag : int; packet_type : ptype; packet_length : int; packet_body : string; } type sigsubpacket = { ssp_length : int; ssp_type : int; ssp_body : string; } val ssp_type_to_string : int -> string type key = packet list val sigtype_to_string : int -> string val content_tag_to_ptype : int -> ptype val ptype_to_string : ptype -> string type mpi = { mpi_bits : int; mpi_data : string; } val pubkey_algorithm_string : int -> string type pubkeyinfo = { pk_version : int; pk_ctime : int64; pk_expiration : int option; pk_alg : int; pk_keylen : int; } type sigtype = Signature_of_a_binary_document | Signature_of_a_canonical_text_document | Standalone_signature | Generic_certification_of_a_User_ID_and_Public_Key_packet | Persona_certification_of_a_User_ID_and_Public_Key_packet | Casual_certification_of_a_User_ID_and_Public_Key_packet | Positive_certification_of_a_User_ID_and_Public_Key_packet | Subkey_Binding_Signature | Signature_directly_on_a_key | Key_revocation_signature | Subkey_revocation_signature | Certification_revocation_signature | Timestamp_signature | Unexpected_sigtype type v3sig = { v3s_sigtype : int; v3s_ctime : int64; v3s_keyid : string; v3s_pk_alg : int; v3s_hash_alg : int; v3s_hash_value : string; v3s_mpis : mpi list; } type v4sig = { v4s_sigtype : int; v4s_pk_alg : int; v4s_hashed_subpackets : sigsubpacket list; v4s_unhashed_subpackets : sigsubpacket list; v4s_hash_value : string; v4s_mpis : mpi list; } type signature = V3sig of v3sig | V4sig of v4sig val int_to_sigtype : int -> sigtype val content_tag_to_string : int -> string val print_packet : packet -> unit val write_packet_new : packet -> < write_byte : int -> 'a; write_int : int -> 'b; write_string : string -> 'c; .. > -> 'c val pk_alg_to_ident : int -> string val write_packet_old : packet -> < write_byte : int -> 'a; write_int : int -> 'b; write_string : string -> 'c; .. > -> 'c val write_packet : packet -> < write_byte : int -> 'a; write_int : int -> 'b; write_string : string -> 'c; .. > -> 'c
802bc42407f9765dd092f03c9f521e9364ed564038ecf40c76c89d799ab4033b
mzp/coq-ruby
cooking.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (*i $Id: cooking.ml 10877 2008-04-30 21:58:41Z herbelin $ i*) open Pp open Util open Names open Term open Sign open Declarations open Environ open Reduction (*s Cooking the constants. *) type work_list = identifier array Cmap.t * identifier array KNmap.t let dirpath_prefix p = match repr_dirpath p with | [] -> anomaly "dirpath_prefix: empty dirpath" | _::l -> make_dirpath l let pop_kn kn = let (mp,dir,l) = Names.repr_kn kn in Names.make_kn mp (dirpath_prefix dir) l let pop_con con = let (mp,dir,l) = Names.repr_con con in Names.make_con mp (dirpath_prefix dir) l type my_global_reference = | ConstRef of constant | IndRef of inductive | ConstructRef of constructor let cache = (Hashtbl.create 13 : (my_global_reference, constr) Hashtbl.t) let clear_cooking_sharing () = Hashtbl.clear cache let share r (cstl,knl) = try Hashtbl.find cache r with Not_found -> let f,l = match r with | IndRef (kn,i) -> mkInd (pop_kn kn,i), KNmap.find kn knl | ConstructRef ((kn,i),j) -> mkConstruct ((pop_kn kn,i),j), KNmap.find kn knl | ConstRef cst -> mkConst (pop_con cst), Cmap.find cst cstl in let c = mkApp (f, Array.map mkVar l) in Hashtbl.add cache r c; (* has raised Not_found if not in work_list *) c let update_case_info ci modlist = try let ind, n = match kind_of_term (share (IndRef ci.ci_ind) modlist) with | App (f,l) -> (destInd f, Array.length l) | Ind ind -> ind, 0 | _ -> assert false in { ci with ci_ind = ind; ci_npar = ci.ci_npar + n } with Not_found -> ci let empty_modlist = (Cmap.empty, KNmap.empty) let expmod_constr modlist c = let rec substrec c = match kind_of_term c with | Case (ci,p,t,br) -> map_constr substrec (mkCase (update_case_info ci modlist,p,t,br)) | Ind ind -> (try share (IndRef ind) modlist with | Not_found -> map_constr substrec c) | Construct cstr -> (try share (ConstructRef cstr) modlist with | Not_found -> map_constr substrec c) | Const cst -> (try share (ConstRef cst) modlist with | Not_found -> map_constr substrec c) | _ -> map_constr substrec c in if modlist = empty_modlist then c else under_outer_cast nf_betaiota (substrec c) let abstract_constant_type = List.fold_left (fun c d -> mkNamedProd_wo_LetIn d c) let abstract_constant_body = List.fold_left (fun c d -> mkNamedLambda_or_LetIn d c) type recipe = { d_from : constant_body; d_abstract : named_context; d_modlist : work_list } let on_body f = Option.map (fun c -> Declarations.from_val (f (Declarations.force c))) let cook_constant env r = let cb = r.d_from in let hyps = Sign.map_named_context (expmod_constr r.d_modlist) r.d_abstract in let body = on_body (fun c -> abstract_constant_body (expmod_constr r.d_modlist c) hyps) cb.const_body in let typ = match cb.const_type with | NonPolymorphicType t -> let typ = abstract_constant_type (expmod_constr r.d_modlist t) hyps in NonPolymorphicType typ | PolymorphicArity (ctx,s) -> let t = mkArity (ctx,Type s.poly_level) in let typ = abstract_constant_type (expmod_constr r.d_modlist t) hyps in let j = make_judge (force (Option.get body)) typ in Typeops.make_polymorphic_if_constant_for_ind env j in let boxed = Cemitcodes.is_boxed cb.const_body_code in (body, typ, cb.const_constraints, cb.const_opaque, boxed,false)
null
https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/kernel/cooking.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** i $Id: cooking.ml 10877 2008-04-30 21:58:41Z herbelin $ i s Cooking the constants. has raised Not_found if not in work_list
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Pp open Util open Names open Term open Sign open Declarations open Environ open Reduction type work_list = identifier array Cmap.t * identifier array KNmap.t let dirpath_prefix p = match repr_dirpath p with | [] -> anomaly "dirpath_prefix: empty dirpath" | _::l -> make_dirpath l let pop_kn kn = let (mp,dir,l) = Names.repr_kn kn in Names.make_kn mp (dirpath_prefix dir) l let pop_con con = let (mp,dir,l) = Names.repr_con con in Names.make_con mp (dirpath_prefix dir) l type my_global_reference = | ConstRef of constant | IndRef of inductive | ConstructRef of constructor let cache = (Hashtbl.create 13 : (my_global_reference, constr) Hashtbl.t) let clear_cooking_sharing () = Hashtbl.clear cache let share r (cstl,knl) = try Hashtbl.find cache r with Not_found -> let f,l = match r with | IndRef (kn,i) -> mkInd (pop_kn kn,i), KNmap.find kn knl | ConstructRef ((kn,i),j) -> mkConstruct ((pop_kn kn,i),j), KNmap.find kn knl | ConstRef cst -> mkConst (pop_con cst), Cmap.find cst cstl in let c = mkApp (f, Array.map mkVar l) in Hashtbl.add cache r c; c let update_case_info ci modlist = try let ind, n = match kind_of_term (share (IndRef ci.ci_ind) modlist) with | App (f,l) -> (destInd f, Array.length l) | Ind ind -> ind, 0 | _ -> assert false in { ci with ci_ind = ind; ci_npar = ci.ci_npar + n } with Not_found -> ci let empty_modlist = (Cmap.empty, KNmap.empty) let expmod_constr modlist c = let rec substrec c = match kind_of_term c with | Case (ci,p,t,br) -> map_constr substrec (mkCase (update_case_info ci modlist,p,t,br)) | Ind ind -> (try share (IndRef ind) modlist with | Not_found -> map_constr substrec c) | Construct cstr -> (try share (ConstructRef cstr) modlist with | Not_found -> map_constr substrec c) | Const cst -> (try share (ConstRef cst) modlist with | Not_found -> map_constr substrec c) | _ -> map_constr substrec c in if modlist = empty_modlist then c else under_outer_cast nf_betaiota (substrec c) let abstract_constant_type = List.fold_left (fun c d -> mkNamedProd_wo_LetIn d c) let abstract_constant_body = List.fold_left (fun c d -> mkNamedLambda_or_LetIn d c) type recipe = { d_from : constant_body; d_abstract : named_context; d_modlist : work_list } let on_body f = Option.map (fun c -> Declarations.from_val (f (Declarations.force c))) let cook_constant env r = let cb = r.d_from in let hyps = Sign.map_named_context (expmod_constr r.d_modlist) r.d_abstract in let body = on_body (fun c -> abstract_constant_body (expmod_constr r.d_modlist c) hyps) cb.const_body in let typ = match cb.const_type with | NonPolymorphicType t -> let typ = abstract_constant_type (expmod_constr r.d_modlist t) hyps in NonPolymorphicType typ | PolymorphicArity (ctx,s) -> let t = mkArity (ctx,Type s.poly_level) in let typ = abstract_constant_type (expmod_constr r.d_modlist t) hyps in let j = make_judge (force (Option.get body)) typ in Typeops.make_polymorphic_if_constant_for_ind env j in let boxed = Cemitcodes.is_boxed cb.const_body_code in (body, typ, cb.const_constraints, cb.const_opaque, boxed,false)
b28eeb2cff378e6b658c93b686d772880eae5c7b2def9292927c185e6c607a0a
cnuernber/dtype-next
gtol_insn.clj
(ns tech.v3.tensor.dimensions.gtol-insn (:require [tech.v3.datatype.base :as dtype] [insn.core :as insn] [camel-snake-kebab.core :as csk]) (:import [java.util.function Function] [java.util List Map HashMap ArrayList] [java.lang.reflect Constructor] [tech.v3.datatype Buffer LongReader])) (defn- ast-symbol-access [ary-name dim-idx] {:ary-name ary-name :dim-idx dim-idx}) (defn- ast-instance-const-fn-access [ary-name dim-idx fn-name] {:ary-name ary-name :dim-idx dim-idx :fn-name fn-name}) (defn- make-symbol [symbol-stem dim-idx] (ast-symbol-access symbol-stem dim-idx)) (defn elemwise-ast [dim-idx direct? offsets? broadcast? trivial-stride? most-rapidly-changing-index? least-rapidly-changing-index?] (let [shape (make-symbol :shape dim-idx) stride (make-symbol :stride dim-idx) offset (make-symbol :offset dim-idx) shape-ecount-stride (make-symbol :shape-ecount-stride dim-idx) idx (if most-rapidly-changing-index? `~'idx `(~'quot ~'idx ~shape-ecount-stride)) offset-idx (if offsets? `(~'+ ~idx ~offset) `~idx) shape-ecount (if direct? `~shape (ast-instance-const-fn-access :shape dim-idx :lsize)) idx-bcast (if (or offsets? broadcast? (not least-rapidly-changing-index?)) `(~'rem ~offset-idx ~shape-ecount) `~offset-idx) elem-idx (if direct? `~idx-bcast `(.read ~shape ~idx-bcast))] (if trivial-stride? `~elem-idx `(~'* ~elem-idx ~stride)))) (defn signature->ast [signature] (let [n-dims (long (:n-dims signature)) direct-vec (:direct-vec signature) offsets? (:offsets? signature) trivial-last-stride? (:trivial-last-stride? signature) broadcast? (:broadcast? signature)] {:signature signature :ast (if (= n-dims 1) (elemwise-ast 0 (direct-vec 0) offsets? broadcast? trivial-last-stride? true true) (let [n-dims-dec (dec n-dims)] (->> (range n-dims) (map (fn [dim-idx] (let [dim-idx (long dim-idx) least-rapidly-changing-index? (== dim-idx 0) ;;This optimization removes the 'rem' on the most ;;significant dimension. Valid if we aren't ;;broadcasting most-rapidly-changing-index? (and (not broadcast?) (== dim-idx n-dims-dec)) trivial-stride? (and most-rapidly-changing-index? trivial-last-stride?)] (elemwise-ast dim-idx (direct-vec dim-idx) offsets? broadcast? trivial-stride? most-rapidly-changing-index? least-rapidly-changing-index?)))) (apply list '+))))})) (def constructor-args (let [name-map {:stride :strides :shape-ecount :shape-ecounts :shape-ecount-stride :shape-ecount-strides :offset :offsets}] (->> [:shape :stride :offset :shape-ecount :shape-ecount-stride] (map-indexed (fn [idx argname] inc because arg0 is ' this ' object [argname {:arg-idx (inc (long idx)) :ary-name (get name-map argname argname) :name (csk/->camelCase (name argname))}])) (into {})))) (defn- rectify-shape-entry [shape-entry] (if (number? shape-entry) (long shape-entry) (dtype/->reader shape-entry))) (defn reduced-dims->constructor-args [{:keys [shape strides offsets shape-ecounts shape-ecount-strides]}] (let [argmap {:shape (object-array (map rectify-shape-entry shape)) :strides (long-array strides) :offsets (long-array offsets) :shape-ecounts (long-array shape-ecounts) :shape-ecount-strides (long-array shape-ecount-strides)}] (->> (vals constructor-args) (map (fn [{:keys [ary-name]}] (if-let [carg (ary-name argmap)] carg (when-not (= ary-name :offsets) (throw (Exception. (format "Failed to find constructor argument %s" ary-name))))))) (object-array)))) (defn bool->str ^String [bval] (if bval "T" "F")) (defn direct-vec->str ^String [^List dvec] (let [builder (StringBuilder.) iter (.iterator dvec)] (loop [continue? (.hasNext iter)] (when continue? (let [next-val (.next iter)] (.append builder (bool->str next-val)) (recur (.hasNext iter))))) (.toString builder))) (defn ast-sig->class-name [{:keys [signature]}] (format "GToL%d%sOff%sBcast%sTrivLastS%s" (:n-dims signature) (direct-vec->str (:direct-vec signature)) (bool->str (:offsets? signature)) (bool->str (:broadcast? signature)) (bool->str (:trivial-last-stride? signature)))) (defmulti apply-ast-fn! (fn [ast ^Map _fields ^List _instructions] (first ast))) (defn ensure-field! [{:keys [ary-name dim-idx] :as field} ^Map fields] (-> (.computeIfAbsent fields field (reify Function (apply [this field] (assoc field :field-idx (.size fields) :name (if (:fn-name field) (format "%s%d-%s" (csk/->camelCase (name ary-name)) dim-idx (csk/->camelCase (name (:fn-name field)))) (format "%s%d" (csk/->camelCase (name ary-name)) dim-idx)))))) :name)) (defn push-arg! [ast fields ^List instructions] (cond (= 'idx ast) (.add instructions [:lload 1]) (map? ast) (do (.add instructions [:aload 0]) (.add instructions [:getfield :this (ensure-field! ast fields) :long])) (seq ast) (apply-ast-fn! ast fields instructions) :else (throw (Exception. (format "Unrecognized ast element: %s" ast))))) (defn reduce-math-op! [math-op ast ^Map fields ^List instructions] (reduce (fn [prev-arg arg] (push-arg! arg fields instructions) (when-not (nil? prev-arg) (.add instructions [math-op])) arg) nil (rest ast))) (defmethod apply-ast-fn! '+ [ast fields instructions] (reduce-math-op! :ladd ast fields instructions)) (defmethod apply-ast-fn! '* [ast fields instructions] (reduce-math-op! :lmul ast fields instructions)) (defmethod apply-ast-fn! 'quot [ast fields instructions] (reduce-math-op! :ldiv ast fields instructions)) (defmethod apply-ast-fn! 'rem [ast fields instructions] (reduce-math-op! :lrem ast fields instructions)) (defmethod apply-ast-fn! '.read [ast ^Map fields ^List instructions] (when-not (= 3 (count ast)) (throw (Exception. (format "Invalid .read ast: %s" ast)))) (let [[_opname this-obj idx] ast] (.add instructions [:aload 0]) (.add instructions [:getfield :this (ensure-field! this-obj fields) Buffer]) (push-arg! idx fields instructions) (.add instructions [:invokeinterface Buffer "readLong"]))) (defmethod apply-ast-fn! '.lsize [ast ^Map fields ^List instructions] (when-not (= 2 (count ast)) (throw (Exception. (format "Invalid .read ast: %s" ast)))) (let [[_opname this-obj] ast] (.add instructions [:aload 0]) (.add instructions [:getfield :this (ensure-field! this-obj fields) Buffer]) (.add instructions [:invokeinterface Buffer "lsize"]))) (defn eval-read-ast! "Eval the read to isns instructions" [ast ^Map fields ^List instructions] The ast could be ' idx (if (= ast 'idx) (push-arg! ast fields instructions) (apply-ast-fn! ast fields instructions)) (.add instructions [:lreturn])) (defn emit-fields [shape-scalar-vec ^Map fields] (concat (->> (vals fields) (sort-by :name) (mapv (fn [{:keys [name _field-idx ary-name dim-idx fn-name]}] (if (and (= ary-name :shape) (not (shape-scalar-vec dim-idx))) (if fn-name {:flags #{:public :final} :name name :type :long} {:flags #{:public :final} :name name :type Buffer}) {:flags #{:public :final} :name name :type :long})))) [{:flags #{:public :final} :name "nElems" :type :long}])) (defn carg-idx ^long [argname] (if-let [idx-val (get-in constructor-args [argname :arg-idx])] (long idx-val) (throw (Exception. (format "Unable to find %s in %s" argname (keys constructor-args)))))) (defn load-constructor-arg [shape-scalar-vec {:keys [ary-name _field-idx name dim-idx fn-name]}] (let [carg-idx (carg-idx ary-name)] (if (= ary-name :shape) (if (not (shape-scalar-vec dim-idx)) (if fn-name [[:aload 0] [:aload carg-idx] [:ldc (int dim-idx)] [:aaload] [:checkcast Buffer] [:invokeinterface Buffer (clojure.core/name fn-name)] [:putfield :this name :long]] [[:aload 0] [:aload carg-idx] [:ldc (int dim-idx)] [:aaload] [:checkcast Buffer] [:putfield :this name Buffer]]) [[:aload 0] [:aload carg-idx] [:ldc (int dim-idx)] [:aaload] [:checkcast Long] [:invokevirtual Long "longValue"] [:putfield :this name :long]]) [[:aload 0] [:aload carg-idx] [:ldc (int dim-idx)] [:laload] [:putfield :this name :long]]))) (defn emit-constructor [shape-type-vec ^Map fields] (concat [[:aload 0] [:invokespecial :super :init [:void]]] (->> (vals fields) (sort-by :name) (mapcat (partial load-constructor-arg shape-type-vec))) [[:aload 0] [:aload 4] [:ldc (int 0)] [:laload] [:aload 5] [:ldc (int 0)] [:laload] [:lmul] [:putfield :this "nElems" :long] [:return]])) (defn gen-ast-class-def [{:keys [signature ast] :as ast-data}] (let [cname (ast-sig->class-name ast-data) pkg-symbol (symbol (format "tech.v3.datatype.%s" cname)) ;;map of name->field-data fields (HashMap.) read-instructions (ArrayList.) ;;Which of the shape items are scalars ;;they are either scalars or readers. shape-scalar-vec (:direct-vec signature)] (eval-read-ast! ast fields read-instructions) {:name pkg-symbol :interfaces [LongReader] :fields (vec (emit-fields shape-scalar-vec fields)) :methods [{:flags #{:public} :name :init :desc [(Class/forName "[Ljava.lang.Object;") (Class/forName "[J") (Class/forName "[J") (Class/forName "[J") (Class/forName "[J") :void] :emit (vec (emit-constructor shape-scalar-vec fields))} {:flags #{:public} :name "lsize" :desc [:long] :emit [[:aload 0] [:getfield :this "nElems" :long] [:lreturn]]} {:flags #{:public} :name "readLong" :desc [:long :long] :emit (vec read-instructions)}]})) (defn generate-constructor "Given a signature, return a fucntion that, given the reduced dimensions returns a implementation of a long reader that maps a global dimension to a local dimension." [signature] (let [ast-data (signature->ast signature) class-def (gen-ast-class-def ast-data)] (try ;;nested so we capture the class definition (let [^Class class-obj (insn/define class-def) ^Constructor first-constructor (first (.getDeclaredConstructors class-obj))] #(try (let [constructor-args (reduced-dims->constructor-args %)] (.newInstance first-constructor constructor-args)) (catch Throwable e (throw (ex-info (format "Error instantiating ast object: %s\n%s" e (with-out-str (println (:ast ast-data)))) {:error e :class-def class-def :signature signature}))))) (catch Throwable e (throw (ex-info (format "Error generating ast object: %s\n%s" e (with-out-str (println (:ast ast-data)))) {:error e :class-def class-def :signature signature}))))))
null
https://raw.githubusercontent.com/cnuernber/dtype-next/4e43212942aafa0145640cf6b655bb83855f567d/src/tech/v3/tensor/dimensions/gtol_insn.clj
clojure
This optimization removes the 'rem' on the most significant dimension. Valid if we aren't broadcasting map of name->field-data Which of the shape items are scalars they are either scalars or readers. nested so we capture the class definition
(ns tech.v3.tensor.dimensions.gtol-insn (:require [tech.v3.datatype.base :as dtype] [insn.core :as insn] [camel-snake-kebab.core :as csk]) (:import [java.util.function Function] [java.util List Map HashMap ArrayList] [java.lang.reflect Constructor] [tech.v3.datatype Buffer LongReader])) (defn- ast-symbol-access [ary-name dim-idx] {:ary-name ary-name :dim-idx dim-idx}) (defn- ast-instance-const-fn-access [ary-name dim-idx fn-name] {:ary-name ary-name :dim-idx dim-idx :fn-name fn-name}) (defn- make-symbol [symbol-stem dim-idx] (ast-symbol-access symbol-stem dim-idx)) (defn elemwise-ast [dim-idx direct? offsets? broadcast? trivial-stride? most-rapidly-changing-index? least-rapidly-changing-index?] (let [shape (make-symbol :shape dim-idx) stride (make-symbol :stride dim-idx) offset (make-symbol :offset dim-idx) shape-ecount-stride (make-symbol :shape-ecount-stride dim-idx) idx (if most-rapidly-changing-index? `~'idx `(~'quot ~'idx ~shape-ecount-stride)) offset-idx (if offsets? `(~'+ ~idx ~offset) `~idx) shape-ecount (if direct? `~shape (ast-instance-const-fn-access :shape dim-idx :lsize)) idx-bcast (if (or offsets? broadcast? (not least-rapidly-changing-index?)) `(~'rem ~offset-idx ~shape-ecount) `~offset-idx) elem-idx (if direct? `~idx-bcast `(.read ~shape ~idx-bcast))] (if trivial-stride? `~elem-idx `(~'* ~elem-idx ~stride)))) (defn signature->ast [signature] (let [n-dims (long (:n-dims signature)) direct-vec (:direct-vec signature) offsets? (:offsets? signature) trivial-last-stride? (:trivial-last-stride? signature) broadcast? (:broadcast? signature)] {:signature signature :ast (if (= n-dims 1) (elemwise-ast 0 (direct-vec 0) offsets? broadcast? trivial-last-stride? true true) (let [n-dims-dec (dec n-dims)] (->> (range n-dims) (map (fn [dim-idx] (let [dim-idx (long dim-idx) least-rapidly-changing-index? (== dim-idx 0) most-rapidly-changing-index? (and (not broadcast?) (== dim-idx n-dims-dec)) trivial-stride? (and most-rapidly-changing-index? trivial-last-stride?)] (elemwise-ast dim-idx (direct-vec dim-idx) offsets? broadcast? trivial-stride? most-rapidly-changing-index? least-rapidly-changing-index?)))) (apply list '+))))})) (def constructor-args (let [name-map {:stride :strides :shape-ecount :shape-ecounts :shape-ecount-stride :shape-ecount-strides :offset :offsets}] (->> [:shape :stride :offset :shape-ecount :shape-ecount-stride] (map-indexed (fn [idx argname] inc because arg0 is ' this ' object [argname {:arg-idx (inc (long idx)) :ary-name (get name-map argname argname) :name (csk/->camelCase (name argname))}])) (into {})))) (defn- rectify-shape-entry [shape-entry] (if (number? shape-entry) (long shape-entry) (dtype/->reader shape-entry))) (defn reduced-dims->constructor-args [{:keys [shape strides offsets shape-ecounts shape-ecount-strides]}] (let [argmap {:shape (object-array (map rectify-shape-entry shape)) :strides (long-array strides) :offsets (long-array offsets) :shape-ecounts (long-array shape-ecounts) :shape-ecount-strides (long-array shape-ecount-strides)}] (->> (vals constructor-args) (map (fn [{:keys [ary-name]}] (if-let [carg (ary-name argmap)] carg (when-not (= ary-name :offsets) (throw (Exception. (format "Failed to find constructor argument %s" ary-name))))))) (object-array)))) (defn bool->str ^String [bval] (if bval "T" "F")) (defn direct-vec->str ^String [^List dvec] (let [builder (StringBuilder.) iter (.iterator dvec)] (loop [continue? (.hasNext iter)] (when continue? (let [next-val (.next iter)] (.append builder (bool->str next-val)) (recur (.hasNext iter))))) (.toString builder))) (defn ast-sig->class-name [{:keys [signature]}] (format "GToL%d%sOff%sBcast%sTrivLastS%s" (:n-dims signature) (direct-vec->str (:direct-vec signature)) (bool->str (:offsets? signature)) (bool->str (:broadcast? signature)) (bool->str (:trivial-last-stride? signature)))) (defmulti apply-ast-fn! (fn [ast ^Map _fields ^List _instructions] (first ast))) (defn ensure-field! [{:keys [ary-name dim-idx] :as field} ^Map fields] (-> (.computeIfAbsent fields field (reify Function (apply [this field] (assoc field :field-idx (.size fields) :name (if (:fn-name field) (format "%s%d-%s" (csk/->camelCase (name ary-name)) dim-idx (csk/->camelCase (name (:fn-name field)))) (format "%s%d" (csk/->camelCase (name ary-name)) dim-idx)))))) :name)) (defn push-arg! [ast fields ^List instructions] (cond (= 'idx ast) (.add instructions [:lload 1]) (map? ast) (do (.add instructions [:aload 0]) (.add instructions [:getfield :this (ensure-field! ast fields) :long])) (seq ast) (apply-ast-fn! ast fields instructions) :else (throw (Exception. (format "Unrecognized ast element: %s" ast))))) (defn reduce-math-op! [math-op ast ^Map fields ^List instructions] (reduce (fn [prev-arg arg] (push-arg! arg fields instructions) (when-not (nil? prev-arg) (.add instructions [math-op])) arg) nil (rest ast))) (defmethod apply-ast-fn! '+ [ast fields instructions] (reduce-math-op! :ladd ast fields instructions)) (defmethod apply-ast-fn! '* [ast fields instructions] (reduce-math-op! :lmul ast fields instructions)) (defmethod apply-ast-fn! 'quot [ast fields instructions] (reduce-math-op! :ldiv ast fields instructions)) (defmethod apply-ast-fn! 'rem [ast fields instructions] (reduce-math-op! :lrem ast fields instructions)) (defmethod apply-ast-fn! '.read [ast ^Map fields ^List instructions] (when-not (= 3 (count ast)) (throw (Exception. (format "Invalid .read ast: %s" ast)))) (let [[_opname this-obj idx] ast] (.add instructions [:aload 0]) (.add instructions [:getfield :this (ensure-field! this-obj fields) Buffer]) (push-arg! idx fields instructions) (.add instructions [:invokeinterface Buffer "readLong"]))) (defmethod apply-ast-fn! '.lsize [ast ^Map fields ^List instructions] (when-not (= 2 (count ast)) (throw (Exception. (format "Invalid .read ast: %s" ast)))) (let [[_opname this-obj] ast] (.add instructions [:aload 0]) (.add instructions [:getfield :this (ensure-field! this-obj fields) Buffer]) (.add instructions [:invokeinterface Buffer "lsize"]))) (defn eval-read-ast! "Eval the read to isns instructions" [ast ^Map fields ^List instructions] The ast could be ' idx (if (= ast 'idx) (push-arg! ast fields instructions) (apply-ast-fn! ast fields instructions)) (.add instructions [:lreturn])) (defn emit-fields [shape-scalar-vec ^Map fields] (concat (->> (vals fields) (sort-by :name) (mapv (fn [{:keys [name _field-idx ary-name dim-idx fn-name]}] (if (and (= ary-name :shape) (not (shape-scalar-vec dim-idx))) (if fn-name {:flags #{:public :final} :name name :type :long} {:flags #{:public :final} :name name :type Buffer}) {:flags #{:public :final} :name name :type :long})))) [{:flags #{:public :final} :name "nElems" :type :long}])) (defn carg-idx ^long [argname] (if-let [idx-val (get-in constructor-args [argname :arg-idx])] (long idx-val) (throw (Exception. (format "Unable to find %s in %s" argname (keys constructor-args)))))) (defn load-constructor-arg [shape-scalar-vec {:keys [ary-name _field-idx name dim-idx fn-name]}] (let [carg-idx (carg-idx ary-name)] (if (= ary-name :shape) (if (not (shape-scalar-vec dim-idx)) (if fn-name [[:aload 0] [:aload carg-idx] [:ldc (int dim-idx)] [:aaload] [:checkcast Buffer] [:invokeinterface Buffer (clojure.core/name fn-name)] [:putfield :this name :long]] [[:aload 0] [:aload carg-idx] [:ldc (int dim-idx)] [:aaload] [:checkcast Buffer] [:putfield :this name Buffer]]) [[:aload 0] [:aload carg-idx] [:ldc (int dim-idx)] [:aaload] [:checkcast Long] [:invokevirtual Long "longValue"] [:putfield :this name :long]]) [[:aload 0] [:aload carg-idx] [:ldc (int dim-idx)] [:laload] [:putfield :this name :long]]))) (defn emit-constructor [shape-type-vec ^Map fields] (concat [[:aload 0] [:invokespecial :super :init [:void]]] (->> (vals fields) (sort-by :name) (mapcat (partial load-constructor-arg shape-type-vec))) [[:aload 0] [:aload 4] [:ldc (int 0)] [:laload] [:aload 5] [:ldc (int 0)] [:laload] [:lmul] [:putfield :this "nElems" :long] [:return]])) (defn gen-ast-class-def [{:keys [signature ast] :as ast-data}] (let [cname (ast-sig->class-name ast-data) pkg-symbol (symbol (format "tech.v3.datatype.%s" cname)) fields (HashMap.) read-instructions (ArrayList.) shape-scalar-vec (:direct-vec signature)] (eval-read-ast! ast fields read-instructions) {:name pkg-symbol :interfaces [LongReader] :fields (vec (emit-fields shape-scalar-vec fields)) :methods [{:flags #{:public} :name :init :desc [(Class/forName "[Ljava.lang.Object;") (Class/forName "[J") (Class/forName "[J") (Class/forName "[J") (Class/forName "[J") :void] :emit (vec (emit-constructor shape-scalar-vec fields))} {:flags #{:public} :name "lsize" :desc [:long] :emit [[:aload 0] [:getfield :this "nElems" :long] [:lreturn]]} {:flags #{:public} :name "readLong" :desc [:long :long] :emit (vec read-instructions)}]})) (defn generate-constructor "Given a signature, return a fucntion that, given the reduced dimensions returns a implementation of a long reader that maps a global dimension to a local dimension." [signature] (let [ast-data (signature->ast signature) class-def (gen-ast-class-def ast-data)] (try (let [^Class class-obj (insn/define class-def) ^Constructor first-constructor (first (.getDeclaredConstructors class-obj))] #(try (let [constructor-args (reduced-dims->constructor-args %)] (.newInstance first-constructor constructor-args)) (catch Throwable e (throw (ex-info (format "Error instantiating ast object: %s\n%s" e (with-out-str (println (:ast ast-data)))) {:error e :class-def class-def :signature signature}))))) (catch Throwable e (throw (ex-info (format "Error generating ast object: %s\n%s" e (with-out-str (println (:ast ast-data)))) {:error e :class-def class-def :signature signature}))))))
6ee1a735a2432bdc46e74aca96d41ccc73687f5a82737e6f15fe5fd35ac1c0d8
nasa/pvslib
patch-20210623-pvsio-fix.lisp
;; groundeval/cl2pvs.lisp (defmethod cl2pvs* (sexpr (type type-name) context) (declare (ignore context)) (if (tc-eq (find-supertype type) *number*) (cond ((rationalp sexpr) (mk-number-expr sexpr)) ( ( floatp sexpr)(mk - number - expr sexpr ) ) ((floatp sexpr)(mk-number-expr (rationalize sexpr))) (t (error 'cl2pvs-error :sexpr sexpr :type type))) (if (tc-eq (find-supertype type) *boolean*) (if sexpr (if (eq sexpr *cant-translate*) (error 'cl2pvs-error :sexpr sexpr :type type) *true*) *false*) (error 'cl2pvs-error :sexpr sexpr :type type))))
null
https://raw.githubusercontent.com/nasa/pvslib/c273c4ea5b0b5bb067ab7e2862185f9624add745/pvs-patches/patch-20210623-pvsio-fix.lisp
lisp
groundeval/cl2pvs.lisp
(defmethod cl2pvs* (sexpr (type type-name) context) (declare (ignore context)) (if (tc-eq (find-supertype type) *number*) (cond ((rationalp sexpr) (mk-number-expr sexpr)) ( ( floatp sexpr)(mk - number - expr sexpr ) ) ((floatp sexpr)(mk-number-expr (rationalize sexpr))) (t (error 'cl2pvs-error :sexpr sexpr :type type))) (if (tc-eq (find-supertype type) *boolean*) (if sexpr (if (eq sexpr *cant-translate*) (error 'cl2pvs-error :sexpr sexpr :type type) *true*) *false*) (error 'cl2pvs-error :sexpr sexpr :type type))))
ec6ddde3e203e3fdb1672bc9dd672ea2bd944efd64c62759876d94e002f5acb6
fragnix/fragnix
Control.Monad.Trans.Except.hs
# LANGUAGE Haskell98 # # LINE 1 " Control / Monad / Trans / Except.hs " # # LANGUAGE CPP # {-# LANGUAGE Safe #-} # LANGUAGE AutoDeriveTypeable # ----------------------------------------------------------------------------- -- | Module : Control . . Trans . Except Copyright : ( C ) 2013 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : -- Stability : experimental -- Portability : portable -- -- This monad transformer extends a monad with the ability throw exceptions. -- -- A sequence of actions terminates normally, producing a value, -- only if none of the actions in the sequence throws an exception. If one throws an exception , the rest of the sequence is skipped and -- the composite action exits with that exception. -- -- If the value of the exception is not required, the variant in " Control . . Trans . Maybe " may be used instead . ----------------------------------------------------------------------------- module Control.Monad.Trans.Except ( -- * The Except monad Except, except, runExcept, mapExcept, withExcept, -- * The ExceptT monad transformer ExceptT(ExceptT), runExceptT, mapExceptT, withExceptT, -- * Exception operations throwE, catchE, -- * Lifting other operations liftCallCC, liftListen, liftPass, ) where import Control.Monad.IO.Class import Control.Monad.Signatures import Control.Monad.Trans.Class import Data.Functor.Classes import Data.Functor.Identity import Control.Applicative import Control.Monad import qualified Control.Monad.Fail as Fail import Control.Monad.Fix import Control.Monad.Zip (MonadZip(mzipWith)) import Data.Foldable (Foldable(foldMap)) import Data.Monoid import Data.Traversable (Traversable(traverse)) -- | The parameterizable exception monad. -- -- Computations are either exceptions or normal values. -- The ' return ' function returns a normal value , while exits on the first exception . For a variant that continues after an error -- and collects all the errors, see 'Control.Applicative.Lift.Errors'. type Except e = ExceptT e Identity -- | Constructor for computations in the exception monad. ( The inverse of ' runExcept ' ) . except :: Either e a -> Except e a except m = ExceptT (Identity m) {-# INLINE except #-} -- | Extractor for computations in the exception monad. -- (The inverse of 'except'). runExcept :: Except e a -> Either e a runExcept (ExceptT m) = runIdentity m # INLINE runExcept # -- | Map the unwrapped computation using the given function. -- * @'runExcept ' ( ' mapExcept ' f m ) = f ( ' runExcept ' m)@ mapExcept :: (Either e a -> Either e' b) -> Except e a -> Except e' b mapExcept f = mapExceptT (Identity . f . runIdentity) # INLINE mapExcept # -- | Transform any exceptions thrown by the computation using the given -- function (a specialization of 'withExceptT'). withExcept :: (e -> e') -> Except e a -> Except e' a withExcept = withExceptT # INLINE withExcept # -- | A monad transformer that adds exceptions to other monads. -- @ExceptT@ constructs a monad parameterized over two things : -- -- * e - The exception type. -- -- * m - The inner monad. -- -- The 'return' function yields a computation that produces the given value , while sequences two subcomputations , exiting on the first exception . newtype ExceptT e m a = ExceptT (m (Either e a)) instance (Eq e, Eq1 m) => Eq1 (ExceptT e m) where liftEq eq (ExceptT x) (ExceptT y) = liftEq (liftEq eq) x y {-# INLINE liftEq #-} instance (Ord e, Ord1 m) => Ord1 (ExceptT e m) where liftCompare comp (ExceptT x) (ExceptT y) = liftCompare (liftCompare comp) x y # INLINE liftCompare # instance (Read e, Read1 m) => Read1 (ExceptT e m) where liftReadsPrec rp rl = readsData $ readsUnaryWith (liftReadsPrec rp' rl') "ExceptT" ExceptT where rp' = liftReadsPrec rp rl rl' = liftReadList rp rl instance (Show e, Show1 m) => Show1 (ExceptT e m) where liftShowsPrec sp sl d (ExceptT m) = showsUnaryWith (liftShowsPrec sp' sl') "ExceptT" d m where sp' = liftShowsPrec sp sl sl' = liftShowList sp sl instance (Eq e, Eq1 m, Eq a) => Eq (ExceptT e m a) where (==) = eq1 instance (Ord e, Ord1 m, Ord a) => Ord (ExceptT e m a) where compare = compare1 instance (Read e, Read1 m, Read a) => Read (ExceptT e m a) where readsPrec = readsPrec1 instance (Show e, Show1 m, Show a) => Show (ExceptT e m a) where showsPrec = showsPrec1 -- | The inverse of 'ExceptT'. runExceptT :: ExceptT e m a -> m (Either e a) runExceptT (ExceptT m) = m # INLINE runExceptT # -- | Map the unwrapped computation using the given function. -- -- * @'runExceptT' ('mapExceptT' f m) = f ('runExceptT' m)@ mapExceptT :: (m (Either e a) -> n (Either e' b)) -> ExceptT e m a -> ExceptT e' n b mapExceptT f m = ExceptT $ f (runExceptT m) # INLINE mapExceptT # -- | Transform any exceptions thrown by the computation using the -- given function. withExceptT :: (Functor m) => (e -> e') -> ExceptT e m a -> ExceptT e' m a withExceptT f = mapExceptT $ fmap $ either (Left . f) Right # INLINE withExceptT # instance (Functor m) => Functor (ExceptT e m) where fmap f = ExceptT . fmap (fmap f) . runExceptT # INLINE fmap # instance (Foldable f) => Foldable (ExceptT e f) where foldMap f (ExceptT a) = foldMap (either (const mempty) f) a {-# INLINE foldMap #-} instance (Traversable f) => Traversable (ExceptT e f) where traverse f (ExceptT a) = ExceptT <$> traverse (either (pure . Left) (fmap Right . f)) a {-# INLINE traverse #-} instance (Functor m, Monad m) => Applicative (ExceptT e m) where pure a = ExceptT $ return (Right a) # INLINE pure # ExceptT f <*> ExceptT v = ExceptT $ do mf <- f case mf of Left e -> return (Left e) Right k -> do mv <- v case mv of Left e -> return (Left e) Right x -> return (Right (k x)) # INLINEABLE ( < * > ) # instance (Functor m, Monad m, Monoid e) => Alternative (ExceptT e m) where empty = ExceptT $ return (Left mempty) {-# INLINE empty #-} ExceptT mx <|> ExceptT my = ExceptT $ do ex <- mx case ex of Left e -> liftM (either (Left . mappend e) Right) my Right x -> return (Right x) # INLINEABLE ( < | > ) # instance (Monad m) => Monad (ExceptT e m) where m >>= k = ExceptT $ do a <- runExceptT m case a of Left e -> return (Left e) Right x -> runExceptT (k x) {-# INLINE (>>=) #-} fail = ExceptT . fail # INLINE fail # instance (Fail.MonadFail m) => Fail.MonadFail (ExceptT e m) where fail = ExceptT . Fail.fail # INLINE fail # instance (Monad m, Monoid e) => MonadPlus (ExceptT e m) where mzero = ExceptT $ return (Left mempty) # INLINE mzero # ExceptT mx `mplus` ExceptT my = ExceptT $ do ex <- mx case ex of Left e -> liftM (either (Left . mappend e) Right) my Right x -> return (Right x) # INLINEABLE mplus # instance (MonadFix m) => MonadFix (ExceptT e m) where mfix f = ExceptT (mfix (runExceptT . f . either (const bomb) id)) where bomb = error "mfix (ExceptT): inner computation returned Left value" # INLINE mfix # instance MonadTrans (ExceptT e) where lift = ExceptT . liftM Right # INLINE lift # instance (MonadIO m) => MonadIO (ExceptT e m) where liftIO = lift . liftIO # INLINE liftIO # instance (MonadZip m) => MonadZip (ExceptT e m) where mzipWith f (ExceptT a) (ExceptT b) = ExceptT $ mzipWith (liftA2 f) a b # INLINE mzipWith # -- | Signal an exception value @e@. -- -- * @'runExceptT' ('throwE' e) = 'return' ('Left' e)@ -- -- * @'throwE' e >>= m = 'throwE' e@ throwE :: (Monad m) => e -> ExceptT e m a throwE = ExceptT . return . Left # INLINE throwE # -- | Handle an exception. -- -- * @'catchE' h ('lift' m) = 'lift' m@ -- -- * @'catchE' h ('throwE' e) = h e@ catchE :: (Monad m) => ExceptT e m a -- ^ the inner computation -> (e -> ExceptT e' m a) -- ^ a handler for exceptions in the inner -- computation -> ExceptT e' m a m `catchE` h = ExceptT $ do a <- runExceptT m case a of Left l -> runExceptT (h l) Right r -> return (Right r) # INLINE catchE # -- | Lift a @callCC@ operation to the new monad. liftCallCC :: CallCC m (Either e a) (Either e b) -> CallCC (ExceptT e m) a b liftCallCC callCC f = ExceptT $ callCC $ \ c -> runExceptT (f (\ a -> ExceptT $ c (Right a))) # INLINE liftCallCC # -- | Lift a @listen@ operation to the new monad. liftListen :: (Monad m) => Listen w m (Either e a) -> Listen w (ExceptT e m) a liftListen listen = mapExceptT $ \ m -> do (a, w) <- listen m return $! fmap (\ r -> (r, w)) a # INLINE liftListen # | Lift a @pass@ operation to the new monad . liftPass :: (Monad m) => Pass w m (Either e a) -> Pass w (ExceptT e m) a liftPass pass = mapExceptT $ \ m -> pass $ do a <- m return $! case a of Left l -> (Left l, id) Right (r, f) -> (Right r, f) # INLINE liftPass #
null
https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/scotty/Control.Monad.Trans.Except.hs
haskell
# LANGUAGE Safe # --------------------------------------------------------------------------- | License : BSD-style (see the file LICENSE) Maintainer : Stability : experimental Portability : portable This monad transformer extends a monad with the ability throw exceptions. A sequence of actions terminates normally, producing a value, only if none of the actions in the sequence throws an exception. the composite action exits with that exception. If the value of the exception is not required, the variant in --------------------------------------------------------------------------- * The Except monad * The ExceptT monad transformer * Exception operations * Lifting other operations | The parameterizable exception monad. Computations are either exceptions or normal values. and collects all the errors, see 'Control.Applicative.Lift.Errors'. | Constructor for computations in the exception monad. # INLINE except # | Extractor for computations in the exception monad. (The inverse of 'except'). | Map the unwrapped computation using the given function. | Transform any exceptions thrown by the computation using the given function (a specialization of 'withExceptT'). | A monad transformer that adds exceptions to other monads. * e - The exception type. * m - The inner monad. The 'return' function yields a computation that produces the given # INLINE liftEq # | The inverse of 'ExceptT'. | Map the unwrapped computation using the given function. * @'runExceptT' ('mapExceptT' f m) = f ('runExceptT' m)@ | Transform any exceptions thrown by the computation using the given function. # INLINE foldMap # # INLINE traverse # # INLINE empty # # INLINE (>>=) # | Signal an exception value @e@. * @'runExceptT' ('throwE' e) = 'return' ('Left' e)@ * @'throwE' e >>= m = 'throwE' e@ | Handle an exception. * @'catchE' h ('lift' m) = 'lift' m@ * @'catchE' h ('throwE' e) = h e@ ^ the inner computation ^ a handler for exceptions in the inner computation | Lift a @callCC@ operation to the new monad. | Lift a @listen@ operation to the new monad.
# LANGUAGE Haskell98 # # LINE 1 " Control / Monad / Trans / Except.hs " # # LANGUAGE CPP # # LANGUAGE AutoDeriveTypeable # Module : Control . . Trans . Except Copyright : ( C ) 2013 If one throws an exception , the rest of the sequence is skipped and " Control . . Trans . Maybe " may be used instead . module Control.Monad.Trans.Except ( Except, except, runExcept, mapExcept, withExcept, ExceptT(ExceptT), runExceptT, mapExceptT, withExceptT, throwE, catchE, liftCallCC, liftListen, liftPass, ) where import Control.Monad.IO.Class import Control.Monad.Signatures import Control.Monad.Trans.Class import Data.Functor.Classes import Data.Functor.Identity import Control.Applicative import Control.Monad import qualified Control.Monad.Fail as Fail import Control.Monad.Fix import Control.Monad.Zip (MonadZip(mzipWith)) import Data.Foldable (Foldable(foldMap)) import Data.Monoid import Data.Traversable (Traversable(traverse)) The ' return ' function returns a normal value , while exits on the first exception . For a variant that continues after an error type Except e = ExceptT e Identity ( The inverse of ' runExcept ' ) . except :: Either e a -> Except e a except m = ExceptT (Identity m) runExcept :: Except e a -> Either e a runExcept (ExceptT m) = runIdentity m # INLINE runExcept # * @'runExcept ' ( ' mapExcept ' f m ) = f ( ' runExcept ' m)@ mapExcept :: (Either e a -> Either e' b) -> Except e a -> Except e' b mapExcept f = mapExceptT (Identity . f . runIdentity) # INLINE mapExcept # withExcept :: (e -> e') -> Except e a -> Except e' a withExcept = withExceptT # INLINE withExcept # @ExceptT@ constructs a monad parameterized over two things : value , while sequences two subcomputations , exiting on the first exception . newtype ExceptT e m a = ExceptT (m (Either e a)) instance (Eq e, Eq1 m) => Eq1 (ExceptT e m) where liftEq eq (ExceptT x) (ExceptT y) = liftEq (liftEq eq) x y instance (Ord e, Ord1 m) => Ord1 (ExceptT e m) where liftCompare comp (ExceptT x) (ExceptT y) = liftCompare (liftCompare comp) x y # INLINE liftCompare # instance (Read e, Read1 m) => Read1 (ExceptT e m) where liftReadsPrec rp rl = readsData $ readsUnaryWith (liftReadsPrec rp' rl') "ExceptT" ExceptT where rp' = liftReadsPrec rp rl rl' = liftReadList rp rl instance (Show e, Show1 m) => Show1 (ExceptT e m) where liftShowsPrec sp sl d (ExceptT m) = showsUnaryWith (liftShowsPrec sp' sl') "ExceptT" d m where sp' = liftShowsPrec sp sl sl' = liftShowList sp sl instance (Eq e, Eq1 m, Eq a) => Eq (ExceptT e m a) where (==) = eq1 instance (Ord e, Ord1 m, Ord a) => Ord (ExceptT e m a) where compare = compare1 instance (Read e, Read1 m, Read a) => Read (ExceptT e m a) where readsPrec = readsPrec1 instance (Show e, Show1 m, Show a) => Show (ExceptT e m a) where showsPrec = showsPrec1 runExceptT :: ExceptT e m a -> m (Either e a) runExceptT (ExceptT m) = m # INLINE runExceptT # mapExceptT :: (m (Either e a) -> n (Either e' b)) -> ExceptT e m a -> ExceptT e' n b mapExceptT f m = ExceptT $ f (runExceptT m) # INLINE mapExceptT # withExceptT :: (Functor m) => (e -> e') -> ExceptT e m a -> ExceptT e' m a withExceptT f = mapExceptT $ fmap $ either (Left . f) Right # INLINE withExceptT # instance (Functor m) => Functor (ExceptT e m) where fmap f = ExceptT . fmap (fmap f) . runExceptT # INLINE fmap # instance (Foldable f) => Foldable (ExceptT e f) where foldMap f (ExceptT a) = foldMap (either (const mempty) f) a instance (Traversable f) => Traversable (ExceptT e f) where traverse f (ExceptT a) = ExceptT <$> traverse (either (pure . Left) (fmap Right . f)) a instance (Functor m, Monad m) => Applicative (ExceptT e m) where pure a = ExceptT $ return (Right a) # INLINE pure # ExceptT f <*> ExceptT v = ExceptT $ do mf <- f case mf of Left e -> return (Left e) Right k -> do mv <- v case mv of Left e -> return (Left e) Right x -> return (Right (k x)) # INLINEABLE ( < * > ) # instance (Functor m, Monad m, Monoid e) => Alternative (ExceptT e m) where empty = ExceptT $ return (Left mempty) ExceptT mx <|> ExceptT my = ExceptT $ do ex <- mx case ex of Left e -> liftM (either (Left . mappend e) Right) my Right x -> return (Right x) # INLINEABLE ( < | > ) # instance (Monad m) => Monad (ExceptT e m) where m >>= k = ExceptT $ do a <- runExceptT m case a of Left e -> return (Left e) Right x -> runExceptT (k x) fail = ExceptT . fail # INLINE fail # instance (Fail.MonadFail m) => Fail.MonadFail (ExceptT e m) where fail = ExceptT . Fail.fail # INLINE fail # instance (Monad m, Monoid e) => MonadPlus (ExceptT e m) where mzero = ExceptT $ return (Left mempty) # INLINE mzero # ExceptT mx `mplus` ExceptT my = ExceptT $ do ex <- mx case ex of Left e -> liftM (either (Left . mappend e) Right) my Right x -> return (Right x) # INLINEABLE mplus # instance (MonadFix m) => MonadFix (ExceptT e m) where mfix f = ExceptT (mfix (runExceptT . f . either (const bomb) id)) where bomb = error "mfix (ExceptT): inner computation returned Left value" # INLINE mfix # instance MonadTrans (ExceptT e) where lift = ExceptT . liftM Right # INLINE lift # instance (MonadIO m) => MonadIO (ExceptT e m) where liftIO = lift . liftIO # INLINE liftIO # instance (MonadZip m) => MonadZip (ExceptT e m) where mzipWith f (ExceptT a) (ExceptT b) = ExceptT $ mzipWith (liftA2 f) a b # INLINE mzipWith # throwE :: (Monad m) => e -> ExceptT e m a throwE = ExceptT . return . Left # INLINE throwE # catchE :: (Monad m) => -> ExceptT e' m a m `catchE` h = ExceptT $ do a <- runExceptT m case a of Left l -> runExceptT (h l) Right r -> return (Right r) # INLINE catchE # liftCallCC :: CallCC m (Either e a) (Either e b) -> CallCC (ExceptT e m) a b liftCallCC callCC f = ExceptT $ callCC $ \ c -> runExceptT (f (\ a -> ExceptT $ c (Right a))) # INLINE liftCallCC # liftListen :: (Monad m) => Listen w m (Either e a) -> Listen w (ExceptT e m) a liftListen listen = mapExceptT $ \ m -> do (a, w) <- listen m return $! fmap (\ r -> (r, w)) a # INLINE liftListen # | Lift a @pass@ operation to the new monad . liftPass :: (Monad m) => Pass w m (Either e a) -> Pass w (ExceptT e m) a liftPass pass = mapExceptT $ \ m -> pass $ do a <- m return $! case a of Left l -> (Left l, id) Right (r, f) -> (Right r, f) # INLINE liftPass #
9afeabd94bd38dcf92c1406d7b3c95409617a37eaa8ee14b4a97e1ffb29d37e0
freiksenet/cl-zmq
package.lisp
(cl:defpackage #:zmq.tests (:use #:cl #:fiveam) (:export #:run-tests))
null
https://raw.githubusercontent.com/freiksenet/cl-zmq/9acd1faa1ea3b2e322241aa126c57ba3a8907b79/tests/package.lisp
lisp
(cl:defpackage #:zmq.tests (:use #:cl #:fiveam) (:export #:run-tests))
ae510f517d0cc6656a351ec2c5dd836c1281a3d3469af9e310c2380fe6a279a8
jappeace/cut-the-crap
Options.hs
# LANGUAGE DataKinds # # LANGUAGE TypeApplications # {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DeriveAnyClass #-} -- | This module defines which options exists, and provides -- functions for parsing cli options. module Cut.Options ( parseProgram , specifyTracks , getOutFileName -- * Program options , ProgramOptions(..) , gnerate_sub_prism , listen_cut_prism -- * fileio, deal with input output files , FileIO , lc_fileio , in_file , out_file , work_dir -- * listen cut, options for video editing by audio , ListenCutOptionsT , ListenCutOptions , silent_treshold , detect_margin , voice_track , music_track , silent_duration , cut_noise , voice_track_map -- * input source prisms , InputSource , input_src_remote , input_src_local_file -- * defaults , simpleOptions ) where import Control.Lens hiding (argument) import Data.Generics.Product.Fields import Data.Generics.Sum import qualified Data.Text as Text import Data.Text.Lens import GHC.Generics (Generic) import Options.Applicative import Network.URI simpleFileIO :: (FileIO InputSource) simpleFileIO = FileIO { fi_inFile = LocalFile "in.mkv" , fi_outFile = "out.mkv" , fi_workDir = Nothing } type s t a b = forall f = > ( a - > f b ) - > s - > f t in_file :: Lens (FileIO a) (FileIO b) a b in_file = field @"fi_inFile" out_file :: Lens' (FileIO a) FilePath out_file = field @"fi_outFile" work_dir :: Lens' (FileIO a) (Maybe FilePath) work_dir = field @"fi_workDir" simpleOptions :: ListenCutOptionsT InputSource simpleOptions = ListenCutOptions { lc_fileIO = simpleFileIO , lc_silentTreshold = _Just # def_silent , lc_detectMargin = _Just # def_detect_margin , lc_voiceTrack = _Just # def_voice_track , lc_musicTrack = Nothing , lc_silentDuration = _Just # def_duration , lc_cutNoise = def_cut_noise } getOutFileName :: ListenCutOptionsT a -> FilePath getOutFileName = reverse . takeWhile ('/' /=) . reverse . view (lc_fileio . out_file) -- | Deals with having an input file and a target output file data FileIO a = FileIO { fi_inFile :: a , fi_outFile :: FilePath , fi_workDir :: Maybe FilePath -- ^ for consistency (or debugging) we may want to specify this. } deriving (Show, Generic) type ListenCutOptions = ListenCutOptionsT FilePath -- | Cut out by listening to sound options data ListenCutOptionsT a = ListenCutOptions { lc_fileIO :: FileIO a , lc_silentTreshold :: Maybe Double , lc_silentDuration :: Maybe Double , lc_detectMargin :: Maybe Double , lc_voiceTrack :: Maybe Int , lc_musicTrack :: Maybe Int , lc_cutNoise :: Bool } deriving (Show, Generic) data ProgramOptions a = ListenCut (ListenCutOptionsT a) | GenerateSubtitles (FileIO a) deriving (Show, Generic) listen_cut_prism :: Prism' (ProgramOptions a) (ListenCutOptionsT a) listen_cut_prism = _Ctor @"ListenCut" gnerate_sub_prism :: Prism' (ProgramOptions a) (FileIO a) gnerate_sub_prism = _Ctor @"GenerateSubtitles" def_voice_track :: Int def_voice_track = 1 def_detect_margin :: Double def_detect_margin = def_duration / 2 def_cut_noise :: Bool def_cut_noise = False def_silent :: Double def_silent = 0.0125 def_duration :: Double def_duration = 0.5 def_voice :: Int def_voice = 1 lc_fileio :: Lens (ListenCutOptionsT a) (ListenCutOptionsT b) (FileIO a) (FileIO b) lc_fileio = field @"lc_fileIO" detect_margin :: Lens' (ListenCutOptionsT a) Double detect_margin = field @"lc_detectMargin" . non def_detect_margin silent_treshold :: Lens' (ListenCutOptionsT a) Double silent_treshold = field @"lc_silentTreshold" . non def_silent silent_duration :: Lens' (ListenCutOptionsT a) Double silent_duration = field @"lc_silentDuration" . non def_duration voice_track :: Lens' (ListenCutOptionsT a) Int voice_track = field @"lc_voiceTrack" . non def_voice music_track :: Lens' (ListenCutOptionsT a) (Maybe Int) music_track = field @"lc_musicTrack" cut_noise :: Lens' (ListenCutOptionsT a) Bool cut_noise = field @"lc_cutNoise" voice_track_map :: (ListenCutOptionsT a) -> Text.Text voice_track_map = mappend "0:" . view (voice_track . to show . packed) specifyTracks :: (ListenCutOptionsT a) -> [Text.Text] specifyTracks options = [ "-map" , "0:0" , "-map" -- then copy only the voice track , voice_track_map options ] data InputSource = LocalFile FilePath | Remote URI deriving (Show, Generic) input_src_local_file :: Prism' InputSource FilePath input_src_local_file = _Ctor @"LocalFile" input_src_remote :: Prism' InputSource URI input_src_remote = _Ctor @"Remote" readFileSource :: ReadM InputSource readFileSource = eitherReader $ \x -> maybe (Left "unlikely error") Right $ (Remote <$> parseURI x) <|> Just (LocalFile x) parseFile :: Parser (FileIO InputSource) parseFile = FileIO <$> argument readFileSource (metavar "INPUT" <> help "The input video, either a file or a uri. This program has tested best with the mkv container type, you can use ffmpeg to convert containers, for example \"ffmpeg -i input.mp4 output.mkv\", see -convert-media-file-formats") <*> argument str (metavar "OUTPUT_FILE" <> help "The output name without format" <> value "out.mkv" <> showDefault) <*> optional (option str ( long "workDir" <> help "If specified will use this as temporary directory to store intermeidate files in, good for debugging. Needs to be absolute" ) ) parseProgram :: Parser (ProgramOptions InputSource) parseProgram = subparser $ command "listen" (info (ListenCut <$> parseSound) $ progDesc "Cut out by listening to sound options. We listen for silences and cut out the parts that are silenced.") <> command "subtitles" (info (GenerateSubtitles <$> parseFile) $ progDesc "[alpha] Generate subtitles for a video. This is an intermediate step towards developing human speech detection and background noise.") parseSound :: Parser (ListenCutOptionsT InputSource) parseSound = ListenCutOptions <$> parseFile <*> optional (option auto ( long "silentTreshold" <> help "The treshold for determining intersting sections, closer to zero is detects more audio (n: -filters.html#silencedetect), you may wish to tweak this variable a bit depending on your mic." <> value def_silent <> showDefault ) ) <*> optional (option auto ( long "silentDuration" <> help "The duration before something can be considered a silence (-filters.html#silencedetect)" <> value def_duration <> showDefault ) ) <*> optional (option auto (long "detectMargin" <> help "Margin seconds around detection" <> value def_detect_margin <> showDefault ) ) <*> optional (option auto (long "voiceTrack" <> help "The track to detect the silences upon" <> value def_voice_track <> showDefault) ) <*> optional (option auto (long "musicTrack" <> help "The track to integrate")) <*> switch (long "cutNoise" <> help "Do the opposite: Cut noise instead of silence")
null
https://raw.githubusercontent.com/jappeace/cut-the-crap/f3baca164edb91681259dcaa07bd23983dc17ba2/src/Cut/Options.hs
haskell
# LANGUAGE TypeOperators # # LANGUAGE DeriveAnyClass # | This module defines which options exists, and provides functions for parsing cli options. * Program options * fileio, deal with input output files * listen cut, options for video editing by audio * input source prisms * defaults | Deals with having an input file and a target output file ^ for consistency (or debugging) we may want to specify this. | Cut out by listening to sound options then copy only the voice track
# LANGUAGE DataKinds # # LANGUAGE TypeApplications # module Cut.Options ( parseProgram , specifyTracks , getOutFileName , ProgramOptions(..) , gnerate_sub_prism , listen_cut_prism , FileIO , lc_fileio , in_file , out_file , work_dir , ListenCutOptionsT , ListenCutOptions , silent_treshold , detect_margin , voice_track , music_track , silent_duration , cut_noise , voice_track_map , InputSource , input_src_remote , input_src_local_file , simpleOptions ) where import Control.Lens hiding (argument) import Data.Generics.Product.Fields import Data.Generics.Sum import qualified Data.Text as Text import Data.Text.Lens import GHC.Generics (Generic) import Options.Applicative import Network.URI simpleFileIO :: (FileIO InputSource) simpleFileIO = FileIO { fi_inFile = LocalFile "in.mkv" , fi_outFile = "out.mkv" , fi_workDir = Nothing } type s t a b = forall f = > ( a - > f b ) - > s - > f t in_file :: Lens (FileIO a) (FileIO b) a b in_file = field @"fi_inFile" out_file :: Lens' (FileIO a) FilePath out_file = field @"fi_outFile" work_dir :: Lens' (FileIO a) (Maybe FilePath) work_dir = field @"fi_workDir" simpleOptions :: ListenCutOptionsT InputSource simpleOptions = ListenCutOptions { lc_fileIO = simpleFileIO , lc_silentTreshold = _Just # def_silent , lc_detectMargin = _Just # def_detect_margin , lc_voiceTrack = _Just # def_voice_track , lc_musicTrack = Nothing , lc_silentDuration = _Just # def_duration , lc_cutNoise = def_cut_noise } getOutFileName :: ListenCutOptionsT a -> FilePath getOutFileName = reverse . takeWhile ('/' /=) . reverse . view (lc_fileio . out_file) data FileIO a = FileIO { fi_inFile :: a , fi_outFile :: FilePath } deriving (Show, Generic) type ListenCutOptions = ListenCutOptionsT FilePath data ListenCutOptionsT a = ListenCutOptions { lc_fileIO :: FileIO a , lc_silentTreshold :: Maybe Double , lc_silentDuration :: Maybe Double , lc_detectMargin :: Maybe Double , lc_voiceTrack :: Maybe Int , lc_musicTrack :: Maybe Int , lc_cutNoise :: Bool } deriving (Show, Generic) data ProgramOptions a = ListenCut (ListenCutOptionsT a) | GenerateSubtitles (FileIO a) deriving (Show, Generic) listen_cut_prism :: Prism' (ProgramOptions a) (ListenCutOptionsT a) listen_cut_prism = _Ctor @"ListenCut" gnerate_sub_prism :: Prism' (ProgramOptions a) (FileIO a) gnerate_sub_prism = _Ctor @"GenerateSubtitles" def_voice_track :: Int def_voice_track = 1 def_detect_margin :: Double def_detect_margin = def_duration / 2 def_cut_noise :: Bool def_cut_noise = False def_silent :: Double def_silent = 0.0125 def_duration :: Double def_duration = 0.5 def_voice :: Int def_voice = 1 lc_fileio :: Lens (ListenCutOptionsT a) (ListenCutOptionsT b) (FileIO a) (FileIO b) lc_fileio = field @"lc_fileIO" detect_margin :: Lens' (ListenCutOptionsT a) Double detect_margin = field @"lc_detectMargin" . non def_detect_margin silent_treshold :: Lens' (ListenCutOptionsT a) Double silent_treshold = field @"lc_silentTreshold" . non def_silent silent_duration :: Lens' (ListenCutOptionsT a) Double silent_duration = field @"lc_silentDuration" . non def_duration voice_track :: Lens' (ListenCutOptionsT a) Int voice_track = field @"lc_voiceTrack" . non def_voice music_track :: Lens' (ListenCutOptionsT a) (Maybe Int) music_track = field @"lc_musicTrack" cut_noise :: Lens' (ListenCutOptionsT a) Bool cut_noise = field @"lc_cutNoise" voice_track_map :: (ListenCutOptionsT a) -> Text.Text voice_track_map = mappend "0:" . view (voice_track . to show . packed) specifyTracks :: (ListenCutOptionsT a) -> [Text.Text] specifyTracks options = [ "-map" , "0:0" , voice_track_map options ] data InputSource = LocalFile FilePath | Remote URI deriving (Show, Generic) input_src_local_file :: Prism' InputSource FilePath input_src_local_file = _Ctor @"LocalFile" input_src_remote :: Prism' InputSource URI input_src_remote = _Ctor @"Remote" readFileSource :: ReadM InputSource readFileSource = eitherReader $ \x -> maybe (Left "unlikely error") Right $ (Remote <$> parseURI x) <|> Just (LocalFile x) parseFile :: Parser (FileIO InputSource) parseFile = FileIO <$> argument readFileSource (metavar "INPUT" <> help "The input video, either a file or a uri. This program has tested best with the mkv container type, you can use ffmpeg to convert containers, for example \"ffmpeg -i input.mp4 output.mkv\", see -convert-media-file-formats") <*> argument str (metavar "OUTPUT_FILE" <> help "The output name without format" <> value "out.mkv" <> showDefault) <*> optional (option str ( long "workDir" <> help "If specified will use this as temporary directory to store intermeidate files in, good for debugging. Needs to be absolute" ) ) parseProgram :: Parser (ProgramOptions InputSource) parseProgram = subparser $ command "listen" (info (ListenCut <$> parseSound) $ progDesc "Cut out by listening to sound options. We listen for silences and cut out the parts that are silenced.") <> command "subtitles" (info (GenerateSubtitles <$> parseFile) $ progDesc "[alpha] Generate subtitles for a video. This is an intermediate step towards developing human speech detection and background noise.") parseSound :: Parser (ListenCutOptionsT InputSource) parseSound = ListenCutOptions <$> parseFile <*> optional (option auto ( long "silentTreshold" <> help "The treshold for determining intersting sections, closer to zero is detects more audio (n: -filters.html#silencedetect), you may wish to tweak this variable a bit depending on your mic." <> value def_silent <> showDefault ) ) <*> optional (option auto ( long "silentDuration" <> help "The duration before something can be considered a silence (-filters.html#silencedetect)" <> value def_duration <> showDefault ) ) <*> optional (option auto (long "detectMargin" <> help "Margin seconds around detection" <> value def_detect_margin <> showDefault ) ) <*> optional (option auto (long "voiceTrack" <> help "The track to detect the silences upon" <> value def_voice_track <> showDefault) ) <*> optional (option auto (long "musicTrack" <> help "The track to integrate")) <*> switch (long "cutNoise" <> help "Do the opposite: Cut noise instead of silence")
fa156c36fd045a43a1dbd3aa03a9e4768fe449aef3118b29e2a839e65cd3ee84
google/ormolu
list-comprehensions-out.hs
foo x = [a | a <- x] bar x y = [(a, b) | a <- x, even a, b <- y, a != b] barbaz x y z w = [ (a, b, c, d) -- Foo | a <- x -- Bar , any even [a, b] , c <- z * z ^ 2 -- Bar baz , d <- w + w -- Baz bar , all even [ a , b , c , d ] ]
null
https://raw.githubusercontent.com/google/ormolu/ffdf145bbdf917d54a3ef4951fc2655e35847ff0/data/examples/declaration/value/function/list-comprehensions-out.hs
haskell
Foo Bar Bar baz Baz bar
foo x = [a | a <- x] bar x y = [(a, b) | a <- x, even a, b <- y, a != b] barbaz x y z w = | a <- , any even [a, b] , c <- z , d <- w , all even [ a , b , c , d ] ]
74aec3bcd937b77c0bf5e23db259885ddd5f6183ac9df094488e3a6c1250e6dc
ocaml/ocaml
odoc_info.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 2001 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. *) (* *) (**************************************************************************) (** Interface to the information collected in source files. *) (** The different kinds of element references. *) type ref_kind = Odoc_types.ref_kind = RK_module | RK_module_type | RK_class | RK_class_type | RK_value | RK_type | RK_extension | RK_exception | RK_attribute | RK_method | RK_section of text | RK_recfield | RK_const and text_element = Odoc_types.text_element = | Raw of string (** Raw text. *) | Code of string (** The string is source code. *) | CodePre of string (** The string is pre-formatted source code. *) | Verbatim of string (** String 'as is'. *) | Bold of text (** Text in bold style. *) | Italic of text (** Text in italic. *) | Emphasize of text (** Emphasized text. *) | Center of text (** Centered text. *) | Left of text (** Left alignment. *) | Right of text (** Right alignment. *) | List of text list (** A list. *) | Enum of text list (** An enumerated list. *) | Newline (** To force a line break. *) | Block of text (** Like html's block quote. *) | Title of int * string option * text (** Style number, optional label, and text. *) | Latex of string (** A string for latex. *) | Link of string * text (** A reference string and the link text. *) | Ref of string * ref_kind option * text option (** A reference to an element. Complete name and kind. An optional text can be given to display this text instead of the element name.*) * . | Subscript of text (** Subscripts. *) | Module_list of string list (** The table of the given modules with their abstract. *) | Index_list (** The links to the various indexes (values, types, ...) *) | Custom of string * text (** to extend \{foo syntax *) | Target of string * string (** (target, code) : to specify code specific to a target format *) (** A text is a list of [text_element]. The order matters. *) and text = text_element list * The different forms of references in \@see tags . type see_ref = Odoc_types.see_ref = See_url of string | See_file of string | See_doc of string (** Raised when parsing string to build a {!Odoc_info.text} structure. [(line, char, string)] *) exception Text_syntax of int * int * string * The information in a \@see tag . type see = see_ref * text (** Parameter name and description. *) type param = (string * text) (** Raised exception name and description. *) type raised_exception = (string * text) type alert = Odoc_types.alert = { alert_name : string; alert_payload : string option; } * Information in a special comment @before 3.12 \@before information was not present . @before 3.12 \@before information was not present. *) type info = Odoc_types.info = { i_desc : text option; (** The description text. *) i_authors : string list; (** The list of authors in \@author tags. *) i_version : string option; (** The string in the \@version tag. *) * The list of \@see tags . * The string in the \@since tag . i_before : (string * text) list ; (** the version number and text in \@before tag *) i_deprecated : text option; (** The description text of the \@deprecated tag. *) i_params : param list; (** The list of parameter descriptions. *) i_raised_exceptions : raised_exception list; (** The list of raised exceptions. *) i_return_value : text option; (** The description text of the return value. *) * A text associated to a custom @-tag . i_alerts : alert list ; (** Alerts associated to the same item. Not from special comments. *) } (** Location of elements in implementation and interface files. *) type location = Odoc_types.location = { loc_impl : Location.t option ; (** implementation location *) loc_inter : Location.t option ; (** interface location *) } (** A dummy location. *) val dummy_loc : location (** Representation of element names. *) module Name : sig type t = string (** Access to the simple name. *) val simple : t -> t (** [concat t1 t2] returns the concatenation of [t1] and [t2].*) val concat : t -> t -> t * Return the depth of the name , i.e. the number of levels to the root . Example : [ depth " Toto.Tutu.name " ] = [ 3 ] . Example : [depth "Toto.Tutu.name"] = [3]. *) val depth : t -> int * Take two names n1 and n2 = n3.n4 and return n4 if n3 = n1 or else n2 . val get_relative : t -> t -> t * Take two names n1 and n2 = n3.n4 and return n4 if n3 = n1 and n1 < > " " or else n2 . val get_relative_opt : t -> t -> t (** Return the name of the 'father' (like [dirname] for a file name).*) val father : t -> t end (** Representation and manipulation of method / function / class / module parameters.*) module Parameter : sig (** {1 Types} *) (** Representation of a simple parameter name *) type simple_name = Odoc_parameter.simple_name = { sn_name : string ; sn_type : Types.type_expr ; mutable sn_text : text option ; } (** Representation of parameter names. We need it to represent parameter names in tuples. The value [Tuple ([], t)] stands for an anonymous parameter.*) type param_info = Odoc_parameter.param_info = Simple_name of simple_name | Tuple of param_info list * Types.type_expr (** A parameter is just a param_info.*) type parameter = param_info * { 1 Functions } (** Access to the name as a string. For tuples, parentheses and commas are added. *) val complete_name : parameter -> string (** Access to the complete type. *) val typ : parameter -> Types.type_expr * Access to the list of names ; only one for a simple parameter , or a list for a tuple . a list for a tuple. *) val names : parameter -> string list (** Access to the description of a specific name. @raise Not_found if no description is associated to the given name. *) val desc_by_name : parameter -> string -> text option (** Access to the type of a specific name. @raise Not_found if no type is associated to the given name. *) val type_by_name : parameter -> string -> Types.type_expr end (** Representation and manipulation of extensions. *) module Extension : sig type private_flag = Odoc_extension.private_flag = Private | Public (** Used when the extension is a rebind of another extension, when we have [extension Xt = Target_xt].*) type extension_alias = Odoc_extension.extension_alias = { xa_name : Name.t ; (** The complete name of the target extension. *) mutable xa_xt : t_extension_constructor option ; (** The target extension, if we found it.*) } and t_extension_constructor = Odoc_extension.t_extension_constructor = { xt_name : Name.t ; xt_args: Odoc_type.constructor_args; xt_ret: Types.type_expr option ; (** the optional return type of the extension *) xt_type_extension: t_type_extension ; (** the type extension containing this constructor *) xt_alias: extension_alias option ; (** [None] when the extension is not a rebind. *) mutable xt_loc: Odoc_types.location ; mutable xt_text: Odoc_types.info option ; (** optional user description *) } and t_type_extension = Odoc_extension.t_type_extension = { mutable te_info : info option ; (** Information found in the optional associated comment. *) te_type_name : Name.t ; (** The type of the extension *) te_type_parameters : Types.type_expr list; te_private : private_flag ; mutable te_constructors: t_extension_constructor list; mutable te_loc : location ; mutable te_code : string option ; } (** Access to the extensions in a group. *) val extension_constructors : t_type_extension -> t_extension_constructor list end (** Representation and manipulation of exceptions. *) module Exception : sig (** Used when the exception is a rebind of another exception, when we have [exception Ex = Target_ex].*) type exception_alias = Odoc_exception.exception_alias = { ea_name : Name.t ; (** The complete name of the target exception. *) mutable ea_ex : t_exception option ; (** The target exception, if we found it.*) } and t_exception = Odoc_exception.t_exception = { ex_name : Name.t ; mutable ex_info : info option ; (** Information found in the optional associated comment. *) ex_args : Odoc_type.constructor_args; ex_ret : Types.type_expr option ; (** The optional return type of the exception. *) ex_alias : exception_alias option ; (** [None] when the exception is not a rebind. *) mutable ex_loc : location ; mutable ex_code : string option ; } end (** Representation and manipulation of types.*) module Type : sig type private_flag = Odoc_type.private_flag = Private | Public (** Description of a record type field. *) type record_field = Odoc_type.record_field = { rf_name : string ; (** Name of the field. *) rf_mutable : bool ; (** [true] if mutable. *) rf_type : Types.type_expr ; (** Type of the field. *) mutable rf_text : info option ; (** Optional description in the associated comment.*) } (** Description of a variant type constructor. *) type constructor_args = Odoc_type.constructor_args = | Cstr_record of record_field list | Cstr_tuple of Types.type_expr list type variant_constructor = Odoc_type.variant_constructor = { vc_name : string ; (** Name of the constructor. *) vc_args : constructor_args; vc_ret : Types.type_expr option ; mutable vc_text : info option ; (** Optional description in the associated comment. *) } (** The various kinds of a type. *) type type_kind = Odoc_type.type_kind = Type_abstract (** Type is abstract, for example [type t]. *) | Type_variant of variant_constructor list (** constructors *) | Type_record of record_field list (** fields *) | Type_open (** Type is open *) type object_field = Odoc_type.object_field = { of_name : string ; of_type : Types.type_expr ; mutable of_text : Odoc_types.info option ; (** optional user description *) } type type_manifest = Odoc_type.type_manifest = | Other of Types.type_expr (** Type manifest directly taken from Typedtree. *) | Object_type of object_field list (** Representation of a type. *) type t_type = Odoc_type.t_type = { ty_name : Name.t ; (** Complete name of the type. *) mutable ty_info : info option ; (** Information found in the optional associated comment. *) ty_parameters : (Types.type_expr * Types.Variance.t) list ; (** type parameters: (type, variance) *) ty_kind : type_kind; (** Type kind. *) ty_private : private_flag; (** Private or public type. *) ty_manifest : type_manifest option ; mutable ty_loc : location ; mutable ty_code : string option; } end (** Representation and manipulation of values, class attributes and class methods. *) module Value : sig (** Representation of a value. *) type t_value = Odoc_value.t_value = { val_name : Name.t ; (** Complete name of the value. *) mutable val_info : info option ; (** Information found in the optional associated comment. *) val_type : Types.type_expr ; (** Type of the value. *) val_recursive : bool ; (** [true] if the value is recursive. *) mutable val_parameters : Odoc_parameter.parameter list ; (** The parameters, if any. *) mutable val_code : string option ; (** The code of the value, if we had the only the implementation file. *) mutable val_loc : location ; } (** Representation of a class attribute. *) type t_attribute = Odoc_value.t_attribute = { att_value : t_value ; (** an attribute has almost all the same information as a value *) att_mutable : bool ; (** [true] if the attribute is mutable. *) att_virtual : bool ; (** [true] if the attribute is virtual. *) } (** Representation of a class method. *) type t_method = Odoc_value.t_method = { met_value : t_value ; (** a method has almost all the same information as a value *) met_private : bool ; (** [true] if the method is private.*) met_virtual : bool ; (** [true] if the method is virtual. *) } (** Return [true] if the value is a function, i.e. it has a functional type. *) val is_function : t_value -> bool (** Access to the description associated to the given parameter name.*) val value_parameter_text_by_name : t_value -> string -> text option end (** Representation and manipulation of classes and class types.*) module Class : sig (** {1 Types} *) (** To keep the order of elements in a class. *) type class_element = Odoc_class.class_element = Class_attribute of Value.t_attribute | Class_method of Value.t_method | Class_comment of text (** Used when we can reference a t_class or a t_class_type. *) type cct = Odoc_class.cct = Cl of t_class | Cltype of t_class_type * Types.type_expr list (** Class type and type parameters. *) and inherited_class = Odoc_class.inherited_class = { ic_name : Name.t ; (** Complete name of the inherited class. *) mutable ic_class : cct option ; (** The associated t_class or t_class_type. *) ic_text : text option ; (** The inheritance description, if any. *) } and class_apply = Odoc_class.class_apply = { capp_name : Name.t ; (** The complete name of the applied class. *) mutable capp_class : t_class option; (** The associated t_class if we found it. *) capp_params : Types.type_expr list; (** The type of expressions the class is applied to. *) capp_params_code : string list ; (** The code of these expressions. *) } and class_constr = Odoc_class.class_constr = { cco_name : Name.t ; (** The complete name of the applied class. *) mutable cco_class : cct option; (** The associated class or class type if we found it. *) cco_type_parameters : Types.type_expr list; (** The type parameters of the class, if needed. *) } and class_kind = Odoc_class.class_kind = Class_structure of inherited_class list * class_element list (** An explicit class structure, used in implementation and interface. *) | Class_apply of class_apply (** Application/alias of a class, used in implementation only. *) | Class_constr of class_constr (** A class used to give the type of the defined class, instead of a structure, used in interface only. For example, it will be used with the name [M1.M2....bar] when the class foo is defined like this : [class foo : int -> bar] *) | Class_constraint of class_kind * class_type_kind (** A class definition with a constraint. *) (** Representation of a class. *) and t_class = Odoc_class.t_class = { cl_name : Name.t ; (** Complete name of the class. *) mutable cl_info : info option ; (** Information found in the optional associated comment. *) cl_type : Types.class_type ; (** Type of the class. *) cl_type_parameters : Types.type_expr list ; (** Type parameters. *) cl_virtual : bool ; (** [true] when the class is virtual. *) mutable cl_kind : class_kind ; (** The way the class is defined. *) mutable cl_parameters : Parameter.parameter list ; (** The parameters of the class. *) mutable cl_loc : location ; } and class_type_alias = Odoc_class.class_type_alias = { cta_name : Name.t ; (** Complete name of the target class type. *) mutable cta_class : cct option ; (** The target t_class or t_class_type, if we found it.*) cta_type_parameters : Types.type_expr list ; (** The type parameters. FIXME : use strings? *) } and class_type_kind = Odoc_class.class_type_kind = Class_signature of inherited_class list * class_element list | Class_type of class_type_alias (** A class type eventually applied to type args. *) (** Representation of a class type. *) and t_class_type = Odoc_class.t_class_type = { clt_name : Name.t ; (** Complete name of the type. *) mutable clt_info : info option ; (** Information found in the optional associated comment. *) clt_type : Types.class_type ; clt_type_parameters : Types.type_expr list ; (** Type parameters. *) clt_virtual : bool ; (** [true] if the class type is virtual *) mutable clt_kind : class_type_kind ; (** The way the class type is defined. *) mutable clt_loc : location ; } * { 1 Functions } (** Access to the elements of a class. *) val class_elements : ?trans:bool -> t_class -> class_element list (** Access to the list of class attributes. *) val class_attributes : ?trans:bool -> t_class -> Value.t_attribute list (** Access to the description associated to the given class parameter name. *) val class_parameter_text_by_name : t_class -> string -> text option (** Access to the methods of a class. *) val class_methods : ?trans:bool -> t_class -> Value.t_method list (** Access to the comments of a class. *) val class_comments : ?trans:bool -> t_class -> text list (** Access to the elements of a class type. *) val class_type_elements : ?trans:bool -> t_class_type -> class_element list (** Access to the list of class type attributes. *) val class_type_attributes : ?trans:bool -> t_class_type -> Value.t_attribute list (** Access to the description associated to the given class type parameter name. *) val class_type_parameter_text_by_name : t_class_type -> string -> text option (** Access to the methods of a class type. *) val class_type_methods : ?trans:bool -> t_class_type -> Value.t_method list (** Access to the comments of a class type. *) val class_type_comments : ?trans:bool -> t_class_type -> text list end (** Representation and manipulation of modules and module types. *) module Module : sig (** {1 Types} *) (** To keep the order of elements in a module. *) type module_element = Odoc_module.module_element = Element_module of t_module | Element_module_type of t_module_type | Element_included_module of included_module | Element_class of Class.t_class | Element_class_type of Class.t_class_type | Element_value of Value.t_value | Element_type_extension of Extension.t_type_extension | Element_exception of Exception.t_exception | Element_type of Type.t_type | Element_module_comment of text (** Used where we can reference t_module or t_module_type. *) and mmt = Odoc_module.mmt = | Mod of t_module | Modtype of t_module_type and included_module = Odoc_module.included_module = { im_name : Name.t ; (** Complete name of the included module. *) mutable im_module : mmt option ; (** The included module or module type, if we found it. *) mutable im_info : Odoc_types.info option ; (** comment associated with the include directive *) } and module_alias = Odoc_module.module_alias = { ma_name : Name.t ; (** Complete name of the target module. *) mutable ma_module : mmt option ; (** The real module or module type if we could associate it. *) } and module_parameter = Odoc_module.module_parameter = { mp_name : string ; (** the name *) mp_type : Types.module_type option ; (** the type *) mp_type_code : string ; (** the original code *) mp_kind : module_type_kind ; (** the way the parameter was built *) } (** Different kinds of a module. *) and module_kind = Odoc_module.module_kind = | Module_struct of module_element list (** A complete module structure. *) | Module_alias of module_alias (** Complete name and corresponding module if we found it *) | Module_functor of module_parameter * module_kind (** A functor, with its parameter and the rest of its definition *) | Module_apply of module_kind * module_kind (** A module defined by application of a functor. *) | Module_apply_unit of module_kind (** A generative application of a functor. *) | Module_with of module_type_kind * string (** A module whose type is a with ... constraint. Should appear in interface files only. *) | Module_constraint of module_kind * module_type_kind (** A module constraint by a module type. *) | Module_typeof of string (** by now only the code of the module expression *) | Module_unpack of string * module_type_alias (** code of the expression and module type alias *) (** Representation of a module. *) and t_module = Odoc_module.t_module = { m_name : Name.t ; (** Complete name of the module. *) mutable m_type : Types.module_type ; (** The type of the module. *) mutable m_info : info option ; (** Information found in the optional associated comment. *) m_is_interface : bool ; (** [true] for modules read from interface files *) m_file : string ; (** The file the module is defined in. *) mutable m_kind : module_kind ; (** The way the module is defined. *) mutable m_loc : location ; mutable m_top_deps : Name.t list ; (** The toplevels module names this module depends on. *) mutable m_code : string option ; (** The whole code of the module *) mutable m_code_intf : string option ; (** The whole code of the interface of the module *) m_text_only : bool ; (** [true] if the module comes from a text file *) } and module_type_alias = Odoc_module.module_type_alias = { mta_name : Name.t ; (** Complete name of the target module type. *) mutable mta_module : t_module_type option ; (** The real module type if we could associate it. *) } (** Different kinds of module type. *) and module_type_kind = Odoc_module.module_type_kind = | Module_type_struct of module_element list (** A complete module signature. *) | Module_type_functor of module_parameter * module_type_kind (** A functor, with its parameter and the rest of its definition *) | Module_type_alias of module_type_alias (** Complete alias name and corresponding module type if we found it. *) | Module_type_with of module_type_kind * string (** The module type kind and the code of the with constraint. *) | Module_type_typeof of string (** by now only the code of the module expression *) (** Representation of a module type. *) and t_module_type = Odoc_module.t_module_type = { mt_name : Name.t ; (** Complete name of the module type. *) mutable mt_info : info option ; (** Information found in the optional associated comment. *) mutable mt_type : Types.module_type option ; (** [None] means that the module type is abstract. *) mt_is_interface : bool ; (** [true] for modules read from interface files. *) mt_file : string ; (** The file the module type is defined in. *) mutable mt_kind : module_type_kind option ; (** The way the module is defined. [None] means that module type is abstract. It is always [None] when the module type was extracted from the implementation file. That means module types are only analysed in interface files. *) mutable mt_loc : location ; } (** {1 Functions for modules} *) (** Access to the elements of a module. *) val module_elements : ?trans:bool -> t_module -> module_element list (** Access to the submodules of a module. *) val module_modules : ?trans:bool -> t_module -> t_module list (** Access to the module types of a module. *) val module_module_types : ?trans:bool -> t_module -> t_module_type list (** Access to the included modules of a module. *) val module_included_modules : ?trans:bool-> t_module -> included_module list (** Access to the type extensions of a module. *) val module_type_extensions : ?trans:bool-> t_module -> Extension.t_type_extension list (** Access to the exceptions of a module. *) val module_exceptions : ?trans:bool-> t_module -> Exception.t_exception list (** Access to the types of a module. *) val module_types : ?trans:bool-> t_module -> Type.t_type list (** Access to the values of a module. *) val module_values : ?trans:bool -> t_module -> Value.t_value list (** Access to functional values of a module. *) val module_functions : ?trans:bool-> t_module -> Value.t_value list (** Access to non-functional values of a module. *) val module_simple_values : ?trans:bool-> t_module -> Value.t_value list (** Access to the classes of a module. *) val module_classes : ?trans:bool-> t_module -> Class.t_class list (** Access to the class types of a module. *) val module_class_types : ?trans:bool-> t_module -> Class.t_class_type list (** The list of classes defined in this module and all its submodules and functors. *) val module_all_classes : ?trans:bool-> t_module -> Class.t_class list (** [true] if the module is functor. *) val module_is_functor : t_module -> bool (** The list of couples (module parameter, optional description). *) val module_parameters : ?trans:bool-> t_module -> (module_parameter * text option) list (** The list of module comments. *) val module_comments : ?trans:bool-> t_module -> text list (** {1 Functions for module types} *) (** Access to the elements of a module type. *) val module_type_elements : ?trans:bool-> t_module_type -> module_element list (** Access to the submodules of a module type. *) val module_type_modules : ?trans:bool-> t_module_type -> t_module list (** Access to the module types of a module type. *) val module_type_module_types : ?trans:bool-> t_module_type -> t_module_type list (** Access to the included modules of a module type. *) val module_type_included_modules : ?trans:bool-> t_module_type -> included_module list (** Access to the exceptions of a module type. *) val module_type_exceptions : ?trans:bool-> t_module_type -> Exception.t_exception list (** Access to the types of a module type. *) val module_type_types : ?trans:bool-> t_module_type -> Type.t_type list (** Access to the values of a module type. *) val module_type_values : ?trans:bool-> t_module_type -> Value.t_value list (** Access to functional values of a module type. *) val module_type_functions : ?trans:bool-> t_module_type -> Value.t_value list (** Access to non-functional values of a module type. *) val module_type_simple_values : ?trans:bool-> t_module_type -> Value.t_value list (** Access to the classes of a module type. *) val module_type_classes : ?trans:bool-> t_module_type -> Class.t_class list (** Access to the class types of a module type. *) val module_type_class_types : ?trans:bool-> t_module_type -> Class.t_class_type list (** The list of classes defined in this module type and all its submodules and functors. *) val module_type_all_classes : ?trans:bool-> t_module_type -> Class.t_class list (** [true] if the module type is functor. *) val module_type_is_functor : t_module_type -> bool (** The list of couples (module parameter, optional description). *) val module_type_parameters : ?trans:bool-> t_module_type -> (module_parameter * text option) list (** The list of module comments. *) val module_type_comments : ?trans:bool-> t_module_type -> text list end * { 2 Getting strings from values } (** This function is used to reset the names of type variables. It must be called when printing the whole type of a function, but not when printing the type of its parameters. Same for classes (call it) and methods and attributes (don't call it).*) val reset_type_names : unit -> unit (** [string_of_variance t variance] returns the variance and injectivity annotation (e.g ["+"] for covariance, ["-"] for contravariance, ["!-"] for injectivity) if the type [t] is abstract.*) val string_of_variance : Type.t_type -> Types.Variance.t -> string (** This function returns a string representing a Types.type_expr. *) val string_of_type_expr : Types.type_expr -> string (** @return a string to display the parameters of the given class, in the same form as the compiler. *) val string_of_class_params : Class.t_class -> string (** This function returns a string to represent the given list of types, with a given separator. *) val string_of_type_list : ?par: bool -> string -> Types.type_expr list -> string (** This function returns a string to represent the list of type parameters for the given type. *) val string_of_type_param_list : Type.t_type -> string (** This function returns a string to represent the list of type parameters for the given type extension. *) val string_of_type_extension_param_list : Extension.t_type_extension -> string (** This function returns a string to represent the given list of type parameters of a class or class type, with a given separator. *) val string_of_class_type_param_list : Types.type_expr list -> string (** This function returns a string representing a [Types.module_type]. @param complete indicates if we must print complete signatures or just [sig end]. Default is [false]. @param code if [complete = false] and the type contains something else than identificators and functors, then the given code is used. *) val string_of_module_type : ?code: string -> ?complete: bool -> Types.module_type -> string (** This function returns a string representing a [Types.class_type]. @param complete indicates if we must print complete signatures or just [object end]. Default is [false]. *) val string_of_class_type : ?complete: bool -> Types.class_type -> string (** Get a string from a text. *) val string_of_text : text -> string (** Get a string from an info structure. *) val string_of_info : info -> string (** @return a string to describe the given type. *) val string_of_type : Type.t_type -> string val string_of_record : Type.record_field list -> string (** @return a string to describe the given type extension. *) val string_of_type_extension : Extension.t_type_extension -> string (** @return a string to describe the given exception. *) val string_of_exception : Exception.t_exception -> string (** @return a string to describe the given value. *) val string_of_value : Value.t_value -> string (** @return a string to describe the given attribute. *) val string_of_attribute : Value.t_attribute -> string (** @return a string to describe the given method. *) val string_of_method : Value.t_method -> string * { 2 Miscellaneous functions } * Return the first sentence ( until the first dot followed by a blank or the first blank line ) of a text . Do n't stop in the middle of [ Code ] , [ CodePre ] , [ Verbatim ] , [ List ] , [ ] , [ Latex ] , [ Link ] , [ Ref ] , [ Subscript ] or [ Superscript ] . or the first blank line) of a text. Don't stop in the middle of [Code], [CodePre], [Verbatim], [List], [Enum], [Latex], [Link], [Ref], [Subscript] or [Superscript]. *) val first_sentence_of_text : text -> text * Return the first sentence ( until the first dot followed by a blank or the first blank line ) of a text , and the remaining text after . Do n't stop in the middle of [ Code ] , [ CodePre ] , [ Verbatim ] , [ List ] , [ ] , [ Latex ] , [ Link ] , [ Ref ] , [ Subscript ] or [ Superscript ] . or the first blank line) of a text, and the remaining text after. Don't stop in the middle of [Code], [CodePre], [Verbatim], [List], [Enum], [Latex], [Link], [Ref], [Subscript] or [Superscript].*) val first_sentence_and_rest_of_text : text -> text * text (** Return the given [text] without any title or list. *) val text_no_title_no_list : text -> text * [ concat sep l ] the given list of text [ l ] , each separated with the text [ sep ] . the text [sep]. *) val text_concat : Odoc_types.text -> Odoc_types.text list -> Odoc_types.text (** Return the list of titles in a [text]. A title is a title level, an optional label and a text.*) val get_titles_in_text : text -> (int * string option * text) list * Take a sorted list of elements , a function to get the name of an element and return the list of list of elements , where each list group elements beginning by the same letter . Since the original list is sorted , elements whose name does not begin with a letter should be in the first returned list . of an element and return the list of list of elements, where each list group elements beginning by the same letter. Since the original list is sorted, elements whose name does not begin with a letter should be in the first returned list.*) val create_index_lists : 'a list -> ('a -> string) -> 'a list list (** Take a type and remove the option top constructor. This is useful when printing labels, we then remove the top option constructor for optional labels.*) val remove_option : Types.type_expr -> Types.type_expr (** Return [true] if the given label is optional.*) val is_optional : Asttypes.arg_label -> bool (** Return the label name for the given label, i.e. removes the beginning '?' if present.*) val label_name : Asttypes.arg_label -> string * Return the given name where the module name or part of it was removed , according to the list of modules which must be hidden ( cf { ! ) part of it was removed, according to the list of modules which must be hidden (cf {!Odoc_args.hidden_modules})*) val use_hidden_modules : Name.t -> Name.t (** Print the given string if the verbose mode is activated. *) val verbose : string -> unit (** Print a warning message to stderr. If warnings must be treated as errors, then the error counter is incremented. *) val warning : string -> unit (** A flag to indicate whether ocamldoc warnings must be printed or not. *) val print_warnings : bool ref * Increment this counter when an error is encountered . The ocamldoc tool will print the number of errors encountered exit with code 1 if this number is greater than 0 . The ocamldoc tool will print the number of errors encountered exit with code 1 if this number is greater than 0. *) val errors : int ref (** Apply a function to an optional value. *) val apply_opt : ('a -> 'b) -> 'a option -> 'b option * Apply a function to a first value if it is not different from a second value . If the two values are different , return the second one . not different from a second value. If the two values are different, return the second one.*) val apply_if_equal : ('a -> 'a) -> 'a -> 'a -> 'a (** [text_of_string s] returns the text structure from the given string. @raise Text_syntax if a syntax error is encountered. *) val text_of_string : string -> text (** [text_string_of_text text] returns the string representing the given [text]. This string can then be parsed again by {!Odoc_info.text_of_string}.*) val text_string_of_text : text -> string (** [info_of_string s] parses the given string like a regular ocamldoc comment and return an {!Odoc_info.info} structure. @return an empty structure if there was a syntax error. TODO: change this *) val info_of_string : string -> info (** [info_of_comment_file file] parses the given file and return an {!Odoc_info.info} structure. The content of the file must have the same syntax as the content of a special comment. The given module list is used for cross reference. @raise Failure if the file could not be opened or there is a syntax error. *) val info_of_comment_file : Module.t_module list -> string -> info (** [remove_ending_newline s] returns [s] without the optional ending newline. *) val remove_ending_newline : string -> string (** Research in elements *) module Search : sig type result_element = Odoc_search.result_element = Res_module of Module.t_module | Res_module_type of Module.t_module_type | Res_class of Class.t_class | Res_class_type of Class.t_class_type | Res_value of Value.t_value | Res_type of Type.t_type | Res_extension of Extension.t_extension_constructor | Res_exception of Exception.t_exception | Res_attribute of Value.t_attribute | Res_method of Value.t_method | Res_section of string * text | Res_recfield of Type.t_type * Type.record_field | Res_const of Type.t_type * Type.variant_constructor (** The type representing a research result.*) type search_result = result_element list (** Research of the elements whose name matches the given regular expression.*) val search_by_name : Module.t_module list -> Str.regexp -> search_result (** A function to search all the values in a list of modules. *) val values : Module.t_module list -> Value.t_value list (** A function to search all the extensions in a list of modules. *) val extensions : Module.t_module list -> Extension.t_extension_constructor list (** A function to search all the exceptions in a list of modules. *) val exceptions : Module.t_module list -> Exception.t_exception list (** A function to search all the types in a list of modules. *) val types : Module.t_module list -> Type.t_type list (** A function to search all the class attributes in a list of modules. *) val attributes : Module.t_module list -> Value.t_attribute list (** A function to search all the class methods in a list of modules. *) val methods : Module.t_module list -> Value.t_method list (** A function to search all the classes in a list of modules. *) val classes : Module.t_module list -> Class.t_class list (** A function to search all the class types in a list of modules. *) val class_types : Module.t_module list -> Class.t_class_type list (** A function to search all the modules in a list of modules. *) val modules : Module.t_module list -> Module.t_module list (** A function to search all the module types in a list of modules. *) val module_types : Module.t_module list -> Module.t_module_type list end (** Scanning of collected information *) module Scan : sig class scanner : object method scan_value : Value.t_value -> unit method scan_type_pre : Type.t_type -> bool method scan_type_const : Type.t_type -> Type.variant_constructor -> unit method scan_type_recfield : Type.t_type -> Type.record_field -> unit method scan_type : Type.t_type -> unit method scan_extension_constructor : Extension.t_extension_constructor -> unit method scan_exception : Exception.t_exception -> unit method scan_attribute : Value.t_attribute -> unit method scan_method : Value.t_method -> unit method scan_included_module : Module.included_module -> unit (** Scan of a type extension *) (** Override this method to perform controls on the extension's type, private and info. This method is called before scanning the extension's constructors. @return true if the extension's constructors must be scanned.*) method scan_type_extension_pre : Extension.t_type_extension -> bool (** This method scans the constructors of the given type extension. *) method scan_type_extension_constructors : Extension.t_type_extension -> unit (** Scan of a type extension. Should not be overridden. It calls [scan_type_extension_pre] and if [scan_type_extension_pre] returns [true], then it calls scan_type_extension_constructors.*) method scan_type_extension : Extension.t_type_extension -> unit (** Scan of a class. *) (** Scan of a comment inside a class. *) method scan_class_comment : text -> unit (** Override this method to perform controls on the class comment and params. This method is called before scanning the class elements. @return true if the class elements must be scanned.*) method scan_class_pre : Class.t_class -> bool (** This method scans the elements of the given class. *) method scan_class_elements : Class.t_class -> unit (** Scan of a class. Should not be overridden. It calls [scan_class_pre] and if [scan_class_pre] returns [true], then it calls scan_class_elements.*) method scan_class : Class.t_class -> unit (** Scan of a class type. *) (** Scan of a comment inside a class type. *) method scan_class_type_comment : text -> unit (** Override this method to perform controls on the class type comment and form. This method is called before scanning the class type elements. @return true if the class type elements must be scanned.*) method scan_class_type_pre : Class.t_class_type -> bool (** This method scans the elements of the given class type. *) method scan_class_type_elements : Class.t_class_type -> unit (** Scan of a class type. Should not be overridden. It calls [scan_class_type_pre] and if [scan_class_type_pre] returns [true], then it calls scan_class_type_elements.*) method scan_class_type : Class.t_class_type -> unit (** Scan of modules. *) (** Scan of a comment inside a module. *) method scan_module_comment : text -> unit (** Override this method to perform controls on the module comment and form. This method is called before scanning the module elements. @return true if the module elements must be scanned.*) method scan_module_pre : Module.t_module -> bool (** This method scans the elements of the given module. *) method scan_module_elements : Module.t_module -> unit (** Scan of a module. Should not be overridden. It calls [scan_module_pre] and if [scan_module_pre] returns [true], then it calls scan_module_elements.*) method scan_module : Module.t_module -> unit (** Scan of module types. *) (** Scan of a comment inside a module type. *) method scan_module_type_comment : text -> unit (** Override this method to perform controls on the module type comment and form. This method is called before scanning the module type elements. @return true if the module type elements must be scanned. *) method scan_module_type_pre : Module.t_module_type -> bool (** This method scans the elements of the given module type. *) method scan_module_type_elements : Module.t_module_type -> unit (** Scan of a module type. Should not be overridden. It calls [scan_module_type_pre] and if [scan_module_type_pre] returns [true], then it calls scan_module_type_elements.*) method scan_module_type : Module.t_module_type -> unit (** Main scanning method. *) (** Scan a list of modules. *) method scan_module_list : Module.t_module list -> unit end end (** Computation of dependencies. *) module Dep : sig (** Modify the module dependencies of the given list of modules, to get the minimum transitivity kernel. *) val kernel_deps_of_modules : Module.t_module list -> unit (** Return the list of dependencies between the given types, in the form of a list [(type name, names of types it depends on)]. @param kernel indicates if we must keep only the transitivity kernel of the dependencies. Default is [false]. *) val deps_of_types : ?kernel: bool -> Type.t_type list -> (Type.t_type * (Name.t list)) list end * { 1 Some global variables } module Global : sig val errors : int ref val warn_error : bool ref * The file used by the generators outputting only one file . val out_file : string ref * Verbose mode or not . val verbose : bool ref (** The directory where files have to be generated. *) val target_dir : string ref (** The optional title to use in the generated documentation. *) val title : string option ref (** The optional file whose content can be used as intro text. *) val intro_file : string option ref (** The flag which indicates if we must generate a table of contents. *) val with_toc : bool ref (** The flag which indicates if we must generate an index. *) val with_index : bool ref (** The flag which indicates if we must generate a header.*) val with_header : bool ref (** The flag which indicates if we must generate a trailer.*) val with_trailer : bool ref end (** Analysis of the given source files. @param init is the list of modules already known from a previous analysis. @return the list of analysed top modules. *) val analyse_files : ?merge_options:Odoc_types.merge_option list -> ?include_dirs:string list -> ?labels:bool -> ?sort_modules:bool -> ?no_stop:bool -> ?init: Odoc_module.t_module list -> Odoc_global.source_file list -> Module.t_module list (** Dump of a list of modules into a file. @raise Failure if an error occurs.*) val dump_modules : string -> Odoc_module.t_module list -> unit (** Load of a list of modules from a file. @raise Failure if an error occurs.*) val load_modules : string -> Odoc_module.t_module list
null
https://raw.githubusercontent.com/ocaml/ocaml/8a61778d2716304203974d20ead1b2736c1694a8/ocamldoc/odoc_info.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. ************************************************************************ * Interface to the information collected in source files. * The different kinds of element references. * Raw text. * The string is source code. * The string is pre-formatted source code. * String 'as is'. * Text in bold style. * Text in italic. * Emphasized text. * Centered text. * Left alignment. * Right alignment. * A list. * An enumerated list. * To force a line break. * Like html's block quote. * Style number, optional label, and text. * A string for latex. * A reference string and the link text. * A reference to an element. Complete name and kind. An optional text can be given to display this text instead of the element name. * Subscripts. * The table of the given modules with their abstract. * The links to the various indexes (values, types, ...) * to extend \{foo syntax * (target, code) : to specify code specific to a target format * A text is a list of [text_element]. The order matters. * Raised when parsing string to build a {!Odoc_info.text} structure. [(line, char, string)] * Parameter name and description. * Raised exception name and description. * The description text. * The list of authors in \@author tags. * The string in the \@version tag. * the version number and text in \@before tag * The description text of the \@deprecated tag. * The list of parameter descriptions. * The list of raised exceptions. * The description text of the return value. * Alerts associated to the same item. Not from special comments. * Location of elements in implementation and interface files. * implementation location * interface location * A dummy location. * Representation of element names. * Access to the simple name. * [concat t1 t2] returns the concatenation of [t1] and [t2]. * Return the name of the 'father' (like [dirname] for a file name). * Representation and manipulation of method / function / class / module parameters. * {1 Types} * Representation of a simple parameter name * Representation of parameter names. We need it to represent parameter names in tuples. The value [Tuple ([], t)] stands for an anonymous parameter. * A parameter is just a param_info. * Access to the name as a string. For tuples, parentheses and commas are added. * Access to the complete type. * Access to the description of a specific name. @raise Not_found if no description is associated to the given name. * Access to the type of a specific name. @raise Not_found if no type is associated to the given name. * Representation and manipulation of extensions. * Used when the extension is a rebind of another extension, when we have [extension Xt = Target_xt]. * The complete name of the target extension. * The target extension, if we found it. * the optional return type of the extension * the type extension containing this constructor * [None] when the extension is not a rebind. * optional user description * Information found in the optional associated comment. * The type of the extension * Access to the extensions in a group. * Representation and manipulation of exceptions. * Used when the exception is a rebind of another exception, when we have [exception Ex = Target_ex]. * The complete name of the target exception. * The target exception, if we found it. * Information found in the optional associated comment. * The optional return type of the exception. * [None] when the exception is not a rebind. * Representation and manipulation of types. * Description of a record type field. * Name of the field. * [true] if mutable. * Type of the field. * Optional description in the associated comment. * Description of a variant type constructor. * Name of the constructor. * Optional description in the associated comment. * The various kinds of a type. * Type is abstract, for example [type t]. * constructors * fields * Type is open * optional user description * Type manifest directly taken from Typedtree. * Representation of a type. * Complete name of the type. * Information found in the optional associated comment. * type parameters: (type, variance) * Type kind. * Private or public type. * Representation and manipulation of values, class attributes and class methods. * Representation of a value. * Complete name of the value. * Information found in the optional associated comment. * Type of the value. * [true] if the value is recursive. * The parameters, if any. * The code of the value, if we had the only the implementation file. * Representation of a class attribute. * an attribute has almost all the same information as a value * [true] if the attribute is mutable. * [true] if the attribute is virtual. * Representation of a class method. * a method has almost all the same information as a value * [true] if the method is private. * [true] if the method is virtual. * Return [true] if the value is a function, i.e. it has a functional type. * Access to the description associated to the given parameter name. * Representation and manipulation of classes and class types. * {1 Types} * To keep the order of elements in a class. * Used when we can reference a t_class or a t_class_type. * Class type and type parameters. * Complete name of the inherited class. * The associated t_class or t_class_type. * The inheritance description, if any. * The complete name of the applied class. * The associated t_class if we found it. * The type of expressions the class is applied to. * The code of these expressions. * The complete name of the applied class. * The associated class or class type if we found it. * The type parameters of the class, if needed. * An explicit class structure, used in implementation and interface. * Application/alias of a class, used in implementation only. * A class used to give the type of the defined class, instead of a structure, used in interface only. For example, it will be used with the name [M1.M2....bar] when the class foo is defined like this : [class foo : int -> bar] * A class definition with a constraint. * Representation of a class. * Complete name of the class. * Information found in the optional associated comment. * Type of the class. * Type parameters. * [true] when the class is virtual. * The way the class is defined. * The parameters of the class. * Complete name of the target class type. * The target t_class or t_class_type, if we found it. * The type parameters. FIXME : use strings? * A class type eventually applied to type args. * Representation of a class type. * Complete name of the type. * Information found in the optional associated comment. * Type parameters. * [true] if the class type is virtual * The way the class type is defined. * Access to the elements of a class. * Access to the list of class attributes. * Access to the description associated to the given class parameter name. * Access to the methods of a class. * Access to the comments of a class. * Access to the elements of a class type. * Access to the list of class type attributes. * Access to the description associated to the given class type parameter name. * Access to the methods of a class type. * Access to the comments of a class type. * Representation and manipulation of modules and module types. * {1 Types} * To keep the order of elements in a module. * Used where we can reference t_module or t_module_type. * Complete name of the included module. * The included module or module type, if we found it. * comment associated with the include directive * Complete name of the target module. * The real module or module type if we could associate it. * the name * the type * the original code * the way the parameter was built * Different kinds of a module. * A complete module structure. * Complete name and corresponding module if we found it * A functor, with its parameter and the rest of its definition * A module defined by application of a functor. * A generative application of a functor. * A module whose type is a with ... constraint. Should appear in interface files only. * A module constraint by a module type. * by now only the code of the module expression * code of the expression and module type alias * Representation of a module. * Complete name of the module. * The type of the module. * Information found in the optional associated comment. * [true] for modules read from interface files * The file the module is defined in. * The way the module is defined. * The toplevels module names this module depends on. * The whole code of the module * The whole code of the interface of the module * [true] if the module comes from a text file * Complete name of the target module type. * The real module type if we could associate it. * Different kinds of module type. * A complete module signature. * A functor, with its parameter and the rest of its definition * Complete alias name and corresponding module type if we found it. * The module type kind and the code of the with constraint. * by now only the code of the module expression * Representation of a module type. * Complete name of the module type. * Information found in the optional associated comment. * [None] means that the module type is abstract. * [true] for modules read from interface files. * The file the module type is defined in. * The way the module is defined. [None] means that module type is abstract. It is always [None] when the module type was extracted from the implementation file. That means module types are only analysed in interface files. * {1 Functions for modules} * Access to the elements of a module. * Access to the submodules of a module. * Access to the module types of a module. * Access to the included modules of a module. * Access to the type extensions of a module. * Access to the exceptions of a module. * Access to the types of a module. * Access to the values of a module. * Access to functional values of a module. * Access to non-functional values of a module. * Access to the classes of a module. * Access to the class types of a module. * The list of classes defined in this module and all its submodules and functors. * [true] if the module is functor. * The list of couples (module parameter, optional description). * The list of module comments. * {1 Functions for module types} * Access to the elements of a module type. * Access to the submodules of a module type. * Access to the module types of a module type. * Access to the included modules of a module type. * Access to the exceptions of a module type. * Access to the types of a module type. * Access to the values of a module type. * Access to functional values of a module type. * Access to non-functional values of a module type. * Access to the classes of a module type. * Access to the class types of a module type. * The list of classes defined in this module type and all its submodules and functors. * [true] if the module type is functor. * The list of couples (module parameter, optional description). * The list of module comments. * This function is used to reset the names of type variables. It must be called when printing the whole type of a function, but not when printing the type of its parameters. Same for classes (call it) and methods and attributes (don't call it). * [string_of_variance t variance] returns the variance and injectivity annotation (e.g ["+"] for covariance, ["-"] for contravariance, ["!-"] for injectivity) if the type [t] is abstract. * This function returns a string representing a Types.type_expr. * @return a string to display the parameters of the given class, in the same form as the compiler. * This function returns a string to represent the given list of types, with a given separator. * This function returns a string to represent the list of type parameters for the given type. * This function returns a string to represent the list of type parameters for the given type extension. * This function returns a string to represent the given list of type parameters of a class or class type, with a given separator. * This function returns a string representing a [Types.module_type]. @param complete indicates if we must print complete signatures or just [sig end]. Default is [false]. @param code if [complete = false] and the type contains something else than identificators and functors, then the given code is used. * This function returns a string representing a [Types.class_type]. @param complete indicates if we must print complete signatures or just [object end]. Default is [false]. * Get a string from a text. * Get a string from an info structure. * @return a string to describe the given type. * @return a string to describe the given type extension. * @return a string to describe the given exception. * @return a string to describe the given value. * @return a string to describe the given attribute. * @return a string to describe the given method. * Return the given [text] without any title or list. * Return the list of titles in a [text]. A title is a title level, an optional label and a text. * Take a type and remove the option top constructor. This is useful when printing labels, we then remove the top option constructor for optional labels. * Return [true] if the given label is optional. * Return the label name for the given label, i.e. removes the beginning '?' if present. * Print the given string if the verbose mode is activated. * Print a warning message to stderr. If warnings must be treated as errors, then the error counter is incremented. * A flag to indicate whether ocamldoc warnings must be printed or not. * Apply a function to an optional value. * [text_of_string s] returns the text structure from the given string. @raise Text_syntax if a syntax error is encountered. * [text_string_of_text text] returns the string representing the given [text]. This string can then be parsed again by {!Odoc_info.text_of_string}. * [info_of_string s] parses the given string like a regular ocamldoc comment and return an {!Odoc_info.info} structure. @return an empty structure if there was a syntax error. TODO: change this * [info_of_comment_file file] parses the given file and return an {!Odoc_info.info} structure. The content of the file must have the same syntax as the content of a special comment. The given module list is used for cross reference. @raise Failure if the file could not be opened or there is a syntax error. * [remove_ending_newline s] returns [s] without the optional ending newline. * Research in elements * The type representing a research result. * Research of the elements whose name matches the given regular expression. * A function to search all the values in a list of modules. * A function to search all the extensions in a list of modules. * A function to search all the exceptions in a list of modules. * A function to search all the types in a list of modules. * A function to search all the class attributes in a list of modules. * A function to search all the class methods in a list of modules. * A function to search all the classes in a list of modules. * A function to search all the class types in a list of modules. * A function to search all the modules in a list of modules. * A function to search all the module types in a list of modules. * Scanning of collected information * Scan of a type extension * Override this method to perform controls on the extension's type, private and info. This method is called before scanning the extension's constructors. @return true if the extension's constructors must be scanned. * This method scans the constructors of the given type extension. * Scan of a type extension. Should not be overridden. It calls [scan_type_extension_pre] and if [scan_type_extension_pre] returns [true], then it calls scan_type_extension_constructors. * Scan of a class. * Scan of a comment inside a class. * Override this method to perform controls on the class comment and params. This method is called before scanning the class elements. @return true if the class elements must be scanned. * This method scans the elements of the given class. * Scan of a class. Should not be overridden. It calls [scan_class_pre] and if [scan_class_pre] returns [true], then it calls scan_class_elements. * Scan of a class type. * Scan of a comment inside a class type. * Override this method to perform controls on the class type comment and form. This method is called before scanning the class type elements. @return true if the class type elements must be scanned. * This method scans the elements of the given class type. * Scan of a class type. Should not be overridden. It calls [scan_class_type_pre] and if [scan_class_type_pre] returns [true], then it calls scan_class_type_elements. * Scan of modules. * Scan of a comment inside a module. * Override this method to perform controls on the module comment and form. This method is called before scanning the module elements. @return true if the module elements must be scanned. * This method scans the elements of the given module. * Scan of a module. Should not be overridden. It calls [scan_module_pre] and if [scan_module_pre] returns [true], then it calls scan_module_elements. * Scan of module types. * Scan of a comment inside a module type. * Override this method to perform controls on the module type comment and form. This method is called before scanning the module type elements. @return true if the module type elements must be scanned. * This method scans the elements of the given module type. * Scan of a module type. Should not be overridden. It calls [scan_module_type_pre] and if [scan_module_type_pre] returns [true], then it calls scan_module_type_elements. * Main scanning method. * Scan a list of modules. * Computation of dependencies. * Modify the module dependencies of the given list of modules, to get the minimum transitivity kernel. * Return the list of dependencies between the given types, in the form of a list [(type name, names of types it depends on)]. @param kernel indicates if we must keep only the transitivity kernel of the dependencies. Default is [false]. * The directory where files have to be generated. * The optional title to use in the generated documentation. * The optional file whose content can be used as intro text. * The flag which indicates if we must generate a table of contents. * The flag which indicates if we must generate an index. * The flag which indicates if we must generate a header. * The flag which indicates if we must generate a trailer. * Analysis of the given source files. @param init is the list of modules already known from a previous analysis. @return the list of analysed top modules. * Dump of a list of modules into a file. @raise Failure if an error occurs. * Load of a list of modules from a file. @raise Failure if an error occurs.
, projet Cristal , INRIA Rocquencourt Copyright 2001 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the type ref_kind = Odoc_types.ref_kind = RK_module | RK_module_type | RK_class | RK_class_type | RK_value | RK_type | RK_extension | RK_exception | RK_attribute | RK_method | RK_section of text | RK_recfield | RK_const and text_element = Odoc_types.text_element = | Title of int * string option * text | Ref of string * ref_kind option * text option * . | Module_list of string list and text = text_element list * The different forms of references in \@see tags . type see_ref = Odoc_types.see_ref = See_url of string | See_file of string | See_doc of string exception Text_syntax of int * int * string * The information in a \@see tag . type see = see_ref * text type param = (string * text) type raised_exception = (string * text) type alert = Odoc_types.alert = { alert_name : string; alert_payload : string option; } * Information in a special comment @before 3.12 \@before information was not present . @before 3.12 \@before information was not present. *) type info = Odoc_types.info = { * The list of \@see tags . * The string in the \@since tag . * A text associated to a custom @-tag . } type location = Odoc_types.location = { } val dummy_loc : location module Name : sig type t = string val simple : t -> t val concat : t -> t -> t * Return the depth of the name , i.e. the number of levels to the root . Example : [ depth " Toto.Tutu.name " ] = [ 3 ] . Example : [depth "Toto.Tutu.name"] = [3]. *) val depth : t -> int * Take two names n1 and n2 = n3.n4 and return n4 if n3 = n1 or else n2 . val get_relative : t -> t -> t * Take two names n1 and n2 = n3.n4 and return n4 if n3 = n1 and n1 < > " " or else n2 . val get_relative_opt : t -> t -> t val father : t -> t end module Parameter : sig type simple_name = Odoc_parameter.simple_name = { sn_name : string ; sn_type : Types.type_expr ; mutable sn_text : text option ; } type param_info = Odoc_parameter.param_info = Simple_name of simple_name | Tuple of param_info list * Types.type_expr type parameter = param_info * { 1 Functions } val complete_name : parameter -> string val typ : parameter -> Types.type_expr * Access to the list of names ; only one for a simple parameter , or a list for a tuple . a list for a tuple. *) val names : parameter -> string list val desc_by_name : parameter -> string -> text option val type_by_name : parameter -> string -> Types.type_expr end module Extension : sig type private_flag = Odoc_extension.private_flag = Private | Public type extension_alias = Odoc_extension.extension_alias = { } and t_extension_constructor = Odoc_extension.t_extension_constructor = { xt_name : Name.t ; xt_args: Odoc_type.constructor_args; mutable xt_loc: Odoc_types.location ; } and t_type_extension = Odoc_extension.t_type_extension = { te_type_parameters : Types.type_expr list; te_private : private_flag ; mutable te_constructors: t_extension_constructor list; mutable te_loc : location ; mutable te_code : string option ; } val extension_constructors : t_type_extension -> t_extension_constructor list end module Exception : sig type exception_alias = Odoc_exception.exception_alias = { } and t_exception = Odoc_exception.t_exception = { ex_name : Name.t ; ex_args : Odoc_type.constructor_args; mutable ex_loc : location ; mutable ex_code : string option ; } end module Type : sig type private_flag = Odoc_type.private_flag = Private | Public type record_field = Odoc_type.record_field = { } type constructor_args = Odoc_type.constructor_args = | Cstr_record of record_field list | Cstr_tuple of Types.type_expr list type variant_constructor = Odoc_type.variant_constructor = { vc_args : constructor_args; vc_ret : Types.type_expr option ; } type type_kind = Odoc_type.type_kind = | Type_variant of variant_constructor list | Type_record of record_field list type object_field = Odoc_type.object_field = { of_name : string ; of_type : Types.type_expr ; } type type_manifest = Odoc_type.type_manifest = | Object_type of object_field list type t_type = Odoc_type.t_type = { ty_parameters : (Types.type_expr * Types.Variance.t) list ; ty_manifest : type_manifest option ; mutable ty_loc : location ; mutable ty_code : string option; } end module Value : sig type t_value = Odoc_value.t_value = { mutable val_loc : location ; } type t_attribute = Odoc_value.t_attribute = { } type t_method = Odoc_value.t_method = { } val is_function : t_value -> bool val value_parameter_text_by_name : t_value -> string -> text option end module Class : sig type class_element = Odoc_class.class_element = Class_attribute of Value.t_attribute | Class_method of Value.t_method | Class_comment of text type cct = Odoc_class.cct = Cl of t_class and inherited_class = Odoc_class.inherited_class = { } and class_apply = Odoc_class.class_apply = { } and class_constr = Odoc_class.class_constr = { mutable cco_class : cct option; } and class_kind = Odoc_class.class_kind = Class_structure of inherited_class list * class_element list | Class_apply of class_apply | Class_constr of class_constr | Class_constraint of class_kind * class_type_kind and t_class = Odoc_class.t_class = { mutable cl_loc : location ; } and class_type_alias = Odoc_class.class_type_alias = { } and class_type_kind = Odoc_class.class_type_kind = Class_signature of inherited_class list * class_element list and t_class_type = Odoc_class.t_class_type = { clt_type : Types.class_type ; mutable clt_loc : location ; } * { 1 Functions } val class_elements : ?trans:bool -> t_class -> class_element list val class_attributes : ?trans:bool -> t_class -> Value.t_attribute list val class_parameter_text_by_name : t_class -> string -> text option val class_methods : ?trans:bool -> t_class -> Value.t_method list val class_comments : ?trans:bool -> t_class -> text list val class_type_elements : ?trans:bool -> t_class_type -> class_element list val class_type_attributes : ?trans:bool -> t_class_type -> Value.t_attribute list val class_type_parameter_text_by_name : t_class_type -> string -> text option val class_type_methods : ?trans:bool -> t_class_type -> Value.t_method list val class_type_comments : ?trans:bool -> t_class_type -> text list end module Module : sig type module_element = Odoc_module.module_element = Element_module of t_module | Element_module_type of t_module_type | Element_included_module of included_module | Element_class of Class.t_class | Element_class_type of Class.t_class_type | Element_value of Value.t_value | Element_type_extension of Extension.t_type_extension | Element_exception of Exception.t_exception | Element_type of Type.t_type | Element_module_comment of text and mmt = Odoc_module.mmt = | Mod of t_module | Modtype of t_module_type and included_module = Odoc_module.included_module = { } and module_alias = Odoc_module.module_alias = { } and module_parameter = Odoc_module.module_parameter = { } and module_kind = Odoc_module.module_kind = | Module_functor of module_parameter * module_kind | Module_apply of module_kind * module_kind | Module_apply_unit of module_kind | Module_with of module_type_kind * string | Module_constraint of module_kind * module_type_kind and t_module = Odoc_module.t_module = { mutable m_loc : location ; } and module_type_alias = Odoc_module.module_type_alias = { } and module_type_kind = Odoc_module.module_type_kind = | Module_type_functor of module_parameter * module_type_kind | Module_type_alias of module_type_alias | Module_type_with of module_type_kind * string | Module_type_typeof of string and t_module_type = Odoc_module.t_module_type = { mutable mt_kind : module_type_kind option ; mutable mt_loc : location ; } val module_elements : ?trans:bool -> t_module -> module_element list val module_modules : ?trans:bool -> t_module -> t_module list val module_module_types : ?trans:bool -> t_module -> t_module_type list val module_included_modules : ?trans:bool-> t_module -> included_module list val module_type_extensions : ?trans:bool-> t_module -> Extension.t_type_extension list val module_exceptions : ?trans:bool-> t_module -> Exception.t_exception list val module_types : ?trans:bool-> t_module -> Type.t_type list val module_values : ?trans:bool -> t_module -> Value.t_value list val module_functions : ?trans:bool-> t_module -> Value.t_value list val module_simple_values : ?trans:bool-> t_module -> Value.t_value list val module_classes : ?trans:bool-> t_module -> Class.t_class list val module_class_types : ?trans:bool-> t_module -> Class.t_class_type list val module_all_classes : ?trans:bool-> t_module -> Class.t_class list val module_is_functor : t_module -> bool val module_parameters : ?trans:bool-> t_module -> (module_parameter * text option) list val module_comments : ?trans:bool-> t_module -> text list val module_type_elements : ?trans:bool-> t_module_type -> module_element list val module_type_modules : ?trans:bool-> t_module_type -> t_module list val module_type_module_types : ?trans:bool-> t_module_type -> t_module_type list val module_type_included_modules : ?trans:bool-> t_module_type -> included_module list val module_type_exceptions : ?trans:bool-> t_module_type -> Exception.t_exception list val module_type_types : ?trans:bool-> t_module_type -> Type.t_type list val module_type_values : ?trans:bool-> t_module_type -> Value.t_value list val module_type_functions : ?trans:bool-> t_module_type -> Value.t_value list val module_type_simple_values : ?trans:bool-> t_module_type -> Value.t_value list val module_type_classes : ?trans:bool-> t_module_type -> Class.t_class list val module_type_class_types : ?trans:bool-> t_module_type -> Class.t_class_type list val module_type_all_classes : ?trans:bool-> t_module_type -> Class.t_class list val module_type_is_functor : t_module_type -> bool val module_type_parameters : ?trans:bool-> t_module_type -> (module_parameter * text option) list val module_type_comments : ?trans:bool-> t_module_type -> text list end * { 2 Getting strings from values } val reset_type_names : unit -> unit val string_of_variance : Type.t_type -> Types.Variance.t -> string val string_of_type_expr : Types.type_expr -> string val string_of_class_params : Class.t_class -> string val string_of_type_list : ?par: bool -> string -> Types.type_expr list -> string val string_of_type_param_list : Type.t_type -> string val string_of_type_extension_param_list : Extension.t_type_extension -> string val string_of_class_type_param_list : Types.type_expr list -> string val string_of_module_type : ?code: string -> ?complete: bool -> Types.module_type -> string val string_of_class_type : ?complete: bool -> Types.class_type -> string val string_of_text : text -> string val string_of_info : info -> string val string_of_type : Type.t_type -> string val string_of_record : Type.record_field list -> string val string_of_type_extension : Extension.t_type_extension -> string val string_of_exception : Exception.t_exception -> string val string_of_value : Value.t_value -> string val string_of_attribute : Value.t_attribute -> string val string_of_method : Value.t_method -> string * { 2 Miscellaneous functions } * Return the first sentence ( until the first dot followed by a blank or the first blank line ) of a text . Do n't stop in the middle of [ Code ] , [ CodePre ] , [ Verbatim ] , [ List ] , [ ] , [ Latex ] , [ Link ] , [ Ref ] , [ Subscript ] or [ Superscript ] . or the first blank line) of a text. Don't stop in the middle of [Code], [CodePre], [Verbatim], [List], [Enum], [Latex], [Link], [Ref], [Subscript] or [Superscript]. *) val first_sentence_of_text : text -> text * Return the first sentence ( until the first dot followed by a blank or the first blank line ) of a text , and the remaining text after . Do n't stop in the middle of [ Code ] , [ CodePre ] , [ Verbatim ] , [ List ] , [ ] , [ Latex ] , [ Link ] , [ Ref ] , [ Subscript ] or [ Superscript ] . or the first blank line) of a text, and the remaining text after. Don't stop in the middle of [Code], [CodePre], [Verbatim], [List], [Enum], [Latex], [Link], [Ref], [Subscript] or [Superscript].*) val first_sentence_and_rest_of_text : text -> text * text val text_no_title_no_list : text -> text * [ concat sep l ] the given list of text [ l ] , each separated with the text [ sep ] . the text [sep]. *) val text_concat : Odoc_types.text -> Odoc_types.text list -> Odoc_types.text val get_titles_in_text : text -> (int * string option * text) list * Take a sorted list of elements , a function to get the name of an element and return the list of list of elements , where each list group elements beginning by the same letter . Since the original list is sorted , elements whose name does not begin with a letter should be in the first returned list . of an element and return the list of list of elements, where each list group elements beginning by the same letter. Since the original list is sorted, elements whose name does not begin with a letter should be in the first returned list.*) val create_index_lists : 'a list -> ('a -> string) -> 'a list list val remove_option : Types.type_expr -> Types.type_expr val is_optional : Asttypes.arg_label -> bool val label_name : Asttypes.arg_label -> string * Return the given name where the module name or part of it was removed , according to the list of modules which must be hidden ( cf { ! ) part of it was removed, according to the list of modules which must be hidden (cf {!Odoc_args.hidden_modules})*) val use_hidden_modules : Name.t -> Name.t val verbose : string -> unit val warning : string -> unit val print_warnings : bool ref * Increment this counter when an error is encountered . The ocamldoc tool will print the number of errors encountered exit with code 1 if this number is greater than 0 . The ocamldoc tool will print the number of errors encountered exit with code 1 if this number is greater than 0. *) val errors : int ref val apply_opt : ('a -> 'b) -> 'a option -> 'b option * Apply a function to a first value if it is not different from a second value . If the two values are different , return the second one . not different from a second value. If the two values are different, return the second one.*) val apply_if_equal : ('a -> 'a) -> 'a -> 'a -> 'a val text_of_string : string -> text val text_string_of_text : text -> string val info_of_string : string -> info val info_of_comment_file : Module.t_module list -> string -> info val remove_ending_newline : string -> string module Search : sig type result_element = Odoc_search.result_element = Res_module of Module.t_module | Res_module_type of Module.t_module_type | Res_class of Class.t_class | Res_class_type of Class.t_class_type | Res_value of Value.t_value | Res_type of Type.t_type | Res_extension of Extension.t_extension_constructor | Res_exception of Exception.t_exception | Res_attribute of Value.t_attribute | Res_method of Value.t_method | Res_section of string * text | Res_recfield of Type.t_type * Type.record_field | Res_const of Type.t_type * Type.variant_constructor type search_result = result_element list val search_by_name : Module.t_module list -> Str.regexp -> search_result val values : Module.t_module list -> Value.t_value list val extensions : Module.t_module list -> Extension.t_extension_constructor list val exceptions : Module.t_module list -> Exception.t_exception list val types : Module.t_module list -> Type.t_type list val attributes : Module.t_module list -> Value.t_attribute list val methods : Module.t_module list -> Value.t_method list val classes : Module.t_module list -> Class.t_class list val class_types : Module.t_module list -> Class.t_class_type list val modules : Module.t_module list -> Module.t_module list val module_types : Module.t_module list -> Module.t_module_type list end module Scan : sig class scanner : object method scan_value : Value.t_value -> unit method scan_type_pre : Type.t_type -> bool method scan_type_const : Type.t_type -> Type.variant_constructor -> unit method scan_type_recfield : Type.t_type -> Type.record_field -> unit method scan_type : Type.t_type -> unit method scan_extension_constructor : Extension.t_extension_constructor -> unit method scan_exception : Exception.t_exception -> unit method scan_attribute : Value.t_attribute -> unit method scan_method : Value.t_method -> unit method scan_included_module : Module.included_module -> unit method scan_type_extension_pre : Extension.t_type_extension -> bool method scan_type_extension_constructors : Extension.t_type_extension -> unit method scan_type_extension : Extension.t_type_extension -> unit method scan_class_comment : text -> unit method scan_class_pre : Class.t_class -> bool method scan_class_elements : Class.t_class -> unit method scan_class : Class.t_class -> unit method scan_class_type_comment : text -> unit method scan_class_type_pre : Class.t_class_type -> bool method scan_class_type_elements : Class.t_class_type -> unit method scan_class_type : Class.t_class_type -> unit method scan_module_comment : text -> unit method scan_module_pre : Module.t_module -> bool method scan_module_elements : Module.t_module -> unit method scan_module : Module.t_module -> unit method scan_module_type_comment : text -> unit method scan_module_type_pre : Module.t_module_type -> bool method scan_module_type_elements : Module.t_module_type -> unit method scan_module_type : Module.t_module_type -> unit method scan_module_list : Module.t_module list -> unit end end module Dep : sig val kernel_deps_of_modules : Module.t_module list -> unit val deps_of_types : ?kernel: bool -> Type.t_type list -> (Type.t_type * (Name.t list)) list end * { 1 Some global variables } module Global : sig val errors : int ref val warn_error : bool ref * The file used by the generators outputting only one file . val out_file : string ref * Verbose mode or not . val verbose : bool ref val target_dir : string ref val title : string option ref val intro_file : string option ref val with_toc : bool ref val with_index : bool ref val with_header : bool ref val with_trailer : bool ref end val analyse_files : ?merge_options:Odoc_types.merge_option list -> ?include_dirs:string list -> ?labels:bool -> ?sort_modules:bool -> ?no_stop:bool -> ?init: Odoc_module.t_module list -> Odoc_global.source_file list -> Module.t_module list val dump_modules : string -> Odoc_module.t_module list -> unit val load_modules : string -> Odoc_module.t_module list
175590df7c06ee780017777e8d810fe0fa9ea8c3027bbb7f403dfc6f7efd5eb9
netguy204/clojure-gl
marching_cubes.clj
(ns clojure-gl.marching-cubes) first an implementation of simplex noise ( eg perlin noise ) ;; based on the java reference implementation found at: /~perlin/noise/ (def permutations [151 160 137 91 90 15 131 13 201 95 96 53 194 233 7 225 140 36 103 30 69 142 8 99 37 240 21 10 23 190 6 148 247 120 234 75 0 26 197 62 94 252 219 203 117 35 11 32 57 177 33 88 237 149 56 87 174 20 125 136 171 168 68 175 74 165 71 134 139 48 27 166 77 146 158 231 83 111 229 122 60 211 133 230 220 105 92 41 55 46 245 40 244 102 143 54 65 25 63 161 1 216 80 73 209 76 132 187 208 89 18 169 200 196 135 130 116 188 159 86 164 100 109 198 173 186 3 64 52 217 226 250 124 123 5 202 38 147 118 126 255 82 85 212 207 206 59 227 47 16 58 17 182 189 28 42 223 183 170 213 119 248 152 2 44 154 163 70 221 153 101 155 167 43 172 9 129 22 39 253 19 98 108 110 79 113 224 232 178 185 112 104 218 246 97 228 251 34 242 193 238 210 144 12 191 179 162 241 81 51 145 235 249 14 239 107 49 192 214 31 181 199 106 157 184 84 204 176 115 121 50 45 127 4 150 254 138 236 205 93 222 114 67 29 24 72 243 141 128 195 78 66 215 61 156 180 151 160 137 91 90 15 131 13 201 95 96 53 194 233 7 225 140 36 103 30 69 142 8 99 37 240 21 10 23 190 6 148 247 120 234 75 0 26 197 62 94 252 219 203 117 35 11 32 57 177 33 88 237 149 56 87 174 20 125 136 171 168 68 175 74 165 71 134 139 48 27 166 77 146 158 231 83 111 229 122 60 211 133 230 220 105 92 41 55 46 245 40 244 102 143 54 65 25 63 161 1 216 80 73 209 76 132 187 208 89 18 169 200 196 135 130 116 188 159 86 164 100 109 198 173 186 3 64 52 217 226 250 124 123 5 202 38 147 118 126 255 82 85 212 207 206 59 227 47 16 58 17 182 189 28 42 223 183 170 213 119 248 152 2 44 154 163 70 221 153 101 155 167 43 172 9 129 22 39 253 19 98 108 110 79 113 224 232 178 185 112 104 218 246 97 228 251 34 242 193 238 210 144 12 191 179 162 241 81 51 145 235 249 14 239 107 49 192 214 31 181 199 106 157 184 84 204 176 115 121 50 45 127 4 150 254 138 236 205 93 222 114 67 29 24 72 243 141 128 195 78 66 215 61 156 180]) (defn fade [t] (* t t t (+ (* t (- (* t 6) 15)) 10))) (defn dfade [t] (* 30 t t (+ (* t (- t 2.0)) 1))) (defn lerp [t a b] (+ a (* t (- b a)))) (defn grad [hash x y z] (let [h (bit-and hash 15) u (if (< h 8) x y) v (if (< h 4) y (if (or (== h 12) (== h 14)) x z))] (+ (if (== (bit-and h 1) 0) u (- u)) (if (== (bit-and h 2) 0) v (- v))))) (defn simplex-noise [x y z] (let [X (bit-and (int (Math/floor x)) 255) Y (bit-and (int (Math/floor y)) 255) Z (bit-and (int (Math/floor z)) 255) x (- x (Math/floor x)) y (- y (Math/floor y)) z (- z (Math/floor z)) u (fade x) v (fade y) w (fade z) A (+ (permutations X) Y) AA (+ (permutations A) Z) AB (+ (permutations (+ A 1)) Z) B (+ (permutations (+ X 1)) Y) BA (+ (permutations B) Z) BB (+ (permutations (+ B 1)) Z) a (grad (permutations AA) x y z) b (grad (permutations BA) (- x 1) y z) c (grad (permutations AB) x (- y 1) z) d (grad (permutations BB) (- x 1) (- y 1) z) e (grad (permutations (+ AA 1)) x y (- z 1)) f (grad (permutations (+ BA 1)) (- x 1) y (- z 1)) g (grad (permutations (+ AB 1)) x (- y 1) (- z 1)) h (grad (permutations (+ BB 1)) (- x 1) (- y 1) (- z 1)) k0 a k1 (- b a) k2 (- c a) k3 (- e a) k4 (- (+ a d) b c) k5 (- (+ a g) c e) k6 (- (+ a f) b e) k7 (- (+ b c e h) a d f g) noise (+ k0 (* u k1) (* v k2) (* w k3) (* u v k4) (* v w k5) (* w u k6) (* u v w k7)) ;; computing the derivative du (dfade x) dv (dfade y) dw (dfade z) dndx (* du (+ k1 (* v k4) (* w k6) (* v w k7))) dndy (* dv (+ k2 (* w k5) (* u k4) (* w u k7))) dndz (* dw (+ k3 (* u k6) (* v k5) (* u v k7)))] [noise dndx dndy dndz])) ;; now the marching cubes algorithm ;; This is based on the C implementation found at: ;; / (def tri-table [[] [0 8 3] [0 1 9] [1 8 3 9 8 1] [1 2 10] [0 8 3 1 2 10] [9 2 10 0 2 9] [2 8 3 2 10 8 10 9 8] [3 11 2] [0 11 2 8 11 0] [1 9 0 2 3 11] [1 11 2 1 9 11 9 8 11] [3 10 1 11 10 3] [0 10 1 0 8 10 8 11 10] [3 9 0 3 11 9 11 10 9] [9 8 10 10 8 11] [4 7 8] [4 3 0 7 3 4] [0 1 9 8 4 7] [4 1 9 4 7 1 7 3 1] [1 2 10 8 4 7] [3 4 7 3 0 4 1 2 10] [9 2 10 9 0 2 8 4 7] [2 10 9 2 9 7 2 7 3 7 9 4] [8 4 7 3 11 2] [11 4 7 11 2 4 2 0 4] [9 0 1 8 4 7 2 3 11] [4 7 11 9 4 11 9 11 2 9 2 1] [3 10 1 3 11 10 7 8 4] [1 11 10 1 4 11 1 0 4 7 11 4] [4 7 8 9 0 11 9 11 10 11 0 3] [4 7 11 4 11 9 9 11 10] [9 5 4] [9 5 4 0 8 3] [0 5 4 1 5 0] [8 5 4 8 3 5 3 1 5] [1 2 10 9 5 4] [3 0 8 1 2 10 4 9 5] [5 2 10 5 4 2 4 0 2] [2 10 5 3 2 5 3 5 4 3 4 8] [9 5 4 2 3 11] [0 11 2 0 8 11 4 9 5] [0 5 4 0 1 5 2 3 11] [2 1 5 2 5 8 2 8 11 4 8 5] [10 3 11 10 1 3 9 5 4] [4 9 5 0 8 1 8 10 1 8 11 10] [5 4 0 5 0 11 5 11 10 11 0 3] [5 4 8 5 8 10 10 8 11] [9 7 8 5 7 9] [9 3 0 9 5 3 5 7 3] [0 7 8 0 1 7 1 5 7] [1 5 3 3 5 7] [9 7 8 9 5 7 10 1 2] [10 1 2 9 5 0 5 3 0 5 7 3] [8 0 2 8 2 5 8 5 7 10 5 2] [2 10 5 2 5 3 3 5 7] [7 9 5 7 8 9 3 11 2] [9 5 7 9 7 2 9 2 0 2 7 11] [2 3 11 0 1 8 1 7 8 1 5 7] [11 2 1 11 1 7 7 1 5] [9 5 8 8 5 7 10 1 3 10 3 11] [5 7 0 5 0 9 7 11 0 1 0 10 11 10 0] [11 10 0 11 0 3 10 5 0 8 0 7 5 7 0] [11 10 5 7 11 5] [10 6 5] [0 8 3 5 10 6] [9 0 1 5 10 6] [1 8 3 1 9 8 5 10 6] [1 6 5 2 6 1] [1 6 5 1 2 6 3 0 8] [9 6 5 9 0 6 0 2 6] [5 9 8 5 8 2 5 2 6 3 2 8] [2 3 11 10 6 5] [11 0 8 11 2 0 10 6 5] [0 1 9 2 3 11 5 10 6] [5 10 6 1 9 2 9 11 2 9 8 11] [6 3 11 6 5 3 5 1 3] [0 8 11 0 11 5 0 5 1 5 11 6] [3 11 6 0 3 6 0 6 5 0 5 9] [6 5 9 6 9 11 11 9 8] [5 10 6 4 7 8] [4 3 0 4 7 3 6 5 10] [1 9 0 5 10 6 8 4 7] [10 6 5 1 9 7 1 7 3 7 9 4] [6 1 2 6 5 1 4 7 8] [1 2 5 5 2 6 3 0 4 3 4 7] [8 4 7 9 0 5 0 6 5 0 2 6] [7 3 9 7 9 4 3 2 9 5 9 6 2 6 9] [3 11 2 7 8 4 10 6 5] [5 10 6 4 7 2 4 2 0 2 7 11] [0 1 9 4 7 8 2 3 11 5 10 6] [9 2 1 9 11 2 9 4 11 7 11 4 5 10 6] [8 4 7 3 11 5 3 5 1 5 11 6] [5 1 11 5 11 6 1 0 11 7 11 4 0 4 11] [0 5 9 0 6 5 0 3 6 11 6 3 8 4 7] [6 5 9 6 9 11 4 7 9 7 11 9] [10 4 9 6 4 10] [4 10 6 4 9 10 0 8 3] [10 0 1 10 6 0 6 4 0] [8 3 1 8 1 6 8 6 4 6 1 10] [1 4 9 1 2 4 2 6 4] [3 0 8 1 2 9 2 4 9 2 6 4] [0 2 4 4 2 6] [8 3 2 8 2 4 4 2 6] [10 4 9 10 6 4 11 2 3] [0 8 2 2 8 11 4 9 10 4 10 6] [3 11 2 0 1 6 0 6 4 6 1 10] [6 4 1 6 1 10 4 8 1 2 1 11 8 11 1] [9 6 4 9 3 6 9 1 3 11 6 3] [8 11 1 8 1 0 11 6 1 9 1 4 6 4 1] [3 11 6 3 6 0 0 6 4] [6 4 8 11 6 8] [7 10 6 7 8 10 8 9 10] [0 7 3 0 10 7 0 9 10 6 7 10] [10 6 7 1 10 7 1 7 8 1 8 0] [10 6 7 10 7 1 1 7 3] [1 2 6 1 6 8 1 8 9 8 6 7] [2 6 9 2 9 1 6 7 9 0 9 3 7 3 9] [7 8 0 7 0 6 6 0 2] [7 3 2 6 7 2] [2 3 11 10 6 8 10 8 9 8 6 7] [2 0 7 2 7 11 0 9 7 6 7 10 9 10 7] [1 8 0 1 7 8 1 10 7 6 7 10 2 3 11] [11 2 1 11 1 7 10 6 1 6 7 1] [8 9 6 8 6 7 9 1 6 11 6 3 1 3 6] [0 9 1 11 6 7] [7 8 0 7 0 6 3 11 0 11 6 0] [7 11 6] [7 6 11] [3 0 8 11 7 6] [0 1 9 11 7 6] [8 1 9 8 3 1 11 7 6] [10 1 2 6 11 7] [1 2 10 3 0 8 6 11 7] [2 9 0 2 10 9 6 11 7] [6 11 7 2 10 3 10 8 3 10 9 8] [7 2 3 6 2 7] [7 0 8 7 6 0 6 2 0] [2 7 6 2 3 7 0 1 9] [1 6 2 1 8 6 1 9 8 8 7 6] [10 7 6 10 1 7 1 3 7] [10 7 6 1 7 10 1 8 7 1 0 8] [0 3 7 0 7 10 0 10 9 6 10 7] [7 6 10 7 10 8 8 10 9] [6 8 4 11 8 6] [3 6 11 3 0 6 0 4 6] [8 6 11 8 4 6 9 0 1] [9 4 6 9 6 3 9 3 1 11 3 6] [6 8 4 6 11 8 2 10 1] [1 2 10 3 0 11 0 6 11 0 4 6] [4 11 8 4 6 11 0 2 9 2 10 9] [10 9 3 10 3 2 9 4 3 11 3 6 4 6 3] [8 2 3 8 4 2 4 6 2] [0 4 2 4 6 2] [1 9 0 2 3 4 2 4 6 4 3 8] [1 9 4 1 4 2 2 4 6] [8 1 3 8 6 1 8 4 6 6 10 1] [10 1 0 10 0 6 6 0 4] [4 6 3 4 3 8 6 10 3 0 3 9 10 9 3] [10 9 4 6 10 4] [4 9 5 7 6 11] [0 8 3 4 9 5 11 7 6] [5 0 1 5 4 0 7 6 11] [11 7 6 8 3 4 3 5 4 3 1 5] [9 5 4 10 1 2 7 6 11] [6 11 7 1 2 10 0 8 3 4 9 5] [7 6 11 5 4 10 4 2 10 4 0 2] [3 4 8 3 5 4 3 2 5 10 5 2 11 7 6] [7 2 3 7 6 2 5 4 9] [9 5 4 0 8 6 0 6 2 6 8 7] [3 6 2 3 7 6 1 5 0 5 4 0] [6 2 8 6 8 7 2 1 8 4 8 5 1 5 8] [9 5 4 10 1 6 1 7 6 1 3 7] [1 6 10 1 7 6 1 0 7 8 7 0 9 5 4] [4 0 10 4 10 5 0 3 10 6 10 7 3 7 10] [7 6 10 7 10 8 5 4 10 4 8 10] [6 9 5 6 11 9 11 8 9] [3 6 11 0 6 3 0 5 6 0 9 5] [0 11 8 0 5 11 0 1 5 5 6 11] [6 11 3 6 3 5 5 3 1] [1 2 10 9 5 11 9 11 8 11 5 6] [0 11 3 0 6 11 0 9 6 5 6 9 1 2 10] [11 8 5 11 5 6 8 0 5 10 5 2 0 2 5] [6 11 3 6 3 5 2 10 3 10 5 3] [5 8 9 5 2 8 5 6 2 3 8 2] [9 5 6 9 6 0 0 6 2] [1 5 8 1 8 0 5 6 8 3 8 2 6 2 8] [1 5 6 2 1 6] [1 3 6 1 6 10 3 8 6 5 6 9 8 9 6] [10 1 0 10 0 6 9 5 0 5 6 0] [0 3 8 5 6 10] [10 5 6] [11 5 10 7 5 11] [11 5 10 11 7 5 8 3 0] [5 11 7 5 10 11 1 9 0] [10 7 5 10 11 7 9 8 1 8 3 1] [11 1 2 11 7 1 7 5 1] [0 8 3 1 2 7 1 7 5 7 2 11] [9 7 5 9 2 7 9 0 2 2 11 7] [7 5 2 7 2 11 5 9 2 3 2 8 9 8 2] [2 5 10 2 3 5 3 7 5] [8 2 0 8 5 2 8 7 5 10 2 5] [9 0 1 5 10 3 5 3 7 3 10 2] [9 8 2 9 2 1 8 7 2 10 2 5 7 5 2] [1 3 5 3 7 5] [0 8 7 0 7 1 1 7 5] [9 0 3 9 3 5 5 3 7] [9 8 7 5 9 7] [5 8 4 5 10 8 10 11 8] [5 0 4 5 11 0 5 10 11 11 3 0] [0 1 9 8 4 10 8 10 11 10 4 5] [10 11 4 10 4 5 11 3 4 9 4 1 3 1 4] [2 5 1 2 8 5 2 11 8 4 5 8] [0 4 11 0 11 3 4 5 11 2 11 1 5 1 11] [0 2 5 0 5 9 2 11 5 4 5 8 11 8 5] [9 4 5 2 11 3] [2 5 10 3 5 2 3 4 5 3 8 4] [5 10 2 5 2 4 4 2 0] [3 10 2 3 5 10 3 8 5 4 5 8 0 1 9] [5 10 2 5 2 4 1 9 2 9 4 2] [8 4 5 8 5 3 3 5 1] [0 4 5 1 0 5] [8 4 5 8 5 3 9 0 5 0 3 5] [9 4 5] [4 11 7 4 9 11 9 10 11] [0 8 3 4 9 7 9 11 7 9 10 11] [1 10 11 1 11 4 1 4 0 7 4 11] [3 1 4 3 4 8 1 10 4 7 4 11 10 11 4] [4 11 7 9 11 4 9 2 11 9 1 2] [9 7 4 9 11 7 9 1 11 2 11 1 0 8 3] [11 7 4 11 4 2 2 4 0] [11 7 4 11 4 2 8 3 4 3 2 4] [2 9 10 2 7 9 2 3 7 7 4 9] [9 10 7 9 7 4 10 2 7 8 7 0 2 0 7] [3 7 10 3 10 2 7 4 10 1 10 0 4 0 10] [1 10 2 8 7 4] [4 9 1 4 1 7 7 1 3] [4 9 1 4 1 7 0 8 1 8 7 1] [4 0 3 7 4 3] [4 8 7] [9 10 8 10 11 8] [3 0 9 3 9 11 11 9 10] [0 1 10 0 10 8 8 10 11] [3 1 10 11 3 10] [1 2 11 1 11 9 9 11 8] [3 0 9 3 9 11 1 2 9 2 11 9] [0 2 11 8 0 11] [3 2 11] [2 3 8 2 8 10 10 8 9] [9 10 2 0 9 2] [2 3 8 2 8 10 0 1 8 1 10 8] [1 10 2] [1 3 8 9 1 8] [0 9 1] [0 3 8] []]) (def grid-vertices [[0 0 0] [1 0 0] [1 1 0] [0 1 0] [0 0 1] [1 0 1] [1 1 1] [0 1 1]]) (def vert-to-grid-indices [[0 1] [1 2] [2 3] [3 0] [4 5] [5 6] [6 7] [7 4] [0 4] [1 5] [2 6] [3 7]]) (defn- cube-index [grid isolevel] (let [value 0 value (if (< (grid 0) isolevel) (bit-or value 1) value) value (if (< (grid 1) isolevel) (bit-or value 2) value) value (if (< (grid 2) isolevel) (bit-or value 4) value) value (if (< (grid 3) isolevel) (bit-or value 8) value) value (if (< (grid 4) isolevel) (bit-or value 16) value) value (if (< (grid 5) isolevel) (bit-or value 32) value) value (if (< (grid 6) isolevel) (bit-or value 64) value) value (if (< (grid 7) isolevel) (bit-or value 128) value)] value)) (defn vertex-interp [isolevel p1 p2 v1 v2] (cond (< (Math/abs (double (- isolevel v1))) 0.00001) p1 (< (Math/abs (double (- isolevel v2))) 0.00001) p2 :else (let [mu (/ (- isolevel v1) (- v2 v1)) x (lerp mu (p1 0) (p2 0)) y (lerp mu (p1 1) (p2 1)) z (lerp mu (p1 2) (p2 2))] [x y z]))) (defn- vertex-position [vert-index grid isolevel] (let [grid-idxs (vert-to-grid-indices vert-index) p1 (grid-vertices (grid-idxs 0)) v1 (grid (grid-idxs 0)) p2 (grid-vertices (grid-idxs 1)) v2 (grid (grid-idxs 1))] (vertex-interp isolevel p1 p2 v1 v2))) (defn polygonise [grid isolevel] (let [index (cube-index grid isolevel)] (map #(vertex-position % grid isolevel) (tri-table index)))) (defn- normalize [x y z] (let [mag (Math/sqrt (+ (* x x) (* y y) (* z z)))] [(/ x mag) (/ y mag) (/ z mag)])) (defn- third [seq] (nth seq 2)) (defn simplex-surface [isolevel xdim ydim zdim] (let [xstep (/ 2.0 xdim) ystep (/ 2.0 ydim) zstep (/ 2.0 zdim) scale-vert (fn [v o] (let [v (map * v [xstep ystep zstep]) ; scale v (map + v o)] ; offset (into [] v))) ;; generate the integer grid indices grid-indices (for [xidx (range xdim) yidx (range ydim) zidx (range zdim)] [xidx yidx zidx]) ;; build the surface over a grid with that many indices but covering dims -1 , 1 surface (map (fn [[xidx yidx zidx]] (let [offset [(- (* xidx xstep) 1) (- (* yidx ystep) 1) (- (* zidx zstep) 1)] grid (into [] (map (fn [v] (let [v (scale-vert v offset) [n _ _ _] (simplex-noise (v 0) (v 1) (v 2))] n)) grid-vertices)) base-tris (polygonise grid isolevel) tris (map #(scale-vert % offset) base-tris) norms (map (fn [v] (let [[_ nx ny nz] (simplex-noise (first v) (second v) (third v))] (normalize nx ny nz))) tris)] {:tris tris :norms norms})) grid-indices)] {:tris (mapcat :tris surface) :norms (mapcat :norms surface)}))
null
https://raw.githubusercontent.com/netguy204/clojure-gl/055f73baf1af0149191f3574ad82f35017c532fc/src/clojure_gl/marching_cubes.clj
clojure
based on the java reference implementation found at: computing the derivative now the marching cubes algorithm This is based on the C implementation found at: / scale offset generate the integer grid indices build the surface over a grid with that many indices but
(ns clojure-gl.marching-cubes) first an implementation of simplex noise ( eg perlin noise ) /~perlin/noise/ (def permutations [151 160 137 91 90 15 131 13 201 95 96 53 194 233 7 225 140 36 103 30 69 142 8 99 37 240 21 10 23 190 6 148 247 120 234 75 0 26 197 62 94 252 219 203 117 35 11 32 57 177 33 88 237 149 56 87 174 20 125 136 171 168 68 175 74 165 71 134 139 48 27 166 77 146 158 231 83 111 229 122 60 211 133 230 220 105 92 41 55 46 245 40 244 102 143 54 65 25 63 161 1 216 80 73 209 76 132 187 208 89 18 169 200 196 135 130 116 188 159 86 164 100 109 198 173 186 3 64 52 217 226 250 124 123 5 202 38 147 118 126 255 82 85 212 207 206 59 227 47 16 58 17 182 189 28 42 223 183 170 213 119 248 152 2 44 154 163 70 221 153 101 155 167 43 172 9 129 22 39 253 19 98 108 110 79 113 224 232 178 185 112 104 218 246 97 228 251 34 242 193 238 210 144 12 191 179 162 241 81 51 145 235 249 14 239 107 49 192 214 31 181 199 106 157 184 84 204 176 115 121 50 45 127 4 150 254 138 236 205 93 222 114 67 29 24 72 243 141 128 195 78 66 215 61 156 180 151 160 137 91 90 15 131 13 201 95 96 53 194 233 7 225 140 36 103 30 69 142 8 99 37 240 21 10 23 190 6 148 247 120 234 75 0 26 197 62 94 252 219 203 117 35 11 32 57 177 33 88 237 149 56 87 174 20 125 136 171 168 68 175 74 165 71 134 139 48 27 166 77 146 158 231 83 111 229 122 60 211 133 230 220 105 92 41 55 46 245 40 244 102 143 54 65 25 63 161 1 216 80 73 209 76 132 187 208 89 18 169 200 196 135 130 116 188 159 86 164 100 109 198 173 186 3 64 52 217 226 250 124 123 5 202 38 147 118 126 255 82 85 212 207 206 59 227 47 16 58 17 182 189 28 42 223 183 170 213 119 248 152 2 44 154 163 70 221 153 101 155 167 43 172 9 129 22 39 253 19 98 108 110 79 113 224 232 178 185 112 104 218 246 97 228 251 34 242 193 238 210 144 12 191 179 162 241 81 51 145 235 249 14 239 107 49 192 214 31 181 199 106 157 184 84 204 176 115 121 50 45 127 4 150 254 138 236 205 93 222 114 67 29 24 72 243 141 128 195 78 66 215 61 156 180]) (defn fade [t] (* t t t (+ (* t (- (* t 6) 15)) 10))) (defn dfade [t] (* 30 t t (+ (* t (- t 2.0)) 1))) (defn lerp [t a b] (+ a (* t (- b a)))) (defn grad [hash x y z] (let [h (bit-and hash 15) u (if (< h 8) x y) v (if (< h 4) y (if (or (== h 12) (== h 14)) x z))] (+ (if (== (bit-and h 1) 0) u (- u)) (if (== (bit-and h 2) 0) v (- v))))) (defn simplex-noise [x y z] (let [X (bit-and (int (Math/floor x)) 255) Y (bit-and (int (Math/floor y)) 255) Z (bit-and (int (Math/floor z)) 255) x (- x (Math/floor x)) y (- y (Math/floor y)) z (- z (Math/floor z)) u (fade x) v (fade y) w (fade z) A (+ (permutations X) Y) AA (+ (permutations A) Z) AB (+ (permutations (+ A 1)) Z) B (+ (permutations (+ X 1)) Y) BA (+ (permutations B) Z) BB (+ (permutations (+ B 1)) Z) a (grad (permutations AA) x y z) b (grad (permutations BA) (- x 1) y z) c (grad (permutations AB) x (- y 1) z) d (grad (permutations BB) (- x 1) (- y 1) z) e (grad (permutations (+ AA 1)) x y (- z 1)) f (grad (permutations (+ BA 1)) (- x 1) y (- z 1)) g (grad (permutations (+ AB 1)) x (- y 1) (- z 1)) h (grad (permutations (+ BB 1)) (- x 1) (- y 1) (- z 1)) k0 a k1 (- b a) k2 (- c a) k3 (- e a) k4 (- (+ a d) b c) k5 (- (+ a g) c e) k6 (- (+ a f) b e) k7 (- (+ b c e h) a d f g) noise (+ k0 (* u k1) (* v k2) (* w k3) (* u v k4) (* v w k5) (* w u k6) (* u v w k7)) du (dfade x) dv (dfade y) dw (dfade z) dndx (* du (+ k1 (* v k4) (* w k6) (* v w k7))) dndy (* dv (+ k2 (* w k5) (* u k4) (* w u k7))) dndz (* dw (+ k3 (* u k6) (* v k5) (* u v k7)))] [noise dndx dndy dndz])) (def tri-table [[] [0 8 3] [0 1 9] [1 8 3 9 8 1] [1 2 10] [0 8 3 1 2 10] [9 2 10 0 2 9] [2 8 3 2 10 8 10 9 8] [3 11 2] [0 11 2 8 11 0] [1 9 0 2 3 11] [1 11 2 1 9 11 9 8 11] [3 10 1 11 10 3] [0 10 1 0 8 10 8 11 10] [3 9 0 3 11 9 11 10 9] [9 8 10 10 8 11] [4 7 8] [4 3 0 7 3 4] [0 1 9 8 4 7] [4 1 9 4 7 1 7 3 1] [1 2 10 8 4 7] [3 4 7 3 0 4 1 2 10] [9 2 10 9 0 2 8 4 7] [2 10 9 2 9 7 2 7 3 7 9 4] [8 4 7 3 11 2] [11 4 7 11 2 4 2 0 4] [9 0 1 8 4 7 2 3 11] [4 7 11 9 4 11 9 11 2 9 2 1] [3 10 1 3 11 10 7 8 4] [1 11 10 1 4 11 1 0 4 7 11 4] [4 7 8 9 0 11 9 11 10 11 0 3] [4 7 11 4 11 9 9 11 10] [9 5 4] [9 5 4 0 8 3] [0 5 4 1 5 0] [8 5 4 8 3 5 3 1 5] [1 2 10 9 5 4] [3 0 8 1 2 10 4 9 5] [5 2 10 5 4 2 4 0 2] [2 10 5 3 2 5 3 5 4 3 4 8] [9 5 4 2 3 11] [0 11 2 0 8 11 4 9 5] [0 5 4 0 1 5 2 3 11] [2 1 5 2 5 8 2 8 11 4 8 5] [10 3 11 10 1 3 9 5 4] [4 9 5 0 8 1 8 10 1 8 11 10] [5 4 0 5 0 11 5 11 10 11 0 3] [5 4 8 5 8 10 10 8 11] [9 7 8 5 7 9] [9 3 0 9 5 3 5 7 3] [0 7 8 0 1 7 1 5 7] [1 5 3 3 5 7] [9 7 8 9 5 7 10 1 2] [10 1 2 9 5 0 5 3 0 5 7 3] [8 0 2 8 2 5 8 5 7 10 5 2] [2 10 5 2 5 3 3 5 7] [7 9 5 7 8 9 3 11 2] [9 5 7 9 7 2 9 2 0 2 7 11] [2 3 11 0 1 8 1 7 8 1 5 7] [11 2 1 11 1 7 7 1 5] [9 5 8 8 5 7 10 1 3 10 3 11] [5 7 0 5 0 9 7 11 0 1 0 10 11 10 0] [11 10 0 11 0 3 10 5 0 8 0 7 5 7 0] [11 10 5 7 11 5] [10 6 5] [0 8 3 5 10 6] [9 0 1 5 10 6] [1 8 3 1 9 8 5 10 6] [1 6 5 2 6 1] [1 6 5 1 2 6 3 0 8] [9 6 5 9 0 6 0 2 6] [5 9 8 5 8 2 5 2 6 3 2 8] [2 3 11 10 6 5] [11 0 8 11 2 0 10 6 5] [0 1 9 2 3 11 5 10 6] [5 10 6 1 9 2 9 11 2 9 8 11] [6 3 11 6 5 3 5 1 3] [0 8 11 0 11 5 0 5 1 5 11 6] [3 11 6 0 3 6 0 6 5 0 5 9] [6 5 9 6 9 11 11 9 8] [5 10 6 4 7 8] [4 3 0 4 7 3 6 5 10] [1 9 0 5 10 6 8 4 7] [10 6 5 1 9 7 1 7 3 7 9 4] [6 1 2 6 5 1 4 7 8] [1 2 5 5 2 6 3 0 4 3 4 7] [8 4 7 9 0 5 0 6 5 0 2 6] [7 3 9 7 9 4 3 2 9 5 9 6 2 6 9] [3 11 2 7 8 4 10 6 5] [5 10 6 4 7 2 4 2 0 2 7 11] [0 1 9 4 7 8 2 3 11 5 10 6] [9 2 1 9 11 2 9 4 11 7 11 4 5 10 6] [8 4 7 3 11 5 3 5 1 5 11 6] [5 1 11 5 11 6 1 0 11 7 11 4 0 4 11] [0 5 9 0 6 5 0 3 6 11 6 3 8 4 7] [6 5 9 6 9 11 4 7 9 7 11 9] [10 4 9 6 4 10] [4 10 6 4 9 10 0 8 3] [10 0 1 10 6 0 6 4 0] [8 3 1 8 1 6 8 6 4 6 1 10] [1 4 9 1 2 4 2 6 4] [3 0 8 1 2 9 2 4 9 2 6 4] [0 2 4 4 2 6] [8 3 2 8 2 4 4 2 6] [10 4 9 10 6 4 11 2 3] [0 8 2 2 8 11 4 9 10 4 10 6] [3 11 2 0 1 6 0 6 4 6 1 10] [6 4 1 6 1 10 4 8 1 2 1 11 8 11 1] [9 6 4 9 3 6 9 1 3 11 6 3] [8 11 1 8 1 0 11 6 1 9 1 4 6 4 1] [3 11 6 3 6 0 0 6 4] [6 4 8 11 6 8] [7 10 6 7 8 10 8 9 10] [0 7 3 0 10 7 0 9 10 6 7 10] [10 6 7 1 10 7 1 7 8 1 8 0] [10 6 7 10 7 1 1 7 3] [1 2 6 1 6 8 1 8 9 8 6 7] [2 6 9 2 9 1 6 7 9 0 9 3 7 3 9] [7 8 0 7 0 6 6 0 2] [7 3 2 6 7 2] [2 3 11 10 6 8 10 8 9 8 6 7] [2 0 7 2 7 11 0 9 7 6 7 10 9 10 7] [1 8 0 1 7 8 1 10 7 6 7 10 2 3 11] [11 2 1 11 1 7 10 6 1 6 7 1] [8 9 6 8 6 7 9 1 6 11 6 3 1 3 6] [0 9 1 11 6 7] [7 8 0 7 0 6 3 11 0 11 6 0] [7 11 6] [7 6 11] [3 0 8 11 7 6] [0 1 9 11 7 6] [8 1 9 8 3 1 11 7 6] [10 1 2 6 11 7] [1 2 10 3 0 8 6 11 7] [2 9 0 2 10 9 6 11 7] [6 11 7 2 10 3 10 8 3 10 9 8] [7 2 3 6 2 7] [7 0 8 7 6 0 6 2 0] [2 7 6 2 3 7 0 1 9] [1 6 2 1 8 6 1 9 8 8 7 6] [10 7 6 10 1 7 1 3 7] [10 7 6 1 7 10 1 8 7 1 0 8] [0 3 7 0 7 10 0 10 9 6 10 7] [7 6 10 7 10 8 8 10 9] [6 8 4 11 8 6] [3 6 11 3 0 6 0 4 6] [8 6 11 8 4 6 9 0 1] [9 4 6 9 6 3 9 3 1 11 3 6] [6 8 4 6 11 8 2 10 1] [1 2 10 3 0 11 0 6 11 0 4 6] [4 11 8 4 6 11 0 2 9 2 10 9] [10 9 3 10 3 2 9 4 3 11 3 6 4 6 3] [8 2 3 8 4 2 4 6 2] [0 4 2 4 6 2] [1 9 0 2 3 4 2 4 6 4 3 8] [1 9 4 1 4 2 2 4 6] [8 1 3 8 6 1 8 4 6 6 10 1] [10 1 0 10 0 6 6 0 4] [4 6 3 4 3 8 6 10 3 0 3 9 10 9 3] [10 9 4 6 10 4] [4 9 5 7 6 11] [0 8 3 4 9 5 11 7 6] [5 0 1 5 4 0 7 6 11] [11 7 6 8 3 4 3 5 4 3 1 5] [9 5 4 10 1 2 7 6 11] [6 11 7 1 2 10 0 8 3 4 9 5] [7 6 11 5 4 10 4 2 10 4 0 2] [3 4 8 3 5 4 3 2 5 10 5 2 11 7 6] [7 2 3 7 6 2 5 4 9] [9 5 4 0 8 6 0 6 2 6 8 7] [3 6 2 3 7 6 1 5 0 5 4 0] [6 2 8 6 8 7 2 1 8 4 8 5 1 5 8] [9 5 4 10 1 6 1 7 6 1 3 7] [1 6 10 1 7 6 1 0 7 8 7 0 9 5 4] [4 0 10 4 10 5 0 3 10 6 10 7 3 7 10] [7 6 10 7 10 8 5 4 10 4 8 10] [6 9 5 6 11 9 11 8 9] [3 6 11 0 6 3 0 5 6 0 9 5] [0 11 8 0 5 11 0 1 5 5 6 11] [6 11 3 6 3 5 5 3 1] [1 2 10 9 5 11 9 11 8 11 5 6] [0 11 3 0 6 11 0 9 6 5 6 9 1 2 10] [11 8 5 11 5 6 8 0 5 10 5 2 0 2 5] [6 11 3 6 3 5 2 10 3 10 5 3] [5 8 9 5 2 8 5 6 2 3 8 2] [9 5 6 9 6 0 0 6 2] [1 5 8 1 8 0 5 6 8 3 8 2 6 2 8] [1 5 6 2 1 6] [1 3 6 1 6 10 3 8 6 5 6 9 8 9 6] [10 1 0 10 0 6 9 5 0 5 6 0] [0 3 8 5 6 10] [10 5 6] [11 5 10 7 5 11] [11 5 10 11 7 5 8 3 0] [5 11 7 5 10 11 1 9 0] [10 7 5 10 11 7 9 8 1 8 3 1] [11 1 2 11 7 1 7 5 1] [0 8 3 1 2 7 1 7 5 7 2 11] [9 7 5 9 2 7 9 0 2 2 11 7] [7 5 2 7 2 11 5 9 2 3 2 8 9 8 2] [2 5 10 2 3 5 3 7 5] [8 2 0 8 5 2 8 7 5 10 2 5] [9 0 1 5 10 3 5 3 7 3 10 2] [9 8 2 9 2 1 8 7 2 10 2 5 7 5 2] [1 3 5 3 7 5] [0 8 7 0 7 1 1 7 5] [9 0 3 9 3 5 5 3 7] [9 8 7 5 9 7] [5 8 4 5 10 8 10 11 8] [5 0 4 5 11 0 5 10 11 11 3 0] [0 1 9 8 4 10 8 10 11 10 4 5] [10 11 4 10 4 5 11 3 4 9 4 1 3 1 4] [2 5 1 2 8 5 2 11 8 4 5 8] [0 4 11 0 11 3 4 5 11 2 11 1 5 1 11] [0 2 5 0 5 9 2 11 5 4 5 8 11 8 5] [9 4 5 2 11 3] [2 5 10 3 5 2 3 4 5 3 8 4] [5 10 2 5 2 4 4 2 0] [3 10 2 3 5 10 3 8 5 4 5 8 0 1 9] [5 10 2 5 2 4 1 9 2 9 4 2] [8 4 5 8 5 3 3 5 1] [0 4 5 1 0 5] [8 4 5 8 5 3 9 0 5 0 3 5] [9 4 5] [4 11 7 4 9 11 9 10 11] [0 8 3 4 9 7 9 11 7 9 10 11] [1 10 11 1 11 4 1 4 0 7 4 11] [3 1 4 3 4 8 1 10 4 7 4 11 10 11 4] [4 11 7 9 11 4 9 2 11 9 1 2] [9 7 4 9 11 7 9 1 11 2 11 1 0 8 3] [11 7 4 11 4 2 2 4 0] [11 7 4 11 4 2 8 3 4 3 2 4] [2 9 10 2 7 9 2 3 7 7 4 9] [9 10 7 9 7 4 10 2 7 8 7 0 2 0 7] [3 7 10 3 10 2 7 4 10 1 10 0 4 0 10] [1 10 2 8 7 4] [4 9 1 4 1 7 7 1 3] [4 9 1 4 1 7 0 8 1 8 7 1] [4 0 3 7 4 3] [4 8 7] [9 10 8 10 11 8] [3 0 9 3 9 11 11 9 10] [0 1 10 0 10 8 8 10 11] [3 1 10 11 3 10] [1 2 11 1 11 9 9 11 8] [3 0 9 3 9 11 1 2 9 2 11 9] [0 2 11 8 0 11] [3 2 11] [2 3 8 2 8 10 10 8 9] [9 10 2 0 9 2] [2 3 8 2 8 10 0 1 8 1 10 8] [1 10 2] [1 3 8 9 1 8] [0 9 1] [0 3 8] []]) (def grid-vertices [[0 0 0] [1 0 0] [1 1 0] [0 1 0] [0 0 1] [1 0 1] [1 1 1] [0 1 1]]) (def vert-to-grid-indices [[0 1] [1 2] [2 3] [3 0] [4 5] [5 6] [6 7] [7 4] [0 4] [1 5] [2 6] [3 7]]) (defn- cube-index [grid isolevel] (let [value 0 value (if (< (grid 0) isolevel) (bit-or value 1) value) value (if (< (grid 1) isolevel) (bit-or value 2) value) value (if (< (grid 2) isolevel) (bit-or value 4) value) value (if (< (grid 3) isolevel) (bit-or value 8) value) value (if (< (grid 4) isolevel) (bit-or value 16) value) value (if (< (grid 5) isolevel) (bit-or value 32) value) value (if (< (grid 6) isolevel) (bit-or value 64) value) value (if (< (grid 7) isolevel) (bit-or value 128) value)] value)) (defn vertex-interp [isolevel p1 p2 v1 v2] (cond (< (Math/abs (double (- isolevel v1))) 0.00001) p1 (< (Math/abs (double (- isolevel v2))) 0.00001) p2 :else (let [mu (/ (- isolevel v1) (- v2 v1)) x (lerp mu (p1 0) (p2 0)) y (lerp mu (p1 1) (p2 1)) z (lerp mu (p1 2) (p2 2))] [x y z]))) (defn- vertex-position [vert-index grid isolevel] (let [grid-idxs (vert-to-grid-indices vert-index) p1 (grid-vertices (grid-idxs 0)) v1 (grid (grid-idxs 0)) p2 (grid-vertices (grid-idxs 1)) v2 (grid (grid-idxs 1))] (vertex-interp isolevel p1 p2 v1 v2))) (defn polygonise [grid isolevel] (let [index (cube-index grid isolevel)] (map #(vertex-position % grid isolevel) (tri-table index)))) (defn- normalize [x y z] (let [mag (Math/sqrt (+ (* x x) (* y y) (* z z)))] [(/ x mag) (/ y mag) (/ z mag)])) (defn- third [seq] (nth seq 2)) (defn simplex-surface [isolevel xdim ydim zdim] (let [xstep (/ 2.0 xdim) ystep (/ 2.0 ydim) zstep (/ 2.0 zdim) scale-vert (fn [v o] (into [] v))) grid-indices (for [xidx (range xdim) yidx (range ydim) zidx (range zdim)] [xidx yidx zidx]) covering dims -1 , 1 surface (map (fn [[xidx yidx zidx]] (let [offset [(- (* xidx xstep) 1) (- (* yidx ystep) 1) (- (* zidx zstep) 1)] grid (into [] (map (fn [v] (let [v (scale-vert v offset) [n _ _ _] (simplex-noise (v 0) (v 1) (v 2))] n)) grid-vertices)) base-tris (polygonise grid isolevel) tris (map #(scale-vert % offset) base-tris) norms (map (fn [v] (let [[_ nx ny nz] (simplex-noise (first v) (second v) (third v))] (normalize nx ny nz))) tris)] {:tris tris :norms norms})) grid-indices)] {:tris (mapcat :tris surface) :norms (mapcat :norms surface)}))
064bef1e1d8e54914df0aa5d072c17160c792cecad16c0061c6e8d98c3d0776c
bcc32/projecteuler-ocaml
sol_008.ml
open! Core open! Import let doit str = Sequence.range 0 (String.length str - 12) |> Sequence.map ~f:(fun i -> String.sub str ~pos:i ~len:13 |> Sequences.digits_of_string |> List.fold ~init:1 ~f:( * )) |> Sequence.max_elt ~compare:Int.compare |> Option.value_exn ;; let main () = doit Problem_008.data |> printf "%d\n" (* 3.3ms *) let%expect_test "answer" = main (); [%expect {| 23514624000 |}] ;; include (val Solution.make ~problem:(Number 8) ~main)
null
https://raw.githubusercontent.com/bcc32/projecteuler-ocaml/712f85902c70adc1ec13dcbbee456c8bfa8450b2/sol/sol_008.ml
ocaml
3.3ms
open! Core open! Import let doit str = Sequence.range 0 (String.length str - 12) |> Sequence.map ~f:(fun i -> String.sub str ~pos:i ~len:13 |> Sequences.digits_of_string |> List.fold ~init:1 ~f:( * )) |> Sequence.max_elt ~compare:Int.compare |> Option.value_exn ;; let main () = doit Problem_008.data |> printf "%d\n" let%expect_test "answer" = main (); [%expect {| 23514624000 |}] ;; include (val Solution.make ~problem:(Number 8) ~main)
0794af425add885726bea78c950745ec9925523524215662a0bdfdc704acb96a
marcoheisig/numpy-file-format
packages.lisp
(in-package #:common-lisp-user) (defpackage #:numpy-file-format (:use #:common-lisp) (:export #:load-array #:store-array))
null
https://raw.githubusercontent.com/marcoheisig/numpy-file-format/e97aef6c592a412fdd1afa9a5f09d0b1ce134510/code/packages.lisp
lisp
(in-package #:common-lisp-user) (defpackage #:numpy-file-format (:use #:common-lisp) (:export #:load-array #:store-array))
57ade47383fac313a533d1956c597416f0569240eaa13183305f1a507b968eb7
release-project/benchmarks
launcher.erl
%%%------------------------------------------------------------------- LAUNCHER MODULE %%% @author upon a design by ( C ) 2014 , RELEASE project %%% @doc %%% Launcher module for the Distributed Erlang instant messenger %%% (IM) application developed as a real benchmark for the Scalable Distributed Erlang extension of the Erlang / OTP %%% language. %%% %%% This module implements the logic to deploy a system similar to the system described in the Section 2 of the document " Instant Messenger Architectures Design Proposal " given a %%% set of virtual machines to host the system. %%% @end Created : 25 Jul 2014 by %%%------------------------------------------------------------------- -module(launcher). -export([start/5, start/6, start_bencherl/1, start_bencherl/5, stop/5, stop/6, launch_router_processes/6, launch_server_supervisors/4]). -import(router,[router_supervisor/6, router_process/1, compression_function/2, hash_code/2]). %% <==== CHANGE router_supervisor/5 TO router_supervisor/1 WHEN USING THE NEW VERSION OF ROUTER MODULE. %% -include("config.hrl"). <==== TO BE USED WITH THE NEW VERSION OF ROUTER MODULE. (NOT FINISHED YET). %%============================================================================ %% APPLICATION DEPLOYMENT LOGIC %%============================================================================ %%-------------------------------------------------------------------- %% @doc %% start/6 launches the sequence to set up the architecture, and run the IM application . %% %% Arguments: %% Servers_Per_Router_Node: (int) The number of server nodes %% that are children of a router node. %% Server_Per_Router_Process: (int) The number of server %% supervisor processes that are %% monitored by a router process. %% Servers_Total: (int) Final number of servers in the system. %% Clients_Total: (int) Final number of client nodes. %% List_Domains: (list) List containing all the domains of %% the hosts in which the system is deployed. %% This is usually one, but can be more if the %% application is hosted in a cluster with %% different domains. : ( int ) Number of hosts in which the system is %% deployed. %% Example : start(2,1,2,4,['domain.do ' ] , 1 ) . start(2,1,2,4,['domain ' ] , 1 ) . %% These launch a system comprising 1 router , 2 servers , and 4 client nodes on 1 host , with domain domain.do or domain . In this case , there are 2 router processes , each of them monitoring one server supervisor process . %% , Servers_Per_Router_Process , Servers_Total , Clients_Total , List_Domains , Num_of_Hosts ) - > %% Status Messages | {error, reason} %% @end %%--------------------------------------------------------------------- start(Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Clients_Total, List_Domains, Num_of_Hosts) -> Num_TS = Servers_Total * Num_of_Hosts, Architecture_Info = {Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Num_TS, Clients_Total}, case List_Domains == [] of true -> io:format("start/4 is finished.~n"); false -> [Domain|New_List_Domains] = List_Domains, case whereis(routers_listener) of undefined -> io:format("~n=============================================~n" ++ "Initiating the Distributed Instant Messenger.~n"++ "=============================================~n"), Routers_Listener_Pid = spawn(fun() -> routers_listener(Num_TS, [], [], [], []) end), register(routers_listener, Routers_Listener_Pid); _ -> ok end, start_host(Num_of_Hosts, Architecture_Info, Domain, whereis(routers_listener)), start(Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Clients_Total, New_List_Domains, Num_of_Hosts - 1) end. %%-------------------------------------------------------------------- %% @doc %% starts the sequence of that launch each of the components that %% will be deployed in a particular hosts from the list specified %% in start/6. %% %% start_host(Num_of_Host, Architecture_Info, Domain, %% Routers_Listener_Pid) -> Status Messages | {error, reason} %% @end %%-------------------------------------------------------------------- start_host(Num_of_Host, Architecture_Info, Domain, Routers_Listener_Pid) -> {Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Num_TS, Clients_Total} = Architecture_Info, case Servers_Total rem Servers_Per_Router_Node of 0 -> Routers = Servers_Total div Servers_Per_Router_Node; _Greater_than_0 -> Routers = (Servers_Total div Servers_Per_Router_Node) + 1 end, case Servers_Per_Router_Process > Servers_Per_Router_Node of true -> S_R_Pr = Servers_Per_Router_Node; false -> S_R_Pr = Servers_Per_Router_Process end, Router_Nodes = node_name_generator(Num_of_Host, router, Domain, Routers, 0), Server_Nodes = node_name_generator(Num_of_Host, server, Domain, Servers_Total, 0), Client_Nodes = node_name_generator(Num_of_Host, client, Domain, Clients_Total, 0), Router_Processes = router_names_generator(Num_of_Host, Servers_Total, Servers_Per_Router_Node, S_R_Pr, 0), io:format("~n=============================================~n" ++ " Launching Host: ~p ~n" ++ "=============================================~n" ++ "Router nodes: ~p~n" ++ "Server nodes: ~p~n" ++ "Client nodes: ~p~n" ++ "Router processes: ~p~n",[Num_of_Host, Router_Nodes, Server_Nodes, Client_Nodes, Router_Processes]), Routers_Listener_Pid ! {Client_Nodes, add_client_node}, case length(Router_Processes) rem Routers of 0 -> Router_Pr_per_R_Nd = length(Router_Processes) div Routers; _Other -> Router_Pr_per_R_Nd = length(Router_Processes) div Routers + 1 end, New_Architecture_Info = {Servers_Per_Router_Node, Servers_Per_Router_Process, Num_TS, Servers_Total, Routers, Router_Pr_per_R_Nd}, Routers_Servers_Lists = {Router_Nodes, Server_Nodes, Router_Processes}, launch_router_supervisors(Routers_Servers_Lists, New_Architecture_Info, Routers_Listener_Pid). %%--------------------------------------------------------------------- %% @doc %% start/5 launches the sequence to set up the architecture, and run the IM application . %% %% Arguments: %% S_RN: (int) The number of server nodes that are children of %% a router node. %% S_RP: (int) The number of server supervisor processes that are %% monitored by a router process. %% S_T: (int) Final number of servers in the system. %% Cl_T: (int) Final number of client nodes. %% List_Domains: (list) List containing all the domains of %% the hosts in which the system is deployed. %% This is usually one, but can be more if the %% application is hosted in a cluster with %% different domains. %% %% Example: %% start(2,1,2,4,['domain_1.do','domain_2.do], ..., 'domain_4.do ]). %% This launches a system comprising 1 router , 2 servers , and 4 client %% nodes, deploying the router on host with domain 'domain_1.do', the two servers on the hosts with domain ' domain_2.do and ' domain_3.do ' , and four client nodes on a host ' domain_4.do ' . %% In this case , there are 2 router processes , each of them monitoring one server supervisor process . %% , S_RP , S_T , Cl_T , List_Domains ) - > %% Status Messages | {error, reason} %% @end %%--------------------------------------------------------------------- start(S_RN, S_RP, S_T, Cl_T, List_Domains) -> case S_T rem S_RP of Rem when Rem == 0 -> R_T = S_T div S_RN; _Rem -> R_T = (S_T div S_RN) + 1 end, case (R_T + S_T) + 1 =< length(List_Domains) of true -> Architecture_Info = {S_RN, S_RP, S_T, S_T, Cl_T}, Nodes = nodes_list(R_T, S_RN, S_T, Cl_T, List_Domains), case whereis(routers_listener) of undefined -> io:format("~n=============================================~n" ++ "Initiating the Distributed Instant Messenger.~n" ++ "=============================================~n"), Routers_Listener_Pid = spawn(fun() -> routers_listener(S_T, [], [], [], []) end), register(routers_listener, Routers_Listener_Pid); Pid -> Routers_Listener_Pid = Pid end, start_distributed(Architecture_Info, Nodes, Routers_Listener_Pid); false -> io:format("ERROR: There are not enough hosts to deploy the system. Aborting.~n") end. %%==================================================================== %% BENCHERL START FUNCTIONS %%==================================================================== %%--------------------------------------------------------------------- %% @doc start_bencherl/1 deploys the IM processes given a list of nodes . %% The function determines the structure of the architecture, assuming that there is one router process per each server node . %% This function is intended to be used with only . %% %% Arguments: %% Nodes: (list) List containing all the nodes comprising the %% architecture of the application. %% %% Example: %% start(['router_1@domain_1.do','router_2@domain_2.do'], %% ..., 'client_4@domain_4.do ]). %% @spec start_bencherl(List_Nodes ) - > Status Messages | { error , reason } %% @end %%-------------------------------------------------------------------- start_bencherl(Nodes) -> %% Classify nodes by type, and work out the architecture layout {Router_Nodes, Server_Nodes, Client_Nodes, _Traffic_Nodes} = extractor(Nodes), %% Total nodes of each kind R_T = length(Router_Nodes), S_T = length(Server_Nodes), Cl_T = length(Client_Nodes), %% Determine the maximum number of server nodes children of a router node case S_T rem R_T of 0 -> S_RN = S_T div R_T; _Other -> S_RN = (S_T div R_T) + 1 end, %% Set up the routers listener for deployment. case whereis(routers_listener) of undefined -> io:format("~n=============================================~n" ++ "Initiating the Distributed Instant Messenger.~n" ++ "=============================================~n"), Routers_Listener_Pid = spawn(fun() -> routers_listener(S_T, [], [], [], []) end), register(routers_listener, Routers_Listener_Pid); Pid -> Routers_Listener_Pid = Pid end, spawn(fun() -> auto_stop(Nodes)end), Architecture_Info = {S_RN, 1, S_T, S_T, Cl_T}, start_distributed(Architecture_Info, Nodes, Routers_Listener_Pid). %%--------------------------------------------------------------------- %% @doc %% start_bencherl/5 is similar to start/5, but in this case the last %% argument is a list containing the nodes where the aplication must be executed . This function is intended to be used with %% only. %% %% Arguments: %% S_RN: (int) The number of server nodes that are children of %% a router node. %% S_RP: (int) The number of server supervisor processes that are %% monitored by a router process. %% S_T: (int) Final number of servers in the system. %% Cl_T: (int) Final number of client nodes. %% Nodes: (list) List containing all the nodes comprising the %% architecture of the application. %% %% Example: %% start(2,1,2,4,['router_1@domain_1.do','router_2@domain_2.do'], %% ..., 'client_4@domain_4.do ]). %% %% @spec start_bencherl(S_RN, S_RP, S_T, Cl_T, List_Domains) -> %% Status Messages | {error, reason} %% @end %%--------------------------------------------------------------------- start_bencherl(S_RN, S_RP, S_T, Cl_T, Nodes) -> Architecture_Info = {S_RN, S_RP, S_T, S_T, Cl_T}, case whereis(routers_listener) of undefined -> io:format("~n=============================================~n"), io:format("Initiating the Distributed Instant Messenger.~n"), io:format("=============================================~n"), Routers_Listener_Pid = spawn(fun() -> routers_listener(S_T, [], [], [], []) end), register(routers_listener, Routers_Listener_Pid); Pid -> Routers_Listener_Pid = Pid end, spawn(fun() -> auto_stop(Nodes)end), start_distributed(Architecture_Info, Nodes, Routers_Listener_Pid). %%=================================================================== %% END BENCHERL START FUNCTIONS %%=================================================================== %%-------------------------------------------------------------------- %% @doc %% starts the sequence of that launch each of the components that %% will be deployed in the hosts from the list specified in start/5. %% It is equivalent to start_host/4 , yet in a distributed environment where each host executes one node . %% %% start_Distributed(Architecture_Info, Nodes, %% Routers_Listener_Pid) -> Status Messages | {error, reason} %% @end %%-------------------------------------------------------------------- start_distributed(Architecture_Info, Nodes, Routers_Listener_Pid) -> {S_RN, S_RP, S_T, Num_TS, _Cl_T} = Architecture_Info, case S_RP > S_RN of true -> S_R_Pr = S_RN; false -> S_R_Pr = S_RP end, {Router_Nodes, Server_Nodes, Client_Nodes, _Traffic_Nodes} = extractor(Nodes), Router_Processes = router_names_generator(1, S_T, S_RN, S_R_Pr, 0), io:format("Router processes: ~p~n", [Router_Processes]), Routers_Listener_Pid ! {Client_Nodes, add_client_node}, case length(Router_Processes) rem length(Router_Nodes) of 0 -> R_Pr_RN = length(Router_Processes) div length(Router_Nodes); _Other -> R_Pr_RN = length(Router_Processes) div length(Router_Nodes) + 1 end, New_Architecture_Info = {S_RN, S_RP, Num_TS, S_T, length(Router_Nodes), R_Pr_RN}, Routers_Servers_Lists = {Router_Nodes, Server_Nodes, Router_Processes}, launch_router_supervisors(Routers_Servers_Lists, New_Architecture_Info, Routers_Listener_Pid). %%-------------------------------------------------------------------- %% @doc %% This function determines the router nodes where the router %% supervisors must be spawned and gathers all the information %% required for that purpose. %% , %% Architecture_Info, Routers_Listener_Pid) -> %% Status Messages | {error, reason} %% @end %%-------------------------------------------------------------------- launch_router_supervisors(Routers_Servers_Lists, Architecture_Info, Routers_Listener_Pid) -> {Router_Nodes, Server_Nodes, Router_Processes} = Routers_Servers_Lists, {Server_Router_Nd, Servers_Router_Pr, Num_Total_Servers, _, _, Router_Pr_Per_R_Nd} = Architecture_Info, [Router_Nd | New_Router_Nd] = Router_Nodes, io:format("Router_Pr_per_R_Nd = ~p; Router_Processes = ~p~n", [Router_Pr_Per_R_Nd, Router_Processes]), case length(Server_Nodes) > Server_Router_Nd of true -> {Servers, New_Server_Nd} = lists:split(Server_Router_Nd, Server_Nodes), {Router_Prcs, New_Router_Processes} = lists:split(Router_Pr_Per_R_Nd, Router_Processes), io:format("launch_router_supervisors.~n" ++ "Router_Nd: ~p~n" ++ "Servers in ~p:~p~n" ++ "Router Processes in ~p:~p~n", [Router_Nd, Router_Nd, Servers, Router_Nd, Router_Prcs]), New_Rs_Ss_Lists = {New_Router_Nd, New_Server_Nd, New_Router_Processes}, start_router_supervisor(Router_Nd, Servers, Servers_Router_Pr, Router_Prcs, Num_Total_Servers, Routers_Listener_Pid), launch_router_supervisors(New_Rs_Ss_Lists, Architecture_Info, Routers_Listener_Pid); false -> start_router_supervisor(Router_Nd, Server_Nodes, Servers_Router_Pr, Router_Processes, Num_Total_Servers, Routers_Listener_Pid), io:format("launch_router_supervisors.~n" ++ "Router_Nd: ~p~nServers in ~p:~p~n" ++ "Router Processes in ~p:~p~n", [Router_Nd, Router_Nd, Server_Nodes, Router_Nd, Router_Processes]) end. %%-------------------------------------------------------------------- %% @doc %% This function spawns a router supervisor on the target node and %% flags the start of the sequence to deploy the router processes. , Server_Nodes , Servers_Router_Pr , %% Router_Processes, Num_Total_Servers, Routers_Listener_Pid) -> %% ok | {error, reason} %% @end %%-------------------------------------------------------------------- start_router_supervisor(Router_Node, Server_Nodes, Servers_Router_Pr, Router_Processes, Num_Total_Servers, Routers_Listener_Pid) -> %%=================================================================================== %% THIS IS ALL TO BE USED WITH THE NEW VERSION OF ROUTER MODULE (NOT FINISHED YET) %%=================================================================================== %% Config = #config{pid=undefined, %% mon_rtrs= Router_Processes, %% rtrs_list=undefined, %% rtrs_info=undefined, %% rtrs_dbs=undefined}, %% <==== ARGUMENT CHANGED TO RECORD %% io:format("============================================~n" ++ %% " Config in launcher = ~p~n" ++ %% "============================================~n", [Config]), R_Sup_Pid = spawn_link(Router_Node , fun ( ) - > %% router_supervisor({normal_state, Config}) %% end), %% Routers_Listener_Pid ! {R_Sup_Pid, add_router_sup}, %% R_Sup_Pid ! {launch_router_processes, Server_Nodes, Servers_Router_Pr , %% Router_Processes, %% Num_Total_Servers, %% Routers_Listener_Pid}, %%=================================================================================== R_Sup_Pid = spawn_link(Router_Node, fun() -> ) < = = = = ADDED one more list ( Servers_List ) . end), Routers_Listener_Pid ! {R_Sup_Pid, add_router_sup}, R_Sup_Pid ! {Server_Nodes, Servers_Router_Pr, Router_Processes, Num_Total_Servers, Routers_Listener_Pid, launch_router_processes}, ok. %%-------------------------------------------------------------------- %% @doc %% This function determines the number of router processes that are %% going to be spawned on a router node and gathers all the information %% required for that purpose. %% @spec launch_router_processes(R_Sup_Pid , Server_Nodes , Servers_Router_Pr , %% Router_Processes, Num_Total_Servers, Routers_Listener_Pid) -> %% Status Messages | {error, reason} %% @end %%-------------------------------------------------------------------- launch_router_processes(R_Sup_Pid, Server_Nodes, Servers_Router_Pr, Router_Processes, Num_Total_Servers, Routers_Listener_Pid) -> case Router_Processes of [] -> io:format("Router processes start sequence, finished.~n"); [Router_Process|New_Router_Processes] -> io:format("launch_router_processes/4 Router_Processes: ~p~n", [Router_Processes]), case length(Server_Nodes) > Servers_Router_Pr of true -> {Servers, New_Server_Nodes} = lists:split(Servers_Router_Pr, Server_Nodes), start_router_process(Router_Process, Servers, Servers_Router_Pr, Num_Total_Servers, R_Sup_Pid, Routers_Listener_Pid), launch_router_processes(R_Sup_Pid, New_Server_Nodes, Servers_Router_Pr, New_Router_Processes, Num_Total_Servers, Routers_Listener_Pid); false -> start_router_process(Router_Process, Server_Nodes, Servers_Router_Pr, Num_Total_Servers, R_Sup_Pid, Routers_Listener_Pid) end end. %%-------------------------------------------------------------------- %% @doc %% This function spawns a router process on the target node and %% flags the start of the sequence to deploy the server supervisor %% process on the target node. %% start_router_process(Router_Name , Server_Nodes , Servers_Router_Pr , %% Num_Total_Servers, R_Sup_Pid, Routers_Listener_Pid) -> %% yes | {error, reason} %% @end %%-------------------------------------------------------------------- start_router_process(Router_Name, Server_Nodes, Servers_Router_Pr, Num_Total_Servers, R_Sup_Pid, Routers_Listener_Pid) -> %% global:register_name(Router_Name, %% R_Pid = spawn_link(fun() -> %% router_process({initial_state, R_Sup_Pid, [], [], []}) %% end)), R_Pid = spawn_link(fun() -> router_process({initial_state, R_Sup_Pid, [], [], []}) end), Routers_Listener_Pid ! {Router_Name, R_Pid, add_router}, R_Pid ! {Router_Name, Server_Nodes, Servers_Router_Pr, Num_Total_Servers, Routers_Listener_Pid, launch_server}, yes. %%=================================================================================== %% THIS IS ALL TO BE USED WITH THE NEW VERSION OF ROUTER MODULE (NOT FINISHED YET) %%=================================================================================== %% R_Pid ! {launch_server, %% Router_Name, %% Server_Nodes, Servers_Router_Pr , %% Num_Total_Servers, %% Routers_Listener_Pid}, %% yes. %%=================================================================================== %%-------------------------------------------------------------------- %% @doc %% This function determines the target nodes to spawn the corresponding %% server supervisor processes. %% , Servers_Router_Pr , %% Num_Total_Servers, Routers_Listener_Pid) -> %% Status Messages | {error, reason} %% @end %%-------------------------------------------------------------------- launch_server_supervisors(Server_Nodes, Servers_Router_Pr, Num_Total_Servers, Routers_Listener_Pid) -> case length(Server_Nodes) > Servers_Router_Pr of true -> {Servers, New_Server_Nodes} = lists:split(Servers_Router_Pr, Server_Nodes), io:format("launch_server_supervisors.~nServers:~p~n", [Server_Nodes]), start_server_supervisors(Servers, Num_Total_Servers, Routers_Listener_Pid), launch_server_supervisors(New_Server_Nodes, Servers_Router_Pr, Num_Total_Servers, Routers_Listener_Pid); false -> io:format("launch_server_supervisors.~nServers:~p~n", [Server_Nodes]), start_server_supervisors(Server_Nodes, Num_Total_Servers, Routers_Listener_Pid) end. %%-------------------------------------------------------------------- %% @doc %% This function spawns the server supervisor processes on the target %% nodes. Then, it notifies the name and pid of the server supervisor %% to allow the routing of the requests made by the clients. %% , Servers_Router_Pr , %% Num_Total_Servers, Routers_Listener_Pid) -> %% Status Messages | {error, reason} %% @end %%-------------------------------------------------------------------- start_server_supervisors(Server_Nodes, Num_Total_Servers, Routers_Listener_Pid) -> case Server_Nodes == [] of true -> io:format("Server supervisors start sequence is finished.~n"); false -> [Server|New_Server_Nodes] = Server_Nodes, S = atom_to_list(Server), Server_Name = string:left(S, string:chr(S,$@) - 1), Server_Sup_Pid = spawn_link(Server, fun() -> server:start_server_supervisor( Server, string_to_atom(Server_Name), Num_Total_Servers) end), Routers_Listener_Pid ! {Server_Name, Server_Sup_Pid, add_server}, start_server_supervisors(New_Server_Nodes, Num_Total_Servers, Routers_Listener_Pid) end. %%==================================================================== %% AUTO STOP APPLICATION LOGIC %%==================================================================== %%-------------------------------------------------------------------- %% @doc auto_stop/1 stops and closes the IM when the benchmarks are %% finished. %% auto_stop(Nodes ) - > fun ( ) %% @end %%-------------------------------------------------------------------- auto_stop(Nodes) -> {_Router_Nodes, _Server_Nodes, Client_Nodes, _Traffic_Nodes} = extractor(Nodes), Auto_Stop_Pid = self(), launch_stop_notifiers(Client_Nodes, Auto_Stop_Pid), auto_stop(Nodes, length(Client_Nodes), 0). %%-------------------------------------------------------------------- %% @doc auto_stop/3 stops and closes the IM when the benchmarks are %% finished. %% auto_stop(Nodes , Total_Loggers , Finished_Loggers ) - > pid ( ) . %% @end %%-------------------------------------------------------------------- auto_stop(Nodes, Total_Loggers, Finished_Loggers) -> receive logger_stopped -> case Finished_Loggers + 1 of Total_Loggers -> spawn(fun() -> stop_nodes_gently(Nodes) end); New_Finished_Loggers -> auto_stop(Nodes, Total_Loggers, New_Finished_Loggers) end; _Other -> io:format("Something failed in auto_stop/3"), auto_stop(Nodes, Total_Loggers, Finished_Loggers) end. %%-------------------------------------------------------------------- %% @doc %% launch_stop_notifiers/2 sets up the processes that notify the %% end of the benchmarks. %% , Auto_Stop_Pid ) - > ok %% @end %%-------------------------------------------------------------------- launch_stop_notifiers(Client_Nodes, Auto_Stop_Pid) -> case Client_Nodes of [] -> ok; [Node|New_Client_Nodes] -> spawn(Node, fun() -> create_notifier(Auto_Stop_Pid) end), launch_stop_notifiers(New_Client_Nodes, Auto_Stop_Pid) end. %%-------------------------------------------------------------------- %% @doc create_notifier/1 is the first stage of the notifier process . %% This process notifies the auto_stop process that a logger is %% stopped. %% create_notifier(Auto_Stop_Pid ) - > fun ( ) . %% @end %%-------------------------------------------------------------------- create_notifier(Auto_Stop_Pid) -> register(stop_notifier, self()), notifier(Auto_Stop_Pid). %%-------------------------------------------------------------------- %% @doc notifier/1 is the second stage of the notifier process . This %% process notifies the auto_stop process that a logger is stopped. %% ) - > logger_stopped %% @end %%-------------------------------------------------------------------- notifier(Auto_Stop_Pid) -> receive logger_stopped -> Auto_Stop_Pid ! logger_stopped; _Other -> io:format("something failed with the notifier~n"), notifier(Auto_Stop_Pid) end. %%==================================================================== %% STOP APPLICATION LOGIC %%==================================================================== %%-------------------------------------------------------------------- %% @doc %% stop/5 stops the application by shutting down all nodes. %% , S_RP , S_T , Cl_T , List_Domains ) - > ok %% @end %%-------------------------------------------------------------------- stop(S_RN, S_RP, S_T, Cl_T, List_Domains) -> case S_T rem S_RP of Rem when Rem == 0 -> R_T = S_T div S_RN; _Rem -> R_T = (S_T div S_RN) + 1 end, stop_nodes(nodes_list(R_T, S_RN, S_T, Cl_T, List_Domains)). %%-------------------------------------------------------------------- %% @doc %% stop/6 stops the application by shutting down all nodes. %% %% @spec stop(Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total , Clients_Total , List_Domains , ) - > ok %% @end %%-------------------------------------------------------------------- stop(Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Clients_Total, List_Domains, Num_of_Hosts) -> Num_TS = Servers_Total * Num_of_Hosts, Architecture_Info = {Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Num_TS, Clients_Total}, case List_Domains == [] of true -> init:stop(); false -> [Domain|New_List_Domains] = List_Domains, stop_host(Num_of_Hosts, Architecture_Info, Domain), stop(Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Clients_Total, New_List_Domains, Num_of_Hosts - 1) end. %%-------------------------------------------------------------------- %% @doc stop_host/3 stops an IM that has been deployed locally in one %% host. %% Traffic_Nodes is hard - coded to 4 . This has an easy fix adding %% Traffic_Total as parameter. This is not done because it is used %% in local tests and debugging. %% , Domain ) - > ok %% @end %%-------------------------------------------------------------------- stop_host(Num_of_Host, Architecture_Info, Domain) -> {Servers_Per_Router_Node, _Servers_Per_Router_Process, Servers_Total, _Num_TS, Clients_Total} = Architecture_Info, case Servers_Total rem Servers_Per_Router_Node of 0 -> Routers = Servers_Total div Servers_Per_Router_Node; _Greater_than_0 -> Routers = (Servers_Total div Servers_Per_Router_Node) + 1 end, Router_Nodes = node_name_generator(Num_of_Host, router, Domain, Routers, 0), Server_Nodes = node_name_generator(Num_of_Host, server, Domain, Servers_Total, 0), Client_Nodes = node_name_generator(Num_of_Host, client, Domain, Clients_Total, 0), Traffic_Nodes = node_name_generator(Num_of_Host, traffic, Domain, 4, 0), stop_nodes(Traffic_Nodes), stop_nodes(Client_Nodes), stop_nodes(Server_Nodes), stop_nodes(Router_Nodes). %%-------------------------------------------------------------------- %% @doc %% stop_nodes/1 stop nodes in the list passed as parameter. %% @spec stop_nodes(Nodes_List ) - > ok %% @end %%-------------------------------------------------------------------- stop_nodes(Nodes_List) -> case Nodes_List of [] -> ok; [Node|Rest_of_Nodes] -> rpc:call(Node, init, stop, []), stop_nodes(Rest_of_Nodes) end. %%-------------------------------------------------------------------- %% @doc %% stop_nodes_gently/1 stop nodes in the list passed as parameter. %% The nodes are stopped in order, so the running processes are %% stopped before node is finished. %% @spec stop_nodes(Nodes_List ) - > ok %% @end %%-------------------------------------------------------------------- stop_nodes_gently(Nodes_List) -> {Router_Nodes, Server_Nodes, Client_Nodes, Traffic_Nodes} = extractor(Nodes_List), stop_nodes(Client_Nodes), stop_nodes(Traffic_Nodes), finish_nodes({router, Router_Nodes}), finish_nodes({server, Server_Nodes}), init:stop(). %%-------------------------------------------------------------------- %% @doc finish_nodes/1 spawn the corresponding finish_node/0 functions %% to finish router and server nodes gently. %% @spec finish_nodes({Node_Type , [ H|T ] } ) - > ok . %% @end %%-------------------------------------------------------------------- finish_nodes({_Node_Type, []}) -> ok; finish_nodes({Node_Type, [H|T]}) -> case Node_Type of router -> spawn(H, fun() -> router:finish_node()end), finish_nodes({router, T}); server -> spawn(H, fun() -> server:finish_node() end), finish_nodes({server, T}) end. %%%======================================================================== %%% AUXILIARY FUNCTIONS FOR ROUTERS INFORMATION AND RELIABILITY %%%======================================================================== %%-------------------------------------------------------------------- %% @doc %% routers_listener/5 is an auxiliary process central to the start %% sequence of the system. It is responsible for receive the pids %% of router supervisors, router processes and server supervisors %% to pass this information to the relevant processes, once these %% processes are all spawned. %% @spec routers_listener(Servers_Total , List_Servers , List_Routers , List_Router_Sups , Client_Nodes ) - > %% Status Messages | {error, reason} %% @end %%-------------------------------------------------------------------- routers_listener(Servers_Total, List_Servers, List_Routers, List_Router_Sups, Client_Nodes) -> receive {Server_Name, Server_Sup_Pid, add_server} -> New_List_Servers = lists:append(List_Servers, [{Server_Name, Server_Sup_Pid}]), io:format("List of servers (routers_listener/4): ~p~n", [New_List_Servers]), if length(New_List_Servers) == Servers_Total -> io:format("launching start_routers_db/2 having Client_Nodes: ~p~n", [Client_Nodes]), Routers_DBs_Pids = launch_routers_db(Client_Nodes, List_Routers, []), feed_router_sup(List_Router_Sups, List_Routers, Routers_DBs_Pids), feed_routers(New_List_Servers, List_Routers, List_Routers); true -> routers_listener(Servers_Total, New_List_Servers, List_Routers, List_Router_Sups, Client_Nodes) end; {Router_Name, Router_Pid, add_router} -> New_List_Routers = lists:append(List_Routers, [{atom_to_list(Router_Name), Router_Pid}]), routers_listener(Servers_Total, List_Servers, New_List_Routers, List_Router_Sups, Client_Nodes); {Router_Sup_Pid, add_router_sup} -> New_List_Router_Sups = lists:append(List_Router_Sups, [Router_Sup_Pid]), routers_listener(Servers_Total, List_Servers, List_Routers, New_List_Router_Sups, Client_Nodes); {New_Clients, add_client_node} -> New_Client_Nodes = lists:append(Client_Nodes, New_Clients), routers_listener(Servers_Total, List_Servers, List_Routers, List_Router_Sups, New_Client_Nodes); Other -> io:format("Something failed here. routers_listener/4 received: ~p~n", [Other]), routers_listener(Servers_Total, List_Servers, List_Routers, List_Router_Sups, Client_Nodes) end. %%-------------------------------------------------------------------- %% @doc launch_routers_db/3 spawns a process on each of the %% client nodes started, and returns a list with the pids of all the processes spawned . %% , List_Routers , Routers_DBs ) - > %% Routers_DBs (list) | {error, reason} %% @end %%-------------------------------------------------------------------- launch_routers_db(Client_Nodes, List_Routers, Routers_DBs) -> case Client_Nodes of [] -> io:format("All routers_db processes started.~n"), Routers_DBs; [Client|New_Client_Nodes] -> New_Routers_DBs = Routers_DBs ++ start_routers_db(Client, List_Routers), launch_routers_db(New_Client_Nodes, List_Routers, New_Routers_DBs) end. %%-------------------------------------------------------------------- %% @doc start_routers_db/2 spawns a process on the target %% client node passed as the argument. It returns a list of length 1 containing the pid of the process spawned . It also %% flags the process to globally register itself. %% @spec launch_routers_db(Client_Node , List_Routers ) - > [ ] | { error , reason } %% @end %%-------------------------------------------------------------------- start_routers_db(Client_Node, List_Routers) -> io:format("Executing start_routers_db/2~n"), R_DB_Pid = spawn(Client_Node, fun() -> routers_db(List_Routers) end), io:format("routers_db Pid = ~p~n", [R_DB_Pid]), R_DB_Pid ! {register_globally}, [R_DB_Pid]. %%-------------------------------------------------------------------- %% @doc %% This process is spawned in all client nodes and it stores the %% pids of all the routers processes spawned in the system. It is %% in charge of providing the clients these pids, so the clients %% can direct their requests to the routers. %% routers_db(Routers_List ) - > Status Messages | Routers_pids ( list ) %% @end %%-------------------------------------------------------------------- routers_db(Routers_List) -> receive {register_globally} -> io:format("routers_db/1 received {register_globally}~n"), global:register_name(routers_db, self()), routers_db(Routers_List); {register_locally} -> io:format("routers_db/1 received {register_locally}~n"), Pid = self(), register(routers_db, Pid), routers_db(Routers_List); {retrieve_routers, Requester_Pid} -> Requester_Pid ! {Routers_List, router_list}, routers_db(Routers_List); {New_Routers_List, receive_router_list}-> routers_db(New_Routers_List); Other -> io:format("Something failed at routers_db/1. Received: ~p~n", [Other]), routers_db(Routers_List) end. %%-------------------------------------------------------------------- %% @doc %% feed_router_sup/3 passes the list of routers spawned in the system %% to the router supervisors. @spec feed_router_sup(List_Router_Sups , List_Routers , Router_DBs_Pids ) - > %% ok | {error, reason} %% @end %%-------------------------------------------------------------------- feed_router_sup(List_Router_Sups, List_Routers, Router_DBs_Pids) -> io:format("feed_router_sup/2~n"), case List_Router_Sups of [] -> ok; [R_Sup_Pid|T] -> R_Sup_Pid ! {list_routers, List_Routers, Router_DBs_Pids}, feed_router_sup(T, List_Routers, Router_DBs_Pids) end. %%-------------------------------------------------------------------- %% @doc %% feed_routers/3 passes the list of routers and servers spawned in %% the system to the router processes. This is needed for reliability , List_Routers , List_Routers_2 ) - > %% Status Message | {error, reason} %% @end %%-------------------------------------------------------------------- feed_routers(List_Servers, List_Routers, List_Routers_2) -> case List_Routers_2 of [] -> io:format("Host is deployed.~n"); [{_, Router_Pid}|New_List_Routers] -> Router_Pid ! { list_routers_servers , List_Routers , List_Servers } , % % < = = = = TO BE USED WITH NEW VERSION OF ROUTER MODULE ( NOT IMPLEMENTED YET ) . Router_Pid ! {list_routers, List_Routers}, Router_Pid ! {list_servers, List_Servers}, feed_routers(List_Servers, List_Routers, New_List_Routers) end. %%========================================================================= %% OTHER AUXILIARY FUNCTIONS %%========================================================================= %%-------------------------------------------------------------------- %% @doc %% This function builds a list containing the names of the target %% nodes given all the details of the architecture of the Instant %% Messenger application. This is used to launch the application on a distributed environment with one node per host . %% , S_RN , S_T , Cl_Total , Domains ) - > list ( ) %% @end %%-------------------------------------------------------------------- nodes_list(R_T, S_RN, S_T, Cl_T, Domains) -> {R_S_Dom, Cl_Dom} = lists:split(R_T + S_T, Domains), R_S_Nodes = router_server_nodes(1,1,S_RN, R_S_Dom, []), Cl_Nodes = client_nodes(Cl_T, 1, hd(Cl_Dom), []), lists:reverse(lists:flatten([Cl_Nodes|R_S_Nodes])). %%-------------------------------------------------------------------- %% @doc %% router_server_nodes/5 builds the list containing the names of %% the router and server nodes where the Instant Messenger %% application will be deployed. %% @spec router_server_nodes(R_Acc , S_Acc , S_RN , Domains , Nodes_List ) - > list ( ) %% @end %%-------------------------------------------------------------------- router_server_nodes(R_Acc, S_Acc, S_RN, Domains, Nodes_List) -> case Domains of [] -> lists:flatten(Nodes_List); [R_Dom|O_Doms] -> Router = [string_to_atom(string:join(["router", integer_to_list(R_Acc)], "_") ++ "@" ++ atom_to_list(R_Dom))], case S_RN =< length(O_Doms) of true -> {S_Doms, New_Domains} = lists:split(S_RN, O_Doms), {Servers, New_S_Acc} = server_nodes(S_Acc, S_Doms, []), New_Nodes_List = [[Servers|Router]|Nodes_List], router_server_nodes(R_Acc + 1, New_S_Acc, S_RN, New_Domains, New_Nodes_List); false -> {Servers, New_S_Acc} = server_nodes(S_Acc, O_Doms, []), New_Nodes_List = [[Servers|Router]|Nodes_List], router_server_nodes(R_Acc + 1, New_S_Acc, S_RN, [], New_Nodes_List) end end. %%-------------------------------------------------------------------- %% @doc server_nodes/3 is an auxiliary function to router_server_nodes/5 . %% It generates the names of the server nodes. %% @spec server_nodes(S_Acc , S_RN , Domains , Nodes ) - > { list ( ) , Integer ( ) } %% @end %%-------------------------------------------------------------------- server_nodes(S_Acc, Domains, Nodes) -> case Domains of [] -> {Nodes, S_Acc}; [H|T] -> New_Nodes = [string_to_atom(string:join(["server", integer_to_list(S_Acc)], "_") ++ "@" ++ atom_to_list(H))|Nodes], server_nodes(S_Acc + 1, T, New_Nodes) end. %%-------------------------------------------------------------------- %% @doc %% client_nodes/4 generates the names of the client nodes. %% @spec client_nodes(Cl_T , Cl_Acc , Domain , Nodes ) - > list ( ) %% @end %%-------------------------------------------------------------------- client_nodes(Cl_T, Cl_Acc, Domain, Nodes) -> case Cl_Acc of Cl_T -> New_Nodes = [string_to_atom(string:join(["client", integer_to_list(Cl_Acc)], "_") ++ "@" ++ atom_to_list(Domain))|Nodes], lists:flatten(New_Nodes); _Other -> New_Nodes = [string_to_atom(string:join(["client", integer_to_list(Cl_Acc)], "_") ++ "@" ++ atom_to_list(Domain))|Nodes], client_nodes(Cl_T, Cl_Acc + 1, Domain, New_Nodes) end. %-------------------------------------------------------------------- %% @doc %% Given a list of nodes, extractor/1 returns a tuple containing three lists : one containing the router nodes , a second that holds the server nodes , and a third with the client nodes . If %% the input list contains invalid names, these are dismissed. %% %% @spec extractor(Nodes_List) -> {list(), list(), list()}. %% @end %%-------------------------------------------------------------------- extractor(Nodes_List) -> extractor(Nodes_List, [],[],[], []). %-------------------------------------------------------------------- %% @doc Given a list of nodes , and three recipient lists for the names %% of the router nodes, server nodes and client nodes, extractor/4 %% behaves in the same way as extractor/1. %% @spec extractor(Nodes_List , R_Nodes , S_Nodes , Cl_Nodes ) - > %% {list(), list(), list()}. %% @end %%-------------------------------------------------------------------- extractor(Nodes_List, R_Nodes, S_Nodes, Cl_Nodes, Tr_Nodes) -> case Nodes_List of [] -> {lists:reverse(R_Nodes), lists:reverse(S_Nodes), lists:reverse(Cl_Nodes), lists:reverse(Tr_Nodes)}; [H|T] -> case string:sub_string(atom_to_list(H), 1, 3) of "rou" -> New_R_Nodes = [H|R_Nodes], extractor(T, New_R_Nodes, S_Nodes, Cl_Nodes, Tr_Nodes); "ser" -> New_S_Nodes = [H|S_Nodes], extractor(T, R_Nodes, New_S_Nodes, Cl_Nodes, Tr_Nodes); "cli" -> New_Cl_Nodes = [H|Cl_Nodes], extractor(T, R_Nodes, S_Nodes, New_Cl_Nodes, Tr_Nodes); "tra" -> New_Tr_Nodes = [H|Tr_Nodes], extractor(T, R_Nodes, S_Nodes, Cl_Nodes, New_Tr_Nodes); _Other -> extractor(T, R_Nodes, S_Nodes, Cl_Nodes, Tr_Nodes) end end. %%-------------------------------------------------------------------- %% @doc %% This function builds the name of a target node given all the %% details of the architecture of the system. %% , Domain , Total_Nodes , ) - > atom ( ) %% @end %%-------------------------------------------------------------------- node_name_generator(Host, Node_Type, Domain, Total_Nodes, Children_Nodes_Per_Node) -> case Children_Nodes_Per_Node of 0 -> [string_to_atom( string:join([atom_to_list(Node_Type), integer_to_list(X)], "_") ++ "@" ++ atom_to_list(Domain)) || X <- lists:seq(((Host * Total_Nodes) - Total_Nodes + 1), Host * Total_Nodes)]; _Other -> [string_to_atom( string:join([atom_to_list(Node_Type), integer_to_list(X), integer_to_list(Y)], "_") ++ "@" ++ atom_to_list(Domain)) || X <- lists:seq(((Host * Total_Nodes) - Total_Nodes + 1), Host * Total_Nodes), Y <- lists:seq(1, Children_Nodes_Per_Node)] end. %%-------------------------------------------------------------------- %% @doc %% This function builds a list containing the name of all the router %% processes that will be used in the system. %% , Domain , Total_Nodes , ) - > list of atom ( ) %% @end %%-------------------------------------------------------------------- router_names_generator(Num_of_Host, Servers_Total, Servers_Router_Node, Servers_Router_Process, Num_of_Sub_Pr) -> B = Servers_Total div Servers_Router_Node, C = Servers_Total div Servers_Router_Process, io:format("Servers_Router_Node: ~p, Servers_Router_Process: ~p~n", [Servers_Router_Node, Servers_Router_Process]), io:format("B = ~p, C = ~p~n", [B, C]), case Servers_Total of Servers_Router_Node -> io:format("true~n"), D = (Servers_Total div Servers_Router_Process); _Other -> io:format("false~n"), case Servers_Router_Node rem Servers_Router_Process == 0 of true -> D = Servers_Total div Servers_Router_Process; false -> D = (Servers_Total div Servers_Router_Node) + (Servers_Total div Servers_Router_Process) end end, io:format("D: ~p~n",[D]), case D * Servers_Router_Process < Servers_Total of true -> A = D + 1; false -> A = D end, io:format("A: ~p~n", [A]), Lower_Limit = (Num_of_Host-1) * A + 1, Upper_Limit = Lower_Limit + A - 1, case Num_of_Sub_Pr of 0 -> [string_to_atom( string:join(["router", integer_to_list(X)], "_")) || X <- lists:seq(Lower_Limit, Upper_Limit)]; _Another -> [string_to_atom( string:join(["router", integer_to_list(X), integer_to_list(Y)], "_")) || X <- lists:seq(Lower_Limit, Upper_Limit), Y <- lists:seq(1, Num_of_Sub_Pr)] end. %%-------------------------------------------------------------------- %% @doc %% string_to_atom/1 takes a string and returns an atom, or an %% existing atom if that is the case. %% ) - > atom ( ) | existing_atom ( ) %% @end %%-------------------------------------------------------------------- string_to_atom(String) -> try list_to_existing_atom(String) of Val -> Val catch error:_ -> list_to_atom(String) end.
null
https://raw.githubusercontent.com/release-project/benchmarks/55f042dca3a2c680e2967c59edc9636456047bd5/IM/RD-IM/launcher.erl
erlang
------------------------------------------------------------------- @doc Launcher module for the Distributed Erlang instant messenger (IM) application developed as a real benchmark for the language. This module implements the logic to deploy a system similar set of virtual machines to host the system. @end ------------------------------------------------------------------- <==== CHANGE router_supervisor/5 TO router_supervisor/1 WHEN USING THE NEW VERSION OF ROUTER MODULE. -include("config.hrl"). <==== TO BE USED WITH THE NEW VERSION OF ROUTER MODULE. (NOT FINISHED YET). ============================================================================ APPLICATION DEPLOYMENT LOGIC ============================================================================ -------------------------------------------------------------------- @doc start/6 launches the sequence to set up the architecture, and Arguments: Servers_Per_Router_Node: (int) The number of server nodes that are children of a router node. Server_Per_Router_Process: (int) The number of server supervisor processes that are monitored by a router process. Servers_Total: (int) Final number of servers in the system. Clients_Total: (int) Final number of client nodes. List_Domains: (list) List containing all the domains of the hosts in which the system is deployed. This is usually one, but can be more if the application is hosted in a cluster with different domains. deployed. Status Messages | {error, reason} @end --------------------------------------------------------------------- -------------------------------------------------------------------- @doc starts the sequence of that launch each of the components that will be deployed in a particular hosts from the list specified in start/6. start_host(Num_of_Host, Architecture_Info, Domain, Routers_Listener_Pid) -> Status Messages | {error, reason} @end -------------------------------------------------------------------- --------------------------------------------------------------------- @doc start/5 launches the sequence to set up the architecture, and Arguments: S_RN: (int) The number of server nodes that are children of a router node. S_RP: (int) The number of server supervisor processes that are monitored by a router process. S_T: (int) Final number of servers in the system. Cl_T: (int) Final number of client nodes. List_Domains: (list) List containing all the domains of the hosts in which the system is deployed. This is usually one, but can be more if the application is hosted in a cluster with different domains. Example: start(2,1,2,4,['domain_1.do','domain_2.do], ..., 'domain_4.do ]). nodes, deploying the router on host with domain 'domain_1.do', Status Messages | {error, reason} @end --------------------------------------------------------------------- ==================================================================== BENCHERL START FUNCTIONS ==================================================================== --------------------------------------------------------------------- @doc The function determines the structure of the architecture, assuming Arguments: Nodes: (list) List containing all the nodes comprising the architecture of the application. Example: start(['router_1@domain_1.do','router_2@domain_2.do'], ..., 'client_4@domain_4.do ]). @end -------------------------------------------------------------------- Classify nodes by type, and work out the architecture layout Total nodes of each kind Determine the maximum number of server nodes children of a router node Set up the routers listener for deployment. --------------------------------------------------------------------- @doc start_bencherl/5 is similar to start/5, but in this case the last argument is a list containing the nodes where the aplication must only. Arguments: S_RN: (int) The number of server nodes that are children of a router node. S_RP: (int) The number of server supervisor processes that are monitored by a router process. S_T: (int) Final number of servers in the system. Cl_T: (int) Final number of client nodes. Nodes: (list) List containing all the nodes comprising the architecture of the application. Example: start(2,1,2,4,['router_1@domain_1.do','router_2@domain_2.do'], ..., 'client_4@domain_4.do ]). @spec start_bencherl(S_RN, S_RP, S_T, Cl_T, List_Domains) -> Status Messages | {error, reason} @end --------------------------------------------------------------------- =================================================================== END BENCHERL START FUNCTIONS =================================================================== -------------------------------------------------------------------- @doc starts the sequence of that launch each of the components that will be deployed in the hosts from the list specified in start/5. start_Distributed(Architecture_Info, Nodes, Routers_Listener_Pid) -> Status Messages | {error, reason} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc This function determines the router nodes where the router supervisors must be spawned and gathers all the information required for that purpose. Architecture_Info, Routers_Listener_Pid) -> Status Messages | {error, reason} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc This function spawns a router supervisor on the target node and flags the start of the sequence to deploy the router processes. Router_Processes, Num_Total_Servers, Routers_Listener_Pid) -> ok | {error, reason} @end -------------------------------------------------------------------- =================================================================================== THIS IS ALL TO BE USED WITH THE NEW VERSION OF ROUTER MODULE (NOT FINISHED YET) =================================================================================== Config = #config{pid=undefined, mon_rtrs= Router_Processes, rtrs_list=undefined, rtrs_info=undefined, rtrs_dbs=undefined}, %% <==== ARGUMENT CHANGED TO RECORD io:format("============================================~n" ++ " Config in launcher = ~p~n" ++ "============================================~n", [Config]), router_supervisor({normal_state, Config}) end), Routers_Listener_Pid ! {R_Sup_Pid, add_router_sup}, R_Sup_Pid ! {launch_router_processes, Server_Nodes, Router_Processes, Num_Total_Servers, Routers_Listener_Pid}, =================================================================================== -------------------------------------------------------------------- @doc This function determines the number of router processes that are going to be spawned on a router node and gathers all the information required for that purpose. Router_Processes, Num_Total_Servers, Routers_Listener_Pid) -> Status Messages | {error, reason} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc This function spawns a router process on the target node and flags the start of the sequence to deploy the server supervisor process on the target node. Num_Total_Servers, R_Sup_Pid, Routers_Listener_Pid) -> yes | {error, reason} @end -------------------------------------------------------------------- global:register_name(Router_Name, R_Pid = spawn_link(fun() -> router_process({initial_state, R_Sup_Pid, [], [], []}) end)), =================================================================================== THIS IS ALL TO BE USED WITH THE NEW VERSION OF ROUTER MODULE (NOT FINISHED YET) =================================================================================== R_Pid ! {launch_server, Router_Name, Server_Nodes, Num_Total_Servers, Routers_Listener_Pid}, yes. =================================================================================== -------------------------------------------------------------------- @doc This function determines the target nodes to spawn the corresponding server supervisor processes. Num_Total_Servers, Routers_Listener_Pid) -> Status Messages | {error, reason} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc This function spawns the server supervisor processes on the target nodes. Then, it notifies the name and pid of the server supervisor to allow the routing of the requests made by the clients. Num_Total_Servers, Routers_Listener_Pid) -> Status Messages | {error, reason} @end -------------------------------------------------------------------- ==================================================================== AUTO STOP APPLICATION LOGIC ==================================================================== -------------------------------------------------------------------- @doc finished. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc finished. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc launch_stop_notifiers/2 sets up the processes that notify the end of the benchmarks. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc This process notifies the auto_stop process that a logger is stopped. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc process notifies the auto_stop process that a logger is stopped. @end -------------------------------------------------------------------- ==================================================================== STOP APPLICATION LOGIC ==================================================================== -------------------------------------------------------------------- @doc stop/5 stops the application by shutting down all nodes. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc stop/6 stops the application by shutting down all nodes. @spec stop(Servers_Per_Router_Node, Servers_Per_Router_Process, @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc host. Traffic_Total as parameter. This is not done because it is used in local tests and debugging. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc stop_nodes/1 stop nodes in the list passed as parameter. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc stop_nodes_gently/1 stop nodes in the list passed as parameter. The nodes are stopped in order, so the running processes are stopped before node is finished. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc to finish router and server nodes gently. @end -------------------------------------------------------------------- ======================================================================== AUXILIARY FUNCTIONS FOR ROUTERS INFORMATION AND RELIABILITY ======================================================================== -------------------------------------------------------------------- @doc routers_listener/5 is an auxiliary process central to the start sequence of the system. It is responsible for receive the pids of router supervisors, router processes and server supervisors to pass this information to the relevant processes, once these processes are all spawned. Status Messages | {error, reason} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc client nodes started, and returns a list with the pids of all Routers_DBs (list) | {error, reason} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc client node passed as the argument. It returns a list of length flags the process to globally register itself. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc This process is spawned in all client nodes and it stores the pids of all the routers processes spawned in the system. It is in charge of providing the clients these pids, so the clients can direct their requests to the routers. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc feed_router_sup/3 passes the list of routers spawned in the system to the router supervisors. ok | {error, reason} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc feed_routers/3 passes the list of routers and servers spawned in the system to the router processes. This is needed for reliability Status Message | {error, reason} @end -------------------------------------------------------------------- % < = = = = TO BE USED WITH NEW VERSION OF ROUTER MODULE ( NOT IMPLEMENTED YET ) . ========================================================================= OTHER AUXILIARY FUNCTIONS ========================================================================= -------------------------------------------------------------------- @doc This function builds a list containing the names of the target nodes given all the details of the architecture of the Instant Messenger application. This is used to launch the application @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc router_server_nodes/5 builds the list containing the names of the router and server nodes where the Instant Messenger application will be deployed. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc It generates the names of the server nodes. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc client_nodes/4 generates the names of the client nodes. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Given a list of nodes, extractor/1 returns a tuple containing the input list contains invalid names, these are dismissed. @spec extractor(Nodes_List) -> {list(), list(), list()}. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc of the router nodes, server nodes and client nodes, extractor/4 behaves in the same way as extractor/1. {list(), list(), list()}. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc This function builds the name of a target node given all the details of the architecture of the system. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc This function builds a list containing the name of all the router processes that will be used in the system. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc string_to_atom/1 takes a string and returns an atom, or an existing atom if that is the case. @end --------------------------------------------------------------------
LAUNCHER MODULE @author upon a design by ( C ) 2014 , RELEASE project Scalable Distributed Erlang extension of the Erlang / OTP to the system described in the Section 2 of the document " Instant Messenger Architectures Design Proposal " given a Created : 25 Jul 2014 by -module(launcher). -export([start/5, start/6, start_bencherl/1, start_bencherl/5, stop/5, stop/6, launch_router_processes/6, launch_server_supervisors/4]). run the IM application . : ( int ) Number of hosts in which the system is Example : start(2,1,2,4,['domain.do ' ] , 1 ) . start(2,1,2,4,['domain ' ] , 1 ) . These launch a system comprising 1 router , 2 servers , and 4 client nodes on 1 host , with domain domain.do or domain . In this case , there are 2 router processes , each of them monitoring one server supervisor process . , Servers_Per_Router_Process , Servers_Total , Clients_Total , List_Domains , Num_of_Hosts ) - > start(Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Clients_Total, List_Domains, Num_of_Hosts) -> Num_TS = Servers_Total * Num_of_Hosts, Architecture_Info = {Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Num_TS, Clients_Total}, case List_Domains == [] of true -> io:format("start/4 is finished.~n"); false -> [Domain|New_List_Domains] = List_Domains, case whereis(routers_listener) of undefined -> io:format("~n=============================================~n" ++ "Initiating the Distributed Instant Messenger.~n"++ "=============================================~n"), Routers_Listener_Pid = spawn(fun() -> routers_listener(Num_TS, [], [], [], []) end), register(routers_listener, Routers_Listener_Pid); _ -> ok end, start_host(Num_of_Hosts, Architecture_Info, Domain, whereis(routers_listener)), start(Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Clients_Total, New_List_Domains, Num_of_Hosts - 1) end. start_host(Num_of_Host, Architecture_Info, Domain, Routers_Listener_Pid) -> {Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Num_TS, Clients_Total} = Architecture_Info, case Servers_Total rem Servers_Per_Router_Node of 0 -> Routers = Servers_Total div Servers_Per_Router_Node; _Greater_than_0 -> Routers = (Servers_Total div Servers_Per_Router_Node) + 1 end, case Servers_Per_Router_Process > Servers_Per_Router_Node of true -> S_R_Pr = Servers_Per_Router_Node; false -> S_R_Pr = Servers_Per_Router_Process end, Router_Nodes = node_name_generator(Num_of_Host, router, Domain, Routers, 0), Server_Nodes = node_name_generator(Num_of_Host, server, Domain, Servers_Total, 0), Client_Nodes = node_name_generator(Num_of_Host, client, Domain, Clients_Total, 0), Router_Processes = router_names_generator(Num_of_Host, Servers_Total, Servers_Per_Router_Node, S_R_Pr, 0), io:format("~n=============================================~n" ++ " Launching Host: ~p ~n" ++ "=============================================~n" ++ "Router nodes: ~p~n" ++ "Server nodes: ~p~n" ++ "Client nodes: ~p~n" ++ "Router processes: ~p~n",[Num_of_Host, Router_Nodes, Server_Nodes, Client_Nodes, Router_Processes]), Routers_Listener_Pid ! {Client_Nodes, add_client_node}, case length(Router_Processes) rem Routers of 0 -> Router_Pr_per_R_Nd = length(Router_Processes) div Routers; _Other -> Router_Pr_per_R_Nd = length(Router_Processes) div Routers + 1 end, New_Architecture_Info = {Servers_Per_Router_Node, Servers_Per_Router_Process, Num_TS, Servers_Total, Routers, Router_Pr_per_R_Nd}, Routers_Servers_Lists = {Router_Nodes, Server_Nodes, Router_Processes}, launch_router_supervisors(Routers_Servers_Lists, New_Architecture_Info, Routers_Listener_Pid). run the IM application . This launches a system comprising 1 router , 2 servers , and 4 client the two servers on the hosts with domain ' domain_2.do and ' domain_3.do ' , and four client nodes on a host ' domain_4.do ' . In this case , there are 2 router processes , each of them monitoring one server supervisor process . , S_RP , S_T , Cl_T , List_Domains ) - > start(S_RN, S_RP, S_T, Cl_T, List_Domains) -> case S_T rem S_RP of Rem when Rem == 0 -> R_T = S_T div S_RN; _Rem -> R_T = (S_T div S_RN) + 1 end, case (R_T + S_T) + 1 =< length(List_Domains) of true -> Architecture_Info = {S_RN, S_RP, S_T, S_T, Cl_T}, Nodes = nodes_list(R_T, S_RN, S_T, Cl_T, List_Domains), case whereis(routers_listener) of undefined -> io:format("~n=============================================~n" ++ "Initiating the Distributed Instant Messenger.~n" ++ "=============================================~n"), Routers_Listener_Pid = spawn(fun() -> routers_listener(S_T, [], [], [], []) end), register(routers_listener, Routers_Listener_Pid); Pid -> Routers_Listener_Pid = Pid end, start_distributed(Architecture_Info, Nodes, Routers_Listener_Pid); false -> io:format("ERROR: There are not enough hosts to deploy the system. Aborting.~n") end. start_bencherl/1 deploys the IM processes given a list of nodes . that there is one router process per each server node . This function is intended to be used with only . @spec start_bencherl(List_Nodes ) - > Status Messages | { error , reason } start_bencherl(Nodes) -> {Router_Nodes, Server_Nodes, Client_Nodes, _Traffic_Nodes} = extractor(Nodes), R_T = length(Router_Nodes), S_T = length(Server_Nodes), Cl_T = length(Client_Nodes), case S_T rem R_T of 0 -> S_RN = S_T div R_T; _Other -> S_RN = (S_T div R_T) + 1 end, case whereis(routers_listener) of undefined -> io:format("~n=============================================~n" ++ "Initiating the Distributed Instant Messenger.~n" ++ "=============================================~n"), Routers_Listener_Pid = spawn(fun() -> routers_listener(S_T, [], [], [], []) end), register(routers_listener, Routers_Listener_Pid); Pid -> Routers_Listener_Pid = Pid end, spawn(fun() -> auto_stop(Nodes)end), Architecture_Info = {S_RN, 1, S_T, S_T, Cl_T}, start_distributed(Architecture_Info, Nodes, Routers_Listener_Pid). be executed . This function is intended to be used with start_bencherl(S_RN, S_RP, S_T, Cl_T, Nodes) -> Architecture_Info = {S_RN, S_RP, S_T, S_T, Cl_T}, case whereis(routers_listener) of undefined -> io:format("~n=============================================~n"), io:format("Initiating the Distributed Instant Messenger.~n"), io:format("=============================================~n"), Routers_Listener_Pid = spawn(fun() -> routers_listener(S_T, [], [], [], []) end), register(routers_listener, Routers_Listener_Pid); Pid -> Routers_Listener_Pid = Pid end, spawn(fun() -> auto_stop(Nodes)end), start_distributed(Architecture_Info, Nodes, Routers_Listener_Pid). It is equivalent to start_host/4 , yet in a distributed environment where each host executes one node . start_distributed(Architecture_Info, Nodes, Routers_Listener_Pid) -> {S_RN, S_RP, S_T, Num_TS, _Cl_T} = Architecture_Info, case S_RP > S_RN of true -> S_R_Pr = S_RN; false -> S_R_Pr = S_RP end, {Router_Nodes, Server_Nodes, Client_Nodes, _Traffic_Nodes} = extractor(Nodes), Router_Processes = router_names_generator(1, S_T, S_RN, S_R_Pr, 0), io:format("Router processes: ~p~n", [Router_Processes]), Routers_Listener_Pid ! {Client_Nodes, add_client_node}, case length(Router_Processes) rem length(Router_Nodes) of 0 -> R_Pr_RN = length(Router_Processes) div length(Router_Nodes); _Other -> R_Pr_RN = length(Router_Processes) div length(Router_Nodes) + 1 end, New_Architecture_Info = {S_RN, S_RP, Num_TS, S_T, length(Router_Nodes), R_Pr_RN}, Routers_Servers_Lists = {Router_Nodes, Server_Nodes, Router_Processes}, launch_router_supervisors(Routers_Servers_Lists, New_Architecture_Info, Routers_Listener_Pid). , launch_router_supervisors(Routers_Servers_Lists, Architecture_Info, Routers_Listener_Pid) -> {Router_Nodes, Server_Nodes, Router_Processes} = Routers_Servers_Lists, {Server_Router_Nd, Servers_Router_Pr, Num_Total_Servers, _, _, Router_Pr_Per_R_Nd} = Architecture_Info, [Router_Nd | New_Router_Nd] = Router_Nodes, io:format("Router_Pr_per_R_Nd = ~p; Router_Processes = ~p~n", [Router_Pr_Per_R_Nd, Router_Processes]), case length(Server_Nodes) > Server_Router_Nd of true -> {Servers, New_Server_Nd} = lists:split(Server_Router_Nd, Server_Nodes), {Router_Prcs, New_Router_Processes} = lists:split(Router_Pr_Per_R_Nd, Router_Processes), io:format("launch_router_supervisors.~n" ++ "Router_Nd: ~p~n" ++ "Servers in ~p:~p~n" ++ "Router Processes in ~p:~p~n", [Router_Nd, Router_Nd, Servers, Router_Nd, Router_Prcs]), New_Rs_Ss_Lists = {New_Router_Nd, New_Server_Nd, New_Router_Processes}, start_router_supervisor(Router_Nd, Servers, Servers_Router_Pr, Router_Prcs, Num_Total_Servers, Routers_Listener_Pid), launch_router_supervisors(New_Rs_Ss_Lists, Architecture_Info, Routers_Listener_Pid); false -> start_router_supervisor(Router_Nd, Server_Nodes, Servers_Router_Pr, Router_Processes, Num_Total_Servers, Routers_Listener_Pid), io:format("launch_router_supervisors.~n" ++ "Router_Nd: ~p~nServers in ~p:~p~n" ++ "Router Processes in ~p:~p~n", [Router_Nd, Router_Nd, Server_Nodes, Router_Nd, Router_Processes]) end. , Server_Nodes , Servers_Router_Pr , start_router_supervisor(Router_Node, Server_Nodes, Servers_Router_Pr, Router_Processes, Num_Total_Servers, Routers_Listener_Pid) -> R_Sup_Pid = spawn_link(Router_Node , fun ( ) - > Servers_Router_Pr , R_Sup_Pid = spawn_link(Router_Node, fun() -> ) < = = = = ADDED one more list ( Servers_List ) . end), Routers_Listener_Pid ! {R_Sup_Pid, add_router_sup}, R_Sup_Pid ! {Server_Nodes, Servers_Router_Pr, Router_Processes, Num_Total_Servers, Routers_Listener_Pid, launch_router_processes}, ok. @spec launch_router_processes(R_Sup_Pid , Server_Nodes , Servers_Router_Pr , launch_router_processes(R_Sup_Pid, Server_Nodes, Servers_Router_Pr, Router_Processes, Num_Total_Servers, Routers_Listener_Pid) -> case Router_Processes of [] -> io:format("Router processes start sequence, finished.~n"); [Router_Process|New_Router_Processes] -> io:format("launch_router_processes/4 Router_Processes: ~p~n", [Router_Processes]), case length(Server_Nodes) > Servers_Router_Pr of true -> {Servers, New_Server_Nodes} = lists:split(Servers_Router_Pr, Server_Nodes), start_router_process(Router_Process, Servers, Servers_Router_Pr, Num_Total_Servers, R_Sup_Pid, Routers_Listener_Pid), launch_router_processes(R_Sup_Pid, New_Server_Nodes, Servers_Router_Pr, New_Router_Processes, Num_Total_Servers, Routers_Listener_Pid); false -> start_router_process(Router_Process, Server_Nodes, Servers_Router_Pr, Num_Total_Servers, R_Sup_Pid, Routers_Listener_Pid) end end. start_router_process(Router_Name , Server_Nodes , Servers_Router_Pr , start_router_process(Router_Name, Server_Nodes, Servers_Router_Pr, Num_Total_Servers, R_Sup_Pid, Routers_Listener_Pid) -> R_Pid = spawn_link(fun() -> router_process({initial_state, R_Sup_Pid, [], [], []}) end), Routers_Listener_Pid ! {Router_Name, R_Pid, add_router}, R_Pid ! {Router_Name, Server_Nodes, Servers_Router_Pr, Num_Total_Servers, Routers_Listener_Pid, launch_server}, yes. Servers_Router_Pr , , Servers_Router_Pr , launch_server_supervisors(Server_Nodes, Servers_Router_Pr, Num_Total_Servers, Routers_Listener_Pid) -> case length(Server_Nodes) > Servers_Router_Pr of true -> {Servers, New_Server_Nodes} = lists:split(Servers_Router_Pr, Server_Nodes), io:format("launch_server_supervisors.~nServers:~p~n", [Server_Nodes]), start_server_supervisors(Servers, Num_Total_Servers, Routers_Listener_Pid), launch_server_supervisors(New_Server_Nodes, Servers_Router_Pr, Num_Total_Servers, Routers_Listener_Pid); false -> io:format("launch_server_supervisors.~nServers:~p~n", [Server_Nodes]), start_server_supervisors(Server_Nodes, Num_Total_Servers, Routers_Listener_Pid) end. , Servers_Router_Pr , start_server_supervisors(Server_Nodes, Num_Total_Servers, Routers_Listener_Pid) -> case Server_Nodes == [] of true -> io:format("Server supervisors start sequence is finished.~n"); false -> [Server|New_Server_Nodes] = Server_Nodes, S = atom_to_list(Server), Server_Name = string:left(S, string:chr(S,$@) - 1), Server_Sup_Pid = spawn_link(Server, fun() -> server:start_server_supervisor( Server, string_to_atom(Server_Name), Num_Total_Servers) end), Routers_Listener_Pid ! {Server_Name, Server_Sup_Pid, add_server}, start_server_supervisors(New_Server_Nodes, Num_Total_Servers, Routers_Listener_Pid) end. auto_stop/1 stops and closes the IM when the benchmarks are auto_stop(Nodes ) - > fun ( ) auto_stop(Nodes) -> {_Router_Nodes, _Server_Nodes, Client_Nodes, _Traffic_Nodes} = extractor(Nodes), Auto_Stop_Pid = self(), launch_stop_notifiers(Client_Nodes, Auto_Stop_Pid), auto_stop(Nodes, length(Client_Nodes), 0). auto_stop/3 stops and closes the IM when the benchmarks are auto_stop(Nodes , Total_Loggers , Finished_Loggers ) - > pid ( ) . auto_stop(Nodes, Total_Loggers, Finished_Loggers) -> receive logger_stopped -> case Finished_Loggers + 1 of Total_Loggers -> spawn(fun() -> stop_nodes_gently(Nodes) end); New_Finished_Loggers -> auto_stop(Nodes, Total_Loggers, New_Finished_Loggers) end; _Other -> io:format("Something failed in auto_stop/3"), auto_stop(Nodes, Total_Loggers, Finished_Loggers) end. , Auto_Stop_Pid ) - > ok launch_stop_notifiers(Client_Nodes, Auto_Stop_Pid) -> case Client_Nodes of [] -> ok; [Node|New_Client_Nodes] -> spawn(Node, fun() -> create_notifier(Auto_Stop_Pid) end), launch_stop_notifiers(New_Client_Nodes, Auto_Stop_Pid) end. create_notifier/1 is the first stage of the notifier process . create_notifier(Auto_Stop_Pid ) - > fun ( ) . create_notifier(Auto_Stop_Pid) -> register(stop_notifier, self()), notifier(Auto_Stop_Pid). notifier/1 is the second stage of the notifier process . This ) - > logger_stopped notifier(Auto_Stop_Pid) -> receive logger_stopped -> Auto_Stop_Pid ! logger_stopped; _Other -> io:format("something failed with the notifier~n"), notifier(Auto_Stop_Pid) end. , S_RP , S_T , Cl_T , List_Domains ) - > ok stop(S_RN, S_RP, S_T, Cl_T, List_Domains) -> case S_T rem S_RP of Rem when Rem == 0 -> R_T = S_T div S_RN; _Rem -> R_T = (S_T div S_RN) + 1 end, stop_nodes(nodes_list(R_T, S_RN, S_T, Cl_T, List_Domains)). Servers_Total , Clients_Total , List_Domains , ) - > ok stop(Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Clients_Total, List_Domains, Num_of_Hosts) -> Num_TS = Servers_Total * Num_of_Hosts, Architecture_Info = {Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Num_TS, Clients_Total}, case List_Domains == [] of true -> init:stop(); false -> [Domain|New_List_Domains] = List_Domains, stop_host(Num_of_Hosts, Architecture_Info, Domain), stop(Servers_Per_Router_Node, Servers_Per_Router_Process, Servers_Total, Clients_Total, New_List_Domains, Num_of_Hosts - 1) end. stop_host/3 stops an IM that has been deployed locally in one Traffic_Nodes is hard - coded to 4 . This has an easy fix adding , Domain ) - > ok stop_host(Num_of_Host, Architecture_Info, Domain) -> {Servers_Per_Router_Node, _Servers_Per_Router_Process, Servers_Total, _Num_TS, Clients_Total} = Architecture_Info, case Servers_Total rem Servers_Per_Router_Node of 0 -> Routers = Servers_Total div Servers_Per_Router_Node; _Greater_than_0 -> Routers = (Servers_Total div Servers_Per_Router_Node) + 1 end, Router_Nodes = node_name_generator(Num_of_Host, router, Domain, Routers, 0), Server_Nodes = node_name_generator(Num_of_Host, server, Domain, Servers_Total, 0), Client_Nodes = node_name_generator(Num_of_Host, client, Domain, Clients_Total, 0), Traffic_Nodes = node_name_generator(Num_of_Host, traffic, Domain, 4, 0), stop_nodes(Traffic_Nodes), stop_nodes(Client_Nodes), stop_nodes(Server_Nodes), stop_nodes(Router_Nodes). @spec stop_nodes(Nodes_List ) - > ok stop_nodes(Nodes_List) -> case Nodes_List of [] -> ok; [Node|Rest_of_Nodes] -> rpc:call(Node, init, stop, []), stop_nodes(Rest_of_Nodes) end. @spec stop_nodes(Nodes_List ) - > ok stop_nodes_gently(Nodes_List) -> {Router_Nodes, Server_Nodes, Client_Nodes, Traffic_Nodes} = extractor(Nodes_List), stop_nodes(Client_Nodes), stop_nodes(Traffic_Nodes), finish_nodes({router, Router_Nodes}), finish_nodes({server, Server_Nodes}), init:stop(). finish_nodes/1 spawn the corresponding finish_node/0 functions @spec finish_nodes({Node_Type , [ H|T ] } ) - > ok . finish_nodes({_Node_Type, []}) -> ok; finish_nodes({Node_Type, [H|T]}) -> case Node_Type of router -> spawn(H, fun() -> router:finish_node()end), finish_nodes({router, T}); server -> spawn(H, fun() -> server:finish_node() end), finish_nodes({server, T}) end. @spec routers_listener(Servers_Total , List_Servers , List_Routers , List_Router_Sups , Client_Nodes ) - > routers_listener(Servers_Total, List_Servers, List_Routers, List_Router_Sups, Client_Nodes) -> receive {Server_Name, Server_Sup_Pid, add_server} -> New_List_Servers = lists:append(List_Servers, [{Server_Name, Server_Sup_Pid}]), io:format("List of servers (routers_listener/4): ~p~n", [New_List_Servers]), if length(New_List_Servers) == Servers_Total -> io:format("launching start_routers_db/2 having Client_Nodes: ~p~n", [Client_Nodes]), Routers_DBs_Pids = launch_routers_db(Client_Nodes, List_Routers, []), feed_router_sup(List_Router_Sups, List_Routers, Routers_DBs_Pids), feed_routers(New_List_Servers, List_Routers, List_Routers); true -> routers_listener(Servers_Total, New_List_Servers, List_Routers, List_Router_Sups, Client_Nodes) end; {Router_Name, Router_Pid, add_router} -> New_List_Routers = lists:append(List_Routers, [{atom_to_list(Router_Name), Router_Pid}]), routers_listener(Servers_Total, List_Servers, New_List_Routers, List_Router_Sups, Client_Nodes); {Router_Sup_Pid, add_router_sup} -> New_List_Router_Sups = lists:append(List_Router_Sups, [Router_Sup_Pid]), routers_listener(Servers_Total, List_Servers, List_Routers, New_List_Router_Sups, Client_Nodes); {New_Clients, add_client_node} -> New_Client_Nodes = lists:append(Client_Nodes, New_Clients), routers_listener(Servers_Total, List_Servers, List_Routers, List_Router_Sups, New_Client_Nodes); Other -> io:format("Something failed here. routers_listener/4 received: ~p~n", [Other]), routers_listener(Servers_Total, List_Servers, List_Routers, List_Router_Sups, Client_Nodes) end. launch_routers_db/3 spawns a process on each of the the processes spawned . , List_Routers , Routers_DBs ) - > launch_routers_db(Client_Nodes, List_Routers, Routers_DBs) -> case Client_Nodes of [] -> io:format("All routers_db processes started.~n"), Routers_DBs; [Client|New_Client_Nodes] -> New_Routers_DBs = Routers_DBs ++ start_routers_db(Client, List_Routers), launch_routers_db(New_Client_Nodes, List_Routers, New_Routers_DBs) end. start_routers_db/2 spawns a process on the target 1 containing the pid of the process spawned . It also @spec launch_routers_db(Client_Node , List_Routers ) - > [ ] | { error , reason } start_routers_db(Client_Node, List_Routers) -> io:format("Executing start_routers_db/2~n"), R_DB_Pid = spawn(Client_Node, fun() -> routers_db(List_Routers) end), io:format("routers_db Pid = ~p~n", [R_DB_Pid]), R_DB_Pid ! {register_globally}, [R_DB_Pid]. routers_db(Routers_List ) - > Status Messages | Routers_pids ( list ) routers_db(Routers_List) -> receive {register_globally} -> io:format("routers_db/1 received {register_globally}~n"), global:register_name(routers_db, self()), routers_db(Routers_List); {register_locally} -> io:format("routers_db/1 received {register_locally}~n"), Pid = self(), register(routers_db, Pid), routers_db(Routers_List); {retrieve_routers, Requester_Pid} -> Requester_Pid ! {Routers_List, router_list}, routers_db(Routers_List); {New_Routers_List, receive_router_list}-> routers_db(New_Routers_List); Other -> io:format("Something failed at routers_db/1. Received: ~p~n", [Other]), routers_db(Routers_List) end. @spec feed_router_sup(List_Router_Sups , List_Routers , Router_DBs_Pids ) - > feed_router_sup(List_Router_Sups, List_Routers, Router_DBs_Pids) -> io:format("feed_router_sup/2~n"), case List_Router_Sups of [] -> ok; [R_Sup_Pid|T] -> R_Sup_Pid ! {list_routers, List_Routers, Router_DBs_Pids}, feed_router_sup(T, List_Routers, Router_DBs_Pids) end. , List_Routers , List_Routers_2 ) - > feed_routers(List_Servers, List_Routers, List_Routers_2) -> case List_Routers_2 of [] -> io:format("Host is deployed.~n"); [{_, Router_Pid}|New_List_Routers] -> Router_Pid ! {list_routers, List_Routers}, Router_Pid ! {list_servers, List_Servers}, feed_routers(List_Servers, List_Routers, New_List_Routers) end. on a distributed environment with one node per host . , S_RN , S_T , Cl_Total , Domains ) - > list ( ) nodes_list(R_T, S_RN, S_T, Cl_T, Domains) -> {R_S_Dom, Cl_Dom} = lists:split(R_T + S_T, Domains), R_S_Nodes = router_server_nodes(1,1,S_RN, R_S_Dom, []), Cl_Nodes = client_nodes(Cl_T, 1, hd(Cl_Dom), []), lists:reverse(lists:flatten([Cl_Nodes|R_S_Nodes])). @spec router_server_nodes(R_Acc , S_Acc , S_RN , Domains , Nodes_List ) - > list ( ) router_server_nodes(R_Acc, S_Acc, S_RN, Domains, Nodes_List) -> case Domains of [] -> lists:flatten(Nodes_List); [R_Dom|O_Doms] -> Router = [string_to_atom(string:join(["router", integer_to_list(R_Acc)], "_") ++ "@" ++ atom_to_list(R_Dom))], case S_RN =< length(O_Doms) of true -> {S_Doms, New_Domains} = lists:split(S_RN, O_Doms), {Servers, New_S_Acc} = server_nodes(S_Acc, S_Doms, []), New_Nodes_List = [[Servers|Router]|Nodes_List], router_server_nodes(R_Acc + 1, New_S_Acc, S_RN, New_Domains, New_Nodes_List); false -> {Servers, New_S_Acc} = server_nodes(S_Acc, O_Doms, []), New_Nodes_List = [[Servers|Router]|Nodes_List], router_server_nodes(R_Acc + 1, New_S_Acc, S_RN, [], New_Nodes_List) end end. server_nodes/3 is an auxiliary function to router_server_nodes/5 . @spec server_nodes(S_Acc , S_RN , Domains , Nodes ) - > { list ( ) , Integer ( ) } server_nodes(S_Acc, Domains, Nodes) -> case Domains of [] -> {Nodes, S_Acc}; [H|T] -> New_Nodes = [string_to_atom(string:join(["server", integer_to_list(S_Acc)], "_") ++ "@" ++ atom_to_list(H))|Nodes], server_nodes(S_Acc + 1, T, New_Nodes) end. @spec client_nodes(Cl_T , Cl_Acc , Domain , Nodes ) - > list ( ) client_nodes(Cl_T, Cl_Acc, Domain, Nodes) -> case Cl_Acc of Cl_T -> New_Nodes = [string_to_atom(string:join(["client", integer_to_list(Cl_Acc)], "_") ++ "@" ++ atom_to_list(Domain))|Nodes], lists:flatten(New_Nodes); _Other -> New_Nodes = [string_to_atom(string:join(["client", integer_to_list(Cl_Acc)], "_") ++ "@" ++ atom_to_list(Domain))|Nodes], client_nodes(Cl_T, Cl_Acc + 1, Domain, New_Nodes) end. three lists : one containing the router nodes , a second that holds the server nodes , and a third with the client nodes . If extractor(Nodes_List) -> extractor(Nodes_List, [],[],[], []). Given a list of nodes , and three recipient lists for the names @spec extractor(Nodes_List , R_Nodes , S_Nodes , Cl_Nodes ) - > extractor(Nodes_List, R_Nodes, S_Nodes, Cl_Nodes, Tr_Nodes) -> case Nodes_List of [] -> {lists:reverse(R_Nodes), lists:reverse(S_Nodes), lists:reverse(Cl_Nodes), lists:reverse(Tr_Nodes)}; [H|T] -> case string:sub_string(atom_to_list(H), 1, 3) of "rou" -> New_R_Nodes = [H|R_Nodes], extractor(T, New_R_Nodes, S_Nodes, Cl_Nodes, Tr_Nodes); "ser" -> New_S_Nodes = [H|S_Nodes], extractor(T, R_Nodes, New_S_Nodes, Cl_Nodes, Tr_Nodes); "cli" -> New_Cl_Nodes = [H|Cl_Nodes], extractor(T, R_Nodes, S_Nodes, New_Cl_Nodes, Tr_Nodes); "tra" -> New_Tr_Nodes = [H|Tr_Nodes], extractor(T, R_Nodes, S_Nodes, Cl_Nodes, New_Tr_Nodes); _Other -> extractor(T, R_Nodes, S_Nodes, Cl_Nodes, Tr_Nodes) end end. , Domain , Total_Nodes , ) - > atom ( ) node_name_generator(Host, Node_Type, Domain, Total_Nodes, Children_Nodes_Per_Node) -> case Children_Nodes_Per_Node of 0 -> [string_to_atom( string:join([atom_to_list(Node_Type), integer_to_list(X)], "_") ++ "@" ++ atom_to_list(Domain)) || X <- lists:seq(((Host * Total_Nodes) - Total_Nodes + 1), Host * Total_Nodes)]; _Other -> [string_to_atom( string:join([atom_to_list(Node_Type), integer_to_list(X), integer_to_list(Y)], "_") ++ "@" ++ atom_to_list(Domain)) || X <- lists:seq(((Host * Total_Nodes) - Total_Nodes + 1), Host * Total_Nodes), Y <- lists:seq(1, Children_Nodes_Per_Node)] end. , Domain , Total_Nodes , ) - > list of atom ( ) router_names_generator(Num_of_Host, Servers_Total, Servers_Router_Node, Servers_Router_Process, Num_of_Sub_Pr) -> B = Servers_Total div Servers_Router_Node, C = Servers_Total div Servers_Router_Process, io:format("Servers_Router_Node: ~p, Servers_Router_Process: ~p~n", [Servers_Router_Node, Servers_Router_Process]), io:format("B = ~p, C = ~p~n", [B, C]), case Servers_Total of Servers_Router_Node -> io:format("true~n"), D = (Servers_Total div Servers_Router_Process); _Other -> io:format("false~n"), case Servers_Router_Node rem Servers_Router_Process == 0 of true -> D = Servers_Total div Servers_Router_Process; false -> D = (Servers_Total div Servers_Router_Node) + (Servers_Total div Servers_Router_Process) end end, io:format("D: ~p~n",[D]), case D * Servers_Router_Process < Servers_Total of true -> A = D + 1; false -> A = D end, io:format("A: ~p~n", [A]), Lower_Limit = (Num_of_Host-1) * A + 1, Upper_Limit = Lower_Limit + A - 1, case Num_of_Sub_Pr of 0 -> [string_to_atom( string:join(["router", integer_to_list(X)], "_")) || X <- lists:seq(Lower_Limit, Upper_Limit)]; _Another -> [string_to_atom( string:join(["router", integer_to_list(X), integer_to_list(Y)], "_")) || X <- lists:seq(Lower_Limit, Upper_Limit), Y <- lists:seq(1, Num_of_Sub_Pr)] end. ) - > atom ( ) | existing_atom ( ) string_to_atom(String) -> try list_to_existing_atom(String) of Val -> Val catch error:_ -> list_to_atom(String) end.
a2eb621aeda45b2d73d09af48f2ab0e49a3698f031902c1ecfac9787705326e0
aiya000/haskell-examples
divideInto.hs
import Data.List main = print $ divideInto 3 [1..10] divideInto :: Int -> [a] -> [[a]] divideInto n xs = unfoldr (\xs -> if null xs then Nothing else Just $ splitAt m xs) xs where m = ((length xs) + n - 1) `div` n
null
https://raw.githubusercontent.com/aiya000/haskell-examples/a337ba0e86be8bb1333e7eea852ba5fa1d177d8a/Room/Function/divideInto.hs
haskell
import Data.List main = print $ divideInto 3 [1..10] divideInto :: Int -> [a] -> [[a]] divideInto n xs = unfoldr (\xs -> if null xs then Nothing else Just $ splitAt m xs) xs where m = ((length xs) + n - 1) `div` n
dcb49f5b9eef32d64a02ef230e5b03c77f4dd97310584238d50a2dff42785bab
albertoruiz/easyVision
Interface.hs
{-# LANGUAGE BangPatterns #-} --------------------------------------------------------------------------- | Module : Vision . GUI.Interface Copyright : ( c ) 2006 - 12 License : GPL Maintainer : ( aruiz at um dot es ) Stability : provisional User interface tools . Module : Vision.GUI.Interface Copyright : (c) Alberto Ruiz 2006-12 License : GPL Maintainer : Alberto Ruiz (aruiz at um dot es) Stability : provisional User interface tools. -} ----------------------------------------------------------------------------- module Vision.GUI.Interface ( -- * Interface VCN, Command, WinInit, interface, standalone, interface3D, standalone3D, -- * Tools Size(..), prepare, runIt, evWindow, inWin, getW, putW, updateW, putWRaw, updateWRaw, kbdcam, kbdQuit, keyAction, Key(..), SpecialKey(..), MouseButton(..), key, kUp, kCtrl, kShift, kAlt, BitmapFont(..) ) where import Vision.GUI.Types import Vision.GUI.Draw import Vision.GUI.Trackball import Util.Geometry hiding (join) --import ImagProc.Ipp(ippSetNumThreads) import Image import Image.Devel(shSize,pixelsToPoints) import Graphics.UI.GLUT hiding (RGB, Matrix, Size, None, Point,color) import qualified Graphics.UI.GLUT as GL import Data.IORef import System.Process(system,readProcessWithExitCode) import System.Exit import Control.Monad(when,forever,join,filterM) import System.Environment import qualified Data.Map as Map import Data.Map hiding (null,map) import Util.Debug(debug,errMsg) import Data . import Control.Applicative import Control.Arrow import Data.Colour.Names import Control.Concurrent import Text.Printf(printf) import Data.List(intercalate) import System.Directory keyAction upds acts def w a b c d = do st <- getW w gp <- unZoomPoint w roi <- get (evRegion w) case Prelude.lookup (a,b,c) upds of Just op -> putW w (withPoint op roi gp d st) Nothing -> case Prelude.lookup (a,b,c) (help acts) of Just op -> withPoint op roi gp d st Nothing -> def a b c d where withPoint f roi gp pos = f roi (gp pos) help acts = acts ++ [(key (SpecialKey KeyF1), \p r w -> callHelp s)] s = evWinTitle w modif = Modifiers {ctrl = Up, shift = Up, alt = Up } kCtrl (k,s,m) = (k, s, m {ctrl = Down}) kShift (k,s,m) = (k, s, m {shift = Down}) kAlt (k,s,m) = (k, s, m {alt = Down}) kUp (k,s,m) = (k, Up, m) key k = (k, Down, modif) -------------------------------------------------------------------------------- type Command state result = ((Key,KeyState,Modifiers), WinRegion -> Point -> state -> result) type WinInit state input = EVWindow state -> input -> IO() type VCN a b = IO (IO (Maybe a) -> IO (Maybe b)) interface :: Size -- win size -> String -- win title -> s -- state 0 -> WinInit s a -- init Window -> [Command s s] -- upds -> [Command s (IO())] -- acts -> (WinRegion -> s -> a -> (s,b)) -- result -> (WinRegion -> s -> a -> b -> Drawing) -- draw -> VCN a b interface = interfaceG False interface3D :: Size -> String -> s -> WinInit s a -> [Command s s] -> [Command s (IO())] -> (WinRegion -> s -> a -> (s,b)) -> (WinRegion -> s -> a -> b -> Drawing) -> VCN a b interface3D = interfaceG True interfaceG threeD sz0 name st0 ft upds acts resultFun resultDisp = do firstTimeRef <- newIORef True let evWin = if threeD then evWindow3D else evWindow w <- evWin st0 name sz0 (keyAction upds acts kbdQuit) displayCallback $= do evInit w dr <- readMVar (evDraw w) renderIn w dr drawRegion w swapBuffers join . get . evAfterD $ w --putStrLn " D" callbackFreq 5 $ do visible <- get (evVisible w) sync <- readIORef (evSync w) ready <- readMVar (evReady w) when (visible && ready && not sync) $ do postRedisplay (Just (evW w)) swapMVar (evReady w) False return () pauser <- newPauser (evPause w) return $ \cam -> do end <- readIORef (evEnd w) if end then return Nothing else do mbthing <- pauser cam case mbthing of FIXME :( Just thing -> do firstTime <- readIORef firstTimeRef when firstTime $ ft w thing >> writeIORef firstTimeRef False state <- getW w roi <- get (evRegion w) let (newState, result) = resultFun roi state thing drawing = resultDisp roi newState thing result seq newState $ putW w newState pause <- readIORef (evPause w) when (not (pause==PauseDraw)) $ swapMVar (evDraw w) drawing >> return () swapMVar(evReady w) True " sync <- readIORef (evSync w) when sync $ postRedisplay (Just (evW w)) modifyIORef (evStats w) (\s -> s { evNCall = evNCall s + 1 }) return (Just result) drawRegion w = do ok <- readIORef (evDrReg w) modifyIORef (evStats w) (\s -> s { evNDraw = evNDraw s + 1 }) when ok $ do (Point x1 y1, Point x2 y2) <- readIORef (evRegion w) stats <- readIORef (evStats w) psz <- readIORef (evPrefSize w) (z,a,b) <- readIORef (evZoom w) wsz <- get windowSize let shpsz = case psz of Nothing -> " " Just sz -> " pSize: " ++ shSize sz ++ " / " info = show (evNCall stats) ++ " frames / " ++ show (evNDraw stats) ++ " draws (" ++ show (evNCall stats - evNDraw stats) ++ ")" ++ shpsz ++ "wSize: " ++ shSize (evSize wsz) -- ++ " zoom = " ++ printf "(%.2f,%.1f,%.1f)" z a b render $ Draw [ color red . lineWd 1.5 $ Closed [ Point x1 y1, Point x2 y1 , Point x2 y2, Point x1 y2] , textF Helvetica10 (Point 0.95 (-0.7)) info ] ---------------------------------------- standalone :: Size -> String -> s -> [Command s s] -> [Command s (IO ())] -> (s -> Drawing) -> IO (EVWindow s) standalone = standaloneG False standalone3D :: Size -> String -> s -> [Command s s] -> [Command s (IO ())] -> (s -> Drawing) -> IO (EVWindow s) standalone3D = standaloneG True standaloneG threeD sz0 name st0 upds acts disp = do let evWin = if threeD then evWindow3D else evWindow w <- evWin st0 name sz0 (keyAction upds acts kbdQuit) displayCallback $= do evInit w --prepZoom w st <- getW w renderIn w (disp st) drawRegion w swapBuffers join . get . evAfterD $ w return w ----------------------------------------------------------------- | Initializes the HOpenGL system . prepare :: IO () prepare = do getArgsAndInitialize initialDisplayMode $= [DoubleBuffered, WithDepthBuffer] ippSetNumThreads 1 return () callbackFreq freq worker = do let callback = do addTimerCallback (1000 `div` freq) callback worker addTimerCallback 10 callback runIt :: IO a -> IO () runIt f = prepare >> f >> mainLoop ---------------------------------------------------------------- irr = (Point p p, Point n n) where p = 0.5; n = -0.5 evWindow st0 name size kbd = do st <- newIORef st0 glw <- createWindow name iconTitle $= name windowSize $= glSize size actionOnWindowClose $ = ContinueExectuion -- Exit by default let Size h w = size rr <- newIORef irr drr <- newIORef False zd <- newIORef (1,0,0) ms <- newIORef None po <- newIORef StaticSize ps <- newIORef Nothing vi <- newIORef True re <- newMVar True dr <- newMVar (Draw ()) sy <- newIORef True pa <- newIORef NoPause dc <- newIORef (WStatus 0 0) ad <- newIORef (return ()) no <- newIORef (return ()) rend <- newIORef False let w = EVW { evW = glw , evSt = st , evDraw = dr , evAfterD = ad , evNotify = no , evSync = sy , evReady = re , evRegion = rr , evDrReg = drr , evZoom = zd , evMove = ms , evPolicy = po , evPrefSize = ps , evVisible = vi , evPause = pa , evStats = dc , evEnd = rend , evWinTitle = name , evInit = clear [ColorBuffer] >> prepZoom w } keyboardMouseCallback $= Just (\k d m p -> kbdroi w (kbd w) k d m p >> postRedisplay Nothing) motionCallback $= Just (\p -> mvroi w p >> postRedisplay Nothing) -- callback to detect minimization? return w evWindow3D ist name sz kbd = do (trackball,kc,mc,auto) <- newTrackball w <- evWindow ist name sz (kc kbd) motionCallback $= Just mc depthFunc $= Just Less textureFilter Texture2D $= ((Nearest, Nothing), Nearest) textureFunction $= Replace let callback = do addTimerCallback 50 callback ok <- auto when ok $ postRedisplay (Just (evW w)) addTimerCallback 1000 callback return w { evInit = clear [ColorBuffer, DepthBuffer] >> trackball} --------------------------------------------------------------- inWin w f = do saved <- get currentWindow currentWindow $= Just (evW w) evInit w f swapBuffers currentWindow $= saved getW = get . evSt putWRaw w x = evSt w $= x updateWRaw w f = evSt w $~ f putW w x = putWRaw w x >> (join . get . evNotify) w updateW w f = updateWRaw w f >> (join . get . evNotify) w ---------------------------------------------------------------- nextPolicy UserSize = DynamicSize nextPolicy StaticSize = UserSize nextPolicy DynamicSize = UserSize nextPauseDraw NoPause = PauseDraw nextPauseDraw _ = NoPause nextPauseCam NoPause = PauseCam nextPauseCam _ = NoPause | keyboard callback for camera control and exiting the application with ESC . p or SPACE pauses , s sets frame by frame mode . kbdcam :: (IO (),IO(),IO()) -> KeyboardMouseCallback kbdcam (pauseC,stepC,passC) = kbd where kbd (Char ' ') Down Modifiers {shift=Up} _ = pauseC kbd (Char ' ') Down Modifiers {shift=Down} _ = passC kbd (Char 's') Down _ _ = stepC kbd a b c d = kbdQuit a b c d | keyboard callback for exiting the application with ESC or q , useful as default callback . -- Also, pressing i saves a screenshot of the full opengl window contents. kbdQuit :: KeyboardMouseCallback kbdQuit ( Char ' \27 ' ) Down Modifiers { alt = Down } _ = leaveMainLoop > > system " killall mplayer " > > return ( ) kbdQuit (Char '\27') Down _ _ = exitWith ExitSuccess kbdQuit (Char 'i') Down _ _ = captureGL >>= saveImage ".png" kbdQuit a Down m _ = errMsg (show a ++ " " ++ show m ++ " not defined") kbdQuit _ _ _ _ = return () kbdroi w _ (Char '0') Down Modifiers {alt=Down} _ = do mbsz <- readIORef (evPrefSize w) case mbsz of Nothing -> return () Just (Size h w') -> writeIORef (evRegion w) irr kbdroi w _ (MouseButton WheelUp) Down Modifiers {ctrl=Down} _ = modifyIORef (evZoom w) (\(z,x,y)->(z*1.1,x*1.1,y*1.1)) kbdroi w _ (MouseButton WheelDown) Down Modifiers {ctrl=Down} _ = modifyIORef (evZoom w) (\(z,x,y)->(z/1.1,x/1.1,y/1.1)) kbdroi w _ (SpecialKey KeyUp) Down Modifiers {ctrl=Down} _ = modifyIORef (evZoom w) (\(z,x,y)->(z*1.1,x*1.1,y*1.1)) kbdroi w _ (SpecialKey KeyDown) Down Modifiers {ctrl=Down} _ = modifyIORef (evZoom w) (\(z,x,y)->(z/1.1,x/1.1,y/1.1)) kbdroi w _ (MouseButton LeftButton) Down Modifiers {ctrl=Down} (Position x y) = writeIORef (evMove w) (MoveZoom x y) kbdroi w _ (MouseButton RightButton) Down Modifiers {ctrl=Down} p = do gp <- unZoomPoint w let pt = gp p modifyIORef (evRegion w) $ \(_,b) -> (pt,b) writeIORef (evDrReg w) True writeIORef (evMove w) SetROI kbdroi w _ (MouseButton LeftButton) Up _ _ = writeIORef (evMove w) None kbdroi w _ (MouseButton RightButton) Up _ _ = writeIORef (evMove w) None kbdroi w _ (SpecialKey KeyF3) Down Modifiers {ctrl=Down} _ = do vi <- get (evVisible w) if vi then writeIORef (evVisible w) False >> windowStatus $= Iconified else writeIORef (evVisible w) True kbdroi w _ (SpecialKey KeyF3) Down _ _ = modifyIORef (evPolicy w) nextPolicy kbdroi w _ (SpecialKey KeyF10) Down _ _ = modifyIORef (evSync w) not kbdroi w _ (SpecialKey KeyF11) Down _ _ = modifyIORef (evDrReg w) not kbdroi w _ (Char '0') Down Modifiers {ctrl=Down} _ = writeIORef (evZoom w) (1,0,0) kbdroi w _ (Char ' ') Down Modifiers {shift=Up} _ = modifyIORef (evPause w) nextPauseCam kbdroi w _ (Char ' ') Down Modifiers {shift=Down} _ = modifyIORef (evPause w) nextPauseDraw kbdroi w _ (Char 's') Down _ _ = writeIORef (evPause w) PauseStep kbdroi w _ (Char '\27') Down Modifiers {ctrl=Down} _ = writeIORef (evEnd w) True kbdroi _ defaultFunc a b c d = defaultFunc a b c d mvroi w (Position x1' y1') = do ms <- readIORef (evMove w) z@(z0,_,dy) <- readIORef (evZoom w) gp <- unZoomPoint w let pt = gp (Position x1' y1') case ms of None -> return () SetROI -> do modifyIORef (evRegion w) $ \(p,_) -> (p,pt) writeIORef (evDrReg w) True MoveZoom x0 y0 -> do modifyIORef (evZoom w) $ \(z,x,y) -> (z, x+fromIntegral (x1'-x0), y-fromIntegral (y1'-y0)) writeIORef (evMove w) (MoveZoom x1' y1') unZoomPoint w = do z@(z0,_,dy) <- readIORef (evZoom w) vp <- get viewport Size wh ww <- evSize `fmap` get windowSize let f (Position x y) = pt where (x',y') = unZoom z vp (x,y) [pt] = pixelsToPoints (Size (wh - round (4*dy/z0)) ww) [Pixel y' x'] return f -------------------------------------------------------------------------------- newPauser refPau = do frozen <- newIORef Nothing return $ \cam -> do pau <- readIORef refPau when (pau == PauseStep) (writeIORef refPau PauseCam >> writeIORef frozen Nothing) old <- readIORef frozen if (pau == PauseCam || pau == PauseStep) then do case old of Nothing -> do {x <- cam; writeIORef frozen (Just x); return x} Just x -> threadDelay 100000 >> return x else do case old of Just _ -> writeIORef frozen Nothing _ -> return () cam -------------------------------------------------------------------------------- callHelp wn = do pname <- getProgName errMsg wn errMsg pname let helpnames = map (++".html") $ concatMap (\x -> [x,"help/"++x,"../help/"++x]) [ intercalate "-" [pname, wn'] , pname , wn' , "help" ] fs <- filterM doesFileExist helpnames let f = head fs if null fs then errMsg "no help file available" else system ("xdg-open "++f) >> return () where wn' = map f wn f ' ' = '_' f x = x
null
https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/packages/gui/src/Vision/GUI/Interface.hs
haskell
# LANGUAGE BangPatterns # ------------------------------------------------------------------------- --------------------------------------------------------------------------- * Interface * Tools import ImagProc.Ipp(ippSetNumThreads) ------------------------------------------------------------------------------ win size win title state 0 init Window upds acts result draw putStrLn " D" ++ " zoom = " ++ printf "(%.2f,%.1f,%.1f)" z a b -------------------------------------- prepZoom w --------------------------------------------------------------- -------------------------------------------------------------- Exit by default callback to detect minimization? ------------------------------------------------------------- -------------------------------------------------------------- Also, pressing i saves a screenshot of the full opengl window contents. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
| Module : Vision . GUI.Interface Copyright : ( c ) 2006 - 12 License : GPL Maintainer : ( aruiz at um dot es ) Stability : provisional User interface tools . Module : Vision.GUI.Interface Copyright : (c) Alberto Ruiz 2006-12 License : GPL Maintainer : Alberto Ruiz (aruiz at um dot es) Stability : provisional User interface tools. -} module Vision.GUI.Interface ( VCN, Command, WinInit, interface, standalone, interface3D, standalone3D, Size(..), prepare, runIt, evWindow, inWin, getW, putW, updateW, putWRaw, updateWRaw, kbdcam, kbdQuit, keyAction, Key(..), SpecialKey(..), MouseButton(..), key, kUp, kCtrl, kShift, kAlt, BitmapFont(..) ) where import Vision.GUI.Types import Vision.GUI.Draw import Vision.GUI.Trackball import Util.Geometry hiding (join) import Image import Image.Devel(shSize,pixelsToPoints) import Graphics.UI.GLUT hiding (RGB, Matrix, Size, None, Point,color) import qualified Graphics.UI.GLUT as GL import Data.IORef import System.Process(system,readProcessWithExitCode) import System.Exit import Control.Monad(when,forever,join,filterM) import System.Environment import qualified Data.Map as Map import Data.Map hiding (null,map) import Util.Debug(debug,errMsg) import Data . import Control.Applicative import Control.Arrow import Data.Colour.Names import Control.Concurrent import Text.Printf(printf) import Data.List(intercalate) import System.Directory keyAction upds acts def w a b c d = do st <- getW w gp <- unZoomPoint w roi <- get (evRegion w) case Prelude.lookup (a,b,c) upds of Just op -> putW w (withPoint op roi gp d st) Nothing -> case Prelude.lookup (a,b,c) (help acts) of Just op -> withPoint op roi gp d st Nothing -> def a b c d where withPoint f roi gp pos = f roi (gp pos) help acts = acts ++ [(key (SpecialKey KeyF1), \p r w -> callHelp s)] s = evWinTitle w modif = Modifiers {ctrl = Up, shift = Up, alt = Up } kCtrl (k,s,m) = (k, s, m {ctrl = Down}) kShift (k,s,m) = (k, s, m {shift = Down}) kAlt (k,s,m) = (k, s, m {alt = Down}) kUp (k,s,m) = (k, Up, m) key k = (k, Down, modif) type Command state result = ((Key,KeyState,Modifiers), WinRegion -> Point -> state -> result) type WinInit state input = EVWindow state -> input -> IO() type VCN a b = IO (IO (Maybe a) -> IO (Maybe b)) -> VCN a b interface = interfaceG False interface3D :: Size -> String -> s -> WinInit s a -> [Command s s] -> [Command s (IO())] -> (WinRegion -> s -> a -> (s,b)) -> (WinRegion -> s -> a -> b -> Drawing) -> VCN a b interface3D = interfaceG True interfaceG threeD sz0 name st0 ft upds acts resultFun resultDisp = do firstTimeRef <- newIORef True let evWin = if threeD then evWindow3D else evWindow w <- evWin st0 name sz0 (keyAction upds acts kbdQuit) displayCallback $= do evInit w dr <- readMVar (evDraw w) renderIn w dr drawRegion w swapBuffers join . get . evAfterD $ w callbackFreq 5 $ do visible <- get (evVisible w) sync <- readIORef (evSync w) ready <- readMVar (evReady w) when (visible && ready && not sync) $ do postRedisplay (Just (evW w)) swapMVar (evReady w) False return () pauser <- newPauser (evPause w) return $ \cam -> do end <- readIORef (evEnd w) if end then return Nothing else do mbthing <- pauser cam case mbthing of FIXME :( Just thing -> do firstTime <- readIORef firstTimeRef when firstTime $ ft w thing >> writeIORef firstTimeRef False state <- getW w roi <- get (evRegion w) let (newState, result) = resultFun roi state thing drawing = resultDisp roi newState thing result seq newState $ putW w newState pause <- readIORef (evPause w) when (not (pause==PauseDraw)) $ swapMVar (evDraw w) drawing >> return () swapMVar(evReady w) True " sync <- readIORef (evSync w) when sync $ postRedisplay (Just (evW w)) modifyIORef (evStats w) (\s -> s { evNCall = evNCall s + 1 }) return (Just result) drawRegion w = do ok <- readIORef (evDrReg w) modifyIORef (evStats w) (\s -> s { evNDraw = evNDraw s + 1 }) when ok $ do (Point x1 y1, Point x2 y2) <- readIORef (evRegion w) stats <- readIORef (evStats w) psz <- readIORef (evPrefSize w) (z,a,b) <- readIORef (evZoom w) wsz <- get windowSize let shpsz = case psz of Nothing -> " " Just sz -> " pSize: " ++ shSize sz ++ " / " info = show (evNCall stats) ++ " frames / " ++ show (evNDraw stats) ++ " draws (" ++ show (evNCall stats - evNDraw stats) ++ ")" ++ shpsz ++ "wSize: " ++ shSize (evSize wsz) render $ Draw [ color red . lineWd 1.5 $ Closed [ Point x1 y1, Point x2 y1 , Point x2 y2, Point x1 y2] , textF Helvetica10 (Point 0.95 (-0.7)) info ] standalone :: Size -> String -> s -> [Command s s] -> [Command s (IO ())] -> (s -> Drawing) -> IO (EVWindow s) standalone = standaloneG False standalone3D :: Size -> String -> s -> [Command s s] -> [Command s (IO ())] -> (s -> Drawing) -> IO (EVWindow s) standalone3D = standaloneG True standaloneG threeD sz0 name st0 upds acts disp = do let evWin = if threeD then evWindow3D else evWindow w <- evWin st0 name sz0 (keyAction upds acts kbdQuit) displayCallback $= do evInit w st <- getW w renderIn w (disp st) drawRegion w swapBuffers join . get . evAfterD $ w return w | Initializes the HOpenGL system . prepare :: IO () prepare = do getArgsAndInitialize initialDisplayMode $= [DoubleBuffered, WithDepthBuffer] ippSetNumThreads 1 return () callbackFreq freq worker = do let callback = do addTimerCallback (1000 `div` freq) callback worker addTimerCallback 10 callback runIt :: IO a -> IO () runIt f = prepare >> f >> mainLoop irr = (Point p p, Point n n) where p = 0.5; n = -0.5 evWindow st0 name size kbd = do st <- newIORef st0 glw <- createWindow name iconTitle $= name windowSize $= glSize size actionOnWindowClose $ = ContinueExectuion let Size h w = size rr <- newIORef irr drr <- newIORef False zd <- newIORef (1,0,0) ms <- newIORef None po <- newIORef StaticSize ps <- newIORef Nothing vi <- newIORef True re <- newMVar True dr <- newMVar (Draw ()) sy <- newIORef True pa <- newIORef NoPause dc <- newIORef (WStatus 0 0) ad <- newIORef (return ()) no <- newIORef (return ()) rend <- newIORef False let w = EVW { evW = glw , evSt = st , evDraw = dr , evAfterD = ad , evNotify = no , evSync = sy , evReady = re , evRegion = rr , evDrReg = drr , evZoom = zd , evMove = ms , evPolicy = po , evPrefSize = ps , evVisible = vi , evPause = pa , evStats = dc , evEnd = rend , evWinTitle = name , evInit = clear [ColorBuffer] >> prepZoom w } keyboardMouseCallback $= Just (\k d m p -> kbdroi w (kbd w) k d m p >> postRedisplay Nothing) motionCallback $= Just (\p -> mvroi w p >> postRedisplay Nothing) return w evWindow3D ist name sz kbd = do (trackball,kc,mc,auto) <- newTrackball w <- evWindow ist name sz (kc kbd) motionCallback $= Just mc depthFunc $= Just Less textureFilter Texture2D $= ((Nearest, Nothing), Nearest) textureFunction $= Replace let callback = do addTimerCallback 50 callback ok <- auto when ok $ postRedisplay (Just (evW w)) addTimerCallback 1000 callback return w { evInit = clear [ColorBuffer, DepthBuffer] >> trackball} inWin w f = do saved <- get currentWindow currentWindow $= Just (evW w) evInit w f swapBuffers currentWindow $= saved getW = get . evSt putWRaw w x = evSt w $= x updateWRaw w f = evSt w $~ f putW w x = putWRaw w x >> (join . get . evNotify) w updateW w f = updateWRaw w f >> (join . get . evNotify) w nextPolicy UserSize = DynamicSize nextPolicy StaticSize = UserSize nextPolicy DynamicSize = UserSize nextPauseDraw NoPause = PauseDraw nextPauseDraw _ = NoPause nextPauseCam NoPause = PauseCam nextPauseCam _ = NoPause | keyboard callback for camera control and exiting the application with ESC . p or SPACE pauses , s sets frame by frame mode . kbdcam :: (IO (),IO(),IO()) -> KeyboardMouseCallback kbdcam (pauseC,stepC,passC) = kbd where kbd (Char ' ') Down Modifiers {shift=Up} _ = pauseC kbd (Char ' ') Down Modifiers {shift=Down} _ = passC kbd (Char 's') Down _ _ = stepC kbd a b c d = kbdQuit a b c d | keyboard callback for exiting the application with ESC or q , useful as default callback . kbdQuit :: KeyboardMouseCallback kbdQuit ( Char ' \27 ' ) Down Modifiers { alt = Down } _ = leaveMainLoop > > system " killall mplayer " > > return ( ) kbdQuit (Char '\27') Down _ _ = exitWith ExitSuccess kbdQuit (Char 'i') Down _ _ = captureGL >>= saveImage ".png" kbdQuit a Down m _ = errMsg (show a ++ " " ++ show m ++ " not defined") kbdQuit _ _ _ _ = return () kbdroi w _ (Char '0') Down Modifiers {alt=Down} _ = do mbsz <- readIORef (evPrefSize w) case mbsz of Nothing -> return () Just (Size h w') -> writeIORef (evRegion w) irr kbdroi w _ (MouseButton WheelUp) Down Modifiers {ctrl=Down} _ = modifyIORef (evZoom w) (\(z,x,y)->(z*1.1,x*1.1,y*1.1)) kbdroi w _ (MouseButton WheelDown) Down Modifiers {ctrl=Down} _ = modifyIORef (evZoom w) (\(z,x,y)->(z/1.1,x/1.1,y/1.1)) kbdroi w _ (SpecialKey KeyUp) Down Modifiers {ctrl=Down} _ = modifyIORef (evZoom w) (\(z,x,y)->(z*1.1,x*1.1,y*1.1)) kbdroi w _ (SpecialKey KeyDown) Down Modifiers {ctrl=Down} _ = modifyIORef (evZoom w) (\(z,x,y)->(z/1.1,x/1.1,y/1.1)) kbdroi w _ (MouseButton LeftButton) Down Modifiers {ctrl=Down} (Position x y) = writeIORef (evMove w) (MoveZoom x y) kbdroi w _ (MouseButton RightButton) Down Modifiers {ctrl=Down} p = do gp <- unZoomPoint w let pt = gp p modifyIORef (evRegion w) $ \(_,b) -> (pt,b) writeIORef (evDrReg w) True writeIORef (evMove w) SetROI kbdroi w _ (MouseButton LeftButton) Up _ _ = writeIORef (evMove w) None kbdroi w _ (MouseButton RightButton) Up _ _ = writeIORef (evMove w) None kbdroi w _ (SpecialKey KeyF3) Down Modifiers {ctrl=Down} _ = do vi <- get (evVisible w) if vi then writeIORef (evVisible w) False >> windowStatus $= Iconified else writeIORef (evVisible w) True kbdroi w _ (SpecialKey KeyF3) Down _ _ = modifyIORef (evPolicy w) nextPolicy kbdroi w _ (SpecialKey KeyF10) Down _ _ = modifyIORef (evSync w) not kbdroi w _ (SpecialKey KeyF11) Down _ _ = modifyIORef (evDrReg w) not kbdroi w _ (Char '0') Down Modifiers {ctrl=Down} _ = writeIORef (evZoom w) (1,0,0) kbdroi w _ (Char ' ') Down Modifiers {shift=Up} _ = modifyIORef (evPause w) nextPauseCam kbdroi w _ (Char ' ') Down Modifiers {shift=Down} _ = modifyIORef (evPause w) nextPauseDraw kbdroi w _ (Char 's') Down _ _ = writeIORef (evPause w) PauseStep kbdroi w _ (Char '\27') Down Modifiers {ctrl=Down} _ = writeIORef (evEnd w) True kbdroi _ defaultFunc a b c d = defaultFunc a b c d mvroi w (Position x1' y1') = do ms <- readIORef (evMove w) z@(z0,_,dy) <- readIORef (evZoom w) gp <- unZoomPoint w let pt = gp (Position x1' y1') case ms of None -> return () SetROI -> do modifyIORef (evRegion w) $ \(p,_) -> (p,pt) writeIORef (evDrReg w) True MoveZoom x0 y0 -> do modifyIORef (evZoom w) $ \(z,x,y) -> (z, x+fromIntegral (x1'-x0), y-fromIntegral (y1'-y0)) writeIORef (evMove w) (MoveZoom x1' y1') unZoomPoint w = do z@(z0,_,dy) <- readIORef (evZoom w) vp <- get viewport Size wh ww <- evSize `fmap` get windowSize let f (Position x y) = pt where (x',y') = unZoom z vp (x,y) [pt] = pixelsToPoints (Size (wh - round (4*dy/z0)) ww) [Pixel y' x'] return f newPauser refPau = do frozen <- newIORef Nothing return $ \cam -> do pau <- readIORef refPau when (pau == PauseStep) (writeIORef refPau PauseCam >> writeIORef frozen Nothing) old <- readIORef frozen if (pau == PauseCam || pau == PauseStep) then do case old of Nothing -> do {x <- cam; writeIORef frozen (Just x); return x} Just x -> threadDelay 100000 >> return x else do case old of Just _ -> writeIORef frozen Nothing _ -> return () cam callHelp wn = do pname <- getProgName errMsg wn errMsg pname let helpnames = map (++".html") $ concatMap (\x -> [x,"help/"++x,"../help/"++x]) [ intercalate "-" [pname, wn'] , pname , wn' , "help" ] fs <- filterM doesFileExist helpnames let f = head fs if null fs then errMsg "no help file available" else system ("xdg-open "++f) >> return () where wn' = map f wn f ' ' = '_' f x = x
b472c46885aaa90c1f81d62452db96aab32edaa90a81e436858979b7320b3fd8
nponeccop/HNC
Options.hs
# LANGUAGE FlexibleContexts # module Utils.Options (err, O(..), Options(..), runOptions) where import Control.Monad import Control.Monad.Except import System.Console.GetOpt import System.Environment import qualified Data.Map as M import qualified Data.Set as S data Options = OptBool String | OptString String String deriving Show data O = O { oBool :: S.Set String , oString :: M.Map String String , oNonOptions :: [String] } deriving Show defaultO = O S.empty M.empty [] xxx = foldM f defaultO where f o (OptBool opt) = if S.member opt $ oBool o then throwError $ "Duplicate " ++ opt ++ " option" else return o { oBool = S.insert opt (oBool o) } f o (OptString opt v) = if M.member opt $ oString o then throwError $ "Duplicate " ++ opt ++ " option" else return o { oString = M.insert opt v (oString o) } getO (o, no) = do oo <- xxx o return $ oo { oNonOptions = no } compilerOpts options argv = case getOpt Permute options argv of (o,n,[] ) -> return (o,n) (_,_,errs) -> ioError (userError (concat errs)) runOptions options bbb = getArgs >>= compilerOpts options >>= aaa >>= bbb aaa x = case getO x of Left err -> ioError $ userError err Right o -> return o err e = ioError $ userError e
null
https://raw.githubusercontent.com/nponeccop/HNC/d8447009a04c56ae2cba4c7c179e39384085ea00/Utils/Options.hs
haskell
# LANGUAGE FlexibleContexts # module Utils.Options (err, O(..), Options(..), runOptions) where import Control.Monad import Control.Monad.Except import System.Console.GetOpt import System.Environment import qualified Data.Map as M import qualified Data.Set as S data Options = OptBool String | OptString String String deriving Show data O = O { oBool :: S.Set String , oString :: M.Map String String , oNonOptions :: [String] } deriving Show defaultO = O S.empty M.empty [] xxx = foldM f defaultO where f o (OptBool opt) = if S.member opt $ oBool o then throwError $ "Duplicate " ++ opt ++ " option" else return o { oBool = S.insert opt (oBool o) } f o (OptString opt v) = if M.member opt $ oString o then throwError $ "Duplicate " ++ opt ++ " option" else return o { oString = M.insert opt v (oString o) } getO (o, no) = do oo <- xxx o return $ oo { oNonOptions = no } compilerOpts options argv = case getOpt Permute options argv of (o,n,[] ) -> return (o,n) (_,_,errs) -> ioError (userError (concat errs)) runOptions options bbb = getArgs >>= compilerOpts options >>= aaa >>= bbb aaa x = case getO x of Left err -> ioError $ userError err Right o -> return o err e = ioError $ userError e
e026d589ea03c7d6dea213a4b255130f12250e395e40be1acfd79744e6a9bb4e
justinethier/cyclone
let-syntax-298.scm
;; From: ;; -scheme/issues/298 (import (scheme base) (scheme write)) (define-syntax bar (syntax-rules () ((_) (let-syntax ((foo (syntax-rules () ((_) 'ok)))) (foo))))) (define-syntax foo (syntax-rules () ((_) 'foo))) (write (bar) ) (write (foo) )
null
https://raw.githubusercontent.com/justinethier/cyclone/a1c2a8f282f37ce180a5921ae26a5deb04768269/tests/let-syntax-298.scm
scheme
From: -scheme/issues/298
(import (scheme base) (scheme write)) (define-syntax bar (syntax-rules () ((_) (let-syntax ((foo (syntax-rules () ((_) 'ok)))) (foo))))) (define-syntax foo (syntax-rules () ((_) 'foo))) (write (bar) ) (write (foo) )
01b210e4fbb9a431db535c68c6099dfdbfc5733b62e19b09c6dbf506a10fdac0
degree9/uikit-hl
button.cljs
(ns uikit-hl.button (:require [hoplon.core :as h] [hoplon.jquery])) (defmulti uk-button! h/kw-dispatcher :default ::default) (defmethod h/do! ::default [elem key val] (uk-button! elem key val)) (defn- format-button [button] (str "uk-button-" button)) (defmethod uk-button! ::default [elem kw v] (elem :class {(format-button (name kw)) v})) (defmethod uk-button! ::button [elem kw v] (h/do! elem :class {:uk-button (clj->js v)})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (h/defelem button [{:keys [default primary secondary danger text link small large] :as attr} kids] (let [attr (dissoc attr :default :primary :secondary :danger :text :link :small :large)] (h/button attr ::button true ::default default ::primary primary ::secondary secondary ::danger danger ::text text ::link link ::small small ::large large kids))) (h/defelem a-button [{:keys [default primary secondary danger text link small large] :as attr} kids] (let [attr (dissoc attr :default :primary :secondary :danger :text :link :small :large)] (h/a attr ::button true ::default default ::primary primary ::secondary secondary ::danger danger ::text text ::link link ::small small ::large large kids))) (h/defelem group [attr kids] (h/div attr ::group true kids))
null
https://raw.githubusercontent.com/degree9/uikit-hl/b226b1429ea50f8e9a6c1d12c082a3be504dda33/src/uikit_hl/button.cljs
clojure
(ns uikit-hl.button (:require [hoplon.core :as h] [hoplon.jquery])) (defmulti uk-button! h/kw-dispatcher :default ::default) (defmethod h/do! ::default [elem key val] (uk-button! elem key val)) (defn- format-button [button] (str "uk-button-" button)) (defmethod uk-button! ::default [elem kw v] (elem :class {(format-button (name kw)) v})) (defmethod uk-button! ::button [elem kw v] (h/do! elem :class {:uk-button (clj->js v)})) (h/defelem button [{:keys [default primary secondary danger text link small large] :as attr} kids] (let [attr (dissoc attr :default :primary :secondary :danger :text :link :small :large)] (h/button attr ::button true ::default default ::primary primary ::secondary secondary ::danger danger ::text text ::link link ::small small ::large large kids))) (h/defelem a-button [{:keys [default primary secondary danger text link small large] :as attr} kids] (let [attr (dissoc attr :default :primary :secondary :danger :text :link :small :large)] (h/a attr ::button true ::default default ::primary primary ::secondary secondary ::danger danger ::text text ::link link ::small small ::large large kids))) (h/defelem group [attr kids] (h/div attr ::group true kids))
d21e1735d729eb6902d3eb67e340599cb8c844255b1d7499d903a0fbbed39a03
nasa/Common-Metadata-Repository
metrics_service.clj
(ns cmr.search.services.community-usage-metrics.metrics-service "Provides functions for storing and retrieving community usage metrics. Community usage metrics are saved in MetadataDB as part of the humanizers JSON." (:require [cheshire.core :as json] [clojure.data.csv :as csv] [clojure.string :as str] [cmr.common-app.services.search.parameter-validation :as cpv] [cmr.common-app.services.search.group-query-conditions :as gc] [cmr.common-app.services.search.query-execution :as qe] [cmr.common-app.services.search.query-model :as qm] [cmr.common.log :as log :refer (debug info warn error)] [cmr.common.services.errors :as errors] [cmr.common.util :as util] [cmr.search.services.community-usage-metrics.metrics-json-schema-validation :as metrics-json] [cmr.search.services.humanizers.humanizer-service :as humanizer-service])) (defn- get-community-usage-columns "The community usage csv has many columns. Get the indices of the columns we want to store. Returns: product-col - the index of the Product in each CSV line version-col - the index of the Version in each CSV line hosts-col - the index of the Hosts in each CSV line" [csv-header] (let [csv-header (mapv str/trim csv-header)] {:product-col (.indexOf csv-header "Product") :version-col (.indexOf csv-header "ProductVersion") :hosts-col (.indexOf csv-header "Hosts")})) (defn- read-csv-column "Read a column from the csv, if the column is exists. Otherwise, return nil." [csv-line col] (when (>= col 0) (nth csv-line col))) (defn- get-collection-by-product-id "Query elastic for a collection with a given product-id, parses out the value before the last : and checks that value against both entry-title or short-name. Also checks the non-parsed value against short-name." [context product-id] (when (seq product-id) (when-let [parsed-product-id (as-> (re-find #"(^.+):|(^.+)" product-id) matches (remove nil? matches) (last matches))] (let [condition (gc/or (qm/string-condition :entry-title parsed-product-id false false) (qm/string-condition :short-name parsed-product-id false false) (qm/string-condition :short-name product-id false false)) query (qm/query {:concept-type :collection :condition condition :page-size 1 :result-format :query-specified :result-fields [:short-name]}) results (qe/execute-query context query)] (:short-name (first (:items results))))))) (defn- cache-or-search "Uses the `product` value to check the short-name-cache. If there is a miss it checks the current-metrics-cache. If the `product` is unavailable in either, elasticsearch is queried directly." [context cache current-metrics product] (if (.containsKey cache product) (.get cache product) ;; return cache hit (if (contains? current-metrics product) (do ;; current-metrics hit (.put cache product product) product) ;; return product as short-name (let [short-name (get-collection-by-product-id context product)] ;; query elastic (.put cache product short-name) short-name)))) ;; return queried short-name (defn- get-short-name "Parse the short-name from the given csv-line and verify it exists in CMR. If it doesn't exist in CMR, use the `product` value as-is. Throws a service error if the product column is empty." [context cache csv-line product-col current-metrics] (let [product (read-csv-column csv-line product-col) _ (when-not (seq product) (errors/throw-service-error :invalid-data "Error parsing 'Product' CSV Data. Product may not be empty.")) short-name (cache-or-search context cache current-metrics product)] (if (seq short-name) short-name (do (warn (format (str "While constructing community metrics humanizer, " "could not find corresponding collection when searching for the term %s. " "CSV line entry: %s") product csv-line)) product)))) (defn- get-access-count "Parse access-count from given csv-line. Throws service errors if the hosts column is empty or contains an invalid integer." [csv-line hosts-col] (let [access-count (read-csv-column csv-line hosts-col)] (if (seq access-count) (try (Long/parseLong (str/replace access-count "," "")) ; Remove commas in large ints (catch java.lang.NumberFormatException e (errors/throw-service-error :invalid-data (format (str "Error parsing 'Hosts' CSV Data. " "Hosts must be an integer. " "CSV line entry: %s") csv-line)))) (errors/throw-service-error :invalid-data (format (str "Error parsing 'Hosts' CSV Data. " "Hosts may not be empty. " "CSV line entry: %s") csv-line))))) (defn- get-version "Version must be 20 characters or less." [csv-line version-col] (let [reported-version (read-csv-column csv-line version-col)] (when (<= (count reported-version) 20) reported-version))) (defn- csv-entry->community-usage-metric "Convert a line in the csv file to a community usage metric. Only storing short-name (product) and access-count (hosts)." [context csv-line product-col hosts-col version-col current-metrics cache] (when (seq (remove empty? csv-line)) ; Don't process empty lines {:short-name (get-short-name context cache csv-line product-col current-metrics) :version (get-version csv-line version-col) :access-count (get-access-count csv-line hosts-col)})) (defn- validate-and-read-csv "Validate the ingested community usage metrics csv and if valid, return the data lines read from the CSV (everything except the header) and column indices of data we want to store. If there is invalid data, throw an error. Perform the following validations: * CSV is neither nil nor empty * A Product column exists * A Hosts column exists" [community-usage-csv] (if community-usage-csv (if-let [csv-lines (seq (csv/read-csv community-usage-csv))] (let [csv-columns (get-community-usage-columns (first csv-lines))] (when (< (:product-col csv-columns) 0) (errors/throw-service-error :invalid-data "A 'Product' column is required in community usage CSV data")) (when (< (:hosts-col csv-columns) 0) (errors/throw-service-error :invalid-data "A 'Hosts' column is required in community usage CSV data")) (when (< (:version-col csv-columns) 0) (errors/throw-service-error :invalid-data "A 'ProductVersion' column is required in community usage CSV data")) (merge {:csv-lines (rest csv-lines)} csv-columns)) (errors/throw-service-error :invalid-data "You posted empty content")) (errors/throw-service-error :invalid-data "You posted empty content"))) (defn get-community-usage-metrics "Retrieves the current community usage metrics from metadata-db. Returns an empty set if unable to retrieve metrics." [context] (:community-usage-metrics (json/decode (:metadata (humanizer-service/fetch-humanizer-concept context)) true))) (defn- get-community-usage-metrics-or-empty-list [context] (try (get-community-usage-metrics context) (catch Exception e (warn e) []))) (defn- community-usage-metrics-list->set "Convert list of {:short-name :access-count} maps into a set of short-names." [metrics-list] (set (map :short-name metrics-list))) (defn- community-usage-csv->community-usage-metrics "Validate the community usage csv and convert to a list of community usage metrics." [context community-usage-csv current-metrics] (let [{:keys [csv-lines product-col hosts-col version-col]} (validate-and-read-csv community-usage-csv) short-name-cache (new java.util.HashMap)] (remove nil? (map #(csv-entry->community-usage-metric context % product-col hosts-col version-col current-metrics short-name-cache) csv-lines)))) (defn- aggregate-usage-metrics "Combine access-counts for entries with the same short-name." [metrics] ;; name-version-groups is map of [short-name, version] [entries that match short-name/version] (let [name-version-groups (group-by (juxt :short-name :version) metrics)] ; Group by short-name and version The first entry in each list has the short - name and version we want so just add up the access - counts in the rest and add that to the first entry to make the access - counts right (map #(util/remove-nil-keys (assoc (first %) :access-count (reduce + (map :access-count %)))) (vals name-version-groups)))) (defn- validate-metrics "Validate metrics against the JSON schema validation" [metrics] (let [json (json/generate-string metrics)] (metrics-json/validate-metrics-json json))) (defn- validate-update-community-usage-params "Currently only validates the parameter comprehensive as a boolean." [params] (cpv/validate-parameters nil params [(partial cpv/validate-boolean-param :comprehensive)])) (defn update-community-usage "Create/update the community usage metrics saving them with the humanizers in metadata db. Do not Do not overwrite the humanizers, just the community usage metrics. Increment the revision id manually to avoid race conditions if multiple updates are happening at the same time. Returns the concept id and revision id of the saved humanizer." [context params community-usage-csv] (validate-update-community-usage-params params) (let [comprehensive (or (:comprehensive params) "false") ;; set default current-metrics (if (= "false" comprehensive) (-> context (get-community-usage-metrics-or-empty-list) (community-usage-metrics-list->set)) #{}) metrics (community-usage-csv->community-usage-metrics context community-usage-csv current-metrics) metrics-agg (aggregate-usage-metrics metrics)] (validate-metrics metrics-agg) (humanizer-service/update-humanizers-metadata context :community-usage-metrics metrics-agg)))
null
https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/4a72d6e579d9044bfc5910f7b008b631c6becfc9/search-app/src/cmr/search/services/community_usage_metrics/metrics_service.clj
clojure
return cache hit current-metrics hit return product as short-name query elastic return queried short-name Remove commas in large ints Don't process empty lines name-version-groups is map of [short-name, version] [entries that match short-name/version] Group by short-name and version set default
(ns cmr.search.services.community-usage-metrics.metrics-service "Provides functions for storing and retrieving community usage metrics. Community usage metrics are saved in MetadataDB as part of the humanizers JSON." (:require [cheshire.core :as json] [clojure.data.csv :as csv] [clojure.string :as str] [cmr.common-app.services.search.parameter-validation :as cpv] [cmr.common-app.services.search.group-query-conditions :as gc] [cmr.common-app.services.search.query-execution :as qe] [cmr.common-app.services.search.query-model :as qm] [cmr.common.log :as log :refer (debug info warn error)] [cmr.common.services.errors :as errors] [cmr.common.util :as util] [cmr.search.services.community-usage-metrics.metrics-json-schema-validation :as metrics-json] [cmr.search.services.humanizers.humanizer-service :as humanizer-service])) (defn- get-community-usage-columns "The community usage csv has many columns. Get the indices of the columns we want to store. Returns: product-col - the index of the Product in each CSV line version-col - the index of the Version in each CSV line hosts-col - the index of the Hosts in each CSV line" [csv-header] (let [csv-header (mapv str/trim csv-header)] {:product-col (.indexOf csv-header "Product") :version-col (.indexOf csv-header "ProductVersion") :hosts-col (.indexOf csv-header "Hosts")})) (defn- read-csv-column "Read a column from the csv, if the column is exists. Otherwise, return nil." [csv-line col] (when (>= col 0) (nth csv-line col))) (defn- get-collection-by-product-id "Query elastic for a collection with a given product-id, parses out the value before the last : and checks that value against both entry-title or short-name. Also checks the non-parsed value against short-name." [context product-id] (when (seq product-id) (when-let [parsed-product-id (as-> (re-find #"(^.+):|(^.+)" product-id) matches (remove nil? matches) (last matches))] (let [condition (gc/or (qm/string-condition :entry-title parsed-product-id false false) (qm/string-condition :short-name parsed-product-id false false) (qm/string-condition :short-name product-id false false)) query (qm/query {:concept-type :collection :condition condition :page-size 1 :result-format :query-specified :result-fields [:short-name]}) results (qe/execute-query context query)] (:short-name (first (:items results))))))) (defn- cache-or-search "Uses the `product` value to check the short-name-cache. If there is a miss it checks the current-metrics-cache. If the `product` is unavailable in either, elasticsearch is queried directly." [context cache current-metrics product] (if (.containsKey cache product) (if (contains? current-metrics product) (.put cache product product) (.put cache product short-name) (defn- get-short-name "Parse the short-name from the given csv-line and verify it exists in CMR. If it doesn't exist in CMR, use the `product` value as-is. Throws a service error if the product column is empty." [context cache csv-line product-col current-metrics] (let [product (read-csv-column csv-line product-col) _ (when-not (seq product) (errors/throw-service-error :invalid-data "Error parsing 'Product' CSV Data. Product may not be empty.")) short-name (cache-or-search context cache current-metrics product)] (if (seq short-name) short-name (do (warn (format (str "While constructing community metrics humanizer, " "could not find corresponding collection when searching for the term %s. " "CSV line entry: %s") product csv-line)) product)))) (defn- get-access-count "Parse access-count from given csv-line. Throws service errors if the hosts column is empty or contains an invalid integer." [csv-line hosts-col] (let [access-count (read-csv-column csv-line hosts-col)] (if (seq access-count) (try (catch java.lang.NumberFormatException e (errors/throw-service-error :invalid-data (format (str "Error parsing 'Hosts' CSV Data. " "Hosts must be an integer. " "CSV line entry: %s") csv-line)))) (errors/throw-service-error :invalid-data (format (str "Error parsing 'Hosts' CSV Data. " "Hosts may not be empty. " "CSV line entry: %s") csv-line))))) (defn- get-version "Version must be 20 characters or less." [csv-line version-col] (let [reported-version (read-csv-column csv-line version-col)] (when (<= (count reported-version) 20) reported-version))) (defn- csv-entry->community-usage-metric "Convert a line in the csv file to a community usage metric. Only storing short-name (product) and access-count (hosts)." [context csv-line product-col hosts-col version-col current-metrics cache] {:short-name (get-short-name context cache csv-line product-col current-metrics) :version (get-version csv-line version-col) :access-count (get-access-count csv-line hosts-col)})) (defn- validate-and-read-csv "Validate the ingested community usage metrics csv and if valid, return the data lines read from the CSV (everything except the header) and column indices of data we want to store. If there is invalid data, throw an error. Perform the following validations: * CSV is neither nil nor empty * A Product column exists * A Hosts column exists" [community-usage-csv] (if community-usage-csv (if-let [csv-lines (seq (csv/read-csv community-usage-csv))] (let [csv-columns (get-community-usage-columns (first csv-lines))] (when (< (:product-col csv-columns) 0) (errors/throw-service-error :invalid-data "A 'Product' column is required in community usage CSV data")) (when (< (:hosts-col csv-columns) 0) (errors/throw-service-error :invalid-data "A 'Hosts' column is required in community usage CSV data")) (when (< (:version-col csv-columns) 0) (errors/throw-service-error :invalid-data "A 'ProductVersion' column is required in community usage CSV data")) (merge {:csv-lines (rest csv-lines)} csv-columns)) (errors/throw-service-error :invalid-data "You posted empty content")) (errors/throw-service-error :invalid-data "You posted empty content"))) (defn get-community-usage-metrics "Retrieves the current community usage metrics from metadata-db. Returns an empty set if unable to retrieve metrics." [context] (:community-usage-metrics (json/decode (:metadata (humanizer-service/fetch-humanizer-concept context)) true))) (defn- get-community-usage-metrics-or-empty-list [context] (try (get-community-usage-metrics context) (catch Exception e (warn e) []))) (defn- community-usage-metrics-list->set "Convert list of {:short-name :access-count} maps into a set of short-names." [metrics-list] (set (map :short-name metrics-list))) (defn- community-usage-csv->community-usage-metrics "Validate the community usage csv and convert to a list of community usage metrics." [context community-usage-csv current-metrics] (let [{:keys [csv-lines product-col hosts-col version-col]} (validate-and-read-csv community-usage-csv) short-name-cache (new java.util.HashMap)] (remove nil? (map #(csv-entry->community-usage-metric context % product-col hosts-col version-col current-metrics short-name-cache) csv-lines)))) (defn- aggregate-usage-metrics "Combine access-counts for entries with the same short-name." [metrics] The first entry in each list has the short - name and version we want so just add up the access - counts in the rest and add that to the first entry to make the access - counts right (map #(util/remove-nil-keys (assoc (first %) :access-count (reduce + (map :access-count %)))) (vals name-version-groups)))) (defn- validate-metrics "Validate metrics against the JSON schema validation" [metrics] (let [json (json/generate-string metrics)] (metrics-json/validate-metrics-json json))) (defn- validate-update-community-usage-params "Currently only validates the parameter comprehensive as a boolean." [params] (cpv/validate-parameters nil params [(partial cpv/validate-boolean-param :comprehensive)])) (defn update-community-usage "Create/update the community usage metrics saving them with the humanizers in metadata db. Do not Do not overwrite the humanizers, just the community usage metrics. Increment the revision id manually to avoid race conditions if multiple updates are happening at the same time. Returns the concept id and revision id of the saved humanizer." [context params community-usage-csv] (validate-update-community-usage-params params) current-metrics (if (= "false" comprehensive) (-> context (get-community-usage-metrics-or-empty-list) (community-usage-metrics-list->set)) #{}) metrics (community-usage-csv->community-usage-metrics context community-usage-csv current-metrics) metrics-agg (aggregate-usage-metrics metrics)] (validate-metrics metrics-agg) (humanizer-service/update-humanizers-metadata context :community-usage-metrics metrics-agg)))
f6f8e4f9b061b219871ed613b332a8a9cb99c8943e4d835e0c45e0434a6afaf7
dyzsr/ocaml-selectml
pr5164_ok.ml
(* TEST flags = " -w -a " * setup-ocamlc.byte-build-env ** ocamlc.byte *** check-ocamlc.byte-output *) module type INCLUDING = sig include module type of List include module type of ListLabels end module Including_typed: INCLUDING = struct include List include ListLabels end
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/typing-modules-bugs/pr5164_ok.ml
ocaml
TEST flags = " -w -a " * setup-ocamlc.byte-build-env ** ocamlc.byte *** check-ocamlc.byte-output
module type INCLUDING = sig include module type of List include module type of ListLabels end module Including_typed: INCLUDING = struct include List include ListLabels end
f40a5d27f057b63f87becb3ac0950dd2fe75f5170761409d8d3cdc7e8ea0fc89
jiangpengnju/htdp2e
know_thy_data.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname know_thy_data) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ; predicate, which is a function that consumes a value and determines whether ; or not it belongs to some class of data. (number? 5) (number? pi) (number? #true) (number? "fortytwo") (define in "123") (if (string? in) (string-length in) "what you input is not string") (rational? pi) (real? e) (exact? pi)
null
https://raw.githubusercontent.com/jiangpengnju/htdp2e/d41555519fbb378330f75c88141f72b00a9ab1d3/fixed-size-data/arithmetic/know_thy_data.rkt
racket
about the language level of this file in a form that our tools can easily process. predicate, which is a function that consumes a value and determines whether or not it belongs to some class of data.
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname know_thy_data) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (number? 5) (number? pi) (number? #true) (number? "fortytwo") (define in "123") (if (string? in) (string-length in) "what you input is not string") (rational? pi) (real? e) (exact? pi)
89c07e259265e49b5dcb50b2d3aa7d40db3326d0ab93a6ec4a3948d60784a27f
sweirich/hs-inferno
TUnionFind.hs
# LANGUAGE UndecidableInstances # # LANGUAGE FlexibleContexts # # LANGUAGE DeriveGeneric # {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE StandaloneDeriving # {-# OPTIONS_GHC -funbox-strict-fields -fdefer-type-errors #-} -- TODO: use a persistant data structure -08-22-144618_purely-functional-data-structures-algorithms-union-find-haskell.html Or Conchon / Filliatre : A persistent Union - Find Data structure , ML Workshop 2007 module Language.Inferno.TUnionFind (Point, fresh, repr, reprT, find, union, equivalent, is_representative) where This module implements a simple and efficient union / find algorithm . See , ` ` Efficiency of a Good But Not Linear Set Union Algorithm '' , JACM 22(2 ) , 1975 . See Robert E. Tarjan, ``Efficiency of a Good But Not Linear Set Union Algorithm'', JACM 22(2), 1975. -} {- This module implements a transactional variant of the union-find algorithm. It uses transactional references instead of ordinary references, so that a series of operations performed within a transaction can be either committed or rolled back. -} See [ UnionFind ] for comparison . The differences are : - we use [ TRef ] instead of [ IORef ] ; - [ find ] does not perform path compression , so as to avoid requiring TransM ; - [ union ] is in TransM - we use [TRef] instead of [IORef]; - [find] does not perform path compression, so as to avoid requiring TransM; - [union] is in TransM -} import Language.Inferno.TRef import Control.Applicative import Control.Monad (when, liftM, liftM2) import Control.Monad.Trans import Control.Monad.Ref import Control.Monad.EqRef import Data.Typeable newtype Point m a = Point { unPoint :: TRef m (Link m a) } deriving (Typeable) data Link m a = Info { weight :: {-# UNPACK #-} !Int, descriptor :: a } | Link {-# UNPACK #-} !(Point m a) -- ^ Pointer to some other element of the equivalence class. instance (MonadEqRef m) => Eq (Point m a) where p1 == p2 = unPoint p1 == unPoint p2 instance (Eq a, MonadEqRef m) => Eq (Link m a) where (Link p1) == (Link p2) = p1 == p2 (Info w1 d1) == (Info w2 d2) = w1 == w2 && d1 == d2 _ == _ = False showIO ( Point r p ) = do l < - readTRef p case l of Info weight desc - > return $ show desc Link q - > showIO q instance Show a = > Show ( Point r r a ) where show = unsafePerformIO . showIO (Point r p) = do l <- readTRef p case l of Info weight desc -> return $ show desc Link q -> showIO q instance Show a => Show (Point r r a) where show = unsafePerformIO . showIO -} readPoint (Point p) = readTRef p writePoint (Point p) x = writeTRef p x -- [fresh desc] creates a fresh point and returns it. It forms an -- equivalence class of its own, whose descriptor is [desc]. fresh :: MonadRef m => a -> m (Point m a) fresh desc = do r <- newTRef (Info {weight=1, descriptor=desc}) return (Point r) | /O(1)/. point@ returns the representative point of @point@ 's equivalence class . -- -- This version of [repr] does not perform path compression. Thus, it can be -- used outside a transaction. repr :: MonadRef m => Point m a -> m (Point m a) repr point@(Point ref) = do link <- readTRef ref case link of Link point' -> repr point' Info _ _ -> return point -- Return the descriptor associated with the argument's -- equivalence class. -- Again, this does not perform path compression. find :: MonadRef m => Point m a -> m a find point = do link <- readTRef (unPoint point) case link of Info _ desc -> return desc Link point' -> do link' <- readTRef (unPoint point') case link' of Info _ desc -> return desc Link _ -> find =<< repr point @reprT point@ returns the representative point of @point@ 's equivalence class . -- -- This version of [repr] performs path compression and -- must be used within a transaction. reprT :: (MonadEqRef m, Eq a) => Point m a -> TransM (Link m a) m (Point m a) reprT point = do link <- lift $ readPoint point case link of Link point' -> do point'' <- reprT point' when (point'' /= point') $ do ref' <- lift $ readPoint point' writePoint point ref' return point'' Info _ _ -> return point [ union f point1 point2 ] merges the equivalence classes associated with [ point1 ] and [ point2 ] into a single class . Then , ( and only then , ) it sets the descriptor of this class to the one produced by applying the function [ f ] to the descriptors of the two original classes . It has no effect if [ point1 ] and [ point2 ] are already in the same equivalence class . The fact that [ point1 ] and [ point2 ] do not originally belong to the same class guarantees that we do not create a cycle in the graph . The weights are used to determine whether [ point1 ] should be made to point to [ point2 ] , or vice - versa . By making the representative of the smaller class point to that of the larger class , we guarantee that paths remain of logarithmic length ( not accounting for path compression , which makes them yet smaller ) . with [point1] and [point2] into a single class. Then, (and only then,) it sets the descriptor of this class to the one produced by applying the function [f] to the descriptors of the two original classes. It has no effect if [point1] and [point2] are already in the same equivalence class. The fact that [point1] and [point2] do not originally belong to the same class guarantees that we do not create a cycle in the graph. The weights are used to determine whether [point1] should be made to point to [point2], or vice-versa. By making the representative of the smaller class point to that of the larger class, we guarantee that paths remain of logarithmic length (not accounting for path compression, which makes them yet smaller). -} union f p1 p2 = do point1 <- reprT p1 point2 <- reprT p2 when (point1 /= point2) $ do (Info w1 desc1) <- lift $ readPoint point1 (Info w2 desc2) <- lift $ readPoint point2 ds <- f desc1 desc2 if w1 >= w2 then do writePoint point2 (Link point1) writePoint point1 (Info (w1 + w2) ds) else do writePoint point1 (Link point2) writePoint point2 (Info (w1 + w2) ds) equivalent p1 p2 = do r1 <- repr p1 r2 <- repr p2 return $ r1 == r2 is_representative point = do l1 <- readTRef (unPoint point) case l1 of Link _ -> return False Info _ _ -> return True -- A test! test :: IO () test = do a <- fresh "a" b <- fresh "b" c <- fresh "c" d <- fresh "d" indubitably $ do union (\x y -> return x) a b union (\x y -> return x) b d b1 <- (equivalent a b) print b1 b2 <- (equivalent b c) print (not b2) b3 <- (equivalent c d) print (not b3) b4 <- (equivalent a d) print b4 {- prop_uf sets k = let num = length sets in forM [1 .. k] $ do j <- -}
null
https://raw.githubusercontent.com/sweirich/hs-inferno/08f6c514a695463332b69e5315b324802687328f/src/Language/Inferno/Generic/TUnionFind.hs
haskell
# LANGUAGE DeriveDataTypeable # # OPTIONS_GHC -funbox-strict-fields -fdefer-type-errors # TODO: use a persistant data structure This module implements a transactional variant of the union-find algorithm. It uses transactional references instead of ordinary references, so that a series of operations performed within a transaction can be either committed or rolled back. # UNPACK # # UNPACK # ^ Pointer to some other element of the equivalence class. [fresh desc] creates a fresh point and returns it. It forms an equivalence class of its own, whose descriptor is [desc]. This version of [repr] does not perform path compression. Thus, it can be used outside a transaction. Return the descriptor associated with the argument's equivalence class. Again, this does not perform path compression. This version of [repr] performs path compression and must be used within a transaction. A test! prop_uf sets k = let num = length sets in forM [1 .. k] $ do j <-
# LANGUAGE UndecidableInstances # # LANGUAGE FlexibleContexts # # LANGUAGE DeriveGeneric # # LANGUAGE StandaloneDeriving # -08-22-144618_purely-functional-data-structures-algorithms-union-find-haskell.html Or Conchon / Filliatre : A persistent Union - Find Data structure , ML Workshop 2007 module Language.Inferno.TUnionFind (Point, fresh, repr, reprT, find, union, equivalent, is_representative) where This module implements a simple and efficient union / find algorithm . See , ` ` Efficiency of a Good But Not Linear Set Union Algorithm '' , JACM 22(2 ) , 1975 . See Robert E. Tarjan, ``Efficiency of a Good But Not Linear Set Union Algorithm'', JACM 22(2), 1975. -} See [ UnionFind ] for comparison . The differences are : - we use [ TRef ] instead of [ IORef ] ; - [ find ] does not perform path compression , so as to avoid requiring TransM ; - [ union ] is in TransM - we use [TRef] instead of [IORef]; - [find] does not perform path compression, so as to avoid requiring TransM; - [union] is in TransM -} import Language.Inferno.TRef import Control.Applicative import Control.Monad (when, liftM, liftM2) import Control.Monad.Trans import Control.Monad.Ref import Control.Monad.EqRef import Data.Typeable newtype Point m a = Point { unPoint :: TRef m (Link m a) } deriving (Typeable) data Link m a = instance (MonadEqRef m) => Eq (Point m a) where p1 == p2 = unPoint p1 == unPoint p2 instance (Eq a, MonadEqRef m) => Eq (Link m a) where (Link p1) == (Link p2) = p1 == p2 (Info w1 d1) == (Info w2 d2) = w1 == w2 && d1 == d2 _ == _ = False showIO ( Point r p ) = do l < - readTRef p case l of Info weight desc - > return $ show desc Link q - > showIO q instance Show a = > Show ( Point r r a ) where show = unsafePerformIO . showIO (Point r p) = do l <- readTRef p case l of Info weight desc -> return $ show desc Link q -> showIO q instance Show a => Show (Point r r a) where show = unsafePerformIO . showIO -} readPoint (Point p) = readTRef p writePoint (Point p) x = writeTRef p x fresh :: MonadRef m => a -> m (Point m a) fresh desc = do r <- newTRef (Info {weight=1, descriptor=desc}) return (Point r) | /O(1)/. point@ returns the representative point of @point@ 's equivalence class . repr :: MonadRef m => Point m a -> m (Point m a) repr point@(Point ref) = do link <- readTRef ref case link of Link point' -> repr point' Info _ _ -> return point find :: MonadRef m => Point m a -> m a find point = do link <- readTRef (unPoint point) case link of Info _ desc -> return desc Link point' -> do link' <- readTRef (unPoint point') case link' of Info _ desc -> return desc Link _ -> find =<< repr point @reprT point@ returns the representative point of @point@ 's equivalence class . reprT :: (MonadEqRef m, Eq a) => Point m a -> TransM (Link m a) m (Point m a) reprT point = do link <- lift $ readPoint point case link of Link point' -> do point'' <- reprT point' when (point'' /= point') $ do ref' <- lift $ readPoint point' writePoint point ref' return point'' Info _ _ -> return point [ union f point1 point2 ] merges the equivalence classes associated with [ point1 ] and [ point2 ] into a single class . Then , ( and only then , ) it sets the descriptor of this class to the one produced by applying the function [ f ] to the descriptors of the two original classes . It has no effect if [ point1 ] and [ point2 ] are already in the same equivalence class . The fact that [ point1 ] and [ point2 ] do not originally belong to the same class guarantees that we do not create a cycle in the graph . The weights are used to determine whether [ point1 ] should be made to point to [ point2 ] , or vice - versa . By making the representative of the smaller class point to that of the larger class , we guarantee that paths remain of logarithmic length ( not accounting for path compression , which makes them yet smaller ) . with [point1] and [point2] into a single class. Then, (and only then,) it sets the descriptor of this class to the one produced by applying the function [f] to the descriptors of the two original classes. It has no effect if [point1] and [point2] are already in the same equivalence class. The fact that [point1] and [point2] do not originally belong to the same class guarantees that we do not create a cycle in the graph. The weights are used to determine whether [point1] should be made to point to [point2], or vice-versa. By making the representative of the smaller class point to that of the larger class, we guarantee that paths remain of logarithmic length (not accounting for path compression, which makes them yet smaller). -} union f p1 p2 = do point1 <- reprT p1 point2 <- reprT p2 when (point1 /= point2) $ do (Info w1 desc1) <- lift $ readPoint point1 (Info w2 desc2) <- lift $ readPoint point2 ds <- f desc1 desc2 if w1 >= w2 then do writePoint point2 (Link point1) writePoint point1 (Info (w1 + w2) ds) else do writePoint point1 (Link point2) writePoint point2 (Info (w1 + w2) ds) equivalent p1 p2 = do r1 <- repr p1 r2 <- repr p2 return $ r1 == r2 is_representative point = do l1 <- readTRef (unPoint point) case l1 of Link _ -> return False Info _ _ -> return True test :: IO () test = do a <- fresh "a" b <- fresh "b" c <- fresh "c" d <- fresh "d" indubitably $ do union (\x y -> return x) a b union (\x y -> return x) b d b1 <- (equivalent a b) print b1 b2 <- (equivalent b c) print (not b2) b3 <- (equivalent c d) print (not b3) b4 <- (equivalent a d) print b4
105c989b0ed62fcf4717c2b7e034b8fe856af282d7d9c7750378e310881661f9
racket/drracket
multi-file-search.rkt
#lang racket/base (require framework framework/private/srcloc-panel racket/class racket/contract racket/unit racket/path racket/list racket/gui/base mzlib/async-channel string-constants drracket/private/drsig mrlib/close-icon drracket/get-module-path "suffix.rkt") (define sc-browse-collections "Browse\nCollections") (define sc-add-another-directory "Add Another Directory") (provide multi-file-search@) search - type = ( make - search - type string make - searcher ( listof ( cons string boolean ) ) ) ;; the param strings are the labels for checkboxes ;; the param booleans are the default values for the checkboxes ;; these are the available searches (define-struct search-type (label make-searcher params) #:transparent) ;; search-info = (make-search-info (listof string) boolean (union #f regexp) search-type string) ;; the search-string field is only informative; not used for actual searching (define-struct search-info (dirs recur? filter searcher search-string) #:transparent) search - types : ( listof search - type ) (define search-types (list (make-search-type (string-constant mfs-string-match/graphics) (λ (info search-string) (exact-match-searcher info search-string)) (list (cons (string-constant mfs-case-sensitive-label) #f))) (make-search-type (string-constant mfs-regexp-match/no-graphics) (λ (info search-string) (regexp-match-searcher info search-string)) (list)))) ;; search-entry = (make-search-entry string string number number number) (define-struct search-entry (base-dir filename line-string line-number col-number match-length) #:transparent) ;; to make these available to be defined in the unit with the right names. (define _search-types search-types) (define _search-type-params search-type-params) (define-unit multi-file-search@ (import [prefix drracket:frame: drracket:frame^] [prefix drracket:unit: drracket:unit^] [prefix drracket: drracket:interface^]) (export drracket:multi-file-search^) (define search-type-params _search-type-params) (define search-types _search-types) ;; multi-file-search : -> void ;; opens a dialog to configure the search and initiates the search (define (multi-file-search) (configure-search (λ (search-info) (open-search-window search-info)))) ;; searcher = (string (string int int int -> void) -> void) ;; this performs a single search. the first argument is the filename to be searched the second argument is called for each match . ;; the arguments are: line-string line-number col-number match-length ;; open-search-window : search-info -> void ;; thread: eventspace main thread ;; opens a window and creates the thread that does the search (define (open-search-window search-info) (define frame (new search-size-frame% [name (let ([fmt-s (string-constant mfs-drscheme-multi-file-search-title)]) (format fmt-s (gui-utils:trim-string (search-info-search-string search-info) (- 200 (string-length fmt-s)))))])) (define panel (make-object saved-vertical-resizable% (send frame get-area-container))) (define button-panel (new-horizontal-panel% [parent (send frame get-area-container)] [alignment '(right center)] [stretchable-height #f])) (define open-button (make-object button% (string-constant mfs-open-file) button-panel (λ (x y) (open-file-callback)))) (define stop-button (make-object button% (string-constant mfs-stop-search) button-panel (λ (x y) (stop-callback)))) (define grow-box-pane (make-object grow-box-spacer-pane% button-panel)) (define zoom-text (make-object (text:searching-mixin racket:text%))) (define results-text (make-object results-text% zoom-text)) (define results-ec (instantiate searching-canvas% () (parent panel) (editor results-text) (frame frame))) (define zoom-ec (instantiate searching-canvas% () (parent panel) (editor zoom-text) (frame frame))) (define (open-file-callback) (send results-text open-file)) ;; sometimes, breaking the other thread puts ;; the break message in the channel behind ;; many many requests. Rather than show those, ;; we use the `broken?' flag as a shortcut. (define broken? #f) (define (stop-callback) (break-thread search-thd) (set! broken? #t) (send stop-button enable #f)) ;; channel : async-channel[(union 'done search-entry)] (define channel (make-async-channel 100)) (define search-thd (thread (λ () (do-search search-info channel)))) (send frame set-text-to-search results-text) ;; just to initialize it to something. (send results-text lock #t) (send frame reflow-container) (send panel set-percentages (preferences:get 'drracket:multi-file-search:percentages)) (send frame show #t) (let loop () (let ([match (yield channel)]) (yield) (cond [(eq? match 'done) (send results-text search-complete) (send stop-button enable #f)] [(or broken? (eq? match 'break)) (send results-text search-interrupted)] [else (send results-text add-match (search-entry-base-dir match) (search-entry-filename match) (search-entry-line-string match) (search-entry-line-number match) (search-entry-col-number match) (search-entry-match-length match)) (loop)])))) (define results-super-text% (text:searching-mixin (text:hide-caret/selection-mixin (text:line-spacing-mixin (text:basic-mixin (editor:keymap-mixin (editor:standard-style-list-mixin (editor:basic-mixin text%)))))))) ;; results-text% : derived from text% ;; init args: zoom-text ;; zoom-text : (instance-of text%) ;; public-methods: ;; add-match : string string int int int int -> void ;; adds a match to the text ;; search-interrupted : -> void ;; inserts a message saying "search interrupted". ;; search-complete is not expected to be called if this method is called. ;; search-complete : -> void ;; inserts a message saying "no matches found" if none were reported (define results-text% (class results-super-text% (init-field zoom-text) (inherit insert last-paragraph erase paragraph-start-position paragraph-end-position last-position change-style set-clickback set-position end-edit-sequence begin-edit-sequence lock) [define filename-delta (make-object style-delta% 'change-bold)] [define match-delta (let ([d (make-object style-delta%)]) (send d set-delta-foreground (make-object color% 0 160 0)) d)] [define hilite-line-delta (make-object style-delta% 'change-style 'italic)] [define unhilite-line-delta (make-object style-delta% 'change-style 'normal)] [define widest-filename #f] [define/private indent-all-lines ;; indent-all-lines : number -> void ;; inserts `offset' spaces to the beginning of each line, except the last one . Must be at least one such line in the text . (λ (offset) (let ([spaces (make-string offset #\space)]) (let loop ([para (- (last-paragraph) 1)]) (let ([para-start (paragraph-start-position para)]) (insert spaces para-start para-start) (change-style filename-delta para-start (+ para-start offset))) (unless (zero? para) (loop (- para 1))))))] ;; match-shown? : boolean ;; indicates if a match has ever been shown. ;; if not, need to clean out the "searching" message ;; and show a match. Done in `add-match' [define match-shown? #f] ;; current-file : (union #f string) ;; the name of the currently viewed file, if one if viewed. ;; line-in-current-file and col-in-current-file are linked [define current-file #f] [define line-in-current-file #f] [define col-in-current-file #f] [define old-line #f] [define/private hilite-line (λ (line) (begin-edit-sequence) (lock #f) (when old-line (change-style unhilite-line-delta (paragraph-start-position old-line) (paragraph-end-position old-line))) (when line (change-style hilite-line-delta (paragraph-start-position line) (paragraph-end-position line))) (set! old-line line) (lock #t) (end-edit-sequence))] [define/public (open-file) (when current-file (let ([f (handler:edit-file current-file)]) (when (and f (is-a? f drracket:unit:frame<%>)) (let* ([t (send f get-definitions-text)] [pos (+ (send t paragraph-start-position line-in-current-file) col-in-current-file)]) (send t set-position pos)))))] (define/public (add-match base-filename full-filename line-string line col match-length) (lock #f) (define new-line-position (last-position)) (define short-filename (path->string (find-relative-path (normalize-path base-filename) (normalize-path full-filename)))) (define this-match-number (last-paragraph)) (define len (string-length short-filename)) (define insertion-start #f) (define (show-this-match) (set! match-shown? #t) (set! current-file full-filename) (set! line-in-current-file line) (set! col-in-current-file col) (set-position new-line-position new-line-position) (send zoom-text begin-edit-sequence) (send zoom-text lock #f) (unless (really-same-file? full-filename (send zoom-text get-filename)) (send zoom-text load-file/gui-error full-filename)) (send zoom-text set-position (send zoom-text paragraph-start-position line)) (let ([start (+ (send zoom-text paragraph-start-position line) col)]) (send zoom-text change-style match-delta start (+ start match-length))) (send zoom-text lock #t) (send zoom-text set-caret-owner #f 'global) (hilite-line this-match-number) (send zoom-text end-edit-sequence)) (unless match-shown? (erase)) (unless widest-filename (set! widest-filename len)) (if (<= len widest-filename) (begin (set! insertion-start (last-position)) (insert (make-string (- widest-filename len) #\space) (last-position) (last-position))) (begin (indent-all-lines (- len widest-filename)) (set! insertion-start (last-position)) (set! widest-filename len))) (let ([filename-start (last-position)]) (insert short-filename (last-position) (last-position)) (insert ": " (last-position) (last-position)) (change-style filename-delta insertion-start (last-position)) (let ([line-start (last-position)]) (insert line-string (last-position) (last-position)) (change-style match-delta (+ line-start col) (+ line-start col match-length))) (set-clickback filename-start (last-position) (λ (_1 _2 _3) (show-this-match))) (insert #\newline (last-position) (last-position)) (unless match-shown? (show-this-match))) (lock #t)) (define/public (search-interrupted) (lock #f) (insert #\newline (last-position) (last-position)) (insert (string-constant mfs-search-interrupted) (last-position) (last-position)) (lock #t)) (define/public (search-complete) (unless match-shown? (lock #f) (insert #\newline (last-position) (last-position)) (insert (string-constant mfs-no-matches-found) (last-position) (last-position)) (lock #t))) (inherit get-style-list set-style-list set-styles-sticky) (super-new) (send zoom-text lock #t) (set-styles-sticky #f) (insert (string-constant mfs-searching...)))) (define (really-same-file? fn1 fn2) (define p1 (with-handlers ((exn:fail? (λ (x) #f))) (open-input-file fn1))) (define p2 (with-handlers ((exn:fail? (λ (x) #f))) (open-input-file fn2))) (cond [(and p1 p2) (begin0 (= (port-file-identity p1) (port-file-identity p2)) (close-input-port p1) (close-input-port p2))] [else (when p1 (close-input-port p1)) (when p2 (close-input-port p2)) #f])) ;; collaborates with search-size-frame% (define searching-canvas% (class canvas:basic% (init-field frame) (inherit get-editor) (define/override (on-focus on?) (when on? (send frame set-text-to-search (get-editor))) (super on-focus on?)) (super-new))) ;; thread: eventspace main thread (define search-size-frame% (class (drracket:frame:basics-mixin (frame:searchable-mixin frame:standard-menus%)) (init-field name) (define/override (on-size w h) (preferences:set 'drracket:multi-file-search:frame-size (cons w h)) (super on-size w h)) (let ([size (preferences:get 'drracket:multi-file-search:frame-size)]) (super-new [label name] [width (car size)] [height (cdr size)])))) ;; this vertical-resizable class just remembers the percentage between the two panels ;; thread: eventspace main thread (define saved-vertical-resizable% (class panel:vertical-dragable% (inherit get-percentages) (define/augment (after-percentage-change) (let ([ps (get-percentages)]) (when (= (length ps) 2) (preferences:set 'drracket:multi-file-search:percentages ps))) (inner (void) after-percentage-change)) (super-new))) ;; do-search : search-info text -> void ;; thread: searching thread ;; called in a new thread that may be broken (to indicate a stop) (define (do-search search-info channel) (define filter (search-info-filter search-info)) (define searcher (search-info-searcher search-info)) (with-handlers ([exn:break? (λ (x) (async-channel-put channel 'break))]) (for ([dir (in-list (search-info-dirs search-info))]) (define get-filenames (if (search-info-recur? search-info) (build-recursive-file-list dir filter) (build-flat-file-list dir filter))) (let loop () (let ([filename (get-filenames)]) (when filename (searcher filename (λ (line-string line-number col-number match-length) (async-channel-put channel (make-search-entry dir filename line-string line-number col-number match-length)))) (loop))))) (async-channel-put channel 'done))) ;; build-recursive-file-list : string (union regexp #f) -> (-> (union string #f)) ;; thread: search thread (define (build-recursive-file-list dir filter) (letrec ([touched (make-hash)] [next-thunk (λ () (process-dir dir (λ () #f)))] [process-dir string[dirname ] ( listof string[filename ] ) - > ( string[filename ] ) (λ (dir k) (let* ([key (normalize-path dir)] [traversed? (hash-ref touched key (λ () #f))]) (cond [traversed? (k)] [else (define content (with-handlers ([exn:fail:filesystem? (λ (x) #f)]) (directory-list dir))) (hash-set! touched key #t) (cond [content (process-dir-contents (map (λ (x) (build-path dir x)) content) k)] [else (k)])])))] [process-dir-contents string[dirname ] ( listof string[filename ] ) - > ( string[filename ] ) (λ (contents k) (cond [(null? contents) (k)] [else (let ([file/dir (car contents)]) (cond [(and (file-exists? file/dir) (or (not filter) (regexp-match filter (path->string file/dir)))) (set! next-thunk (λ () (process-dir-contents (cdr contents) k))) file/dir] [(directory-exists? file/dir) (process-dir-contents (cdr contents) (λ () (process-dir file/dir k)))] [else (process-dir-contents (cdr contents) k)]))]))]) (λ () (next-thunk)))) ;; build-flat-file-list : path (union #f regexp) -> (-> (union string #f)) ;; thread: searching thread (define (build-flat-file-list dir filter) (let ([contents (map (λ (x) (build-path dir x)) (with-handlers ([exn:fail:filesystem? (λ (x) '())]) (directory-list dir)))]) (λ () (let loop () (cond [(null? contents) #f] [(and filter (regexp-match filter (path->string (car contents)))) (begin0 (car contents) (set! contents (cdr contents)))] [else (set! contents (cdr contents)) (loop)])))))) (define configure-search-window #f) ;; configure-search : -> (union #f search-info) ;; thread: eventspace main thread ;; configures the search (define (configure-search open-search-window) (cond [configure-search-window (send configure-search-window show #t)] [else (keymap:call/text-keymap-initializer (λ () (set! configure-search-window (new frame% [label (string-constant mfs-configure-search)] [width 500] [stretchable-height #f])) (define outer-files-panel (make-object vertical-panel% configure-search-window '(border))) (define outer-method-panel (make-object vertical-panel% configure-search-window '(border))) (define button-panel (new-horizontal-panel% [parent configure-search-window] [alignment '(right center)] [stretchable-height #f])) (define files-label (make-object message% (string-constant mfs-files-section) outer-files-panel)) (define files-inset-outer-panel (make-object horizontal-panel% outer-files-panel)) (define files-inset-panel (make-object horizontal-panel% files-inset-outer-panel)) (define files-panel (make-object vertical-panel% files-inset-outer-panel)) (define method-label (make-object message% (string-constant mfs-search-section) outer-method-panel)) (define method-inset-outer-panel (make-object horizontal-panel% outer-method-panel)) (define method-inset-panel (make-object horizontal-panel% method-inset-outer-panel)) (define method-panel (make-object vertical-panel% method-inset-outer-panel)) (define multi-dir+browse-collections-panel (new-horizontal-panel% [alignment '(center top)] [stretchable-height #f] [parent files-panel])) (define multi-dir-panel (new-vertical-panel% [parent multi-dir+browse-collections-panel])) (define dir-fields '()) (define (add-a-dir-field init-value) (send configure-search-window begin-container-sequence) (define need-to-add-closers? (and (pair? dir-fields) (null? (cdr dir-fields)))) (define dir-panel (new-horizontal-panel% [parent multi-dir-panel] [stretchable-height #f])) (define dir-field (new combo-field% [parent dir-panel] [label (string-constant mfs-dir)] [choices (preferences:get 'drracket:multi-file-search:directories)] [init-value init-value] [stretchable-width #t] [stretchable-height #f] [callback (λ (x y) (update-directory-prefs))])) (define dir-button (new button% [label (string-constant browse...)] [parent dir-panel] [callback (λ (x y) (dir-button-callback))])) (define (dir-button-callback) (define old-d (string->path (send dir-field get-value))) (define new-d (get-directory #f #f (and (directory-exists? old-d) old-d))) (when (and new-d (directory-exists? new-d)) (define str (path->string new-d)) (send dir-field set-value str) (update-directory-prefs))) (set! dir-fields (cons dir-field dir-fields)) (update-directory-prefs) (cond [(null? (cdr dir-fields)) ;; len=1 : add to none of them (void)] [(null? (cddr dir-fields)) ;; len=2 : add to all of them (for ([dir-panel (in-list (send multi-dir-panel get-children))]) (add-a-closer dir-panel))] [else len>2 : add to this one (add-a-closer dir-panel)]) (send configure-search-window end-container-sequence)) (define (add-a-closer dir-panel) (define ci (new close-icon% [parent dir-panel] [callback (λ () (remove-a-dir-panel dir-panel))])) (send dir-panel change-children (λ (l) (append (remove ci l) (list ci))))) (define (remove-a-dir-panel dir-panel) (define dir-field (for/or ([child (in-list (send dir-panel get-children))]) (and (is-a? child combo-field%) child))) (set! dir-fields (remove dir-field dir-fields)) (send multi-dir-panel change-children (λ (l) (remove dir-panel l))) (update-directory-prefs) (when (and (pair? dir-fields) (null? (cdr dir-fields))) only one dir field left , get rid of the close - icon (let loop ([parent multi-dir-panel]) (for ([child (in-list (send parent get-children))]) (cond [(is-a? child close-icon%) (send parent change-children (λ (l) (remove child l)))] [(is-a? child area-container<%>) (loop child)]))))) (define (update-directory-prefs) (define new-pref (for/list ([dir-field (in-list dir-fields)]) (define dfv (send dir-field get-value)) (and (path-string? dfv) dfv))) (when (andmap values new-pref) (preferences:set 'drracket:multi-file-search:directory new-pref))) (define browse-collections-button (new button% [label sc-browse-collections] [parent multi-dir+browse-collections-panel] [callback (λ (x y) (define paths (get-module-path-from-user #:dir? #t)) (when paths (define delta-dirs (- (length dir-fields) (length paths))) (cond [(< delta-dirs 0) (for ([x (in-range (- delta-dirs))]) (add-a-dir-field ""))] [(> delta-dirs 0) (for ([x (in-range delta-dirs)] [dir-field (in-list (send multi-dir-panel get-children))]) (remove-a-dir-panel dir-field))]) (for ([path (in-list paths)] [dir-field (in-list dir-fields)]) (send dir-field set-value (path->string path))) (update-directory-prefs)))])) (define recur+another-parent (new-horizontal-panel% [parent files-panel] [stretchable-height #f])) (define recur-check-box (new check-box% [label (string-constant mfs-recur-over-subdirectories)] [parent recur+another-parent] [callback (λ (x y) (recur-check-box-callback))])) (new-horizontal-panel% [parent recur+another-parent]) ;; spacer (define another-dir-button (new button% [label sc-add-another-directory] [parent recur+another-parent] [callback (λ (x y) (add-a-dir-field ""))])) (define filter-panel (make-object horizontal-panel% files-panel)) (define filter-check-box (make-object check-box% (string-constant mfs-regexp-filename-filter) filter-panel (λ (x y) (filter-check-box-callback)))) (define filter-text-field (make-object text-field% #f filter-panel (λ (x y) (filter-text-field-callback)))) (define methods-choice (make-object choice% #f (map search-type-label search-types) method-panel (λ (x y) (methods-choice-callback)))) (define search-text-field (make-object text-field% (string-constant mfs-search-string) method-panel (λ (x y) (search-text-field-callback)))) (define active-method-panel (make-object panel:single% method-panel)) (define methods-check-boxess (let ([pref (preferences:get 'drracket:multi-file-search:search-check-boxes)]) (map (λ (search-type prefs-settings) (let ([p (make-object vertical-panel% active-method-panel)] [params (search-type-params search-type)]) (send p set-alignment 'left 'center) (map (λ (flag-pair prefs-setting) (let ([cb (make-object check-box% (car flag-pair) p (λ (evt chk) (method-callback chk)))]) (send cb set-value prefs-setting) cb)) params (if (= (length params) (length prefs-settings)) prefs-settings (map (λ (x) #f) params))))) search-types (if (= (length search-types) (length pref)) pref (map (λ (x) '()) search-types))))) (define-values (ok-button cancel-button) (gui-utils:ok/cancel-buttons button-panel (λ (x y) (ok-button-callback)) (λ (x y) (cancel-button-callback)))) (define spacer (make-object grow-box-spacer-pane% button-panel)) ;; initialized to a searcher during the ok button callback ;; so the user can be informed of an error before the dialog ;; closes. (define searcher #f) ;; initialized to a regexp if the user wants to filter filenames, ;; during the ok-button-callback, so errors can be signaled. (define filter #f) ;; title for message box that signals error messages (define message-box-title (string-constant mfs-drscheme-multi-file-search)) (define (ok-button-callback) (define dirs (for/list ([df (in-list dir-fields)]) (send df get-value))) (define dont-exist (for/list ([dir (in-list dirs)] #:unless (with-handlers ([exn:fail:filesystem? (λ (x) #f)]) (and (path-string? dir) (directory-exists? dir)))) dir)) (cond [(null? dont-exist) (define new-l (append dirs (remove* dirs (preferences:get 'drracket:multi-file-search:directories)))) (preferences:set 'drracket:multi-file-search:directories (take new-l (min (length new-l) 10))) (define _searcher ((search-type-make-searcher (list-ref search-types (send methods-choice get-selection))) (map (λ (cb) (send cb get-value)) (send (send active-method-panel active-child) get-children)) (send search-text-field get-value))) (if (string? _searcher) (message-box message-box-title _searcher configure-search-window) (let ([the-regexp (with-handlers ([(λ (x) #t) (λ (exn) (format "~a" (exn-message exn)))]) (and (send filter-check-box get-value) (regexp (send filter-text-field get-value))))]) (if (string? the-regexp) (message-box message-box-title the-regexp configure-search-window) (begin (set! searcher _searcher) (set! filter the-regexp) (send configure-search-window show #f) (set! configure-search-window #f) (open-search-window (make-search-info (for/list ([dir-field (in-list dir-fields)]) (send dir-field get-value)) (send recur-check-box get-value) (and (send filter-check-box get-value) (regexp (send filter-text-field get-value))) searcher (send search-text-field get-value)))))))] [else (message-box message-box-title (format (string-constant mfs-not-a-dir) (car dont-exist)) configure-search-window)])) (define (cancel-button-callback) (send configure-search-window show #f) (set! configure-search-window #f)) (define (method-callback chk) (preferences:set 'drracket:multi-file-search:search-check-boxes (let loop ([methods-check-boxess methods-check-boxess]) (cond [(null? methods-check-boxess) null] [else (cons (let loop ([methods-check-boxes (car methods-check-boxess)]) (cond [(null? methods-check-boxes) null] [else (cons (send (car methods-check-boxes) get-value) (loop (cdr methods-check-boxes)))])) (loop (cdr methods-check-boxess)))])))) (define (filter-check-box-callback) (preferences:set 'drracket:multi-file-search:filter? (send filter-check-box get-value)) (send filter-text-field enable (send filter-check-box get-value))) (define (filter-text-field-callback) (preferences:set 'drracket:multi-file-search:filter-regexp (send filter-text-field get-value))) (define (recur-check-box-callback) (preferences:set 'drracket:multi-file-search:recur? (send recur-check-box get-value))) (define (methods-choice-callback) (define which (send methods-choice get-selection)) (preferences:set 'drracket:multi-file-search:search-type which) (set-method which)) (define (set-method which) (send active-method-panel active-child (list-ref (send active-method-panel get-children) which))) (define (search-text-field-callback) (preferences:set 'drracket:multi-file-search:search-string (send search-text-field get-value))) (send outer-files-panel stretchable-height #f) (send outer-files-panel set-alignment 'left 'center) (send files-inset-panel min-width 20) (send files-inset-panel stretchable-width #f) (send files-panel set-alignment 'left 'center) (send recur-check-box set-value (preferences:get 'drracket:multi-file-search:recur?)) (send filter-check-box set-value (preferences:get 'drracket:multi-file-search:filter?)) (send search-text-field set-value (preferences:get 'drracket:multi-file-search:search-string)) (send filter-text-field set-value (preferences:get 'drracket:multi-file-search:filter-regexp)) (for ([pth/f (in-list (preferences:get 'drracket:multi-file-search:directory))]) (define pth (or pth/f (path->string (car (filesystem-root-list))))) (add-a-dir-field pth)) (send outer-method-panel stretchable-height #f) (send outer-method-panel set-alignment 'left 'center) (send method-inset-panel min-width 20) (send method-inset-panel stretchable-width #f) (send method-panel set-alignment 'left 'center) (send filter-panel stretchable-height #f) (send methods-choice set-selection (preferences:get 'drracket:multi-file-search:search-type)) (set-method (preferences:get 'drracket:multi-file-search:search-type)) (send search-text-field focus) (let ([t (send search-text-field get-editor)]) (send t set-position 0 (send t last-position))) (send configure-search-window show #t)))])) ;; exact-match-searcher : make-searcher (define (exact-match-searcher params key) ;; thread: main eventspace thread (let ([case-sensitive? (car params)]) (λ (filename add-entry) ;; thread: searching thread (let ([text (make-object text:line-spacing%)]) (send text load-file filename) (let loop ([pos 0]) (let ([found (send text find-string key 'forward pos 'eof #t case-sensitive?)]) (when found (let* ([para (send text position-paragraph found)] [para-start (send text paragraph-start-position para)] [line-string (send text get-text para-start (send text paragraph-end-position para))] [line-number para] [col-number (- found para-start)] [match-length (string-length key)]) (add-entry line-string line-number col-number match-length) (loop (+ found 1)))))))))) ;; regexp-match-searcher : make-searcher ;; thread: searching thread (define (regexp-match-searcher parmas key) ;; thread: main eventspace thread (let ([re:key (with-handlers ([(λ (x) #t) (λ (exn) (format "~a" (exn-message exn)))]) (regexp key))]) (if (string? re:key) re:key (λ (filename add-entry) ;; thread: searching thread (call-with-input-file filename (λ (port) (let loop ([line-number 0]) (let ([line (read-line port)]) (cond [(eof-object? line) (void)] [else (let ([match (regexp-match-positions re:key line)]) (when match (let ([pos (car match)]) (add-entry line line-number (car pos) (- (cdr pos) (car pos)))))) (loop (+ line-number 1))])))) #:mode 'text))))) (preferences:set-default 'drracket:multi-file-search:directories '() (lambda (x) (and (list? x) (andmap string? x)))) drracket : mult - file - search : search - check - boxes : ( listof ( listof boolean ) ) (preferences:set-default 'drracket:multi-file-search:search-check-boxes (map (λ (x) (map cdr (search-type-params x))) search-types) (listof (listof boolean?))) (preferences:set-default 'drracket:multi-file-search:recur? #t boolean?) (preferences:set-default 'drracket:multi-file-search:filter? #t boolean?) (preferences:set-default 'drracket:multi-file-search:filter-regexp (string-append "\\.(" (all-racket-suffixes (lambda (s) (regexp-quote (bytes->string/utf-8 s))) "|") ")$") string?) (preferences:set-default 'drracket:multi-file-search:search-string "" string?) (preferences:set-default 'drracket:multi-file-search:search-type 1 (λ (x) (and (exact-nonnegative-integer? x) (< x (length search-types))))) (preferences:set-default 'drracket:multi-file-search:percentages '(1/3 2/3) (and/c (listof (between/c 0 1)) (λ (x) (= 1 (apply + x))))) (preferences:set-default 'drracket:multi-file-search:frame-size '(300 . 400) (cons/c dimension-integer? dimension-integer?)) (preferences:set-default 'drracket:multi-file-search:directory ;; #f means the filesystem root, but that's ;; expensive to compute under windows so we ;; delay the computation until the dialog ;; is opened. '(#f) (non-empty-listof (or/c #f (and/c string? path-string?)))) (module+ main (configure-search))
null
https://raw.githubusercontent.com/racket/drracket/d7f34d721867db1dd4e12ad71ba8e3c14ab9af5f/drracket/drracket/private/multi-file-search.rkt
racket
the param strings are the labels for checkboxes the param booleans are the default values for the checkboxes these are the available searches search-info = (make-search-info (listof string) boolean (union #f regexp) search-type string) the search-string field is only informative; not used for actual searching search-entry = (make-search-entry string string number number number) to make these available to be defined in the unit with the right names. multi-file-search : -> void opens a dialog to configure the search and initiates the search searcher = (string (string int int int -> void) -> void) this performs a single search. the arguments are: line-string line-number col-number match-length open-search-window : search-info -> void thread: eventspace main thread opens a window and creates the thread that does the search sometimes, breaking the other thread puts the break message in the channel behind many many requests. Rather than show those, we use the `broken?' flag as a shortcut. channel : async-channel[(union 'done search-entry)] just to initialize it to something. results-text% : derived from text% init args: zoom-text zoom-text : (instance-of text%) public-methods: add-match : string string int int int int -> void adds a match to the text search-interrupted : -> void inserts a message saying "search interrupted". search-complete is not expected to be called if this method is called. search-complete : -> void inserts a message saying "no matches found" if none were reported indent-all-lines : number -> void inserts `offset' spaces to the beginning of each line, match-shown? : boolean indicates if a match has ever been shown. if not, need to clean out the "searching" message and show a match. Done in `add-match' current-file : (union #f string) the name of the currently viewed file, if one if viewed. line-in-current-file and col-in-current-file are linked collaborates with search-size-frame% thread: eventspace main thread this vertical-resizable class just remembers the percentage between the thread: eventspace main thread do-search : search-info text -> void thread: searching thread called in a new thread that may be broken (to indicate a stop) build-recursive-file-list : string (union regexp #f) -> (-> (union string #f)) thread: search thread build-flat-file-list : path (union #f regexp) -> (-> (union string #f)) thread: searching thread configure-search : -> (union #f search-info) thread: eventspace main thread configures the search len=1 : add to none of them len=2 : add to all of them spacer initialized to a searcher during the ok button callback so the user can be informed of an error before the dialog closes. initialized to a regexp if the user wants to filter filenames, during the ok-button-callback, so errors can be signaled. title for message box that signals error messages exact-match-searcher : make-searcher thread: main eventspace thread thread: searching thread regexp-match-searcher : make-searcher thread: searching thread thread: main eventspace thread thread: searching thread #f means the filesystem root, but that's expensive to compute under windows so we delay the computation until the dialog is opened.
#lang racket/base (require framework framework/private/srcloc-panel racket/class racket/contract racket/unit racket/path racket/list racket/gui/base mzlib/async-channel string-constants drracket/private/drsig mrlib/close-icon drracket/get-module-path "suffix.rkt") (define sc-browse-collections "Browse\nCollections") (define sc-add-another-directory "Add Another Directory") (provide multi-file-search@) search - type = ( make - search - type string make - searcher ( listof ( cons string boolean ) ) ) (define-struct search-type (label make-searcher params) #:transparent) (define-struct search-info (dirs recur? filter searcher search-string) #:transparent) search - types : ( listof search - type ) (define search-types (list (make-search-type (string-constant mfs-string-match/graphics) (λ (info search-string) (exact-match-searcher info search-string)) (list (cons (string-constant mfs-case-sensitive-label) #f))) (make-search-type (string-constant mfs-regexp-match/no-graphics) (λ (info search-string) (regexp-match-searcher info search-string)) (list)))) (define-struct search-entry (base-dir filename line-string line-number col-number match-length) #:transparent) (define _search-types search-types) (define _search-type-params search-type-params) (define-unit multi-file-search@ (import [prefix drracket:frame: drracket:frame^] [prefix drracket:unit: drracket:unit^] [prefix drracket: drracket:interface^]) (export drracket:multi-file-search^) (define search-type-params _search-type-params) (define search-types _search-types) (define (multi-file-search) (configure-search (λ (search-info) (open-search-window search-info)))) the first argument is the filename to be searched the second argument is called for each match . (define (open-search-window search-info) (define frame (new search-size-frame% [name (let ([fmt-s (string-constant mfs-drscheme-multi-file-search-title)]) (format fmt-s (gui-utils:trim-string (search-info-search-string search-info) (- 200 (string-length fmt-s)))))])) (define panel (make-object saved-vertical-resizable% (send frame get-area-container))) (define button-panel (new-horizontal-panel% [parent (send frame get-area-container)] [alignment '(right center)] [stretchable-height #f])) (define open-button (make-object button% (string-constant mfs-open-file) button-panel (λ (x y) (open-file-callback)))) (define stop-button (make-object button% (string-constant mfs-stop-search) button-panel (λ (x y) (stop-callback)))) (define grow-box-pane (make-object grow-box-spacer-pane% button-panel)) (define zoom-text (make-object (text:searching-mixin racket:text%))) (define results-text (make-object results-text% zoom-text)) (define results-ec (instantiate searching-canvas% () (parent panel) (editor results-text) (frame frame))) (define zoom-ec (instantiate searching-canvas% () (parent panel) (editor zoom-text) (frame frame))) (define (open-file-callback) (send results-text open-file)) (define broken? #f) (define (stop-callback) (break-thread search-thd) (set! broken? #t) (send stop-button enable #f)) (define channel (make-async-channel 100)) (define search-thd (thread (λ () (do-search search-info channel)))) (send results-text lock #t) (send frame reflow-container) (send panel set-percentages (preferences:get 'drracket:multi-file-search:percentages)) (send frame show #t) (let loop () (let ([match (yield channel)]) (yield) (cond [(eq? match 'done) (send results-text search-complete) (send stop-button enable #f)] [(or broken? (eq? match 'break)) (send results-text search-interrupted)] [else (send results-text add-match (search-entry-base-dir match) (search-entry-filename match) (search-entry-line-string match) (search-entry-line-number match) (search-entry-col-number match) (search-entry-match-length match)) (loop)])))) (define results-super-text% (text:searching-mixin (text:hide-caret/selection-mixin (text:line-spacing-mixin (text:basic-mixin (editor:keymap-mixin (editor:standard-style-list-mixin (editor:basic-mixin text%)))))))) (define results-text% (class results-super-text% (init-field zoom-text) (inherit insert last-paragraph erase paragraph-start-position paragraph-end-position last-position change-style set-clickback set-position end-edit-sequence begin-edit-sequence lock) [define filename-delta (make-object style-delta% 'change-bold)] [define match-delta (let ([d (make-object style-delta%)]) (send d set-delta-foreground (make-object color% 0 160 0)) d)] [define hilite-line-delta (make-object style-delta% 'change-style 'italic)] [define unhilite-line-delta (make-object style-delta% 'change-style 'normal)] [define widest-filename #f] [define/private indent-all-lines except the last one . Must be at least one such line in the text . (λ (offset) (let ([spaces (make-string offset #\space)]) (let loop ([para (- (last-paragraph) 1)]) (let ([para-start (paragraph-start-position para)]) (insert spaces para-start para-start) (change-style filename-delta para-start (+ para-start offset))) (unless (zero? para) (loop (- para 1))))))] [define match-shown? #f] [define current-file #f] [define line-in-current-file #f] [define col-in-current-file #f] [define old-line #f] [define/private hilite-line (λ (line) (begin-edit-sequence) (lock #f) (when old-line (change-style unhilite-line-delta (paragraph-start-position old-line) (paragraph-end-position old-line))) (when line (change-style hilite-line-delta (paragraph-start-position line) (paragraph-end-position line))) (set! old-line line) (lock #t) (end-edit-sequence))] [define/public (open-file) (when current-file (let ([f (handler:edit-file current-file)]) (when (and f (is-a? f drracket:unit:frame<%>)) (let* ([t (send f get-definitions-text)] [pos (+ (send t paragraph-start-position line-in-current-file) col-in-current-file)]) (send t set-position pos)))))] (define/public (add-match base-filename full-filename line-string line col match-length) (lock #f) (define new-line-position (last-position)) (define short-filename (path->string (find-relative-path (normalize-path base-filename) (normalize-path full-filename)))) (define this-match-number (last-paragraph)) (define len (string-length short-filename)) (define insertion-start #f) (define (show-this-match) (set! match-shown? #t) (set! current-file full-filename) (set! line-in-current-file line) (set! col-in-current-file col) (set-position new-line-position new-line-position) (send zoom-text begin-edit-sequence) (send zoom-text lock #f) (unless (really-same-file? full-filename (send zoom-text get-filename)) (send zoom-text load-file/gui-error full-filename)) (send zoom-text set-position (send zoom-text paragraph-start-position line)) (let ([start (+ (send zoom-text paragraph-start-position line) col)]) (send zoom-text change-style match-delta start (+ start match-length))) (send zoom-text lock #t) (send zoom-text set-caret-owner #f 'global) (hilite-line this-match-number) (send zoom-text end-edit-sequence)) (unless match-shown? (erase)) (unless widest-filename (set! widest-filename len)) (if (<= len widest-filename) (begin (set! insertion-start (last-position)) (insert (make-string (- widest-filename len) #\space) (last-position) (last-position))) (begin (indent-all-lines (- len widest-filename)) (set! insertion-start (last-position)) (set! widest-filename len))) (let ([filename-start (last-position)]) (insert short-filename (last-position) (last-position)) (insert ": " (last-position) (last-position)) (change-style filename-delta insertion-start (last-position)) (let ([line-start (last-position)]) (insert line-string (last-position) (last-position)) (change-style match-delta (+ line-start col) (+ line-start col match-length))) (set-clickback filename-start (last-position) (λ (_1 _2 _3) (show-this-match))) (insert #\newline (last-position) (last-position)) (unless match-shown? (show-this-match))) (lock #t)) (define/public (search-interrupted) (lock #f) (insert #\newline (last-position) (last-position)) (insert (string-constant mfs-search-interrupted) (last-position) (last-position)) (lock #t)) (define/public (search-complete) (unless match-shown? (lock #f) (insert #\newline (last-position) (last-position)) (insert (string-constant mfs-no-matches-found) (last-position) (last-position)) (lock #t))) (inherit get-style-list set-style-list set-styles-sticky) (super-new) (send zoom-text lock #t) (set-styles-sticky #f) (insert (string-constant mfs-searching...)))) (define (really-same-file? fn1 fn2) (define p1 (with-handlers ((exn:fail? (λ (x) #f))) (open-input-file fn1))) (define p2 (with-handlers ((exn:fail? (λ (x) #f))) (open-input-file fn2))) (cond [(and p1 p2) (begin0 (= (port-file-identity p1) (port-file-identity p2)) (close-input-port p1) (close-input-port p2))] [else (when p1 (close-input-port p1)) (when p2 (close-input-port p2)) #f])) (define searching-canvas% (class canvas:basic% (init-field frame) (inherit get-editor) (define/override (on-focus on?) (when on? (send frame set-text-to-search (get-editor))) (super on-focus on?)) (super-new))) (define search-size-frame% (class (drracket:frame:basics-mixin (frame:searchable-mixin frame:standard-menus%)) (init-field name) (define/override (on-size w h) (preferences:set 'drracket:multi-file-search:frame-size (cons w h)) (super on-size w h)) (let ([size (preferences:get 'drracket:multi-file-search:frame-size)]) (super-new [label name] [width (car size)] [height (cdr size)])))) two panels (define saved-vertical-resizable% (class panel:vertical-dragable% (inherit get-percentages) (define/augment (after-percentage-change) (let ([ps (get-percentages)]) (when (= (length ps) 2) (preferences:set 'drracket:multi-file-search:percentages ps))) (inner (void) after-percentage-change)) (super-new))) (define (do-search search-info channel) (define filter (search-info-filter search-info)) (define searcher (search-info-searcher search-info)) (with-handlers ([exn:break? (λ (x) (async-channel-put channel 'break))]) (for ([dir (in-list (search-info-dirs search-info))]) (define get-filenames (if (search-info-recur? search-info) (build-recursive-file-list dir filter) (build-flat-file-list dir filter))) (let loop () (let ([filename (get-filenames)]) (when filename (searcher filename (λ (line-string line-number col-number match-length) (async-channel-put channel (make-search-entry dir filename line-string line-number col-number match-length)))) (loop))))) (async-channel-put channel 'done))) (define (build-recursive-file-list dir filter) (letrec ([touched (make-hash)] [next-thunk (λ () (process-dir dir (λ () #f)))] [process-dir string[dirname ] ( listof string[filename ] ) - > ( string[filename ] ) (λ (dir k) (let* ([key (normalize-path dir)] [traversed? (hash-ref touched key (λ () #f))]) (cond [traversed? (k)] [else (define content (with-handlers ([exn:fail:filesystem? (λ (x) #f)]) (directory-list dir))) (hash-set! touched key #t) (cond [content (process-dir-contents (map (λ (x) (build-path dir x)) content) k)] [else (k)])])))] [process-dir-contents string[dirname ] ( listof string[filename ] ) - > ( string[filename ] ) (λ (contents k) (cond [(null? contents) (k)] [else (let ([file/dir (car contents)]) (cond [(and (file-exists? file/dir) (or (not filter) (regexp-match filter (path->string file/dir)))) (set! next-thunk (λ () (process-dir-contents (cdr contents) k))) file/dir] [(directory-exists? file/dir) (process-dir-contents (cdr contents) (λ () (process-dir file/dir k)))] [else (process-dir-contents (cdr contents) k)]))]))]) (λ () (next-thunk)))) (define (build-flat-file-list dir filter) (let ([contents (map (λ (x) (build-path dir x)) (with-handlers ([exn:fail:filesystem? (λ (x) '())]) (directory-list dir)))]) (λ () (let loop () (cond [(null? contents) #f] [(and filter (regexp-match filter (path->string (car contents)))) (begin0 (car contents) (set! contents (cdr contents)))] [else (set! contents (cdr contents)) (loop)])))))) (define configure-search-window #f) (define (configure-search open-search-window) (cond [configure-search-window (send configure-search-window show #t)] [else (keymap:call/text-keymap-initializer (λ () (set! configure-search-window (new frame% [label (string-constant mfs-configure-search)] [width 500] [stretchable-height #f])) (define outer-files-panel (make-object vertical-panel% configure-search-window '(border))) (define outer-method-panel (make-object vertical-panel% configure-search-window '(border))) (define button-panel (new-horizontal-panel% [parent configure-search-window] [alignment '(right center)] [stretchable-height #f])) (define files-label (make-object message% (string-constant mfs-files-section) outer-files-panel)) (define files-inset-outer-panel (make-object horizontal-panel% outer-files-panel)) (define files-inset-panel (make-object horizontal-panel% files-inset-outer-panel)) (define files-panel (make-object vertical-panel% files-inset-outer-panel)) (define method-label (make-object message% (string-constant mfs-search-section) outer-method-panel)) (define method-inset-outer-panel (make-object horizontal-panel% outer-method-panel)) (define method-inset-panel (make-object horizontal-panel% method-inset-outer-panel)) (define method-panel (make-object vertical-panel% method-inset-outer-panel)) (define multi-dir+browse-collections-panel (new-horizontal-panel% [alignment '(center top)] [stretchable-height #f] [parent files-panel])) (define multi-dir-panel (new-vertical-panel% [parent multi-dir+browse-collections-panel])) (define dir-fields '()) (define (add-a-dir-field init-value) (send configure-search-window begin-container-sequence) (define need-to-add-closers? (and (pair? dir-fields) (null? (cdr dir-fields)))) (define dir-panel (new-horizontal-panel% [parent multi-dir-panel] [stretchable-height #f])) (define dir-field (new combo-field% [parent dir-panel] [label (string-constant mfs-dir)] [choices (preferences:get 'drracket:multi-file-search:directories)] [init-value init-value] [stretchable-width #t] [stretchable-height #f] [callback (λ (x y) (update-directory-prefs))])) (define dir-button (new button% [label (string-constant browse...)] [parent dir-panel] [callback (λ (x y) (dir-button-callback))])) (define (dir-button-callback) (define old-d (string->path (send dir-field get-value))) (define new-d (get-directory #f #f (and (directory-exists? old-d) old-d))) (when (and new-d (directory-exists? new-d)) (define str (path->string new-d)) (send dir-field set-value str) (update-directory-prefs))) (set! dir-fields (cons dir-field dir-fields)) (update-directory-prefs) (cond [(null? (cdr dir-fields)) (void)] [(null? (cddr dir-fields)) (for ([dir-panel (in-list (send multi-dir-panel get-children))]) (add-a-closer dir-panel))] [else len>2 : add to this one (add-a-closer dir-panel)]) (send configure-search-window end-container-sequence)) (define (add-a-closer dir-panel) (define ci (new close-icon% [parent dir-panel] [callback (λ () (remove-a-dir-panel dir-panel))])) (send dir-panel change-children (λ (l) (append (remove ci l) (list ci))))) (define (remove-a-dir-panel dir-panel) (define dir-field (for/or ([child (in-list (send dir-panel get-children))]) (and (is-a? child combo-field%) child))) (set! dir-fields (remove dir-field dir-fields)) (send multi-dir-panel change-children (λ (l) (remove dir-panel l))) (update-directory-prefs) (when (and (pair? dir-fields) (null? (cdr dir-fields))) only one dir field left , get rid of the close - icon (let loop ([parent multi-dir-panel]) (for ([child (in-list (send parent get-children))]) (cond [(is-a? child close-icon%) (send parent change-children (λ (l) (remove child l)))] [(is-a? child area-container<%>) (loop child)]))))) (define (update-directory-prefs) (define new-pref (for/list ([dir-field (in-list dir-fields)]) (define dfv (send dir-field get-value)) (and (path-string? dfv) dfv))) (when (andmap values new-pref) (preferences:set 'drracket:multi-file-search:directory new-pref))) (define browse-collections-button (new button% [label sc-browse-collections] [parent multi-dir+browse-collections-panel] [callback (λ (x y) (define paths (get-module-path-from-user #:dir? #t)) (when paths (define delta-dirs (- (length dir-fields) (length paths))) (cond [(< delta-dirs 0) (for ([x (in-range (- delta-dirs))]) (add-a-dir-field ""))] [(> delta-dirs 0) (for ([x (in-range delta-dirs)] [dir-field (in-list (send multi-dir-panel get-children))]) (remove-a-dir-panel dir-field))]) (for ([path (in-list paths)] [dir-field (in-list dir-fields)]) (send dir-field set-value (path->string path))) (update-directory-prefs)))])) (define recur+another-parent (new-horizontal-panel% [parent files-panel] [stretchable-height #f])) (define recur-check-box (new check-box% [label (string-constant mfs-recur-over-subdirectories)] [parent recur+another-parent] [callback (λ (x y) (recur-check-box-callback))])) (define another-dir-button (new button% [label sc-add-another-directory] [parent recur+another-parent] [callback (λ (x y) (add-a-dir-field ""))])) (define filter-panel (make-object horizontal-panel% files-panel)) (define filter-check-box (make-object check-box% (string-constant mfs-regexp-filename-filter) filter-panel (λ (x y) (filter-check-box-callback)))) (define filter-text-field (make-object text-field% #f filter-panel (λ (x y) (filter-text-field-callback)))) (define methods-choice (make-object choice% #f (map search-type-label search-types) method-panel (λ (x y) (methods-choice-callback)))) (define search-text-field (make-object text-field% (string-constant mfs-search-string) method-panel (λ (x y) (search-text-field-callback)))) (define active-method-panel (make-object panel:single% method-panel)) (define methods-check-boxess (let ([pref (preferences:get 'drracket:multi-file-search:search-check-boxes)]) (map (λ (search-type prefs-settings) (let ([p (make-object vertical-panel% active-method-panel)] [params (search-type-params search-type)]) (send p set-alignment 'left 'center) (map (λ (flag-pair prefs-setting) (let ([cb (make-object check-box% (car flag-pair) p (λ (evt chk) (method-callback chk)))]) (send cb set-value prefs-setting) cb)) params (if (= (length params) (length prefs-settings)) prefs-settings (map (λ (x) #f) params))))) search-types (if (= (length search-types) (length pref)) pref (map (λ (x) '()) search-types))))) (define-values (ok-button cancel-button) (gui-utils:ok/cancel-buttons button-panel (λ (x y) (ok-button-callback)) (λ (x y) (cancel-button-callback)))) (define spacer (make-object grow-box-spacer-pane% button-panel)) (define searcher #f) (define filter #f) (define message-box-title (string-constant mfs-drscheme-multi-file-search)) (define (ok-button-callback) (define dirs (for/list ([df (in-list dir-fields)]) (send df get-value))) (define dont-exist (for/list ([dir (in-list dirs)] #:unless (with-handlers ([exn:fail:filesystem? (λ (x) #f)]) (and (path-string? dir) (directory-exists? dir)))) dir)) (cond [(null? dont-exist) (define new-l (append dirs (remove* dirs (preferences:get 'drracket:multi-file-search:directories)))) (preferences:set 'drracket:multi-file-search:directories (take new-l (min (length new-l) 10))) (define _searcher ((search-type-make-searcher (list-ref search-types (send methods-choice get-selection))) (map (λ (cb) (send cb get-value)) (send (send active-method-panel active-child) get-children)) (send search-text-field get-value))) (if (string? _searcher) (message-box message-box-title _searcher configure-search-window) (let ([the-regexp (with-handlers ([(λ (x) #t) (λ (exn) (format "~a" (exn-message exn)))]) (and (send filter-check-box get-value) (regexp (send filter-text-field get-value))))]) (if (string? the-regexp) (message-box message-box-title the-regexp configure-search-window) (begin (set! searcher _searcher) (set! filter the-regexp) (send configure-search-window show #f) (set! configure-search-window #f) (open-search-window (make-search-info (for/list ([dir-field (in-list dir-fields)]) (send dir-field get-value)) (send recur-check-box get-value) (and (send filter-check-box get-value) (regexp (send filter-text-field get-value))) searcher (send search-text-field get-value)))))))] [else (message-box message-box-title (format (string-constant mfs-not-a-dir) (car dont-exist)) configure-search-window)])) (define (cancel-button-callback) (send configure-search-window show #f) (set! configure-search-window #f)) (define (method-callback chk) (preferences:set 'drracket:multi-file-search:search-check-boxes (let loop ([methods-check-boxess methods-check-boxess]) (cond [(null? methods-check-boxess) null] [else (cons (let loop ([methods-check-boxes (car methods-check-boxess)]) (cond [(null? methods-check-boxes) null] [else (cons (send (car methods-check-boxes) get-value) (loop (cdr methods-check-boxes)))])) (loop (cdr methods-check-boxess)))])))) (define (filter-check-box-callback) (preferences:set 'drracket:multi-file-search:filter? (send filter-check-box get-value)) (send filter-text-field enable (send filter-check-box get-value))) (define (filter-text-field-callback) (preferences:set 'drracket:multi-file-search:filter-regexp (send filter-text-field get-value))) (define (recur-check-box-callback) (preferences:set 'drracket:multi-file-search:recur? (send recur-check-box get-value))) (define (methods-choice-callback) (define which (send methods-choice get-selection)) (preferences:set 'drracket:multi-file-search:search-type which) (set-method which)) (define (set-method which) (send active-method-panel active-child (list-ref (send active-method-panel get-children) which))) (define (search-text-field-callback) (preferences:set 'drracket:multi-file-search:search-string (send search-text-field get-value))) (send outer-files-panel stretchable-height #f) (send outer-files-panel set-alignment 'left 'center) (send files-inset-panel min-width 20) (send files-inset-panel stretchable-width #f) (send files-panel set-alignment 'left 'center) (send recur-check-box set-value (preferences:get 'drracket:multi-file-search:recur?)) (send filter-check-box set-value (preferences:get 'drracket:multi-file-search:filter?)) (send search-text-field set-value (preferences:get 'drracket:multi-file-search:search-string)) (send filter-text-field set-value (preferences:get 'drracket:multi-file-search:filter-regexp)) (for ([pth/f (in-list (preferences:get 'drracket:multi-file-search:directory))]) (define pth (or pth/f (path->string (car (filesystem-root-list))))) (add-a-dir-field pth)) (send outer-method-panel stretchable-height #f) (send outer-method-panel set-alignment 'left 'center) (send method-inset-panel min-width 20) (send method-inset-panel stretchable-width #f) (send method-panel set-alignment 'left 'center) (send filter-panel stretchable-height #f) (send methods-choice set-selection (preferences:get 'drracket:multi-file-search:search-type)) (set-method (preferences:get 'drracket:multi-file-search:search-type)) (send search-text-field focus) (let ([t (send search-text-field get-editor)]) (send t set-position 0 (send t last-position))) (send configure-search-window show #t)))])) (let ([case-sensitive? (car params)]) (let ([text (make-object text:line-spacing%)]) (send text load-file filename) (let loop ([pos 0]) (let ([found (send text find-string key 'forward pos 'eof #t case-sensitive?)]) (when found (let* ([para (send text position-paragraph found)] [para-start (send text paragraph-start-position para)] [line-string (send text get-text para-start (send text paragraph-end-position para))] [line-number para] [col-number (- found para-start)] [match-length (string-length key)]) (add-entry line-string line-number col-number match-length) (loop (+ found 1)))))))))) (let ([re:key (with-handlers ([(λ (x) #t) (λ (exn) (format "~a" (exn-message exn)))]) (regexp key))]) (if (string? re:key) re:key (call-with-input-file filename (λ (port) (let loop ([line-number 0]) (let ([line (read-line port)]) (cond [(eof-object? line) (void)] [else (let ([match (regexp-match-positions re:key line)]) (when match (let ([pos (car match)]) (add-entry line line-number (car pos) (- (cdr pos) (car pos)))))) (loop (+ line-number 1))])))) #:mode 'text))))) (preferences:set-default 'drracket:multi-file-search:directories '() (lambda (x) (and (list? x) (andmap string? x)))) drracket : mult - file - search : search - check - boxes : ( listof ( listof boolean ) ) (preferences:set-default 'drracket:multi-file-search:search-check-boxes (map (λ (x) (map cdr (search-type-params x))) search-types) (listof (listof boolean?))) (preferences:set-default 'drracket:multi-file-search:recur? #t boolean?) (preferences:set-default 'drracket:multi-file-search:filter? #t boolean?) (preferences:set-default 'drracket:multi-file-search:filter-regexp (string-append "\\.(" (all-racket-suffixes (lambda (s) (regexp-quote (bytes->string/utf-8 s))) "|") ")$") string?) (preferences:set-default 'drracket:multi-file-search:search-string "" string?) (preferences:set-default 'drracket:multi-file-search:search-type 1 (λ (x) (and (exact-nonnegative-integer? x) (< x (length search-types))))) (preferences:set-default 'drracket:multi-file-search:percentages '(1/3 2/3) (and/c (listof (between/c 0 1)) (λ (x) (= 1 (apply + x))))) (preferences:set-default 'drracket:multi-file-search:frame-size '(300 . 400) (cons/c dimension-integer? dimension-integer?)) (preferences:set-default 'drracket:multi-file-search:directory '(#f) (non-empty-listof (or/c #f (and/c string? path-string?)))) (module+ main (configure-search))
235cfae4e53302580819cbd4d11693be35a9575b5f1d87e4d6d5b62070a869ff
finnishtransportagency/harja
tierekisteri_haku.clj
(ns harja.palvelin.palvelut.tierekisteri-haku (:require [harja.palvelin.komponentit.http-palvelin :refer [julkaise-palvelut poista-palvelut]] [clojure.spec.alpha :as s] [com.stuartsierra.component :as component] [harja.kyselyt.tieverkko :as tv] [harja.geo :as geo] [harja.kyselyt.konversio :as konv] [taoensso.timbre :as log] [harja.domain [oikeudet :as oikeudet] [yllapitokohde :as yllapitokohde] [tierekisteri :as tr-domain]] [clojure.string :as str]) (:import (org.postgresql.util PSQLException))) (def +threshold+ 250) (defn muunna-geometria [tros] (assoc tros :geometria (geo/pg->clj (:geometria tros)))) (defn hae-tr-pisteilla "params on mappi {:x1 .. :y1 .. :x2 .. :y2 ..}" [db params] (log/debug "hae tr pisteillä: " params) (try (when-let [tros (first (tv/hae-tr-osoite-valille db (:x1 params) (:y1 params) (:x2 params) (:y2 params) +threshold+))] (muunna-geometria tros)) (catch PSQLException e (if (= (.getMessage e) "ERROR: pisteillä ei yhteistä tietä") nil ;; else (throw e))))) (defn hae-tr-pisteella "params on mappi {:x .. :y ..}" [db {:keys [x y] :as params}] (let [tros (first (tv/hae-tr-osoite db {:x x :y y :treshold +threshold+}))] (muunna-geometria tros))) (defn hae-tr-viiva "Params on mappi: {:numero int, :alkuosa int, :alkuetaisyys int, :loppuosa int, :loppuetaisyys int}" [db params] (log/debug "Haetaan viiva osoiteelle " (pr-str params)) (let [korjattu-osoite params viiva? (and (:loppuosa korjattu-osoite) (:loppuetaisyys korjattu-osoite)) geom (geo/pg->clj (if viiva? (tv/tierekisteriosoite-viivaksi db (:numero korjattu-osoite) (:alkuosa korjattu-osoite) (:alkuetaisyys korjattu-osoite) (:loppuosa korjattu-osoite) (:loppuetaisyys korjattu-osoite)) (tv/tierekisteriosoite-pisteeksi db (:numero korjattu-osoite) (:alkuosa korjattu-osoite) (:alkuetaisyys korjattu-osoite))))] (if geom [geom] {:virhe "Tierekisteriosoitetta ei löydy"}))) (defn hae-tr-pituudet [db params] TODO heti , , otetaan se käyttöön tässä (reduce (fn [m pituuden-tiedot] (update m (:osa pituuden-tiedot) (fn [osa] (assoc osa (:ajorata pituuden-tiedot) (:pituus pituuden-tiedot))))) {} (tv/hae-ajoratojen-pituudet db params))) (defn hae-osien-pituudet "Hakee tierekisteriosien pituudet annetulle tielle ja osan välille. Params mäpissä tulee olla :tie, :aosa ja :losa. Palauttaa pituuden metreinä." [db params] (into {} (map (juxt :osa :pituus)) (tv/hae-osien-pituudet db params))) (defn hae-ajoratojen-pituudet "Hakee tierekisteriosien pituudet annetun tien osien ajoradoille. Params mäpissä tulee olla :tie, :aosa ja :losa. Palauttaa pituuden metreinä." [db params] (tv/hae-ajoratojen-pituudet db params)) (defn hae-tieosan-ajoradat [db params] "Hakee annetun tien osan ajoradat. Parametri-mapissa täytyy olla :tie ja :osa" (mapv :ajorata (tv/hae-tieosan-ajoradat db params))) (defn hae-tieosan-ajoratojen-geometriat [db {:keys [tie osa ajorata]}] "Hakee annetun tien osan ajoratojen geometriat. Parametri-mapissa täytyy olla ainakin :tie ja :osa" (mapv :geom (tv/hae-tieosan-ajoratojen-geometriat db {:tie tie :osa osa :ajorata (when-not (str/blank? ajorata) ajorata)}))) (defn validoi-tr-osoite-tieverkolla "Tarkistaa, onko annettu tieosoite validi Harjan tieverkolla. Palauttaa mapin, jossa avaimet: :ok? Oliko TR-osoite validi (true / false) :syy Tekstimuotoinen selitys siitä, miksi ei ole validi (voi olla myös null)" [db {:keys [tienumero aosa aet losa let ajorata] :as tieosoite}] (try (clojure.core/let [osien-pituudet (hae-osien-pituudet db {:tie tienumero :aosa aosa :losa losa}) ajoratojen-pituudet (hae-ajoratojen-pituudet db {:tie tienumero :aosa aosa :losa losa}) ajorata-olemassa? (fn [osa ajorata] (or (not ajorata) (some #(and (= osa (:osa %)) (= ajorata (:ajorata %))) ajoratojen-pituudet))) tulos {:aosa-olemassa? (tr-domain/osa-olemassa-verkolla? aosa osien-pituudet) :losa-olemassa? (tr-domain/osa-olemassa-verkolla? losa osien-pituudet) :alkuosan-ajorata-olemassa? (ajorata-olemassa? aosa ajorata) :loppuosan-ajorata-olemassa? (ajorata-olemassa? losa ajorata) :aosa-pituus-validi? (tr-domain/osan-pituus-sopiva-verkolla? aosa aet ajoratojen-pituudet) :losa-pituus-validi? (tr-domain/osan-pituus-sopiva-verkolla? losa let ajoratojen-pituudet) :geometria-validi? (some? (hae-tr-viiva db {:numero tienumero :alkuosa aosa :alkuetaisyys aet :loppuosa losa :loppuetaisyys let}))} kaikki-ok? (every? true? (vals tulos))] {:ok? kaikki-ok? :syy (cond (not (:aosa-olemassa? tulos)) (str "Alkuosaa " aosa " ei ole olemassa") (not (:losa-olemassa? tulos)) (str "Loppuosaa " losa " ei ole olemassa") (not (:alkuosan-ajorata-olemassa? tulos)) (str "Alkuosan " aosa " ajorataa " ajorata " ei ole olemassa") (not (:loppuosan-ajorata-olemassa? tulos)) (str "Loppuosan " losa " ajorataa " ajorata " ei ole olemassa") (not (:aosa-pituus-validi? tulos)) (str "Alkuosan pituus " aet " ei kelpaa") (not (:losa-pituus-validi? tulos)) (str "Loppuosan pituus " let " ei kelpaa") (not (:geometria-validi? tulos)) "Osoitteelle ei saada muodostettua geometriaa" :default nil)}) (catch PSQLException e {:ok? false :syy "Odottamaton virhe tieosoitteen validoinnissa"}))) (defn hae-tr-osoite-gps-koordinaateilla [db wgs84-koordinaatit] (try (let [euref-koordinaatit (geo/wgs84->euref wgs84-koordinaatit)] (hae-tr-pisteella db euref-koordinaatit)) (catch Exception e (let [virhe (format "Poikkeus hakiessa tierekisteristeriosoitetta WGS84-koordinaateille %s" wgs84-koordinaatit)] (log/error e virhe) {:virhe virhe})))) (defn osavali-olemassa? "Palauttaa true, mikäli tien osien välissä on ainakin yksi osa." [db tie osa1 osa2] (>= (count (tv/tien-osavali db {:tie tie :osa1 osa1 :osa2 osa2})) 1)) (defn hae-osien-tiedot [db params] {:pre (s/valid? ::yllapitokohde/tr-paalupiste params)} (tv/hae-trpisteiden-valinen-tieto-yhdistaa db params)) (defrecord TierekisteriHaku [] component/Lifecycle (start [{:keys [http-palvelin db] :as this}] (julkaise-palvelut http-palvelin :hae-tr-pisteilla (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tr-pisteilla db params)) :hae-tr-pisteella (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tr-pisteella db params)) :hae-tr-viivaksi (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tr-viiva db params)) :hae-tr-osien-pituudet (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-osien-pituudet db params)) :hae-tr-pituudet (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tr-pituudet db params)) :hae-tr-tiedot (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-osien-tiedot db params)) :hae-tr-osan-ajoradat (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tieosan-ajoradat db params)) :hae-tr-osan-ajoratojen-geometriat (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tieosan-ajoratojen-geometriat db params)) :hae-tr-gps-koordinaateilla (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tr-osoite-gps-koordinaateilla db params))) this) (stop [{http :http-palvelin :as this}] (poista-palvelut http :hae-tr-pisteilla :hae-tr-pisteella :hae-tr-viivaksi :hae-osien-pituudet :hae-tr-pituudet :hae-tr-tiedot :hae-tr-osan-ajoradat :hae-tr-osan-ajoratojen-geometriat :hae-tr-gps-koordinaateilla) this))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/f0fbb0be3f265ddd5d2f0ae42f052d4ea0b94209/src/clj/harja/palvelin/palvelut/tierekisteri_haku.clj
clojure
else
(ns harja.palvelin.palvelut.tierekisteri-haku (:require [harja.palvelin.komponentit.http-palvelin :refer [julkaise-palvelut poista-palvelut]] [clojure.spec.alpha :as s] [com.stuartsierra.component :as component] [harja.kyselyt.tieverkko :as tv] [harja.geo :as geo] [harja.kyselyt.konversio :as konv] [taoensso.timbre :as log] [harja.domain [oikeudet :as oikeudet] [yllapitokohde :as yllapitokohde] [tierekisteri :as tr-domain]] [clojure.string :as str]) (:import (org.postgresql.util PSQLException))) (def +threshold+ 250) (defn muunna-geometria [tros] (assoc tros :geometria (geo/pg->clj (:geometria tros)))) (defn hae-tr-pisteilla "params on mappi {:x1 .. :y1 .. :x2 .. :y2 ..}" [db params] (log/debug "hae tr pisteillä: " params) (try (when-let [tros (first (tv/hae-tr-osoite-valille db (:x1 params) (:y1 params) (:x2 params) (:y2 params) +threshold+))] (muunna-geometria tros)) (catch PSQLException e (if (= (.getMessage e) "ERROR: pisteillä ei yhteistä tietä") nil (throw e))))) (defn hae-tr-pisteella "params on mappi {:x .. :y ..}" [db {:keys [x y] :as params}] (let [tros (first (tv/hae-tr-osoite db {:x x :y y :treshold +threshold+}))] (muunna-geometria tros))) (defn hae-tr-viiva "Params on mappi: {:numero int, :alkuosa int, :alkuetaisyys int, :loppuosa int, :loppuetaisyys int}" [db params] (log/debug "Haetaan viiva osoiteelle " (pr-str params)) (let [korjattu-osoite params viiva? (and (:loppuosa korjattu-osoite) (:loppuetaisyys korjattu-osoite)) geom (geo/pg->clj (if viiva? (tv/tierekisteriosoite-viivaksi db (:numero korjattu-osoite) (:alkuosa korjattu-osoite) (:alkuetaisyys korjattu-osoite) (:loppuosa korjattu-osoite) (:loppuetaisyys korjattu-osoite)) (tv/tierekisteriosoite-pisteeksi db (:numero korjattu-osoite) (:alkuosa korjattu-osoite) (:alkuetaisyys korjattu-osoite))))] (if geom [geom] {:virhe "Tierekisteriosoitetta ei löydy"}))) (defn hae-tr-pituudet [db params] TODO heti , , otetaan se käyttöön tässä (reduce (fn [m pituuden-tiedot] (update m (:osa pituuden-tiedot) (fn [osa] (assoc osa (:ajorata pituuden-tiedot) (:pituus pituuden-tiedot))))) {} (tv/hae-ajoratojen-pituudet db params))) (defn hae-osien-pituudet "Hakee tierekisteriosien pituudet annetulle tielle ja osan välille. Params mäpissä tulee olla :tie, :aosa ja :losa. Palauttaa pituuden metreinä." [db params] (into {} (map (juxt :osa :pituus)) (tv/hae-osien-pituudet db params))) (defn hae-ajoratojen-pituudet "Hakee tierekisteriosien pituudet annetun tien osien ajoradoille. Params mäpissä tulee olla :tie, :aosa ja :losa. Palauttaa pituuden metreinä." [db params] (tv/hae-ajoratojen-pituudet db params)) (defn hae-tieosan-ajoradat [db params] "Hakee annetun tien osan ajoradat. Parametri-mapissa täytyy olla :tie ja :osa" (mapv :ajorata (tv/hae-tieosan-ajoradat db params))) (defn hae-tieosan-ajoratojen-geometriat [db {:keys [tie osa ajorata]}] "Hakee annetun tien osan ajoratojen geometriat. Parametri-mapissa täytyy olla ainakin :tie ja :osa" (mapv :geom (tv/hae-tieosan-ajoratojen-geometriat db {:tie tie :osa osa :ajorata (when-not (str/blank? ajorata) ajorata)}))) (defn validoi-tr-osoite-tieverkolla "Tarkistaa, onko annettu tieosoite validi Harjan tieverkolla. Palauttaa mapin, jossa avaimet: :ok? Oliko TR-osoite validi (true / false) :syy Tekstimuotoinen selitys siitä, miksi ei ole validi (voi olla myös null)" [db {:keys [tienumero aosa aet losa let ajorata] :as tieosoite}] (try (clojure.core/let [osien-pituudet (hae-osien-pituudet db {:tie tienumero :aosa aosa :losa losa}) ajoratojen-pituudet (hae-ajoratojen-pituudet db {:tie tienumero :aosa aosa :losa losa}) ajorata-olemassa? (fn [osa ajorata] (or (not ajorata) (some #(and (= osa (:osa %)) (= ajorata (:ajorata %))) ajoratojen-pituudet))) tulos {:aosa-olemassa? (tr-domain/osa-olemassa-verkolla? aosa osien-pituudet) :losa-olemassa? (tr-domain/osa-olemassa-verkolla? losa osien-pituudet) :alkuosan-ajorata-olemassa? (ajorata-olemassa? aosa ajorata) :loppuosan-ajorata-olemassa? (ajorata-olemassa? losa ajorata) :aosa-pituus-validi? (tr-domain/osan-pituus-sopiva-verkolla? aosa aet ajoratojen-pituudet) :losa-pituus-validi? (tr-domain/osan-pituus-sopiva-verkolla? losa let ajoratojen-pituudet) :geometria-validi? (some? (hae-tr-viiva db {:numero tienumero :alkuosa aosa :alkuetaisyys aet :loppuosa losa :loppuetaisyys let}))} kaikki-ok? (every? true? (vals tulos))] {:ok? kaikki-ok? :syy (cond (not (:aosa-olemassa? tulos)) (str "Alkuosaa " aosa " ei ole olemassa") (not (:losa-olemassa? tulos)) (str "Loppuosaa " losa " ei ole olemassa") (not (:alkuosan-ajorata-olemassa? tulos)) (str "Alkuosan " aosa " ajorataa " ajorata " ei ole olemassa") (not (:loppuosan-ajorata-olemassa? tulos)) (str "Loppuosan " losa " ajorataa " ajorata " ei ole olemassa") (not (:aosa-pituus-validi? tulos)) (str "Alkuosan pituus " aet " ei kelpaa") (not (:losa-pituus-validi? tulos)) (str "Loppuosan pituus " let " ei kelpaa") (not (:geometria-validi? tulos)) "Osoitteelle ei saada muodostettua geometriaa" :default nil)}) (catch PSQLException e {:ok? false :syy "Odottamaton virhe tieosoitteen validoinnissa"}))) (defn hae-tr-osoite-gps-koordinaateilla [db wgs84-koordinaatit] (try (let [euref-koordinaatit (geo/wgs84->euref wgs84-koordinaatit)] (hae-tr-pisteella db euref-koordinaatit)) (catch Exception e (let [virhe (format "Poikkeus hakiessa tierekisteristeriosoitetta WGS84-koordinaateille %s" wgs84-koordinaatit)] (log/error e virhe) {:virhe virhe})))) (defn osavali-olemassa? "Palauttaa true, mikäli tien osien välissä on ainakin yksi osa." [db tie osa1 osa2] (>= (count (tv/tien-osavali db {:tie tie :osa1 osa1 :osa2 osa2})) 1)) (defn hae-osien-tiedot [db params] {:pre (s/valid? ::yllapitokohde/tr-paalupiste params)} (tv/hae-trpisteiden-valinen-tieto-yhdistaa db params)) (defrecord TierekisteriHaku [] component/Lifecycle (start [{:keys [http-palvelin db] :as this}] (julkaise-palvelut http-palvelin :hae-tr-pisteilla (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tr-pisteilla db params)) :hae-tr-pisteella (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tr-pisteella db params)) :hae-tr-viivaksi (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tr-viiva db params)) :hae-tr-osien-pituudet (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-osien-pituudet db params)) :hae-tr-pituudet (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tr-pituudet db params)) :hae-tr-tiedot (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-osien-tiedot db params)) :hae-tr-osan-ajoradat (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tieosan-ajoradat db params)) :hae-tr-osan-ajoratojen-geometriat (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tieosan-ajoratojen-geometriat db params)) :hae-tr-gps-koordinaateilla (fn [_ params] (oikeudet/ei-oikeustarkistusta!) (hae-tr-osoite-gps-koordinaateilla db params))) this) (stop [{http :http-palvelin :as this}] (poista-palvelut http :hae-tr-pisteilla :hae-tr-pisteella :hae-tr-viivaksi :hae-osien-pituudet :hae-tr-pituudet :hae-tr-tiedot :hae-tr-osan-ajoradat :hae-tr-osan-ajoratojen-geometriat :hae-tr-gps-koordinaateilla) this))
06ec72021d562b5ba2388acf16f7626bd9accd65888856dc5958cfea1c5b9546
mirage/ocaml-cohttp
curl.ml
open Cohttp module Curl = Cohttp_curl_async module Sexp = Sexplib0.Sexp open Async_kernel module Writer = Async_unix.Writer module Time = Core.Time let ( let* ) x f = Deferred.bind x ~f let client uri meth' () = let meth = Cohttp.Code.method_of_string meth' in let reply = let context = Curl.Context.create () in let request = Curl.Request.create ~timeout:(Time.Span.of_ms 5000.) meth ~uri ~input:Curl.Source.empty ~output:Curl.Sink.string in Curl.submit context request in let* resp, response_body = Deferred.both (Curl.Response.response reply) (Curl.Response.body reply) in Format.eprintf "response:%a@.%!" Sexp.pp_hum (Response.sexp_of_t resp); let status = Response.status resp in (match Code.is_success (Code.code_of_status status) with | false -> prerr_endline (Code.string_of_status status) | true -> ()); let output_body c = Writer.write c response_body; Writer.flushed c in output_body (Lazy.force Writer.stdout) let _ = let open Async_command in async_spec ~summary:"Fetch URL and print it" Spec.( empty +> anon ("url" %: string) +> flag "-X" (optional_with_default "GET" string) ~doc:" Set HTTP method") client |> Command_unix.run
null
https://raw.githubusercontent.com/mirage/ocaml-cohttp/55bcbf24f570cc177fee9484df8b87d61c110855/cohttp-curl-async/bin/curl.ml
ocaml
open Cohttp module Curl = Cohttp_curl_async module Sexp = Sexplib0.Sexp open Async_kernel module Writer = Async_unix.Writer module Time = Core.Time let ( let* ) x f = Deferred.bind x ~f let client uri meth' () = let meth = Cohttp.Code.method_of_string meth' in let reply = let context = Curl.Context.create () in let request = Curl.Request.create ~timeout:(Time.Span.of_ms 5000.) meth ~uri ~input:Curl.Source.empty ~output:Curl.Sink.string in Curl.submit context request in let* resp, response_body = Deferred.both (Curl.Response.response reply) (Curl.Response.body reply) in Format.eprintf "response:%a@.%!" Sexp.pp_hum (Response.sexp_of_t resp); let status = Response.status resp in (match Code.is_success (Code.code_of_status status) with | false -> prerr_endline (Code.string_of_status status) | true -> ()); let output_body c = Writer.write c response_body; Writer.flushed c in output_body (Lazy.force Writer.stdout) let _ = let open Async_command in async_spec ~summary:"Fetch URL and print it" Spec.( empty +> anon ("url" %: string) +> flag "-X" (optional_with_default "GET" string) ~doc:" Set HTTP method") client |> Command_unix.run
c4a0fe3abe2447e6eb4f0b5105097cec825a231ef0b5ca4f34c90257e9ba55cb
larcenists/larceny
inv2.scm
(text (seq (nop) (inv (alt z! l! a!)) (nop))) 00000000 90 nop 00000001 7405 jz 0x8 00000003 7C03 jl 0x8 00000005 7701 ja 0x8 00000007 90 nop ;In order for the outer seq to win its arguments must win. In order ;for the inv to win its argument must lose. It's argument is alt, and ;for an alt to lose all its arguments must lose. Therefore if any of its arguments win , the inv will lose as will the outer seq . Hence the 's past everything .
null
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/src/Lib/Sassy/tests/prims/inv2.scm
scheme
In order for the outer seq to win its arguments must win. In order for the inv to win its argument must lose. It's argument is alt, and for an alt to lose all its arguments must lose. Therefore if any of
(text (seq (nop) (inv (alt z! l! a!)) (nop))) 00000000 90 nop 00000001 7405 jz 0x8 00000003 7C03 jl 0x8 00000005 7701 ja 0x8 00000007 90 nop its arguments win , the inv will lose as will the outer seq . Hence the 's past everything .
9f04d5bbe525a24143d16a4b2e9d8ebb98727d77366c78c768299a140e3152cb
faylang/fay
Cont.hs
# LANGUAGE KindSignatures # # LANGUAGE RebindableSyntax # {-# LANGUAGE RankNTypes #-} # LANGUAGE NoImplicitPrelude # -- | An example implementation of the lovely continuation monad. module Cont where import FFI import Prelude -------------------------------------------------------------------------------- -- Entry point. -- | Main entry point. main :: Fay () main = runContT demo (const (return ())) demo :: Deferred () demo = case contT of CC return (>>=) (>>) callCC lift -> do lift (putStrLn "Hello!") sync setTimeout 500 contents <- sync readFile "README.md" lift (putStrLn ("File contents is: " ++ take 10 contents ++ "...")) -------------------------------------------------------------------------------- -- Deferred library. -- | An example deferred monad. type Deferred a = ContT () Fay a -- | Set an asynchronous timeout. setTimeout :: Int -> (() -> Fay ()) -> Fay () setTimeout = ffi "global.setTimeout(%2,%1)" readFile :: String -> (String -> Fay b) -> Fay b readFile = ffi "require('fs').readFile(%1,'utf-8',function(_,s){ %2(s); })" sync :: (t -> (a -> Fay r) -> Fay r) -> t -> ContT r Fay a sync m a = ContT $ \c -> m a c -------------------------------------------------------------------------------- Continuation library . -- | The continuation monad. data ContT r m a = ContT { runContT :: (a -> m r) -> m r } class Monad (m :: * -> *) instance (Monad m) => Monad (ContT r m) data CC = CC { cc_return :: forall a r. a -> ContT r Fay a , cc_bind :: forall a b r. ContT r Fay a -> (a -> ContT r Fay b) -> ContT r Fay b , cc_then :: forall a b r. ContT r Fay a -> ContT r Fay b -> ContT r Fay b , cc_callCC :: forall a b r. ((a -> ContT r Fay b) -> ContT r Fay a) -> ContT r Fay a , cc_lift :: forall a r. Fay a -> ContT r Fay a } -- | The continuation monad module. contT = let return a = ContT (\f -> f a) m >>= k = ContT $ \c -> runContT m (\a -> runContT (k a) c) m >> n = m >>= \_ -> n callCC f = ContT $ \c -> runContT (f (\a -> ContT $ \_ -> c a)) c lift m = ContT (\x -> m >>=* x) in CC return (>>=) (>>) callCC lift where (>>=*) = (>>=)
null
https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/examples/Cont.hs
haskell
# LANGUAGE RankNTypes # | An example implementation of the lovely continuation monad. ------------------------------------------------------------------------------ Entry point. | Main entry point. ------------------------------------------------------------------------------ Deferred library. | An example deferred monad. | Set an asynchronous timeout. ------------------------------------------------------------------------------ | The continuation monad. | The continuation monad module.
# LANGUAGE KindSignatures # # LANGUAGE RebindableSyntax # # LANGUAGE NoImplicitPrelude # module Cont where import FFI import Prelude main :: Fay () main = runContT demo (const (return ())) demo :: Deferred () demo = case contT of CC return (>>=) (>>) callCC lift -> do lift (putStrLn "Hello!") sync setTimeout 500 contents <- sync readFile "README.md" lift (putStrLn ("File contents is: " ++ take 10 contents ++ "...")) type Deferred a = ContT () Fay a setTimeout :: Int -> (() -> Fay ()) -> Fay () setTimeout = ffi "global.setTimeout(%2,%1)" readFile :: String -> (String -> Fay b) -> Fay b readFile = ffi "require('fs').readFile(%1,'utf-8',function(_,s){ %2(s); })" sync :: (t -> (a -> Fay r) -> Fay r) -> t -> ContT r Fay a sync m a = ContT $ \c -> m a c Continuation library . data ContT r m a = ContT { runContT :: (a -> m r) -> m r } class Monad (m :: * -> *) instance (Monad m) => Monad (ContT r m) data CC = CC { cc_return :: forall a r. a -> ContT r Fay a , cc_bind :: forall a b r. ContT r Fay a -> (a -> ContT r Fay b) -> ContT r Fay b , cc_then :: forall a b r. ContT r Fay a -> ContT r Fay b -> ContT r Fay b , cc_callCC :: forall a b r. ((a -> ContT r Fay b) -> ContT r Fay a) -> ContT r Fay a , cc_lift :: forall a r. Fay a -> ContT r Fay a } contT = let return a = ContT (\f -> f a) m >>= k = ContT $ \c -> runContT m (\a -> runContT (k a) c) m >> n = m >>= \_ -> n callCC f = ContT $ \c -> runContT (f (\a -> ContT $ \_ -> c a)) c lift m = ContT (\x -> m >>=* x) in CC return (>>=) (>>) callCC lift where (>>=*) = (>>=)
e54fde104fa317833eeb94a0b37b6bf62b9db637de745fd5e71c2489b69d444a
egobrain/tq_transform
tq_transform_utils.erl
Copyright ( c ) 2011 - 2013 , < > %% %% Permission to use, copy, modify, and/or 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. -module(tq_transform_utils). -include_lib("tq_transform/include/access_mode.hrl"). -export([ mode_to_acl/1, check_acl/2 ]). -export([ error_writer_foldl/3, error_writer_map/2, error_map_funs/2 ]). -export([ valid/1 ]). -export([ print_module/1, pretty_print/1 ]). -spec mode_to_acl(Mode) -> #access_mode{} when Mode :: r | w | rw | sr | sw | srsw | rsw | srw. mode_to_acl(r) -> #access_mode{r=true, sr=true, w=false, sw=false}; mode_to_acl(w) -> #access_mode{r=false, sr=false, w=true, sw=true}; mode_to_acl(rw) -> #access_mode{r=true, sr=true, w=true, sw=true}; mode_to_acl(sr) -> #access_mode{r=false, sr=true, w=false, sw=false}; mode_to_acl(sw) -> #access_mode{r=false, sr=false, w=false, sw=true}; mode_to_acl(srsw) -> #access_mode{r=false, sr=true, w=false, sw=true}; mode_to_acl(rsw) -> #access_mode{r=true, sr=true, w=false, sw=true}; mode_to_acl(srw) -> #access_mode{r=false, sr=true, w=true, sw=true}. -spec check_acl(FieldAcl, AccessAcl) -> boolean() when FieldAcl :: Acl, AccessAcl :: Acl, Acl :: #access_mode{}. check_acl(FieldAcl, AccessAcl) -> [_|L1] = tuple_to_list(FieldAcl), [_|L2] = tuple_to_list(AccessAcl), List = lists:zipwith(fun(_, false) -> true; (A1, true) -> A1 end, L1, L2), lists:foldl(fun(A1, A2) -> A1 andalso A2 end, true, List). -spec error_writer_foldl(Fun, State, List) -> {ok, NewState} | {error, Reasons} when List :: [Elem], Fun :: fun((Elem, State) -> {ok, NewState} | {error, Reason}), Reasons :: [Reason]. error_writer_foldl(Fun, InitState, Opts) -> {ResultState, ResultErrors} = lists:foldl(fun(Val, {State, Errors}) -> case Fun(Val, State) of {ok, State2} -> {State2, Errors}; {error, Reason} -> {State, [Reason | Errors]} end end, {InitState, []}, Opts), case ResultErrors of [] -> {ok, ResultState}; _ -> {error, lists:reverse(ResultErrors)} end. -spec error_writer_map(Fun, ArgsList) -> {ok, ResultList} | {error, Errors} when Fun :: fun((Arg) -> {ok, Result} | {error, Error}), ArgsList :: [Arg], ResultList :: [Result], Errors :: [Error]. error_writer_map(Fun, List) when is_list(List) -> MapFun = fun(Item, Acc) -> case Fun(Item) of ok -> {ok, Acc}; {ok, Res} -> {ok, [Res | Acc]}; {error, Reason} -> {error, Reason} end end, case error_writer_foldl(MapFun, [], List) of {ok, Result} -> {ok, lists:reverse(Result)}; {error, _} = Err -> Err end. -spec error_map_funs(Funs, State) -> {ok, State} | {error, Reason} when Funs :: [Fun], Fun :: fun((State) -> {ok, State} | {error, Reason}). error_map_funs([], State) -> {ok, State}; error_map_funs([Fun|Rest], State) -> case Fun(State) of {ok, State2} -> error_map_funs(Rest, State2); {error, _Reason} = Err -> Err end. -spec valid(ListToValid) -> ok | {error, Reasons} when ListToValid :: [{Field, Validator, Value}], Validator :: fun((Value) -> ok | {error, Reason}), Reasons :: [{Field, Reason}]. valid(List) -> Res = error_writer_foldl(fun({Field, Validator, Value}, State) -> case Validator(Value) of ok -> {ok, State}; {error, Reason} -> {error, {Field, Reason}} end end, ok, List), case Res of {ok, ok} -> ok; {error, _Reason} = Err -> Err end. %% Pretty print pretty_print(Forms0) -> Forms = epp:restore_typed_record_fields(revert(Forms0)), [io_lib:fwrite("~s~n", [lists:flatten([erl_pp:form(Fm) || Fm <- Forms])])]. revert(Tree) -> [erl_syntax:revert(T) || T <- lists:flatten(Tree)]. print_module(Module) -> BeamFileName = code:which(Module), case beam_lib:chunks(BeamFileName, [abstract_code]) of {ok, {_, [{abstract_code, {raw_abstract_v1,Forms}}]}} -> Code = pretty_print(Forms), io:format("~s~n", [Code]); Error -> Error end. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). error_writer_foldl_test_() -> Sum = fun (Int, Acc) when is_integer(Int) -> {ok, Acc+Int}; (Other, _Acc) -> {error, {not_integer, Other}} end, Tests = [ {[1, 2, 3, 4], {ok, 10}}, {[1, 2, 3, e1, 4, 5, e2], {error, [{not_integer, e1}, {not_integer, e2}]}}, {[1, 2, 3, error], {error, [{not_integer, error}]}}, {[], {ok, 0}}, {[error], {error, [{not_integer, error}]}}, {[1], {ok, 1}} ], F = fun(D, R) -> R = error_writer_foldl(Sum, 0, D) end, [fun() -> F(From, To) end || {From, To} <- Tests]. error_writer_map_test_() -> Sum = fun (Int) when is_integer(Int) -> {ok, Int+10}; (Other) -> {error, {not_integer, Other}} end, Tests = [ {[1, 2, 3, 4], {ok, [11, 12, 13, 14]}}, {[1, 2, 3, e1, 4, 5, e2], {error, [{not_integer, e1}, {not_integer, e2}]}}, {[1, 2, 3, error], {error, [{not_integer, error}]}}, {[], {ok, []}}, {[error], {error, [{not_integer, error}]}}, {[1], {ok, [11]}} ], F = fun(D, R) -> R = error_writer_map(Sum, D) end, [fun() -> F(From, To) end || {From, To} <- Tests]. error_map_funs_test_() -> Succ = fun(A) -> {ok, A+1} end, Err = fun(A) -> {error, A} end, Tests = [ {[], {ok, 0}}, {[Succ], {ok, 1}}, {[Succ, Succ], {ok, 2}}, {[Succ, Succ, Succ], {ok, 3}}, {[Err], {error, 0}}, {[Err, Succ, Succ], {error, 0}}, {[Succ, Err, Succ], {error, 1}}, {[Succ, Succ, Err], {error, 2}} ], [fun() -> R = error_map_funs(Funs, 0) end || {Funs, R} <- Tests]. -endif.
null
https://raw.githubusercontent.com/egobrain/tq_transform/6729f12b1a2fa5ece41ebb15b716c7f8b9360a33/src/tq_transform_utils.erl
erlang
Permission to use, copy, modify, and/or 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. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Pretty print
Copyright ( c ) 2011 - 2013 , < > THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN -module(tq_transform_utils). -include_lib("tq_transform/include/access_mode.hrl"). -export([ mode_to_acl/1, check_acl/2 ]). -export([ error_writer_foldl/3, error_writer_map/2, error_map_funs/2 ]). -export([ valid/1 ]). -export([ print_module/1, pretty_print/1 ]). -spec mode_to_acl(Mode) -> #access_mode{} when Mode :: r | w | rw | sr | sw | srsw | rsw | srw. mode_to_acl(r) -> #access_mode{r=true, sr=true, w=false, sw=false}; mode_to_acl(w) -> #access_mode{r=false, sr=false, w=true, sw=true}; mode_to_acl(rw) -> #access_mode{r=true, sr=true, w=true, sw=true}; mode_to_acl(sr) -> #access_mode{r=false, sr=true, w=false, sw=false}; mode_to_acl(sw) -> #access_mode{r=false, sr=false, w=false, sw=true}; mode_to_acl(srsw) -> #access_mode{r=false, sr=true, w=false, sw=true}; mode_to_acl(rsw) -> #access_mode{r=true, sr=true, w=false, sw=true}; mode_to_acl(srw) -> #access_mode{r=false, sr=true, w=true, sw=true}. -spec check_acl(FieldAcl, AccessAcl) -> boolean() when FieldAcl :: Acl, AccessAcl :: Acl, Acl :: #access_mode{}. check_acl(FieldAcl, AccessAcl) -> [_|L1] = tuple_to_list(FieldAcl), [_|L2] = tuple_to_list(AccessAcl), List = lists:zipwith(fun(_, false) -> true; (A1, true) -> A1 end, L1, L2), lists:foldl(fun(A1, A2) -> A1 andalso A2 end, true, List). -spec error_writer_foldl(Fun, State, List) -> {ok, NewState} | {error, Reasons} when List :: [Elem], Fun :: fun((Elem, State) -> {ok, NewState} | {error, Reason}), Reasons :: [Reason]. error_writer_foldl(Fun, InitState, Opts) -> {ResultState, ResultErrors} = lists:foldl(fun(Val, {State, Errors}) -> case Fun(Val, State) of {ok, State2} -> {State2, Errors}; {error, Reason} -> {State, [Reason | Errors]} end end, {InitState, []}, Opts), case ResultErrors of [] -> {ok, ResultState}; _ -> {error, lists:reverse(ResultErrors)} end. -spec error_writer_map(Fun, ArgsList) -> {ok, ResultList} | {error, Errors} when Fun :: fun((Arg) -> {ok, Result} | {error, Error}), ArgsList :: [Arg], ResultList :: [Result], Errors :: [Error]. error_writer_map(Fun, List) when is_list(List) -> MapFun = fun(Item, Acc) -> case Fun(Item) of ok -> {ok, Acc}; {ok, Res} -> {ok, [Res | Acc]}; {error, Reason} -> {error, Reason} end end, case error_writer_foldl(MapFun, [], List) of {ok, Result} -> {ok, lists:reverse(Result)}; {error, _} = Err -> Err end. -spec error_map_funs(Funs, State) -> {ok, State} | {error, Reason} when Funs :: [Fun], Fun :: fun((State) -> {ok, State} | {error, Reason}). error_map_funs([], State) -> {ok, State}; error_map_funs([Fun|Rest], State) -> case Fun(State) of {ok, State2} -> error_map_funs(Rest, State2); {error, _Reason} = Err -> Err end. -spec valid(ListToValid) -> ok | {error, Reasons} when ListToValid :: [{Field, Validator, Value}], Validator :: fun((Value) -> ok | {error, Reason}), Reasons :: [{Field, Reason}]. valid(List) -> Res = error_writer_foldl(fun({Field, Validator, Value}, State) -> case Validator(Value) of ok -> {ok, State}; {error, Reason} -> {error, {Field, Reason}} end end, ok, List), case Res of {ok, ok} -> ok; {error, _Reason} = Err -> Err end. pretty_print(Forms0) -> Forms = epp:restore_typed_record_fields(revert(Forms0)), [io_lib:fwrite("~s~n", [lists:flatten([erl_pp:form(Fm) || Fm <- Forms])])]. revert(Tree) -> [erl_syntax:revert(T) || T <- lists:flatten(Tree)]. print_module(Module) -> BeamFileName = code:which(Module), case beam_lib:chunks(BeamFileName, [abstract_code]) of {ok, {_, [{abstract_code, {raw_abstract_v1,Forms}}]}} -> Code = pretty_print(Forms), io:format("~s~n", [Code]); Error -> Error end. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). error_writer_foldl_test_() -> Sum = fun (Int, Acc) when is_integer(Int) -> {ok, Acc+Int}; (Other, _Acc) -> {error, {not_integer, Other}} end, Tests = [ {[1, 2, 3, 4], {ok, 10}}, {[1, 2, 3, e1, 4, 5, e2], {error, [{not_integer, e1}, {not_integer, e2}]}}, {[1, 2, 3, error], {error, [{not_integer, error}]}}, {[], {ok, 0}}, {[error], {error, [{not_integer, error}]}}, {[1], {ok, 1}} ], F = fun(D, R) -> R = error_writer_foldl(Sum, 0, D) end, [fun() -> F(From, To) end || {From, To} <- Tests]. error_writer_map_test_() -> Sum = fun (Int) when is_integer(Int) -> {ok, Int+10}; (Other) -> {error, {not_integer, Other}} end, Tests = [ {[1, 2, 3, 4], {ok, [11, 12, 13, 14]}}, {[1, 2, 3, e1, 4, 5, e2], {error, [{not_integer, e1}, {not_integer, e2}]}}, {[1, 2, 3, error], {error, [{not_integer, error}]}}, {[], {ok, []}}, {[error], {error, [{not_integer, error}]}}, {[1], {ok, [11]}} ], F = fun(D, R) -> R = error_writer_map(Sum, D) end, [fun() -> F(From, To) end || {From, To} <- Tests]. error_map_funs_test_() -> Succ = fun(A) -> {ok, A+1} end, Err = fun(A) -> {error, A} end, Tests = [ {[], {ok, 0}}, {[Succ], {ok, 1}}, {[Succ, Succ], {ok, 2}}, {[Succ, Succ, Succ], {ok, 3}}, {[Err], {error, 0}}, {[Err, Succ, Succ], {error, 0}}, {[Succ, Err, Succ], {error, 1}}, {[Succ, Succ, Err], {error, 2}} ], [fun() -> R = error_map_funs(Funs, 0) end || {Funs, R} <- Tests]. -endif.
797e3a509b045da54c5187a7f20563a59680b221a28c76d4ef7ea31641255e8f
2016rshah/Tic-Hack-Toe
TicTacToe.hs
module TicTacToe where # LANGUAGE FlexibleInstances # import Data.Either import Safe import Data.Maybe import Data.List |Slots in the board can either be filled with Naughts or Crosses data Symbol = X | O deriving (Show, Eq) -- |Empty slots are referred to by their location on the board type Piece = Either Int Symbol |A set of three pieces is used to represent rows , columns , and diagonals how do I constrain this to a length of three ? |The game board is made up of three rows of three pieces each . data Board = Board Three Three Three deriving (Eq) --Thank you to for the show function instance Show Board where show board = unlines . surround "+---+---+---+" . map (concat . surround "|". map showSquare) $ (rows board) where surround x xs = [x] ++ intersperse x xs ++ [x] showSquare = either (\n -> " " ++ show n ++ " ") (\n -> color n) -- | \ESC[ for ANSI escape esc :: Int -> String esc i = concat ["\ESC[", show i, "m"] | Black=30 , Red=31 , Green=32 , Yellow=33 , Blue=34 , Magenta=35 , Cyan=36 , White=37 color :: Symbol -> String color s | s == X = esc 32++" "++show s++" "++esc 0 | otherwise = esc 31++" "++show s++" "++esc 0 -- |Convenience function for constructing an empty board emptyBoard :: Board emptyBoard = Board [Left 1, Left 2, Left 3] [Left 4, Left 5, Left 6] [Left 7, Left 8, Left 9] |Given either a row , column , or diagonal , it checks whether it is entirely filled with naughts or crosses full :: Three -> Bool full ts@[a,b,c] = noLefts && allEqual where noLefts = foldl (\acc curr -> acc && (isRight curr)) True ts allEqual = a == b && b == c -- |Given a game board, check whether the game is over because someone won won :: Board -> Bool won b = foldl (\acc curr -> acc || (full curr)) False ((rows b) ++ (cols b) ++ (diags b)) -- |Given a game board, check whether the game is over due to a draw draw :: Board -> Bool draw b = length (possibleMoves b) == 0 -- |Message to display to the user about the results of the game winner :: Board -> String winner b = if length winnerType > 0 then head winnerType else "It was a draw!" where allConfigs = ((rows b) ++ (cols b) ++ (diags b)) winnerType = [if a == (Right O) then "The computer wins!" else "You win!" | curr@[a,b,c] <- allConfigs, full curr] -- |Extract rows from game board rows :: Board -> [Three] rows (Board x y z) = [x, y, z] -- |Extract columns from game board cols :: Board -> [Three] cols (Board [a, b, c] [d, e, f] [g, h, i]) = [[a, d, g], [b, e, h], [c, f, i]] -- |Extract diagonals from game board diags :: Board -> [Three] diags (Board [a, _, c] [_, e, _] [g, _, i]) = [[a, e, i], [c, e, g]] -- |List of places where a piece can be placed possibleMoves :: Board -> [Piece] possibleMoves board = filter isLeft (boardToList board) -- |Helper function to convert a board into a list of values boardToList :: Board -> [Piece] boardToList (Board x y z) = x ++ y ++ z -- |Helper function to convert a list of values into a board listToBoard :: [Piece] -> Board listToBoard [a,b,c,d,e,f,g,h,i] = Board [a,b,c] [d,e,f] [g,h,i] -- |Function to update the game board with a new value at a specified point findAndReplace :: Board -> Piece -> Piece -> Board findAndReplace b p1 p2 = listToBoard [if x==p1 then p2 else x | x <- bl] where bl = boardToList b if O 's can immediately win , and if so , do it winningOMove :: Board -> Maybe Board winningOMove b = headMay [findAndReplace b p (Right O) | p <- (possibleMoves b), won (findAndReplace b p (Right O))] if X 's can immediately win , and if so , block it blockXWin :: Board -> Maybe Board blockXWin b = headMay [findAndReplace b p (Right O) | p <- (possibleMoves b), won (findAndReplace b p (Right X))] -- |Check whether a board has been forked isFork :: Board -> Bool isFork b = 2 == length [findAndReplace b p (Right O) | p <- (possibleMoves b), won (findAndReplace b p (Right O))] if O 's can make a fork , and if so , do it forkO :: Board -> Maybe Board forkO b = headMay [findAndReplace b p (Right O) | p <- (possibleMoves b), isFork (findAndReplace b p (Right O))] if X 's can make a fork , and if so , block it blockXFork :: Board -> Maybe Board blockXFork b = headMay [findAndReplace b p (Right O) | p <- (possibleMoves b), isFork (findAndReplace b p (Right X))] |Decision tree for AI that will go down the list to make its move makeOMove :: Board -> Board makeOMove board@(Board x@[a, b, c] y@[d, e, f] z@[g, h, i]) | isJust (winningOMove board) = fromJust (winningOMove board) | isJust (blockXWin board) = fromJust (blockXWin board) | isJust (forkO board) = fromJust (forkO board) | isJust (blockXFork board) = fromJust (blockXFork board) | elem e (possibleMoves board) = findAndReplace board e (Right O) | otherwise = if length (possibleMoves board) > 0 then findAndReplace board (head (possibleMoves board)) (Right O) else board --This should not happen
null
https://raw.githubusercontent.com/2016rshah/Tic-Hack-Toe/e96fa9869f2a15c8cde30c9606ef52d24a27508d/src/TicTacToe.hs
haskell
|Empty slots are referred to by their location on the board Thank you to for the show function | \ESC[ for ANSI escape |Convenience function for constructing an empty board |Given a game board, check whether the game is over because someone won |Given a game board, check whether the game is over due to a draw |Message to display to the user about the results of the game |Extract rows from game board |Extract columns from game board |Extract diagonals from game board |List of places where a piece can be placed |Helper function to convert a board into a list of values |Helper function to convert a list of values into a board |Function to update the game board with a new value at a specified point |Check whether a board has been forked This should not happen
module TicTacToe where # LANGUAGE FlexibleInstances # import Data.Either import Safe import Data.Maybe import Data.List |Slots in the board can either be filled with Naughts or Crosses data Symbol = X | O deriving (Show, Eq) type Piece = Either Int Symbol |A set of three pieces is used to represent rows , columns , and diagonals how do I constrain this to a length of three ? |The game board is made up of three rows of three pieces each . data Board = Board Three Three Three deriving (Eq) instance Show Board where show board = unlines . surround "+---+---+---+" . map (concat . surround "|". map showSquare) $ (rows board) where surround x xs = [x] ++ intersperse x xs ++ [x] showSquare = either (\n -> " " ++ show n ++ " ") (\n -> color n) esc :: Int -> String esc i = concat ["\ESC[", show i, "m"] | Black=30 , Red=31 , Green=32 , Yellow=33 , Blue=34 , Magenta=35 , Cyan=36 , White=37 color :: Symbol -> String color s | s == X = esc 32++" "++show s++" "++esc 0 | otherwise = esc 31++" "++show s++" "++esc 0 emptyBoard :: Board emptyBoard = Board [Left 1, Left 2, Left 3] [Left 4, Left 5, Left 6] [Left 7, Left 8, Left 9] |Given either a row , column , or diagonal , it checks whether it is entirely filled with naughts or crosses full :: Three -> Bool full ts@[a,b,c] = noLefts && allEqual where noLefts = foldl (\acc curr -> acc && (isRight curr)) True ts allEqual = a == b && b == c won :: Board -> Bool won b = foldl (\acc curr -> acc || (full curr)) False ((rows b) ++ (cols b) ++ (diags b)) draw :: Board -> Bool draw b = length (possibleMoves b) == 0 winner :: Board -> String winner b = if length winnerType > 0 then head winnerType else "It was a draw!" where allConfigs = ((rows b) ++ (cols b) ++ (diags b)) winnerType = [if a == (Right O) then "The computer wins!" else "You win!" | curr@[a,b,c] <- allConfigs, full curr] rows :: Board -> [Three] rows (Board x y z) = [x, y, z] cols :: Board -> [Three] cols (Board [a, b, c] [d, e, f] [g, h, i]) = [[a, d, g], [b, e, h], [c, f, i]] diags :: Board -> [Three] diags (Board [a, _, c] [_, e, _] [g, _, i]) = [[a, e, i], [c, e, g]] possibleMoves :: Board -> [Piece] possibleMoves board = filter isLeft (boardToList board) boardToList :: Board -> [Piece] boardToList (Board x y z) = x ++ y ++ z listToBoard :: [Piece] -> Board listToBoard [a,b,c,d,e,f,g,h,i] = Board [a,b,c] [d,e,f] [g,h,i] findAndReplace :: Board -> Piece -> Piece -> Board findAndReplace b p1 p2 = listToBoard [if x==p1 then p2 else x | x <- bl] where bl = boardToList b if O 's can immediately win , and if so , do it winningOMove :: Board -> Maybe Board winningOMove b = headMay [findAndReplace b p (Right O) | p <- (possibleMoves b), won (findAndReplace b p (Right O))] if X 's can immediately win , and if so , block it blockXWin :: Board -> Maybe Board blockXWin b = headMay [findAndReplace b p (Right O) | p <- (possibleMoves b), won (findAndReplace b p (Right X))] isFork :: Board -> Bool isFork b = 2 == length [findAndReplace b p (Right O) | p <- (possibleMoves b), won (findAndReplace b p (Right O))] if O 's can make a fork , and if so , do it forkO :: Board -> Maybe Board forkO b = headMay [findAndReplace b p (Right O) | p <- (possibleMoves b), isFork (findAndReplace b p (Right O))] if X 's can make a fork , and if so , block it blockXFork :: Board -> Maybe Board blockXFork b = headMay [findAndReplace b p (Right O) | p <- (possibleMoves b), isFork (findAndReplace b p (Right X))] |Decision tree for AI that will go down the list to make its move makeOMove :: Board -> Board makeOMove board@(Board x@[a, b, c] y@[d, e, f] z@[g, h, i]) | isJust (winningOMove board) = fromJust (winningOMove board) | isJust (blockXWin board) = fromJust (blockXWin board) | isJust (forkO board) = fromJust (forkO board) | isJust (blockXFork board) = fromJust (blockXFork board) | elem e (possibleMoves board) = findAndReplace board e (Right O) | otherwise = if length (possibleMoves board) > 0 then findAndReplace board (head (possibleMoves board)) (Right O)
3bcf7fcba18012e01a5b2b7f9441d6bb356736d1f8457ee7e8427fdee1be32f3
cmoid/erlbutt
tangle.erl
SPDX - License - Identifier : GPL-2.0 - only %% Copyright ( C ) 2021 Dionne Associates , LLC . -module(tangle). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -include("ssb.hrl"). -export([get_tangle/1, parents/2, ancestors/2, children/2, descendants/2, get_msgs/1 ]). get_tangle(TangleId) -> %% retrieve tangle root author Auth = mess_auth:get(TangleId), FeedPid = utils:find_or_create_feed_pid(Auth), Targets = ssb_feed:references(FeedPid, TangleId, TangleId), Fun = fun([M, A]) -> find_paths(M, A, TangleId) end, {TangleId, Auth, lists:map(Fun, Targets)}. get_msgs({TangleId, Auth, Nodes}) -> [get_msg(TangleId, Auth) | get_msgs1(Nodes, [])]. get_msgs1(Nodes, Msgs) -> Fun = fun({Id, Auth, Rest}) -> get_msgs1(Rest, [get_msg(Id, Auth) | Msgs]); ({Id, Auth}) -> lists:reverse([get_msg(Id, Auth) | Msgs]) end, TmpRes = lists:flatten(lists:map(Fun, Nodes)), lists:reverse(lists:foldl(fun(E, Acc) -> case lists:member(E, Acc) of true -> Acc; _Else -> [E | Acc] end end, [], TmpRes)). get_msg(Id, Auth) -> Feed = utils:find_or_create_feed_pid(Auth), Msg = ssb_feed:fetch_msg(Feed, Id), {Content} = Msg#message.content, ?pgv(<<"text">>, Content). children(MsgId, TangleId) -> %% retrieve tangle root author Auth = mess_auth:get(MsgId), FeedPid = utils:find_or_create_feed_pid(Auth), {MsgId, ssb_feed:references(FeedPid, MsgId, TangleId)}. descendants(MsgId, TangleId) -> %% retrieve tangle root author Auth = mess_auth:get(MsgId), FeedPid = utils:find_or_create_feed_pid(Auth), Targets = ssb_feed:references(FeedPid, MsgId, TangleId), Fun = fun([M, A]) -> find_paths(M, A, TangleId) end, {MsgId, lists:map(Fun, Targets)}. parents(MsgId, TangleId) -> %% retrieve message author Auth = mess_auth:get(MsgId), FeedPid = utils:find_or_create_feed_pid(Auth), Msg = ssb_feed:fetch_msg(FeedPid, MsgId), Branches = message:is_branch(Msg), case Branches of false -> none; {TangleId, BranchList} -> {MsgId, lists:map(fun(P) -> [P, mess_auth:get(P)] end, BranchList)}; _Else -> none end. ancestors(MsgId, TangleId) -> %% retrieve message author Auth = mess_auth:get(MsgId), FeedPid = utils:find_or_create_feed_pid(Auth), Msg = ssb_feed:fetch_msg(FeedPid, MsgId), Branches = message:is_branch(Msg), case Branches of false -> none; {TangleId, BranchList} -> {MsgId, lists:map(fun(P) -> find_par_paths(P, mess_auth:get(P), TangleId) end, BranchList)}; _Else -> none end. %%%=================================================================== Internal functions %%%=================================================================== find_paths(MsgId, AuthId, RootId) -> Pid = utils:find_or_create_feed_pid(AuthId), Targets = ssb_feed:references(Pid, MsgId, RootId), Fun = fun([M, A]) -> find_paths(M, A, RootId) end, case Targets of [] -> {MsgId, AuthId}; done -> {MsgId, AuthId}; _Else -> {MsgId, AuthId, lists:map(Fun, Targets)} end. find_par_paths(MsgId, AuthId, RootId) -> Pid = utils:find_or_create_feed_pid(AuthId), Msg = ssb_feed:fetch_msg(Pid, MsgId), Branches = message:is_branch(Msg), case Branches of false -> {MsgId, AuthId}; {RootId, BranchList} -> {MsgId, AuthId, lists:map(fun(P) -> find_par_paths(P, mess_auth:get(P), RootId) end, BranchList)}; _Else -> {MsgId, AuthId} end. -ifdef(TEST). basic_test() -> {Auth, Priv, Feed} = init(), #message{id = Id} = make_msg_one(Auth, Priv, Feed), #message{content = {Content}} = ssb_feed:fetch_msg(Feed, Id), ?assert(<<"bar">> == ?pgv(<<"foo">>, Content)). tangle1_test() -> {Auth, Priv, Feed} = init(), #message{id = Id} = make_msg_one(Auth, Priv, Feed), #message{id = Id2} = make_msg(2, Id, Id, Id, Auth, Priv, Feed), ?assert({Id, Auth, [{Id2, Auth}]} == tangle:get_tangle(Id)). tangle2_test() -> {Auth, Priv, Feed} = init(), #message{id = Id} = make_msg_one(Auth, Priv, Feed), #message{id = Id2} = make_msg(2, Id, Id, Id, Auth, Priv, Feed), #message{id = Id3} = make_msg(3, Id2, Id, Id2, Auth, Priv, Feed), ?assert({Id, Auth, [{Id2, Auth, [{Id3, Auth}]}]} == tangle:get_tangle(Id)). tangle3_test() -> {Auth, Priv, Feed} = init(), #message{id = Id} = make_msg_one(Auth, Priv, Feed), #message{id = Id2} = make_msg(2, Id, Id, Id, Auth, Priv, Feed), #message{id = Id3} = make_msg(3, Id2, Id, Id2, Auth, Priv, Feed), ?assert({Id, Auth, [{Id2, Auth, [{Id3, Auth}]}]} == tangle:get_tangle(Id)), %% Now create another feed {Auth2, Priv2, Feed2} = create_id(), #message{id = Id4} = make_msg(4, Id2, Id, Id2, Auth2, Priv2, Feed2), ?assert({Id, Auth, [{Id2, Auth, [{Id4, Auth2}, {Id3, Auth}]}]} == tangle:get_tangle(Id)). tangle4_test() -> {Auth, Priv, Feed} = init(), #message{id = Id} = make_msg_one(Auth, Priv, Feed), #message{id = Id2} = make_msg(2, Id, Id, Id, Auth, Priv, Feed), #message{id = Id3} = make_msg(3, Id2, Id, Id2, Auth, Priv, Feed), ?assert({Id, Auth, [{Id2, Auth, [{Id3, Auth}]}]} == tangle:get_tangle(Id)), %% Now create another feed {Auth2, Priv2, Feed2} = create_id(), #message{id = Id4} = make_msg(4, Id2, Id, Id2, Auth2, Priv2, Feed2), #message{id = Id5} = make_msg(5, Id4, Id, [Id4, Id3], Auth2, Priv2, Feed2), ?assert({Id, Auth, [{Id2, Auth, [{Id4, Auth2, [{Id5, Auth2}]}, {Id3, Auth, [{Id5, Auth2}]}]}]} == tangle:get_tangle(Id)). init() -> keys:start_link(), config:start_link("test/ssb.cfg"), mess_auth:start_link(), create_id(). create_id() -> {Pub, Priv} = utils:create_key_pair(), Auth = utils:display_pub(Pub), {ok, Feed} = ssb_feed:start_link(Auth), {Auth, Priv, Feed}. make_msg_one(Auth, Priv, Feed) -> Msg = message:new_msg(nil, 1, {[{<<"foo">>, <<"bar">>}]}, {Auth, Priv}), ssb_feed:store_msg(Feed, Msg), Msg. make_msg(N, Prev, Root, BranchList, Auth, Priv, Feed) -> Msg = message:new_msg(Prev, N, {[{<<"type">>, <<"post">>}, {<<"test">>, <<"bar">>}, {<<"root">>, Root}, {<<"branch">>, BranchList}]}, {Auth, Priv}), ssb_feed:store_msg(Feed, Msg), Msg. -endif.
null
https://raw.githubusercontent.com/cmoid/erlbutt/9e15ace3e9009c8bce6cf3251cf16e1f8611e16a/apps/ssb/src/tangle.erl
erlang
retrieve tangle root author retrieve tangle root author retrieve tangle root author retrieve message author retrieve message author =================================================================== =================================================================== Now create another feed Now create another feed
SPDX - License - Identifier : GPL-2.0 - only Copyright ( C ) 2021 Dionne Associates , LLC . -module(tangle). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -include("ssb.hrl"). -export([get_tangle/1, parents/2, ancestors/2, children/2, descendants/2, get_msgs/1 ]). get_tangle(TangleId) -> Auth = mess_auth:get(TangleId), FeedPid = utils:find_or_create_feed_pid(Auth), Targets = ssb_feed:references(FeedPid, TangleId, TangleId), Fun = fun([M, A]) -> find_paths(M, A, TangleId) end, {TangleId, Auth, lists:map(Fun, Targets)}. get_msgs({TangleId, Auth, Nodes}) -> [get_msg(TangleId, Auth) | get_msgs1(Nodes, [])]. get_msgs1(Nodes, Msgs) -> Fun = fun({Id, Auth, Rest}) -> get_msgs1(Rest, [get_msg(Id, Auth) | Msgs]); ({Id, Auth}) -> lists:reverse([get_msg(Id, Auth) | Msgs]) end, TmpRes = lists:flatten(lists:map(Fun, Nodes)), lists:reverse(lists:foldl(fun(E, Acc) -> case lists:member(E, Acc) of true -> Acc; _Else -> [E | Acc] end end, [], TmpRes)). get_msg(Id, Auth) -> Feed = utils:find_or_create_feed_pid(Auth), Msg = ssb_feed:fetch_msg(Feed, Id), {Content} = Msg#message.content, ?pgv(<<"text">>, Content). children(MsgId, TangleId) -> Auth = mess_auth:get(MsgId), FeedPid = utils:find_or_create_feed_pid(Auth), {MsgId, ssb_feed:references(FeedPid, MsgId, TangleId)}. descendants(MsgId, TangleId) -> Auth = mess_auth:get(MsgId), FeedPid = utils:find_or_create_feed_pid(Auth), Targets = ssb_feed:references(FeedPid, MsgId, TangleId), Fun = fun([M, A]) -> find_paths(M, A, TangleId) end, {MsgId, lists:map(Fun, Targets)}. parents(MsgId, TangleId) -> Auth = mess_auth:get(MsgId), FeedPid = utils:find_or_create_feed_pid(Auth), Msg = ssb_feed:fetch_msg(FeedPid, MsgId), Branches = message:is_branch(Msg), case Branches of false -> none; {TangleId, BranchList} -> {MsgId, lists:map(fun(P) -> [P, mess_auth:get(P)] end, BranchList)}; _Else -> none end. ancestors(MsgId, TangleId) -> Auth = mess_auth:get(MsgId), FeedPid = utils:find_or_create_feed_pid(Auth), Msg = ssb_feed:fetch_msg(FeedPid, MsgId), Branches = message:is_branch(Msg), case Branches of false -> none; {TangleId, BranchList} -> {MsgId, lists:map(fun(P) -> find_par_paths(P, mess_auth:get(P), TangleId) end, BranchList)}; _Else -> none end. Internal functions find_paths(MsgId, AuthId, RootId) -> Pid = utils:find_or_create_feed_pid(AuthId), Targets = ssb_feed:references(Pid, MsgId, RootId), Fun = fun([M, A]) -> find_paths(M, A, RootId) end, case Targets of [] -> {MsgId, AuthId}; done -> {MsgId, AuthId}; _Else -> {MsgId, AuthId, lists:map(Fun, Targets)} end. find_par_paths(MsgId, AuthId, RootId) -> Pid = utils:find_or_create_feed_pid(AuthId), Msg = ssb_feed:fetch_msg(Pid, MsgId), Branches = message:is_branch(Msg), case Branches of false -> {MsgId, AuthId}; {RootId, BranchList} -> {MsgId, AuthId, lists:map(fun(P) -> find_par_paths(P, mess_auth:get(P), RootId) end, BranchList)}; _Else -> {MsgId, AuthId} end. -ifdef(TEST). basic_test() -> {Auth, Priv, Feed} = init(), #message{id = Id} = make_msg_one(Auth, Priv, Feed), #message{content = {Content}} = ssb_feed:fetch_msg(Feed, Id), ?assert(<<"bar">> == ?pgv(<<"foo">>, Content)). tangle1_test() -> {Auth, Priv, Feed} = init(), #message{id = Id} = make_msg_one(Auth, Priv, Feed), #message{id = Id2} = make_msg(2, Id, Id, Id, Auth, Priv, Feed), ?assert({Id, Auth, [{Id2, Auth}]} == tangle:get_tangle(Id)). tangle2_test() -> {Auth, Priv, Feed} = init(), #message{id = Id} = make_msg_one(Auth, Priv, Feed), #message{id = Id2} = make_msg(2, Id, Id, Id, Auth, Priv, Feed), #message{id = Id3} = make_msg(3, Id2, Id, Id2, Auth, Priv, Feed), ?assert({Id, Auth, [{Id2, Auth, [{Id3, Auth}]}]} == tangle:get_tangle(Id)). tangle3_test() -> {Auth, Priv, Feed} = init(), #message{id = Id} = make_msg_one(Auth, Priv, Feed), #message{id = Id2} = make_msg(2, Id, Id, Id, Auth, Priv, Feed), #message{id = Id3} = make_msg(3, Id2, Id, Id2, Auth, Priv, Feed), ?assert({Id, Auth, [{Id2, Auth, [{Id3, Auth}]}]} == tangle:get_tangle(Id)), {Auth2, Priv2, Feed2} = create_id(), #message{id = Id4} = make_msg(4, Id2, Id, Id2, Auth2, Priv2, Feed2), ?assert({Id, Auth, [{Id2, Auth, [{Id4, Auth2}, {Id3, Auth}]}]} == tangle:get_tangle(Id)). tangle4_test() -> {Auth, Priv, Feed} = init(), #message{id = Id} = make_msg_one(Auth, Priv, Feed), #message{id = Id2} = make_msg(2, Id, Id, Id, Auth, Priv, Feed), #message{id = Id3} = make_msg(3, Id2, Id, Id2, Auth, Priv, Feed), ?assert({Id, Auth, [{Id2, Auth, [{Id3, Auth}]}]} == tangle:get_tangle(Id)), {Auth2, Priv2, Feed2} = create_id(), #message{id = Id4} = make_msg(4, Id2, Id, Id2, Auth2, Priv2, Feed2), #message{id = Id5} = make_msg(5, Id4, Id, [Id4, Id3], Auth2, Priv2, Feed2), ?assert({Id, Auth, [{Id2, Auth, [{Id4, Auth2, [{Id5, Auth2}]}, {Id3, Auth, [{Id5, Auth2}]}]}]} == tangle:get_tangle(Id)). init() -> keys:start_link(), config:start_link("test/ssb.cfg"), mess_auth:start_link(), create_id(). create_id() -> {Pub, Priv} = utils:create_key_pair(), Auth = utils:display_pub(Pub), {ok, Feed} = ssb_feed:start_link(Auth), {Auth, Priv, Feed}. make_msg_one(Auth, Priv, Feed) -> Msg = message:new_msg(nil, 1, {[{<<"foo">>, <<"bar">>}]}, {Auth, Priv}), ssb_feed:store_msg(Feed, Msg), Msg. make_msg(N, Prev, Root, BranchList, Auth, Priv, Feed) -> Msg = message:new_msg(Prev, N, {[{<<"type">>, <<"post">>}, {<<"test">>, <<"bar">>}, {<<"root">>, Root}, {<<"branch">>, BranchList}]}, {Auth, Priv}), ssb_feed:store_msg(Feed, Msg), Msg. -endif.
cf55aba1242cfeced318879b8110a6a1defdc24c805a632e36afd2edf3d888a2
JoelSanchez/ventas
category_test.clj
(ns ventas.entities.category-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [ventas.database :as db] [ventas.database.entity :as entity] [ventas.database.seed :as seed] [ventas.entities.category :as sut] [ventas.entities.i18n :as entities.i18n] [ventas.test-tools :as test-tools])) (def example-category {:category/name (entities.i18n/->entity {:en_US "Example category"}) :category/keyword :example-category :category/image {:schema/type :schema.type/file :file/extension "jpg"} :category/parent {:category/name (entities.i18n/->entity {:en_US "Example parent category"}) :category/keyword :example-category-parent :category/image {:schema/type :schema.type/file :file/extension "jpg"} :category/parent {:category/name (entities.i18n/->entity {:en_US "Example root category"}) :category/keyword :example-category-root :schema/type :schema.type/category} :schema/type :schema.type/category} :schema/type :schema.type/category}) (declare category) (use-fixtures :once #(test-tools/with-test-context (seed/seed :minimal? true) (with-redefs [category (entity/create* example-category)] (%)))) (deftest serialization (is (= "jpg" (get-in (entity/serialize category) [:image :extension]))) (is (not (:category/image (entity/deserialize :category (entity/serialize category)))))) (deftest get-image (is (= "jpg" (:extension (sut/get-image category))))) (deftest get-parents (let [pulled-category (db/pull '[{:category/parent [*]} *] (:db/id category))] (is (= #{(get-in pulled-category [:db/id]) (get-in pulled-category [:category/parent :db/id]) (get-in pulled-category [:category/parent :category/parent :db/id])} (sut/get-parents category))))) (deftest get-parent-slug (is (= "example-parent-category-example-category" (-> (sut/get-parent-slug (:db/id category)) :i18n/translations first :i18n.translation/value)))) (deftest add-slug-to-category (let [slug (:ventas/slug (#'sut/add-slug-to-category category))] (is slug) (is (= "example-parent-category-example-category" (entity/find-serialize slug {:culture [:i18n.culture/keyword :en_US]})))))
null
https://raw.githubusercontent.com/JoelSanchez/ventas/dc8fc8ff9f63dfc8558ecdaacfc4983903b8e9a1/test/clj/ventas/entities/category_test.clj
clojure
(ns ventas.entities.category-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [ventas.database :as db] [ventas.database.entity :as entity] [ventas.database.seed :as seed] [ventas.entities.category :as sut] [ventas.entities.i18n :as entities.i18n] [ventas.test-tools :as test-tools])) (def example-category {:category/name (entities.i18n/->entity {:en_US "Example category"}) :category/keyword :example-category :category/image {:schema/type :schema.type/file :file/extension "jpg"} :category/parent {:category/name (entities.i18n/->entity {:en_US "Example parent category"}) :category/keyword :example-category-parent :category/image {:schema/type :schema.type/file :file/extension "jpg"} :category/parent {:category/name (entities.i18n/->entity {:en_US "Example root category"}) :category/keyword :example-category-root :schema/type :schema.type/category} :schema/type :schema.type/category} :schema/type :schema.type/category}) (declare category) (use-fixtures :once #(test-tools/with-test-context (seed/seed :minimal? true) (with-redefs [category (entity/create* example-category)] (%)))) (deftest serialization (is (= "jpg" (get-in (entity/serialize category) [:image :extension]))) (is (not (:category/image (entity/deserialize :category (entity/serialize category)))))) (deftest get-image (is (= "jpg" (:extension (sut/get-image category))))) (deftest get-parents (let [pulled-category (db/pull '[{:category/parent [*]} *] (:db/id category))] (is (= #{(get-in pulled-category [:db/id]) (get-in pulled-category [:category/parent :db/id]) (get-in pulled-category [:category/parent :category/parent :db/id])} (sut/get-parents category))))) (deftest get-parent-slug (is (= "example-parent-category-example-category" (-> (sut/get-parent-slug (:db/id category)) :i18n/translations first :i18n.translation/value)))) (deftest add-slug-to-category (let [slug (:ventas/slug (#'sut/add-slug-to-category category))] (is slug) (is (= "example-parent-category-example-category" (entity/find-serialize slug {:culture [:i18n.culture/keyword :en_US]})))))
0b844ac3978d2e2dffff1ec976110d27bfde2b53eee48d337598147e68aa9a2f
pjotrp/guix
haskell-build-system.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2015 < > Copyright © 2015 < > ;;; ;;; 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 (guix build haskell-build-system) #:use-module ((guix build gnu-build-system) #:prefix gnu:) #:use-module (guix build utils) #:use-module (srfi srfi-1) #:use-module (srfi srfi-26) #:use-module (ice-9 rdelim) #:use-module (ice-9 regex) #:use-module (ice-9 match) #:export (%standard-phases haskell-build)) ;; Commentary: ;; Builder - side code of the standard Haskell package build procedure . ;; The compiler , to find libraries , relies on a library database with a binary cache . For GHC the cache has to be named ' package.cache ' . If every ;; library would generate the cache at build time, then they would clash in ;; profiles. For this reason we do not generate the cache when we generate ;; libraries substitutes. Instead: ;; ;; - At build time we use the 'setup-compiler' phase to generate a temporary ;; library database and its cache. ;; ;; - We generate the cache when a profile is created. ;; ;; Code: ;; Directory where we create the temporary libraries database with its cache ;; as required by the compiler. (define %tmp-db-dir (string-append (or (getenv "TMP") "/tmp") "/package.conf.d")) (define (run-setuphs command params) (let ((setup-file (cond ((file-exists? "Setup.hs") "Setup.hs") ((file-exists? "Setup.lhs") "Setup.lhs") (else #f)))) (if setup-file (begin (format #t "running \"runhaskell Setup.hs\" with command ~s \ and parameters ~s~%" command params) (zero? (apply system* "runhaskell" setup-file command params))) (error "no Setup.hs nor Setup.lhs found")))) (define* (configure #:key outputs inputs tests? (configure-flags '()) #:allow-other-keys) "Configure a given Haskell package." (let* ((out (assoc-ref outputs "out")) (doc (assoc-ref outputs "doc")) (lib (assoc-ref outputs "lib")) (bin (assoc-ref outputs "bin")) (input-dirs (match inputs (((_ . dir) ...) dir) (_ '()))) (params (append `(,(string-append "--prefix=" out)) `(,(string-append "--libdir=" (or lib out) "/lib")) `(,(string-append "--bindir=" (or bin out) "/bin")) `(,(string-append "--docdir=" (or doc out) "/share/doc/" (package-name-version out))) '("--libsubdir=$compiler/$pkg-$version") `(,(string-append "--package-db=" %tmp-db-dir)) '("--global") `(,@(map (cut string-append "--extra-include-dirs=" <>) (search-path-as-list '("include") input-dirs))) `(,@(map (cut string-append "--extra-lib-dirs=" <>) (search-path-as-list '("lib") input-dirs))) (if tests? '("--enable-tests") '()) configure-flags))) For packages where the Cabal build - type is set to " Configure " , ;; ./configure will be executed. In these cases, the following ;; environment variable is needed to be able to find the shell executable. ;; For other package types, the configure script isn't present. For more information , see the Build Information section of ;; <-guide/developing-packages.html>. (when (file-exists? "configure") (setenv "CONFIG_SHELL" "sh")) (run-setuphs "configure" params))) (define* (build #:rest empty) "Build a given Haskell package." (run-setuphs "build" '())) (define* (install #:rest empty) "Install a given Haskell package." (run-setuphs "copy" '())) (define (package-name-version store-dir) "Given a store directory STORE-DIR return 'name-version' of the package." (let* ((base (basename store-dir))) (string-drop base (+ 1 (string-index base #\-))))) (define (grep rx port) "Given a regular-expression RX including a group, read from PORT until the first match and return the content of the group." (let ((line (read-line port))) (if (eof-object? line) #f (let ((rx-result (regexp-exec rx line))) (if rx-result (match:substring rx-result 1) (grep rx port)))))) (define* (setup-compiler #:key system inputs outputs #:allow-other-keys) "Setup the compiler environment." (let* ((haskell (assoc-ref inputs "haskell")) (name-version (package-name-version haskell))) (cond ((string-match "ghc" name-version) (make-ghc-package-database system inputs outputs)) (else (format #t "Compiler ~a not supported~%" name-version))))) (define (make-ghc-package-database system inputs outputs) "Generate the GHC package database." (let* ((haskell (assoc-ref inputs "haskell")) (input-dirs (match inputs (((_ . dir) ...) dir) (_ '()))) (conf-dirs (search-path-as-list `(,(string-append "lib/" (package-name-version haskell) "/package.conf.d")) input-dirs)) (conf-files (append-map (cut find-files <> "\\.conf$") conf-dirs))) (mkdir-p %tmp-db-dir) (for-each (lambda (file) (copy-file file (string-append %tmp-db-dir "/" (basename file)))) conf-files) (zero? (system* "ghc-pkg" (string-append "--package-db=" %tmp-db-dir) "recache")))) (define* (register #:key name system inputs outputs #:allow-other-keys) "Generate the compiler registration file for a given Haskell package. Don't generate the cache as it would clash in user profiles." (let* ((out (assoc-ref outputs "out")) (haskell (assoc-ref inputs "haskell")) (lib (string-append out "/lib")) (config-dir (string-append lib "/" (package-name-version haskell) "/package.conf.d")) (id-rx (make-regexp "^id: *(.*)$")) (config-file (string-append out "/" name ".conf")) (params (list (string-append "--gen-pkg-config=" config-file)))) (run-setuphs "register" params) ;; The conf file is created only when there is a library to register. (when (file-exists? config-file) (mkdir-p config-dir) (let ((config-file-name+id (call-with-ascii-input-file config-file (cut grep id-rx <>)))) (rename-file config-file (string-append config-dir "/" config-file-name+id ".conf")))) #t)) (define* (check #:key tests? test-target #:allow-other-keys) "Run the test suite of a given Haskell package." (if tests? (run-setuphs test-target '()) (begin (format #t "test suite not run~%") #t))) (define* (haddock #:key outputs haddock? haddock-flags #:allow-other-keys) "Run the test suite of a given Haskell package." (if haddock? (run-setuphs "haddock" haddock-flags) #t)) (define %standard-phases (modify-phases gnu:%standard-phases (add-before 'configure 'setup-compiler setup-compiler) (add-before 'install 'haddock haddock) (add-after 'install 'register register) (replace 'install install) (replace 'check check) (replace 'build build) (replace 'configure configure))) (define* (haskell-build #:key inputs (phases %standard-phases) #:allow-other-keys #:rest args) "Build the given Haskell package, applying all of PHASES in order." (apply gnu:gnu-build #:inputs inputs #:phases phases args)) ;;; haskell-build-system.scm ends here
null
https://raw.githubusercontent.com/pjotrp/guix/96250294012c2f1520b67f12ea80bfd6b98075a2/guix/build/haskell-build-system.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. Commentary: library would generate the cache at build time, then they would clash in profiles. For this reason we do not generate the cache when we generate libraries substitutes. Instead: - At build time we use the 'setup-compiler' phase to generate a temporary library database and its cache. - We generate the cache when a profile is created. Code: Directory where we create the temporary libraries database with its cache as required by the compiler. ./configure will be executed. In these cases, the following environment variable is needed to be able to find the shell executable. For other package types, the configure script isn't present. For more <-guide/developing-packages.html>. The conf file is created only when there is a library to register. haskell-build-system.scm ends here
Copyright © 2015 < > Copyright © 2015 < > 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 (guix build haskell-build-system) #:use-module ((guix build gnu-build-system) #:prefix gnu:) #:use-module (guix build utils) #:use-module (srfi srfi-1) #:use-module (srfi srfi-26) #:use-module (ice-9 rdelim) #:use-module (ice-9 regex) #:use-module (ice-9 match) #:export (%standard-phases haskell-build)) Builder - side code of the standard Haskell package build procedure . The compiler , to find libraries , relies on a library database with a binary cache . For GHC the cache has to be named ' package.cache ' . If every (define %tmp-db-dir (string-append (or (getenv "TMP") "/tmp") "/package.conf.d")) (define (run-setuphs command params) (let ((setup-file (cond ((file-exists? "Setup.hs") "Setup.hs") ((file-exists? "Setup.lhs") "Setup.lhs") (else #f)))) (if setup-file (begin (format #t "running \"runhaskell Setup.hs\" with command ~s \ and parameters ~s~%" command params) (zero? (apply system* "runhaskell" setup-file command params))) (error "no Setup.hs nor Setup.lhs found")))) (define* (configure #:key outputs inputs tests? (configure-flags '()) #:allow-other-keys) "Configure a given Haskell package." (let* ((out (assoc-ref outputs "out")) (doc (assoc-ref outputs "doc")) (lib (assoc-ref outputs "lib")) (bin (assoc-ref outputs "bin")) (input-dirs (match inputs (((_ . dir) ...) dir) (_ '()))) (params (append `(,(string-append "--prefix=" out)) `(,(string-append "--libdir=" (or lib out) "/lib")) `(,(string-append "--bindir=" (or bin out) "/bin")) `(,(string-append "--docdir=" (or doc out) "/share/doc/" (package-name-version out))) '("--libsubdir=$compiler/$pkg-$version") `(,(string-append "--package-db=" %tmp-db-dir)) '("--global") `(,@(map (cut string-append "--extra-include-dirs=" <>) (search-path-as-list '("include") input-dirs))) `(,@(map (cut string-append "--extra-lib-dirs=" <>) (search-path-as-list '("lib") input-dirs))) (if tests? '("--enable-tests") '()) configure-flags))) For packages where the Cabal build - type is set to " Configure " , information , see the Build Information section of (when (file-exists? "configure") (setenv "CONFIG_SHELL" "sh")) (run-setuphs "configure" params))) (define* (build #:rest empty) "Build a given Haskell package." (run-setuphs "build" '())) (define* (install #:rest empty) "Install a given Haskell package." (run-setuphs "copy" '())) (define (package-name-version store-dir) "Given a store directory STORE-DIR return 'name-version' of the package." (let* ((base (basename store-dir))) (string-drop base (+ 1 (string-index base #\-))))) (define (grep rx port) "Given a regular-expression RX including a group, read from PORT until the first match and return the content of the group." (let ((line (read-line port))) (if (eof-object? line) #f (let ((rx-result (regexp-exec rx line))) (if rx-result (match:substring rx-result 1) (grep rx port)))))) (define* (setup-compiler #:key system inputs outputs #:allow-other-keys) "Setup the compiler environment." (let* ((haskell (assoc-ref inputs "haskell")) (name-version (package-name-version haskell))) (cond ((string-match "ghc" name-version) (make-ghc-package-database system inputs outputs)) (else (format #t "Compiler ~a not supported~%" name-version))))) (define (make-ghc-package-database system inputs outputs) "Generate the GHC package database." (let* ((haskell (assoc-ref inputs "haskell")) (input-dirs (match inputs (((_ . dir) ...) dir) (_ '()))) (conf-dirs (search-path-as-list `(,(string-append "lib/" (package-name-version haskell) "/package.conf.d")) input-dirs)) (conf-files (append-map (cut find-files <> "\\.conf$") conf-dirs))) (mkdir-p %tmp-db-dir) (for-each (lambda (file) (copy-file file (string-append %tmp-db-dir "/" (basename file)))) conf-files) (zero? (system* "ghc-pkg" (string-append "--package-db=" %tmp-db-dir) "recache")))) (define* (register #:key name system inputs outputs #:allow-other-keys) "Generate the compiler registration file for a given Haskell package. Don't generate the cache as it would clash in user profiles." (let* ((out (assoc-ref outputs "out")) (haskell (assoc-ref inputs "haskell")) (lib (string-append out "/lib")) (config-dir (string-append lib "/" (package-name-version haskell) "/package.conf.d")) (id-rx (make-regexp "^id: *(.*)$")) (config-file (string-append out "/" name ".conf")) (params (list (string-append "--gen-pkg-config=" config-file)))) (run-setuphs "register" params) (when (file-exists? config-file) (mkdir-p config-dir) (let ((config-file-name+id (call-with-ascii-input-file config-file (cut grep id-rx <>)))) (rename-file config-file (string-append config-dir "/" config-file-name+id ".conf")))) #t)) (define* (check #:key tests? test-target #:allow-other-keys) "Run the test suite of a given Haskell package." (if tests? (run-setuphs test-target '()) (begin (format #t "test suite not run~%") #t))) (define* (haddock #:key outputs haddock? haddock-flags #:allow-other-keys) "Run the test suite of a given Haskell package." (if haddock? (run-setuphs "haddock" haddock-flags) #t)) (define %standard-phases (modify-phases gnu:%standard-phases (add-before 'configure 'setup-compiler setup-compiler) (add-before 'install 'haddock haddock) (add-after 'install 'register register) (replace 'install install) (replace 'check check) (replace 'build build) (replace 'configure configure))) (define* (haskell-build #:key inputs (phases %standard-phases) #:allow-other-keys #:rest args) "Build the given Haskell package, applying all of PHASES in order." (apply gnu:gnu-build #:inputs inputs #:phases phases args))
e9866a3ad450eff3c85ed8a8408d20f5e38f43558bacf86fe36b8c77d5b9e616
dcSpark/fracada-il-primo
build-redeemer.hs
{-# LANGUAGE OverloadedStrings #-} import Cardano.Api import Cardano.Api.Shelley import Data.Aeson import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Lazy.Char8 as BL8 import Fracada.Validator import Ledger (Signature (..)) import Plutus.V1.Ledger.Api import qualified Plutus.V1.Ledger.Api as Plutus import Prelude readSignature :: String -> IO Signature readSignature fileName = do decodedData <- B16.decode <$> LB.toStrict <$> BL8.readFile fileName case decodedData of Right data' -> return $ Signature $ Plutus.toBuiltin data' Left err -> error err encodeRedeemer :: Maybe AddToken -> BL8.ByteString encodeRedeemer redeemer = let redeemerAsData = Plutus.builtinDataToData $ toBuiltinData redeemer in Data.Aeson.encode (scriptDataToJson ScriptDataJsonDetailedSchema $ fromPlutusData redeemerAsData) main :: IO () main = do putStrLn $ "Usage:" putStrLn $ "build-redeemer < paths to signed datum hash files for each signature" stdInText <- getContents sigs' <- mapM readSignature $ lines stdInText let redeemer = Just $ AddToken sigs' encoded = encodeRedeemer redeemer putStrLn $ "encoded redeemer: " ++ show encoded BL8.writeFile "redeemer.json" encoded
null
https://raw.githubusercontent.com/dcSpark/fracada-il-primo/0400e8f7d465d309d9638eb4a50eede2fed4effb/scripts/build-redeemer.hs
haskell
# LANGUAGE OverloadedStrings #
import Cardano.Api import Cardano.Api.Shelley import Data.Aeson import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Lazy.Char8 as BL8 import Fracada.Validator import Ledger (Signature (..)) import Plutus.V1.Ledger.Api import qualified Plutus.V1.Ledger.Api as Plutus import Prelude readSignature :: String -> IO Signature readSignature fileName = do decodedData <- B16.decode <$> LB.toStrict <$> BL8.readFile fileName case decodedData of Right data' -> return $ Signature $ Plutus.toBuiltin data' Left err -> error err encodeRedeemer :: Maybe AddToken -> BL8.ByteString encodeRedeemer redeemer = let redeemerAsData = Plutus.builtinDataToData $ toBuiltinData redeemer in Data.Aeson.encode (scriptDataToJson ScriptDataJsonDetailedSchema $ fromPlutusData redeemerAsData) main :: IO () main = do putStrLn $ "Usage:" putStrLn $ "build-redeemer < paths to signed datum hash files for each signature" stdInText <- getContents sigs' <- mapM readSignature $ lines stdInText let redeemer = Just $ AddToken sigs' encoded = encodeRedeemer redeemer putStrLn $ "encoded redeemer: " ++ show encoded BL8.writeFile "redeemer.json" encoded